diff --git a/0001-imp-added-Ubuntu-22.04-build-configuration.patch b/0001-imp-added-Ubuntu-22.04-build-configuration.patch new file mode 100644 index 0000000..64379ad --- /dev/null +++ b/0001-imp-added-Ubuntu-22.04-build-configuration.patch @@ -0,0 +1,77 @@ +From 74aeaf35a24dd182f7abbe944c8316ed598a1fb5 Mon Sep 17 00:00:00 2001 +From: =?UTF-8?q?Ren=C3=A9=20Reucher?= +Date: Thu, 9 Jun 2022 11:35:55 +0200 +Subject: [PATCH] imp: added Ubuntu 22.04 build configuration + +--- + arch/Linux/Ubuntu_14.10.cfg | 1 - + arch/Linux/Ubuntu_15.04.cfg | 1 - + arch/Linux/Ubuntu_15.10.cfg | 1 - + arch/Linux/Ubuntu_16.04.cfg | 1 - + arch/Linux/Ubuntu_16.10.cfg | 1 - + arch/Linux/Ubuntu_20.04.cfg | 1 - + arch/Linux/{Ubuntu_14.04.cfg => Ubuntu_22.04.cfg} | 0 + 7 files changed, 6 deletions(-) + delete mode 120000 arch/Linux/Ubuntu_14.10.cfg + delete mode 120000 arch/Linux/Ubuntu_15.04.cfg + delete mode 120000 arch/Linux/Ubuntu_15.10.cfg + delete mode 120000 arch/Linux/Ubuntu_16.04.cfg + delete mode 120000 arch/Linux/Ubuntu_16.10.cfg + delete mode 120000 arch/Linux/Ubuntu_20.04.cfg + rename arch/Linux/{Ubuntu_14.04.cfg => Ubuntu_22.04.cfg} (100%) + +diff --git a/arch/Linux/Ubuntu_14.10.cfg b/arch/Linux/Ubuntu_14.10.cfg +deleted file mode 120000 +index 7ab1dcc2f..000000000 +--- a/arch/Linux/Ubuntu_14.10.cfg ++++ /dev/null +@@ -1 +0,0 @@ +-Debian.cfg +\ No newline at end of file +diff --git a/arch/Linux/Ubuntu_15.04.cfg b/arch/Linux/Ubuntu_15.04.cfg +deleted file mode 120000 +index 7ab1dcc2f..000000000 +--- a/arch/Linux/Ubuntu_15.04.cfg ++++ /dev/null +@@ -1 +0,0 @@ +-Debian.cfg +\ No newline at end of file +diff --git a/arch/Linux/Ubuntu_15.10.cfg b/arch/Linux/Ubuntu_15.10.cfg +deleted file mode 120000 +index 7ab1dcc2f..000000000 +--- a/arch/Linux/Ubuntu_15.10.cfg ++++ /dev/null +@@ -1 +0,0 @@ +-Debian.cfg +\ No newline at end of file +diff --git a/arch/Linux/Ubuntu_16.04.cfg b/arch/Linux/Ubuntu_16.04.cfg +deleted file mode 120000 +index 7ab1dcc2f..000000000 +--- a/arch/Linux/Ubuntu_16.04.cfg ++++ /dev/null +@@ -1 +0,0 @@ +-Debian.cfg +\ No newline at end of file +diff --git a/arch/Linux/Ubuntu_16.10.cfg b/arch/Linux/Ubuntu_16.10.cfg +deleted file mode 120000 +index 7ab1dcc2f..000000000 +--- a/arch/Linux/Ubuntu_16.10.cfg ++++ /dev/null +@@ -1 +0,0 @@ +-Debian.cfg +\ No newline at end of file +diff --git a/arch/Linux/Ubuntu_20.04.cfg b/arch/Linux/Ubuntu_20.04.cfg +deleted file mode 120000 +index 7ab1dcc2f..000000000 +--- a/arch/Linux/Ubuntu_20.04.cfg ++++ /dev/null +@@ -1 +0,0 @@ +-Debian.cfg +\ No newline at end of file +diff --git a/arch/Linux/Ubuntu_14.04.cfg b/arch/Linux/Ubuntu_22.04.cfg +similarity index 100% +rename from arch/Linux/Ubuntu_14.04.cfg +rename to arch/Linux/Ubuntu_22.04.cfg +-- +2.44.0 + diff --git a/0001-imp-removed-ancient-build-configs.patch b/0001-imp-removed-ancient-build-configs.patch new file mode 100644 index 0000000..3832512 --- /dev/null +++ b/0001-imp-removed-ancient-build-configs.patch @@ -0,0 +1,71 @@ +From 112724d69e3acf27ae055de6183663e8a2fb79b8 Mon Sep 17 00:00:00 2001 +From: =?UTF-8?q?Ren=C3=A9=20Reucher?= +Date: Thu, 9 Jun 2022 15:48:10 +0200 +Subject: [PATCH] imp: removed ancient build configs + +--- + arch/Linux/Debian_6.0.1.cfg | 1 - + arch/Linux/Debian_6.0.2.cfg | 1 - + arch/Linux/Debian_GNU_Linux_7.cfg | 1 - + arch/Linux/Debian_lenny-sid.cfg | 1 - + arch/Linux/Debian_squeeze-sid.cfg | 1 - + arch/Linux/Debian_wheezy-sid.cfg | 1 - + 6 files changed, 6 deletions(-) + delete mode 120000 arch/Linux/Debian_6.0.1.cfg + delete mode 120000 arch/Linux/Debian_6.0.2.cfg + delete mode 120000 arch/Linux/Debian_GNU_Linux_7.cfg + delete mode 120000 arch/Linux/Debian_lenny-sid.cfg + delete mode 120000 arch/Linux/Debian_squeeze-sid.cfg + delete mode 120000 arch/Linux/Debian_wheezy-sid.cfg + +diff --git a/arch/Linux/Debian_6.0.1.cfg b/arch/Linux/Debian_6.0.1.cfg +deleted file mode 120000 +index 7ab1dcc2f..000000000 +--- a/arch/Linux/Debian_6.0.1.cfg ++++ /dev/null +@@ -1 +0,0 @@ +-Debian.cfg +\ No newline at end of file +diff --git a/arch/Linux/Debian_6.0.2.cfg b/arch/Linux/Debian_6.0.2.cfg +deleted file mode 120000 +index 7ab1dcc2f..000000000 +--- a/arch/Linux/Debian_6.0.2.cfg ++++ /dev/null +@@ -1 +0,0 @@ +-Debian.cfg +\ No newline at end of file +diff --git a/arch/Linux/Debian_GNU_Linux_7.cfg b/arch/Linux/Debian_GNU_Linux_7.cfg +deleted file mode 120000 +index 7ab1dcc2f..000000000 +--- a/arch/Linux/Debian_GNU_Linux_7.cfg ++++ /dev/null +@@ -1 +0,0 @@ +-Debian.cfg +\ No newline at end of file +diff --git a/arch/Linux/Debian_lenny-sid.cfg b/arch/Linux/Debian_lenny-sid.cfg +deleted file mode 120000 +index 7ab1dcc2f..000000000 +--- a/arch/Linux/Debian_lenny-sid.cfg ++++ /dev/null +@@ -1 +0,0 @@ +-Debian.cfg +\ No newline at end of file +diff --git a/arch/Linux/Debian_squeeze-sid.cfg b/arch/Linux/Debian_squeeze-sid.cfg +deleted file mode 120000 +index 7ab1dcc2f..000000000 +--- a/arch/Linux/Debian_squeeze-sid.cfg ++++ /dev/null +@@ -1 +0,0 @@ +-Debian.cfg +\ No newline at end of file +diff --git a/arch/Linux/Debian_wheezy-sid.cfg b/arch/Linux/Debian_wheezy-sid.cfg +deleted file mode 120000 +index 7ab1dcc2f..000000000 +--- a/arch/Linux/Debian_wheezy-sid.cfg ++++ /dev/null +@@ -1 +0,0 @@ +-Debian.cfg +\ No newline at end of file +-- +2.44.0 + diff --git a/0002-imp-Updated-Fedora-and-Ubuntu-build-configurations.-.patch b/0002-imp-Updated-Fedora-and-Ubuntu-build-configurations.-.patch new file mode 100644 index 0000000..539014a --- /dev/null +++ b/0002-imp-Updated-Fedora-and-Ubuntu-build-configurations.-.patch @@ -0,0 +1,68 @@ +From 29449822f0e0878dcfc5303d5fbd2f94a73b8ddd Mon Sep 17 00:00:00 2001 +From: Julian Sikorski +Date: Sat, 17 Feb 2024 17:43:06 +0100 +Subject: [PATCH 02/10] imp: Updated Fedora and Ubuntu build configurations. + (#36) + +* Replaced Fedora 34/35/36/37 with 38/39/40/41. +* Added Ubuntu 20.04/23.10/24.04 referencing Debian configuration. +--- + arch/Linux/{Fedora_release_34.cfg => Fedora_release_38.cfg} | 0 + arch/Linux/{Fedora_release_35.cfg => Fedora_release_39.cfg} | 0 + arch/Linux/{Fedora_release_36.cfg => Fedora_release_40.cfg} | 0 + arch/Linux/{Fedora_release_37.cfg => Fedora_release_41.cfg} | 0 + arch/Linux/Ubuntu_20.04.cfg | 1 + + arch/Linux/Ubuntu_23.10.cfg | 1 + + arch/Linux/Ubuntu_24.04.cfg | 1 + + 7 files changed, 3 insertions(+) + rename arch/Linux/{Fedora_release_34.cfg => Fedora_release_38.cfg} (100%) + rename arch/Linux/{Fedora_release_35.cfg => Fedora_release_39.cfg} (100%) + rename arch/Linux/{Fedora_release_36.cfg => Fedora_release_40.cfg} (100%) + rename arch/Linux/{Fedora_release_37.cfg => Fedora_release_41.cfg} (100%) + create mode 120000 arch/Linux/Ubuntu_20.04.cfg + create mode 120000 arch/Linux/Ubuntu_23.10.cfg + create mode 120000 arch/Linux/Ubuntu_24.04.cfg + +diff --git a/arch/Linux/Fedora_release_34.cfg b/arch/Linux/Fedora_release_38.cfg +similarity index 100% +rename from arch/Linux/Fedora_release_34.cfg +rename to arch/Linux/Fedora_release_38.cfg +diff --git a/arch/Linux/Fedora_release_35.cfg b/arch/Linux/Fedora_release_39.cfg +similarity index 100% +rename from arch/Linux/Fedora_release_35.cfg +rename to arch/Linux/Fedora_release_39.cfg +diff --git a/arch/Linux/Fedora_release_36.cfg b/arch/Linux/Fedora_release_40.cfg +similarity index 100% +rename from arch/Linux/Fedora_release_36.cfg +rename to arch/Linux/Fedora_release_40.cfg +diff --git a/arch/Linux/Fedora_release_37.cfg b/arch/Linux/Fedora_release_41.cfg +similarity index 100% +rename from arch/Linux/Fedora_release_37.cfg +rename to arch/Linux/Fedora_release_41.cfg +diff --git a/arch/Linux/Ubuntu_20.04.cfg b/arch/Linux/Ubuntu_20.04.cfg +new file mode 120000 +index 000000000..7ab1dcc2f +--- /dev/null ++++ b/arch/Linux/Ubuntu_20.04.cfg +@@ -0,0 +1 @@ ++Debian.cfg +\ No newline at end of file +diff --git a/arch/Linux/Ubuntu_23.10.cfg b/arch/Linux/Ubuntu_23.10.cfg +new file mode 120000 +index 000000000..7ab1dcc2f +--- /dev/null ++++ b/arch/Linux/Ubuntu_23.10.cfg +@@ -0,0 +1 @@ ++Debian.cfg +\ No newline at end of file +diff --git a/arch/Linux/Ubuntu_24.04.cfg b/arch/Linux/Ubuntu_24.04.cfg +new file mode 120000 +index 000000000..7ab1dcc2f +--- /dev/null ++++ b/arch/Linux/Ubuntu_24.04.cfg +@@ -0,0 +1 @@ ++Debian.cfg +\ No newline at end of file +-- +2.44.0 + diff --git a/0007-imp-Updated-bundled-libraries-to-their-current-upstr.patch b/0007-imp-Updated-bundled-libraries-to-their-current-upstr.patch new file mode 100644 index 0000000..516199b --- /dev/null +++ b/0007-imp-Updated-bundled-libraries-to-their-current-upstr.patch @@ -0,0 +1,28821 @@ +From b3350346eb06eef812d9045a9f06f7c1547a8403 Mon Sep 17 00:00:00 2001 +From: Julian Sikorski +Date: Thu, 7 Mar 2024 16:20:22 +0100 +Subject: [PATCH 07/10] imp: Updated bundled libraries to their current + upstream versions. (#41) + +* Updated bundled zlib to 1.3.1 +* Updated bundled LZMA SDK to 23.01 +* Updated bundled minizip to 4.0.4 +--- + qmc2.pro | 2 +- + src/lzma/7z.h | 12 +- + src/lzma/7zAlloc.c | 69 +-- + src/lzma/7zAlloc.h | 6 +- + src/lzma/7zArcIn.c | 405 ++++++++--------- + src/lzma/7zBuf.h | 6 +- + src/lzma/7zCrc.c | 130 +++--- + src/lzma/7zCrc.h | 14 +- + src/lzma/7zCrcOpt.c | 16 +- + src/lzma/7zDec.c | 172 ++++--- + src/lzma/7zFile.c | 33 +- + src/lzma/7zFile.h | 9 +- + src/lzma/7zStream.c | 67 ++- + src/lzma/7zTypes.h | 274 +++++++----- + src/lzma/7zVersion.h | 10 +- + src/lzma/7zWindows.h | 101 +++++ + src/lzma/Aes.c | 108 +++-- + src/lzma/Aes.h | 36 +- + src/lzma/AesOpt.c | 348 ++++++++------ + src/lzma/Alloc.c | 192 +++++--- + src/lzma/Alloc.h | 19 +- + src/lzma/Bcj2.c | 319 +++++++------ + src/lzma/Bcj2.h | 270 +++++++++-- + src/lzma/Bcj2Enc.c | 559 +++++++++++++++-------- + src/lzma/Bra.c | 496 +++++++++++++------- + src/lzma/Bra.h | 115 +++-- + src/lzma/Bra86.c | 221 ++++++--- + src/lzma/BraIA64.c | 57 +-- + src/lzma/Compiler.h | 162 ++++++- + src/lzma/CpuArch.c | 795 ++++++++++++++++++++++---------- + src/lzma/CpuArch.h | 233 ++++++---- + src/lzma/Delta.h | 6 +- + src/lzma/DllSecur.c | 127 +++--- + src/lzma/DllSecur.h | 6 +- + src/lzma/LzFind.c | 519 ++++++++++++--------- + src/lzma/LzFind.h | 53 ++- + src/lzma/LzFindMt.c | 70 +-- + src/lzma/LzFindMt.h | 10 +- + src/lzma/LzFindOpt.c | 14 +- + src/lzma/LzHash.h | 8 +- + src/lzma/Lzma2Dec.c | 12 +- + src/lzma/Lzma2Dec.h | 15 +- + src/lzma/Lzma2DecMt.c | 155 +++---- + src/lzma/Lzma2DecMt.h | 20 +- + src/lzma/Lzma2Enc.c | 174 +++---- + src/lzma/Lzma2Enc.h | 20 +- + src/lzma/Lzma86.h | 6 +- + src/lzma/Lzma86Dec.c | 7 +- + src/lzma/Lzma86Enc.c | 7 +- + src/lzma/LzmaDec.c | 190 ++++---- + src/lzma/LzmaDec.h | 17 +- + src/lzma/LzmaEnc.c | 389 ++++++++-------- + src/lzma/LzmaEnc.h | 23 +- + src/lzma/LzmaLib.c | 8 +- + src/lzma/LzmaLib.h | 12 +- + src/lzma/MtCoder.c | 104 ++--- + src/lzma/MtCoder.h | 50 +-- + src/lzma/MtDec.c | 101 ++--- + src/lzma/MtDec.h | 34 +- + src/lzma/Ppmd.h | 12 +- + src/lzma/Ppmd7.c | 186 ++++---- + src/lzma/Ppmd7.h | 10 +- + src/lzma/Ppmd7Dec.c | 57 ++- + src/lzma/Ppmd7Enc.c | 87 ++-- + src/lzma/Precomp.h | 6 +- + src/lzma/RotateDefs.h | 28 +- + src/lzma/Sha256.c | 150 ++++--- + src/lzma/Sha256.h | 12 +- + src/lzma/Sha256Opt.c | 129 +++--- + src/lzma/Sort.h | 6 +- + src/lzma/Threads.c | 86 ++-- + src/lzma/Threads.h | 50 ++- + src/lzma/Xz.c | 4 +- + src/lzma/Xz.h | 56 ++- + src/lzma/XzCrc64.c | 32 +- + src/lzma/XzCrc64.h | 12 +- + src/lzma/XzCrc64Opt.c | 28 +- + src/lzma/XzDec.c | 300 +++++++------ + src/lzma/XzEnc.c | 270 ++++++----- + src/lzma/XzEnc.h | 23 +- + src/lzma/XzIn.c | 75 ++-- + src/lzma/lzma-sdk.txt | 2 +- + src/minizip/README.minizip | 2 +- + src/minizip/mz.h | 56 ++- + src/minizip/mz_compat.c | 352 +++++++++------ + src/minizip/mz_compat.h | 101 +++-- + src/minizip/mz_crypt.c | 25 +- + src/minizip/mz_crypt.h | 28 +- + src/minizip/mz_os.c | 39 +- + src/minizip/mz_os.h | 9 +- + src/minizip/mz_os_posix.c | 99 ++-- + src/minizip/mz_os_win32.c | 166 ++++--- + src/minizip/mz_strm.c | 67 ++- + src/minizip/mz_strm.h | 8 +- + src/minizip/mz_strm_mem.c | 38 +- + src/minizip/mz_strm_mem.h | 4 +- + src/minizip/mz_strm_os.h | 4 +- + src/minizip/mz_strm_os_posix.c | 44 +- + src/minizip/mz_strm_os_win32.c | 50 +-- + src/minizip/mz_strm_zlib.c | 37 +- + src/minizip/mz_strm_zlib.h | 4 +- + src/minizip/mz_zip.c | 358 ++++++++------- + src/minizip/mz_zip.h | 9 +- + src/sevenzipfile.cpp | 2 +- + src/zlib/README.zlib | 19 +- + src/zlib/adler32.c | 32 +- + src/zlib/compress.c | 21 +- + src/zlib/crc32.c | 255 ++++------- + src/zlib/deflate.c | 796 +++++++++++++++------------------ + src/zlib/deflate.h | 55 ++- + src/zlib/gzclose.c | 4 +- + src/zlib/gzguts.h | 31 +- + src/zlib/gzlib.c | 113 ++--- + src/zlib/gzread.c | 96 +--- + src/zlib/gzwrite.c | 84 +--- + src/zlib/infback.c | 47 +- + src/zlib/inffast.c | 5 +- + src/zlib/inffast.h | 2 +- + src/zlib/inflate.c | 138 ++---- + src/zlib/inftrees.c | 17 +- + src/zlib/inftrees.h | 12 +- + src/zlib/trees.c | 645 ++++++++++++-------------- + src/zlib/uncompr.c | 16 +- + src/zlib/zconf.h | 37 +- + src/zlib/zlib.h | 401 ++++++++--------- + src/zlib/zutil.c | 62 +-- + src/zlib/zutil.h | 46 +- + 127 files changed, 7506 insertions(+), 5964 deletions(-) + create mode 100644 src/lzma/7zWindows.h + +diff --git a/qmc2.pro b/qmc2.pro +index 90bd30a45..9891fedee 100644 +--- a/qmc2.pro ++++ b/qmc2.pro +@@ -303,7 +303,7 @@ TRANSLATIONS += data/lng/qmc2_de.ts \ + data/lng/qmc2_us.ts + RESOURCES += qmc2.qrc + QMAKE_MAKEFILE = Makefile.qmake +-DEFINES += _7ZIP_PPMD_SUPPORT _7ZIP_ST ++DEFINES += Z7_PPMD_SUPPORT Z7_ST + + contains(DEFINES, QMC2_LIBARCHIVE_ENABLED) { + SOURCES += src/archivefile.cpp +diff --git a/src/lzma/7z.h b/src/lzma/7z.h +index 304f75ffc..9e27c0152 100644 +--- a/src/lzma/7z.h ++++ b/src/lzma/7z.h +@@ -1,8 +1,8 @@ + /* 7z.h -- 7z interface +-2018-07-02 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + +-#ifndef __7Z_H +-#define __7Z_H ++#ifndef ZIP7_INC_7Z_H ++#define ZIP7_INC_7Z_H + + #include "7zTypes.h" + +@@ -98,7 +98,7 @@ typedef struct + UInt64 SzAr_GetFolderUnpackSize(const CSzAr *p, UInt32 folderIndex); + + SRes SzAr_DecodeFolder(const CSzAr *p, UInt32 folderIndex, +- ILookInStream *stream, UInt64 startPos, ++ ILookInStreamPtr stream, UInt64 startPos, + Byte *outBuffer, size_t outSize, + ISzAllocPtr allocMain); + +@@ -174,7 +174,7 @@ UInt16 *SzArEx_GetFullNameUtf16_Back(const CSzArEx *p, size_t fileIndex, UInt16 + + SRes SzArEx_Extract( + const CSzArEx *db, +- ILookInStream *inStream, ++ ILookInStreamPtr inStream, + UInt32 fileIndex, /* index of file */ + UInt32 *blockIndex, /* index of solid block */ + Byte **outBuffer, /* pointer to pointer to output buffer (allocated with allocMain) */ +@@ -196,7 +196,7 @@ SZ_ERROR_INPUT_EOF + SZ_ERROR_FAIL + */ + +-SRes SzArEx_Open(CSzArEx *p, ILookInStream *inStream, ++SRes SzArEx_Open(CSzArEx *p, ILookInStreamPtr inStream, + ISzAllocPtr allocMain, ISzAllocPtr allocTemp); + + EXTERN_C_END +diff --git a/src/lzma/7zAlloc.c b/src/lzma/7zAlloc.c +index c924a529f..2f0659af6 100644 +--- a/src/lzma/7zAlloc.c ++++ b/src/lzma/7zAlloc.c +@@ -1,5 +1,5 @@ +-/* 7zAlloc.c -- Allocation functions +-2017-04-03 : Igor Pavlov : Public domain */ ++/* 7zAlloc.c -- Allocation functions for 7z processing ++2023-03-04 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -7,74 +7,83 @@ + + #include "7zAlloc.h" + +-/* #define _SZ_ALLOC_DEBUG */ +-/* use _SZ_ALLOC_DEBUG to debug alloc/free operations */ ++/* #define SZ_ALLOC_DEBUG */ ++/* use SZ_ALLOC_DEBUG to debug alloc/free operations */ + +-#ifdef _SZ_ALLOC_DEBUG ++#ifdef SZ_ALLOC_DEBUG + ++/* + #ifdef _WIN32 +-#include ++#include "7zWindows.h" + #endif ++*/ + + #include +-int g_allocCount = 0; +-int g_allocCountTemp = 0; ++static int g_allocCount = 0; ++static int g_allocCountTemp = 0; + ++static void Print_Alloc(const char *s, size_t size, int *counter) ++{ ++ const unsigned size2 = (unsigned)size; ++ fprintf(stderr, "\n%s count = %10d : %10u bytes; ", s, *counter, size2); ++ (*counter)++; ++} ++static void Print_Free(const char *s, int *counter) ++{ ++ (*counter)--; ++ fprintf(stderr, "\n%s count = %10d", s, *counter); ++} + #endif + + void *SzAlloc(ISzAllocPtr p, size_t size) + { +- UNUSED_VAR(p); ++ UNUSED_VAR(p) + if (size == 0) + return 0; +- #ifdef _SZ_ALLOC_DEBUG +- fprintf(stderr, "\nAlloc %10u bytes; count = %10d", (unsigned)size, g_allocCount); +- g_allocCount++; ++ #ifdef SZ_ALLOC_DEBUG ++ Print_Alloc("Alloc", size, &g_allocCount); + #endif + return malloc(size); + } + + void SzFree(ISzAllocPtr p, void *address) + { +- UNUSED_VAR(p); +- #ifdef _SZ_ALLOC_DEBUG +- if (address != 0) +- { +- g_allocCount--; +- fprintf(stderr, "\nFree; count = %10d", g_allocCount); +- } ++ UNUSED_VAR(p) ++ #ifdef SZ_ALLOC_DEBUG ++ if (address) ++ Print_Free("Free ", &g_allocCount); + #endif + free(address); + } + + void *SzAllocTemp(ISzAllocPtr p, size_t size) + { +- UNUSED_VAR(p); ++ UNUSED_VAR(p) + if (size == 0) + return 0; +- #ifdef _SZ_ALLOC_DEBUG +- fprintf(stderr, "\nAlloc_temp %10u bytes; count = %10d", (unsigned)size, g_allocCountTemp); +- g_allocCountTemp++; ++ #ifdef SZ_ALLOC_DEBUG ++ Print_Alloc("Alloc_temp", size, &g_allocCountTemp); ++ /* + #ifdef _WIN32 + return HeapAlloc(GetProcessHeap(), 0, size); + #endif ++ */ + #endif + return malloc(size); + } + + void SzFreeTemp(ISzAllocPtr p, void *address) + { +- UNUSED_VAR(p); +- #ifdef _SZ_ALLOC_DEBUG +- if (address != 0) +- { +- g_allocCountTemp--; +- fprintf(stderr, "\nFree_temp; count = %10d", g_allocCountTemp); +- } ++ UNUSED_VAR(p) ++ #ifdef SZ_ALLOC_DEBUG ++ if (address) ++ Print_Free("Free_temp ", &g_allocCountTemp); ++ /* + #ifdef _WIN32 + HeapFree(GetProcessHeap(), 0, address); + return; + #endif ++ */ + #endif + free(address); + } +diff --git a/src/lzma/7zAlloc.h b/src/lzma/7zAlloc.h +index 44778f9b2..b2b8b0cdd 100644 +--- a/src/lzma/7zAlloc.h ++++ b/src/lzma/7zAlloc.h +@@ -1,8 +1,8 @@ + /* 7zAlloc.h -- Allocation functions +-2017-04-03 : Igor Pavlov : Public domain */ ++2023-03-04 : Igor Pavlov : Public domain */ + +-#ifndef __7Z_ALLOC_H +-#define __7Z_ALLOC_H ++#ifndef ZIP7_INC_7Z_ALLOC_H ++#define ZIP7_INC_7Z_ALLOC_H + + #include "7zTypes.h" + +diff --git a/src/lzma/7zArcIn.c b/src/lzma/7zArcIn.c +index c2405bdef..14b77551e 100644 +--- a/src/lzma/7zArcIn.c ++++ b/src/lzma/7zArcIn.c +@@ -1,5 +1,5 @@ + /* 7zArcIn.c -- 7z Input functions +-2021-02-09 : Igor Pavlov : Public domain */ ++2023-05-11 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -10,10 +10,11 @@ + #include "7zCrc.h" + #include "CpuArch.h" + +-#define MY_ALLOC(T, p, size, alloc) { \ +- if ((p = (T *)ISzAlloc_Alloc(alloc, (size) * sizeof(T))) == NULL) return SZ_ERROR_MEM; } ++#define MY_ALLOC(T, p, size, alloc) \ ++ { if ((p = (T *)ISzAlloc_Alloc(alloc, (size) * sizeof(T))) == NULL) return SZ_ERROR_MEM; } + +-#define MY_ALLOC_ZE(T, p, size, alloc) { if ((size) == 0) p = NULL; else MY_ALLOC(T, p, size, alloc) } ++#define MY_ALLOC_ZE(T, p, size, alloc) \ ++ { if ((size) == 0) p = NULL; else MY_ALLOC(T, p, size, alloc) } + + #define MY_ALLOC_AND_CPY(to, size, from, alloc) \ + { MY_ALLOC(Byte, to, size, alloc); memcpy(to, from, size); } +@@ -58,7 +59,7 @@ enum EIdEnum + + const Byte k7zSignature[k7zSignatureSize] = {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C}; + +-#define SzBitUi32s_Init(p) { (p)->Defs = NULL; (p)->Vals = NULL; } ++#define SzBitUi32s_INIT(p) { (p)->Defs = NULL; (p)->Vals = NULL; } + + static SRes SzBitUi32s_Alloc(CSzBitUi32s *p, size_t num, ISzAllocPtr alloc) + { +@@ -69,8 +70,8 @@ static SRes SzBitUi32s_Alloc(CSzBitUi32s *p, size_t num, ISzAllocPtr alloc) + } + else + { +- MY_ALLOC(Byte, p->Defs, (num + 7) >> 3, alloc); +- MY_ALLOC(UInt32, p->Vals, num, alloc); ++ MY_ALLOC(Byte, p->Defs, (num + 7) >> 3, alloc) ++ MY_ALLOC(UInt32, p->Vals, num, alloc) + } + return SZ_OK; + } +@@ -81,7 +82,7 @@ static void SzBitUi32s_Free(CSzBitUi32s *p, ISzAllocPtr alloc) + ISzAlloc_Free(alloc, p->Vals); p->Vals = NULL; + } + +-#define SzBitUi64s_Init(p) { (p)->Defs = NULL; (p)->Vals = NULL; } ++#define SzBitUi64s_INIT(p) { (p)->Defs = NULL; (p)->Vals = NULL; } + + static void SzBitUi64s_Free(CSzBitUi64s *p, ISzAllocPtr alloc) + { +@@ -96,7 +97,7 @@ static void SzAr_Init(CSzAr *p) + p->NumFolders = 0; + + p->PackPositions = NULL; +- SzBitUi32s_Init(&p->FolderCRCs); ++ SzBitUi32s_INIT(&p->FolderCRCs) + + p->FoCodersOffsets = NULL; + p->FoStartPackStreamIndex = NULL; +@@ -142,11 +143,11 @@ void SzArEx_Init(CSzArEx *p) + p->FileNameOffsets = NULL; + p->FileNames = NULL; + +- SzBitUi32s_Init(&p->CRCs); +- SzBitUi32s_Init(&p->Attribs); +- // SzBitUi32s_Init(&p->Parents); +- SzBitUi64s_Init(&p->MTime); +- SzBitUi64s_Init(&p->CTime); ++ SzBitUi32s_INIT(&p->CRCs) ++ SzBitUi32s_INIT(&p->Attribs) ++ // SzBitUi32s_INIT(&p->Parents) ++ SzBitUi64s_INIT(&p->MTime) ++ SzBitUi64s_INIT(&p->CTime) + } + + void SzArEx_Free(CSzArEx *p, ISzAllocPtr alloc) +@@ -180,11 +181,20 @@ static int TestSignatureCandidate(const Byte *testBytes) + return 1; + } + +-#define SzData_Clear(p) { (p)->Data = NULL; (p)->Size = 0; } ++#define SzData_CLEAR(p) { (p)->Data = NULL; (p)->Size = 0; } ++ ++#define SZ_READ_BYTE_SD_NOCHECK(_sd_, dest) \ ++ (_sd_)->Size--; dest = *(_sd_)->Data++; ++ ++#define SZ_READ_BYTE_SD(_sd_, dest) \ ++ if ((_sd_)->Size == 0) return SZ_ERROR_ARCHIVE; \ ++ SZ_READ_BYTE_SD_NOCHECK(_sd_, dest) + +-#define SZ_READ_BYTE_SD(_sd_, dest) if ((_sd_)->Size == 0) return SZ_ERROR_ARCHIVE; (_sd_)->Size--; dest = *(_sd_)->Data++; + #define SZ_READ_BYTE(dest) SZ_READ_BYTE_SD(sd, dest) +-#define SZ_READ_BYTE_2(dest) if (sd.Size == 0) return SZ_ERROR_ARCHIVE; sd.Size--; dest = *sd.Data++; ++ ++#define SZ_READ_BYTE_2(dest) \ ++ if (sd.Size == 0) return SZ_ERROR_ARCHIVE; \ ++ sd.Size--; dest = *sd.Data++; + + #define SKIP_DATA(sd, size) { sd->Size -= (size_t)(size); sd->Data += (size_t)(size); } + #define SKIP_DATA2(sd, size) { sd.Size -= (size_t)(size); sd.Data += (size_t)(size); } +@@ -192,25 +202,25 @@ static int TestSignatureCandidate(const Byte *testBytes) + #define SZ_READ_32(dest) if (sd.Size < 4) return SZ_ERROR_ARCHIVE; \ + dest = GetUi32(sd.Data); SKIP_DATA2(sd, 4); + +-static MY_NO_INLINE SRes ReadNumber(CSzData *sd, UInt64 *value) ++static Z7_NO_INLINE SRes ReadNumber(CSzData *sd, UInt64 *value) + { + Byte firstByte, mask; + unsigned i; + UInt32 v; + +- SZ_READ_BYTE(firstByte); ++ SZ_READ_BYTE(firstByte) + if ((firstByte & 0x80) == 0) + { + *value = firstByte; + return SZ_OK; + } +- SZ_READ_BYTE(v); ++ SZ_READ_BYTE(v) + if ((firstByte & 0x40) == 0) + { + *value = (((UInt32)firstByte & 0x3F) << 8) | v; + return SZ_OK; + } +- SZ_READ_BYTE(mask); ++ SZ_READ_BYTE(mask) + *value = v | ((UInt32)mask << 8); + mask = 0x20; + for (i = 2; i < 8; i++) +@@ -218,11 +228,11 @@ static MY_NO_INLINE SRes ReadNumber(CSzData *sd, UInt64 *value) + Byte b; + if ((firstByte & mask) == 0) + { +- UInt64 highPart = (unsigned)firstByte & (unsigned)(mask - 1); ++ const UInt64 highPart = (unsigned)firstByte & (unsigned)(mask - 1); + *value |= (highPart << (8 * i)); + return SZ_OK; + } +- SZ_READ_BYTE(b); ++ SZ_READ_BYTE(b) + *value |= ((UInt64)b << (8 * i)); + mask >>= 1; + } +@@ -230,7 +240,7 @@ static MY_NO_INLINE SRes ReadNumber(CSzData *sd, UInt64 *value) + } + + +-static MY_NO_INLINE SRes SzReadNumber32(CSzData *sd, UInt32 *value) ++static Z7_NO_INLINE SRes SzReadNumber32(CSzData *sd, UInt32 *value) + { + Byte firstByte; + UInt64 value64; +@@ -244,7 +254,7 @@ static MY_NO_INLINE SRes SzReadNumber32(CSzData *sd, UInt32 *value) + sd->Size--; + return SZ_OK; + } +- RINOK(ReadNumber(sd, &value64)); ++ RINOK(ReadNumber(sd, &value64)) + if (value64 >= (UInt32)0x80000000 - 1) + return SZ_ERROR_UNSUPPORTED; + if (value64 >= ((UInt64)(1) << ((sizeof(size_t) - 1) * 8 + 4))) +@@ -258,10 +268,10 @@ static MY_NO_INLINE SRes SzReadNumber32(CSzData *sd, UInt32 *value) + static SRes SkipData(CSzData *sd) + { + UInt64 size; +- RINOK(ReadNumber(sd, &size)); ++ RINOK(ReadNumber(sd, &size)) + if (size > sd->Size) + return SZ_ERROR_ARCHIVE; +- SKIP_DATA(sd, size); ++ SKIP_DATA(sd, size) + return SZ_OK; + } + +@@ -270,22 +280,22 @@ static SRes WaitId(CSzData *sd, UInt32 id) + for (;;) + { + UInt64 type; +- RINOK(ReadID(sd, &type)); ++ RINOK(ReadID(sd, &type)) + if (type == id) + return SZ_OK; + if (type == k7zIdEnd) + return SZ_ERROR_ARCHIVE; +- RINOK(SkipData(sd)); ++ RINOK(SkipData(sd)) + } + } + + static SRes RememberBitVector(CSzData *sd, UInt32 numItems, const Byte **v) + { +- UInt32 numBytes = (numItems + 7) >> 3; ++ const UInt32 numBytes = (numItems + 7) >> 3; + if (numBytes > sd->Size) + return SZ_ERROR_ARCHIVE; + *v = sd->Data; +- SKIP_DATA(sd, numBytes); ++ SKIP_DATA(sd, numBytes) + return SZ_OK; + } + +@@ -307,48 +317,48 @@ static UInt32 CountDefinedBits(const Byte *bits, UInt32 numItems) + return sum; + } + +-static MY_NO_INLINE SRes ReadBitVector(CSzData *sd, UInt32 numItems, Byte **v, ISzAllocPtr alloc) ++static Z7_NO_INLINE SRes ReadBitVector(CSzData *sd, UInt32 numItems, Byte **v, ISzAllocPtr alloc) + { + Byte allAreDefined; + Byte *v2; +- UInt32 numBytes = (numItems + 7) >> 3; ++ const UInt32 numBytes = (numItems + 7) >> 3; + *v = NULL; +- SZ_READ_BYTE(allAreDefined); ++ SZ_READ_BYTE(allAreDefined) + if (numBytes == 0) + return SZ_OK; + if (allAreDefined == 0) + { + if (numBytes > sd->Size) + return SZ_ERROR_ARCHIVE; +- MY_ALLOC_AND_CPY(*v, numBytes, sd->Data, alloc); +- SKIP_DATA(sd, numBytes); ++ MY_ALLOC_AND_CPY(*v, numBytes, sd->Data, alloc) ++ SKIP_DATA(sd, numBytes) + return SZ_OK; + } +- MY_ALLOC(Byte, *v, numBytes, alloc); ++ MY_ALLOC(Byte, *v, numBytes, alloc) + v2 = *v; + memset(v2, 0xFF, (size_t)numBytes); + { +- unsigned numBits = (unsigned)numItems & 7; ++ const unsigned numBits = (unsigned)numItems & 7; + if (numBits != 0) + v2[(size_t)numBytes - 1] = (Byte)((((UInt32)1 << numBits) - 1) << (8 - numBits)); + } + return SZ_OK; + } + +-static MY_NO_INLINE SRes ReadUi32s(CSzData *sd2, UInt32 numItems, CSzBitUi32s *crcs, ISzAllocPtr alloc) ++static Z7_NO_INLINE SRes ReadUi32s(CSzData *sd2, UInt32 numItems, CSzBitUi32s *crcs, ISzAllocPtr alloc) + { + UInt32 i; + CSzData sd; + UInt32 *vals; + const Byte *defs; +- MY_ALLOC_ZE(UInt32, crcs->Vals, numItems, alloc); ++ MY_ALLOC_ZE(UInt32, crcs->Vals, numItems, alloc) + sd = *sd2; + defs = crcs->Defs; + vals = crcs->Vals; + for (i = 0; i < numItems; i++) + if (SzBitArray_Check(defs, i)) + { +- SZ_READ_32(vals[i]); ++ SZ_READ_32(vals[i]) + } + else + vals[i] = 0; +@@ -359,7 +369,7 @@ static MY_NO_INLINE SRes ReadUi32s(CSzData *sd2, UInt32 numItems, CSzBitUi32s *c + static SRes ReadBitUi32s(CSzData *sd, UInt32 numItems, CSzBitUi32s *crcs, ISzAllocPtr alloc) + { + SzBitUi32s_Free(crcs, alloc); +- RINOK(ReadBitVector(sd, numItems, &crcs->Defs, alloc)); ++ RINOK(ReadBitVector(sd, numItems, &crcs->Defs, alloc)) + return ReadUi32s(sd, numItems, crcs, alloc); + } + +@@ -367,36 +377,36 @@ static SRes SkipBitUi32s(CSzData *sd, UInt32 numItems) + { + Byte allAreDefined; + UInt32 numDefined = numItems; +- SZ_READ_BYTE(allAreDefined); ++ SZ_READ_BYTE(allAreDefined) + if (!allAreDefined) + { +- size_t numBytes = (numItems + 7) >> 3; ++ const size_t numBytes = (numItems + 7) >> 3; + if (numBytes > sd->Size) + return SZ_ERROR_ARCHIVE; + numDefined = CountDefinedBits(sd->Data, numItems); +- SKIP_DATA(sd, numBytes); ++ SKIP_DATA(sd, numBytes) + } + if (numDefined > (sd->Size >> 2)) + return SZ_ERROR_ARCHIVE; +- SKIP_DATA(sd, (size_t)numDefined * 4); ++ SKIP_DATA(sd, (size_t)numDefined * 4) + return SZ_OK; + } + + static SRes ReadPackInfo(CSzAr *p, CSzData *sd, ISzAllocPtr alloc) + { +- RINOK(SzReadNumber32(sd, &p->NumPackStreams)); ++ RINOK(SzReadNumber32(sd, &p->NumPackStreams)) + +- RINOK(WaitId(sd, k7zIdSize)); +- MY_ALLOC(UInt64, p->PackPositions, (size_t)p->NumPackStreams + 1, alloc); ++ RINOK(WaitId(sd, k7zIdSize)) ++ MY_ALLOC(UInt64, p->PackPositions, (size_t)p->NumPackStreams + 1, alloc) + { + UInt64 sum = 0; + UInt32 i; +- UInt32 numPackStreams = p->NumPackStreams; ++ const UInt32 numPackStreams = p->NumPackStreams; + for (i = 0; i < numPackStreams; i++) + { + UInt64 packSize; + p->PackPositions[i] = sum; +- RINOK(ReadNumber(sd, &packSize)); ++ RINOK(ReadNumber(sd, &packSize)) + sum += packSize; + if (sum < packSize) + return SZ_ERROR_ARCHIVE; +@@ -407,16 +417,16 @@ static SRes ReadPackInfo(CSzAr *p, CSzData *sd, ISzAllocPtr alloc) + for (;;) + { + UInt64 type; +- RINOK(ReadID(sd, &type)); ++ RINOK(ReadID(sd, &type)) + if (type == k7zIdEnd) + return SZ_OK; + if (type == k7zIdCRC) + { + /* CRC of packed streams is unused now */ +- RINOK(SkipBitUi32s(sd, p->NumPackStreams)); ++ RINOK(SkipBitUi32s(sd, p->NumPackStreams)) + continue; + } +- RINOK(SkipData(sd)); ++ RINOK(SkipData(sd)) + } + } + +@@ -442,7 +452,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) + f->NumPackStreams = 0; + f->UnpackStream = 0; + +- RINOK(SzReadNumber32(sd, &numCoders)); ++ RINOK(SzReadNumber32(sd, &numCoders)) + if (numCoders == 0 || numCoders > SZ_NUM_CODERS_IN_FOLDER_MAX) + return SZ_ERROR_UNSUPPORTED; + +@@ -453,7 +463,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) + unsigned idSize, j; + UInt64 id; + +- SZ_READ_BYTE(mainByte); ++ SZ_READ_BYTE(mainByte) + if ((mainByte & 0xC0) != 0) + return SZ_ERROR_UNSUPPORTED; + +@@ -481,12 +491,12 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) + { + UInt32 numStreams; + +- RINOK(SzReadNumber32(sd, &numStreams)); ++ RINOK(SzReadNumber32(sd, &numStreams)) + if (numStreams > k_NumCodersStreams_in_Folder_MAX) + return SZ_ERROR_UNSUPPORTED; + coder->NumStreams = (Byte)numStreams; + +- RINOK(SzReadNumber32(sd, &numStreams)); ++ RINOK(SzReadNumber32(sd, &numStreams)) + if (numStreams != 1) + return SZ_ERROR_UNSUPPORTED; + } +@@ -499,7 +509,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) + if ((mainByte & 0x20) != 0) + { + UInt32 propsSize = 0; +- RINOK(SzReadNumber32(sd, &propsSize)); ++ RINOK(SzReadNumber32(sd, &propsSize)) + if (propsSize > sd->Size) + return SZ_ERROR_ARCHIVE; + if (propsSize >= 0x80) +@@ -549,12 +559,12 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) + { + CSzBond *bp = f->Bonds + i; + +- RINOK(SzReadNumber32(sd, &bp->InIndex)); ++ RINOK(SzReadNumber32(sd, &bp->InIndex)) + if (bp->InIndex >= numInStreams || streamUsed[bp->InIndex]) + return SZ_ERROR_ARCHIVE; + streamUsed[bp->InIndex] = True7z; + +- RINOK(SzReadNumber32(sd, &bp->OutIndex)); ++ RINOK(SzReadNumber32(sd, &bp->OutIndex)) + if (bp->OutIndex >= numCoders || coderUsed[bp->OutIndex]) + return SZ_ERROR_ARCHIVE; + coderUsed[bp->OutIndex] = True7z; +@@ -584,7 +594,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) + for (i = 0; i < numPackStreams; i++) + { + UInt32 index; +- RINOK(SzReadNumber32(sd, &index)); ++ RINOK(SzReadNumber32(sd, &index)) + if (index >= numInStreams || streamUsed[index]) + return SZ_ERROR_ARCHIVE; + streamUsed[index] = True7z; +@@ -598,7 +608,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) + } + + +-static MY_NO_INLINE SRes SkipNumbers(CSzData *sd2, UInt32 num) ++static Z7_NO_INLINE SRes SkipNumbers(CSzData *sd2, UInt32 num) + { + CSzData sd; + sd = *sd2; +@@ -606,7 +616,7 @@ static MY_NO_INLINE SRes SkipNumbers(CSzData *sd2, UInt32 num) + { + Byte firstByte, mask; + unsigned i; +- SZ_READ_BYTE_2(firstByte); ++ SZ_READ_BYTE_2(firstByte) + if ((firstByte & 0x80) == 0) + continue; + if ((firstByte & 0x40) == 0) +@@ -622,7 +632,7 @@ static MY_NO_INLINE SRes SkipNumbers(CSzData *sd2, UInt32 num) + mask >>= 1; + if (i > sd.Size) + return SZ_ERROR_ARCHIVE; +- SKIP_DATA2(sd, i); ++ SKIP_DATA2(sd, i) + } + *sd2 = sd; + return SZ_OK; +@@ -645,30 +655,30 @@ static SRes ReadUnpackInfo(CSzAr *p, + const Byte *startBufPtr; + Byte external; + +- RINOK(WaitId(sd2, k7zIdFolder)); ++ RINOK(WaitId(sd2, k7zIdFolder)) + +- RINOK(SzReadNumber32(sd2, &numFolders)); ++ RINOK(SzReadNumber32(sd2, &numFolders)) + if (numFolders > numFoldersMax) + return SZ_ERROR_UNSUPPORTED; + p->NumFolders = numFolders; + +- SZ_READ_BYTE_SD(sd2, external); ++ SZ_READ_BYTE_SD(sd2, external) + if (external == 0) + sd = *sd2; + else + { + UInt32 index; +- RINOK(SzReadNumber32(sd2, &index)); ++ RINOK(SzReadNumber32(sd2, &index)) + if (index >= numTempBufs) + return SZ_ERROR_ARCHIVE; + sd.Data = tempBufs[index].data; + sd.Size = tempBufs[index].size; + } + +- MY_ALLOC(size_t, p->FoCodersOffsets, (size_t)numFolders + 1, alloc); +- MY_ALLOC(UInt32, p->FoStartPackStreamIndex, (size_t)numFolders + 1, alloc); +- MY_ALLOC(UInt32, p->FoToCoderUnpackSizes, (size_t)numFolders + 1, alloc); +- MY_ALLOC_ZE(Byte, p->FoToMainUnpackSizeIndex, (size_t)numFolders, alloc); ++ MY_ALLOC(size_t, p->FoCodersOffsets, (size_t)numFolders + 1, alloc) ++ MY_ALLOC(UInt32, p->FoStartPackStreamIndex, (size_t)numFolders + 1, alloc) ++ MY_ALLOC(UInt32, p->FoToCoderUnpackSizes, (size_t)numFolders + 1, alloc) ++ MY_ALLOC_ZE(Byte, p->FoToMainUnpackSizeIndex, (size_t)numFolders, alloc) + + startBufPtr = sd.Data; + +@@ -681,7 +691,7 @@ static SRes ReadUnpackInfo(CSzAr *p, + + p->FoCodersOffsets[fo] = (size_t)(sd.Data - startBufPtr); + +- RINOK(SzReadNumber32(&sd, &numCoders)); ++ RINOK(SzReadNumber32(&sd, &numCoders)) + if (numCoders == 0 || numCoders > k_Scan_NumCoders_MAX) + return SZ_ERROR_UNSUPPORTED; + +@@ -691,7 +701,7 @@ static SRes ReadUnpackInfo(CSzAr *p, + unsigned idSize; + UInt32 coderInStreams; + +- SZ_READ_BYTE_2(mainByte); ++ SZ_READ_BYTE_2(mainByte) + if ((mainByte & 0xC0) != 0) + return SZ_ERROR_UNSUPPORTED; + idSize = (mainByte & 0xF); +@@ -699,15 +709,15 @@ static SRes ReadUnpackInfo(CSzAr *p, + return SZ_ERROR_UNSUPPORTED; + if (idSize > sd.Size) + return SZ_ERROR_ARCHIVE; +- SKIP_DATA2(sd, idSize); ++ SKIP_DATA2(sd, idSize) + + coderInStreams = 1; + + if ((mainByte & 0x10) != 0) + { + UInt32 coderOutStreams; +- RINOK(SzReadNumber32(&sd, &coderInStreams)); +- RINOK(SzReadNumber32(&sd, &coderOutStreams)); ++ RINOK(SzReadNumber32(&sd, &coderInStreams)) ++ RINOK(SzReadNumber32(&sd, &coderOutStreams)) + if (coderInStreams > k_Scan_NumCodersStreams_in_Folder_MAX || coderOutStreams != 1) + return SZ_ERROR_UNSUPPORTED; + } +@@ -717,10 +727,10 @@ static SRes ReadUnpackInfo(CSzAr *p, + if ((mainByte & 0x20) != 0) + { + UInt32 propsSize; +- RINOK(SzReadNumber32(&sd, &propsSize)); ++ RINOK(SzReadNumber32(&sd, &propsSize)) + if (propsSize > sd.Size) + return SZ_ERROR_ARCHIVE; +- SKIP_DATA2(sd, propsSize); ++ SKIP_DATA2(sd, propsSize) + } + } + +@@ -734,7 +744,7 @@ static SRes ReadUnpackInfo(CSzAr *p, + Byte coderUsed[k_Scan_NumCoders_MAX]; + + UInt32 i; +- UInt32 numBonds = numCoders - 1; ++ const UInt32 numBonds = numCoders - 1; + if (numInStreams < numBonds) + return SZ_ERROR_ARCHIVE; + +@@ -750,12 +760,12 @@ static SRes ReadUnpackInfo(CSzAr *p, + { + UInt32 index; + +- RINOK(SzReadNumber32(&sd, &index)); ++ RINOK(SzReadNumber32(&sd, &index)) + if (index >= numInStreams || streamUsed[index]) + return SZ_ERROR_ARCHIVE; + streamUsed[index] = True7z; + +- RINOK(SzReadNumber32(&sd, &index)); ++ RINOK(SzReadNumber32(&sd, &index)) + if (index >= numCoders || coderUsed[index]) + return SZ_ERROR_ARCHIVE; + coderUsed[index] = True7z; +@@ -767,7 +777,7 @@ static SRes ReadUnpackInfo(CSzAr *p, + for (i = 0; i < numPackStreams; i++) + { + UInt32 index; +- RINOK(SzReadNumber32(&sd, &index)); ++ RINOK(SzReadNumber32(&sd, &index)) + if (index >= numInStreams || streamUsed[index]) + return SZ_ERROR_ARCHIVE; + streamUsed[index] = True7z; +@@ -802,7 +812,7 @@ static SRes ReadUnpackInfo(CSzAr *p, + const size_t dataSize = (size_t)(sd.Data - startBufPtr); + p->FoStartPackStreamIndex[fo] = packStreamIndex; + p->FoCodersOffsets[fo] = dataSize; +- MY_ALLOC_ZE_AND_CPY(p->CodersData, dataSize, startBufPtr, alloc); ++ MY_ALLOC_ZE_AND_CPY(p->CodersData, dataSize, startBufPtr, alloc) + } + + if (external != 0) +@@ -812,21 +822,21 @@ static SRes ReadUnpackInfo(CSzAr *p, + sd = *sd2; + } + +- RINOK(WaitId(&sd, k7zIdCodersUnpackSize)); ++ RINOK(WaitId(&sd, k7zIdCodersUnpackSize)) + +- MY_ALLOC_ZE(UInt64, p->CoderUnpackSizes, (size_t)numCodersOutStreams, alloc); ++ MY_ALLOC_ZE(UInt64, p->CoderUnpackSizes, (size_t)numCodersOutStreams, alloc) + { + UInt32 i; + for (i = 0; i < numCodersOutStreams; i++) + { +- RINOK(ReadNumber(&sd, p->CoderUnpackSizes + i)); ++ RINOK(ReadNumber(&sd, p->CoderUnpackSizes + i)) + } + } + + for (;;) + { + UInt64 type; +- RINOK(ReadID(&sd, &type)); ++ RINOK(ReadID(&sd, &type)) + if (type == k7zIdEnd) + { + *sd2 = sd; +@@ -834,10 +844,10 @@ static SRes ReadUnpackInfo(CSzAr *p, + } + if (type == k7zIdCRC) + { +- RINOK(ReadBitUi32s(&sd, numFolders, &p->FolderCRCs, alloc)); ++ RINOK(ReadBitUi32s(&sd, numFolders, &p->FolderCRCs, alloc)) + continue; + } +- RINOK(SkipData(&sd)); ++ RINOK(SkipData(&sd)) + } + } + +@@ -862,13 +872,13 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi) + { + UInt64 type = 0; + UInt32 numSubDigests = 0; +- UInt32 numFolders = p->NumFolders; ++ const UInt32 numFolders = p->NumFolders; + UInt32 numUnpackStreams = numFolders; + UInt32 numUnpackSizesInData = 0; + + for (;;) + { +- RINOK(ReadID(sd, &type)); ++ RINOK(ReadID(sd, &type)) + if (type == k7zIdNumUnpackStream) + { + UInt32 i; +@@ -878,7 +888,7 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi) + for (i = 0; i < numFolders; i++) + { + UInt32 numStreams; +- RINOK(SzReadNumber32(sd, &numStreams)); ++ RINOK(SzReadNumber32(sd, &numStreams)) + if (numUnpackStreams > numUnpackStreams + numStreams) + return SZ_ERROR_UNSUPPORTED; + numUnpackStreams += numStreams; +@@ -892,7 +902,7 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi) + } + if (type == k7zIdCRC || type == k7zIdSize || type == k7zIdEnd) + break; +- RINOK(SkipData(sd)); ++ RINOK(SkipData(sd)) + } + + if (!ssi->sdNumSubStreams.Data) +@@ -908,9 +918,9 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi) + if (type == k7zIdSize) + { + ssi->sdSizes.Data = sd->Data; +- RINOK(SkipNumbers(sd, numUnpackSizesInData)); ++ RINOK(SkipNumbers(sd, numUnpackSizesInData)) + ssi->sdSizes.Size = (size_t)(sd->Data - ssi->sdSizes.Data); +- RINOK(ReadID(sd, &type)); ++ RINOK(ReadID(sd, &type)) + } + + for (;;) +@@ -920,14 +930,14 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi) + if (type == k7zIdCRC) + { + ssi->sdCRCs.Data = sd->Data; +- RINOK(SkipBitUi32s(sd, numSubDigests)); ++ RINOK(SkipBitUi32s(sd, numSubDigests)) + ssi->sdCRCs.Size = (size_t)(sd->Data - ssi->sdCRCs.Data); + } + else + { +- RINOK(SkipData(sd)); ++ RINOK(SkipData(sd)) + } +- RINOK(ReadID(sd, &type)); ++ RINOK(ReadID(sd, &type)) + } + } + +@@ -940,31 +950,31 @@ static SRes SzReadStreamsInfo(CSzAr *p, + { + UInt64 type; + +- SzData_Clear(&ssi->sdSizes); +- SzData_Clear(&ssi->sdCRCs); +- SzData_Clear(&ssi->sdNumSubStreams); ++ SzData_CLEAR(&ssi->sdSizes) ++ SzData_CLEAR(&ssi->sdCRCs) ++ SzData_CLEAR(&ssi->sdNumSubStreams) + + *dataOffset = 0; +- RINOK(ReadID(sd, &type)); ++ RINOK(ReadID(sd, &type)) + if (type == k7zIdPackInfo) + { +- RINOK(ReadNumber(sd, dataOffset)); ++ RINOK(ReadNumber(sd, dataOffset)) + if (*dataOffset > p->RangeLimit) + return SZ_ERROR_ARCHIVE; +- RINOK(ReadPackInfo(p, sd, alloc)); ++ RINOK(ReadPackInfo(p, sd, alloc)) + if (p->PackPositions[p->NumPackStreams] > p->RangeLimit - *dataOffset) + return SZ_ERROR_ARCHIVE; +- RINOK(ReadID(sd, &type)); ++ RINOK(ReadID(sd, &type)) + } + if (type == k7zIdUnpackInfo) + { +- RINOK(ReadUnpackInfo(p, sd, numFoldersMax, tempBufs, numTempBufs, alloc)); +- RINOK(ReadID(sd, &type)); ++ RINOK(ReadUnpackInfo(p, sd, numFoldersMax, tempBufs, numTempBufs, alloc)) ++ RINOK(ReadID(sd, &type)) + } + if (type == k7zIdSubStreamsInfo) + { +- RINOK(ReadSubStreamsInfo(p, sd, ssi)); +- RINOK(ReadID(sd, &type)); ++ RINOK(ReadSubStreamsInfo(p, sd, ssi)) ++ RINOK(ReadID(sd, &type)) + } + else + { +@@ -976,7 +986,7 @@ static SRes SzReadStreamsInfo(CSzAr *p, + } + + static SRes SzReadAndDecodePackedStreams( +- ILookInStream *inStream, ++ ILookInStreamPtr inStream, + CSzData *sd, + CBuf *tempBufs, + UInt32 numFoldersMax, +@@ -988,7 +998,7 @@ static SRes SzReadAndDecodePackedStreams( + UInt32 fo; + CSubStreamInfo ssi; + +- RINOK(SzReadStreamsInfo(p, sd, numFoldersMax, NULL, 0, &dataStartPos, &ssi, allocTemp)); ++ RINOK(SzReadStreamsInfo(p, sd, numFoldersMax, NULL, 0, &dataStartPos, &ssi, allocTemp)) + + dataStartPos += baseOffset; + if (p->NumFolders == 0) +@@ -1000,7 +1010,7 @@ static SRes SzReadAndDecodePackedStreams( + for (fo = 0; fo < p->NumFolders; fo++) + { + CBuf *tempBuf = tempBufs + fo; +- UInt64 unpackSize = SzAr_GetFolderUnpackSize(p, fo); ++ const UInt64 unpackSize = SzAr_GetFolderUnpackSize(p, fo); + if ((size_t)unpackSize != unpackSize) + return SZ_ERROR_MEM; + if (!Buf_Create(tempBuf, (size_t)unpackSize, allocTemp)) +@@ -1010,8 +1020,8 @@ static SRes SzReadAndDecodePackedStreams( + for (fo = 0; fo < p->NumFolders; fo++) + { + const CBuf *tempBuf = tempBufs + fo; +- RINOK(LookInStream_SeekTo(inStream, dataStartPos)); +- RINOK(SzAr_DecodeFolder(p, fo, inStream, dataStartPos, tempBuf->data, tempBuf->size, allocTemp)); ++ RINOK(LookInStream_SeekTo(inStream, dataStartPos)) ++ RINOK(SzAr_DecodeFolder(p, fo, inStream, dataStartPos, tempBuf->data, tempBuf->size, allocTemp)) + } + + return SZ_OK; +@@ -1046,7 +1056,7 @@ static SRes SzReadFileNames(const Byte *data, size_t size, UInt32 numFiles, size + return (pos == size) ? SZ_OK : SZ_ERROR_ARCHIVE; + } + +-static MY_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num, ++static Z7_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num, + CSzData *sd2, + const CBuf *tempBufs, UInt32 numTempBufs, + ISzAllocPtr alloc) +@@ -1057,22 +1067,22 @@ static MY_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num, + Byte *defs; + Byte external; + +- RINOK(ReadBitVector(sd2, num, &p->Defs, alloc)); ++ RINOK(ReadBitVector(sd2, num, &p->Defs, alloc)) + +- SZ_READ_BYTE_SD(sd2, external); ++ SZ_READ_BYTE_SD(sd2, external) + if (external == 0) + sd = *sd2; + else + { + UInt32 index; +- RINOK(SzReadNumber32(sd2, &index)); ++ RINOK(SzReadNumber32(sd2, &index)) + if (index >= numTempBufs) + return SZ_ERROR_ARCHIVE; + sd.Data = tempBufs[index].data; + sd.Size = tempBufs[index].size; + } + +- MY_ALLOC_ZE(CNtfsFileTime, p->Vals, num, alloc); ++ MY_ALLOC_ZE(CNtfsFileTime, p->Vals, num, alloc) + vals = p->Vals; + defs = p->Defs; + for (i = 0; i < num; i++) +@@ -1082,7 +1092,7 @@ static MY_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num, + return SZ_ERROR_ARCHIVE; + vals[i].Low = GetUi32(sd.Data); + vals[i].High = GetUi32(sd.Data + 4); +- SKIP_DATA2(sd, 8); ++ SKIP_DATA2(sd, 8) + } + else + vals[i].High = vals[i].Low = 0; +@@ -1100,7 +1110,7 @@ static MY_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num, + static SRes SzReadHeader2( + CSzArEx *p, /* allocMain */ + CSzData *sd, +- ILookInStream *inStream, ++ ILookInStreamPtr inStream, + CBuf *tempBufs, UInt32 *numTempBufs, + ISzAllocPtr allocMain, + ISzAllocPtr allocTemp +@@ -1111,26 +1121,26 @@ static SRes SzReadHeader2( + { + UInt64 type; + +- SzData_Clear(&ssi.sdSizes); +- SzData_Clear(&ssi.sdCRCs); +- SzData_Clear(&ssi.sdNumSubStreams); ++ SzData_CLEAR(&ssi.sdSizes) ++ SzData_CLEAR(&ssi.sdCRCs) ++ SzData_CLEAR(&ssi.sdNumSubStreams) + + ssi.NumSubDigests = 0; + ssi.NumTotalSubStreams = 0; + +- RINOK(ReadID(sd, &type)); ++ RINOK(ReadID(sd, &type)) + + if (type == k7zIdArchiveProperties) + { + for (;;) + { + UInt64 type2; +- RINOK(ReadID(sd, &type2)); ++ RINOK(ReadID(sd, &type2)) + if (type2 == k7zIdEnd) + break; +- RINOK(SkipData(sd)); ++ RINOK(SkipData(sd)) + } +- RINOK(ReadID(sd, &type)); ++ RINOK(ReadID(sd, &type)) + } + + if (type == k7zIdAdditionalStreamsInfo) +@@ -1148,15 +1158,15 @@ static SRes SzReadHeader2( + + if (res != SZ_OK) + return res; +- RINOK(ReadID(sd, &type)); ++ RINOK(ReadID(sd, &type)) + } + + if (type == k7zIdMainStreamsInfo) + { + RINOK(SzReadStreamsInfo(&p->db, sd, (UInt32)1 << 30, tempBufs, *numTempBufs, +- &p->dataPos, &ssi, allocMain)); ++ &p->dataPos, &ssi, allocMain)) + p->dataPos += p->startPosAfterHeader; +- RINOK(ReadID(sd, &type)); ++ RINOK(ReadID(sd, &type)) + } + + if (type == k7zIdEnd) +@@ -1174,23 +1184,23 @@ static SRes SzReadHeader2( + const Byte *emptyStreams = NULL; + const Byte *emptyFiles = NULL; + +- RINOK(SzReadNumber32(sd, &numFiles)); ++ RINOK(SzReadNumber32(sd, &numFiles)) + p->NumFiles = numFiles; + + for (;;) + { + UInt64 type; + UInt64 size; +- RINOK(ReadID(sd, &type)); ++ RINOK(ReadID(sd, &type)) + if (type == k7zIdEnd) + break; +- RINOK(ReadNumber(sd, &size)); ++ RINOK(ReadNumber(sd, &size)) + if (size > sd->Size) + return SZ_ERROR_ARCHIVE; + + if (type >= ((UInt32)1 << 8)) + { +- SKIP_DATA(sd, size); ++ SKIP_DATA(sd, size) + } + else switch ((unsigned)type) + { +@@ -1200,7 +1210,7 @@ static SRes SzReadHeader2( + const Byte *namesData; + Byte external; + +- SZ_READ_BYTE(external); ++ SZ_READ_BYTE(external) + if (external == 0) + { + namesSize = (size_t)size - 1; +@@ -1209,7 +1219,7 @@ static SRes SzReadHeader2( + else + { + UInt32 index; +- RINOK(SzReadNumber32(sd, &index)); ++ RINOK(SzReadNumber32(sd, &index)) + if (index >= *numTempBufs) + return SZ_ERROR_ARCHIVE; + namesData = (tempBufs)[index].data; +@@ -1218,25 +1228,25 @@ static SRes SzReadHeader2( + + if ((namesSize & 1) != 0) + return SZ_ERROR_ARCHIVE; +- MY_ALLOC(size_t, p->FileNameOffsets, numFiles + 1, allocMain); +- MY_ALLOC_ZE_AND_CPY(p->FileNames, namesSize, namesData, allocMain); ++ MY_ALLOC(size_t, p->FileNameOffsets, numFiles + 1, allocMain) ++ MY_ALLOC_ZE_AND_CPY(p->FileNames, namesSize, namesData, allocMain) + RINOK(SzReadFileNames(p->FileNames, namesSize, numFiles, p->FileNameOffsets)) + if (external == 0) + { +- SKIP_DATA(sd, namesSize); ++ SKIP_DATA(sd, namesSize) + } + break; + } + case k7zIdEmptyStream: + { +- RINOK(RememberBitVector(sd, numFiles, &emptyStreams)); ++ RINOK(RememberBitVector(sd, numFiles, &emptyStreams)) + numEmptyStreams = CountDefinedBits(emptyStreams, numFiles); + emptyFiles = NULL; + break; + } + case k7zIdEmptyFile: + { +- RINOK(RememberBitVector(sd, numEmptyStreams, &emptyFiles)); ++ RINOK(RememberBitVector(sd, numEmptyStreams, &emptyFiles)) + break; + } + case k7zIdWinAttrib: +@@ -1245,22 +1255,22 @@ static SRes SzReadHeader2( + CSzData sdSwitch; + CSzData *sdPtr; + SzBitUi32s_Free(&p->Attribs, allocMain); +- RINOK(ReadBitVector(sd, numFiles, &p->Attribs.Defs, allocMain)); ++ RINOK(ReadBitVector(sd, numFiles, &p->Attribs.Defs, allocMain)) + +- SZ_READ_BYTE(external); ++ SZ_READ_BYTE(external) + if (external == 0) + sdPtr = sd; + else + { + UInt32 index; +- RINOK(SzReadNumber32(sd, &index)); ++ RINOK(SzReadNumber32(sd, &index)) + if (index >= *numTempBufs) + return SZ_ERROR_ARCHIVE; + sdSwitch.Data = (tempBufs)[index].data; + sdSwitch.Size = (tempBufs)[index].size; + sdPtr = &sdSwitch; + } +- RINOK(ReadUi32s(sdPtr, numFiles, &p->Attribs, allocMain)); ++ RINOK(ReadUi32s(sdPtr, numFiles, &p->Attribs, allocMain)) + break; + } + /* +@@ -1273,11 +1283,11 @@ static SRes SzReadHeader2( + break; + } + */ +- case k7zIdMTime: RINOK(ReadTime(&p->MTime, numFiles, sd, tempBufs, *numTempBufs, allocMain)); break; +- case k7zIdCTime: RINOK(ReadTime(&p->CTime, numFiles, sd, tempBufs, *numTempBufs, allocMain)); break; ++ case k7zIdMTime: RINOK(ReadTime(&p->MTime, numFiles, sd, tempBufs, *numTempBufs, allocMain)) break; ++ case k7zIdCTime: RINOK(ReadTime(&p->CTime, numFiles, sd, tempBufs, *numTempBufs, allocMain)) break; + default: + { +- SKIP_DATA(sd, size); ++ SKIP_DATA(sd, size) + } + } + } +@@ -1288,10 +1298,10 @@ static SRes SzReadHeader2( + for (;;) + { + UInt64 type; +- RINOK(ReadID(sd, &type)); ++ RINOK(ReadID(sd, &type)) + if (type == k7zIdEnd) + break; +- RINOK(SkipData(sd)); ++ RINOK(SkipData(sd)) + } + + { +@@ -1303,40 +1313,37 @@ static SRes SzReadHeader2( + UInt64 unpackPos = 0; + const Byte *digestsDefs = NULL; + const Byte *digestsVals = NULL; +- UInt32 digestsValsIndex = 0; +- UInt32 digestIndex; +- Byte allDigestsDefined = 0; ++ UInt32 digestIndex = 0; + Byte isDirMask = 0; + Byte crcMask = 0; + Byte mask = 0x80; + +- MY_ALLOC(UInt32, p->FolderToFile, p->db.NumFolders + 1, allocMain); +- MY_ALLOC_ZE(UInt32, p->FileToFolder, p->NumFiles, allocMain); +- MY_ALLOC(UInt64, p->UnpackPositions, p->NumFiles + 1, allocMain); +- MY_ALLOC_ZE(Byte, p->IsDirs, (p->NumFiles + 7) >> 3, allocMain); ++ MY_ALLOC(UInt32, p->FolderToFile, p->db.NumFolders + 1, allocMain) ++ MY_ALLOC_ZE(UInt32, p->FileToFolder, p->NumFiles, allocMain) ++ MY_ALLOC(UInt64, p->UnpackPositions, p->NumFiles + 1, allocMain) ++ MY_ALLOC_ZE(Byte, p->IsDirs, (p->NumFiles + 7) >> 3, allocMain) + +- RINOK(SzBitUi32s_Alloc(&p->CRCs, p->NumFiles, allocMain)); ++ RINOK(SzBitUi32s_Alloc(&p->CRCs, p->NumFiles, allocMain)) + + if (ssi.sdCRCs.Size != 0) + { +- SZ_READ_BYTE_SD(&ssi.sdCRCs, allDigestsDefined); ++ Byte allDigestsDefined = 0; ++ SZ_READ_BYTE_SD_NOCHECK(&ssi.sdCRCs, allDigestsDefined) + if (allDigestsDefined) + digestsVals = ssi.sdCRCs.Data; + else + { +- size_t numBytes = (ssi.NumSubDigests + 7) >> 3; ++ const size_t numBytes = (ssi.NumSubDigests + 7) >> 3; + digestsDefs = ssi.sdCRCs.Data; + digestsVals = digestsDefs + numBytes; + } + } + +- digestIndex = 0; +- + for (i = 0; i < numFiles; i++, mask >>= 1) + { + if (mask == 0) + { +- UInt32 byteIndex = (i - 1) >> 3; ++ const UInt32 byteIndex = (i - 1) >> 3; + p->IsDirs[byteIndex] = isDirMask; + p->CRCs.Defs[byteIndex] = crcMask; + isDirMask = 0; +@@ -1374,18 +1381,17 @@ static SRes SzReadHeader2( + numSubStreams = 1; + if (ssi.sdNumSubStreams.Data) + { +- RINOK(SzReadNumber32(&ssi.sdNumSubStreams, &numSubStreams)); ++ RINOK(SzReadNumber32(&ssi.sdNumSubStreams, &numSubStreams)) + } + remSubStreams = numSubStreams; + if (numSubStreams != 0) + break; + { +- UInt64 folderUnpackSize = SzAr_GetFolderUnpackSize(&p->db, folderIndex); ++ const UInt64 folderUnpackSize = SzAr_GetFolderUnpackSize(&p->db, folderIndex); + unpackPos += folderUnpackSize; + if (unpackPos < folderUnpackSize) + return SZ_ERROR_ARCHIVE; + } +- + folderIndex++; + } + } +@@ -1397,47 +1403,44 @@ static SRes SzReadHeader2( + + if (--remSubStreams == 0) + { +- UInt64 folderUnpackSize = SzAr_GetFolderUnpackSize(&p->db, folderIndex); +- UInt64 startFolderUnpackPos = p->UnpackPositions[p->FolderToFile[folderIndex]]; ++ const UInt64 folderUnpackSize = SzAr_GetFolderUnpackSize(&p->db, folderIndex); ++ const UInt64 startFolderUnpackPos = p->UnpackPositions[p->FolderToFile[folderIndex]]; + if (folderUnpackSize < unpackPos - startFolderUnpackPos) + return SZ_ERROR_ARCHIVE; + unpackPos = startFolderUnpackPos + folderUnpackSize; + if (unpackPos < folderUnpackSize) + return SZ_ERROR_ARCHIVE; + +- if (numSubStreams == 1 && SzBitWithVals_Check(&p->db.FolderCRCs, i)) ++ if (numSubStreams == 1 && SzBitWithVals_Check(&p->db.FolderCRCs, folderIndex)) + { + p->CRCs.Vals[i] = p->db.FolderCRCs.Vals[folderIndex]; + crcMask |= mask; + } +- else if (allDigestsDefined || (digestsDefs && SzBitArray_Check(digestsDefs, digestIndex))) +- { +- p->CRCs.Vals[i] = GetUi32(digestsVals + (size_t)digestsValsIndex * 4); +- digestsValsIndex++; +- crcMask |= mask; +- } +- + folderIndex++; + } + else + { + UInt64 v; +- RINOK(ReadNumber(&ssi.sdSizes, &v)); ++ RINOK(ReadNumber(&ssi.sdSizes, &v)) + unpackPos += v; + if (unpackPos < v) + return SZ_ERROR_ARCHIVE; +- if (allDigestsDefined || (digestsDefs && SzBitArray_Check(digestsDefs, digestIndex))) ++ } ++ if ((crcMask & mask) == 0 && digestsVals) ++ { ++ if (!digestsDefs || SzBitArray_Check(digestsDefs, digestIndex)) + { +- p->CRCs.Vals[i] = GetUi32(digestsVals + (size_t)digestsValsIndex * 4); +- digestsValsIndex++; ++ p->CRCs.Vals[i] = GetUi32(digestsVals); ++ digestsVals += 4; + crcMask |= mask; + } ++ digestIndex++; + } + } + + if (mask != 0x80) + { +- UInt32 byteIndex = (i - 1) >> 3; ++ const UInt32 byteIndex = (i - 1) >> 3; + p->IsDirs[byteIndex] = isDirMask; + p->CRCs.Defs[byteIndex] = crcMask; + } +@@ -1454,7 +1457,7 @@ static SRes SzReadHeader2( + break; + if (!ssi.sdNumSubStreams.Data) + return SZ_ERROR_ARCHIVE; +- RINOK(SzReadNumber32(&ssi.sdNumSubStreams, &numSubStreams)); ++ RINOK(SzReadNumber32(&ssi.sdNumSubStreams, &numSubStreams)) + if (numSubStreams != 0) + return SZ_ERROR_ARCHIVE; + /* +@@ -1479,7 +1482,7 @@ static SRes SzReadHeader2( + static SRes SzReadHeader( + CSzArEx *p, + CSzData *sd, +- ILookInStream *inStream, ++ ILookInStreamPtr inStream, + ISzAllocPtr allocMain, + ISzAllocPtr allocTemp) + { +@@ -1498,7 +1501,7 @@ static SRes SzReadHeader( + for (i = 0; i < NUM_ADDITIONAL_STREAMS_MAX; i++) + Buf_Free(tempBufs + i, allocTemp); + +- RINOK(res); ++ RINOK(res) + + if (sd->Size != 0) + return SZ_ERROR_FAIL; +@@ -1508,7 +1511,7 @@ static SRes SzReadHeader( + + static SRes SzArEx_Open2( + CSzArEx *p, +- ILookInStream *inStream, ++ ILookInStreamPtr inStream, + ISzAllocPtr allocMain, + ISzAllocPtr allocTemp) + { +@@ -1521,9 +1524,9 @@ static SRes SzArEx_Open2( + SRes res; + + startArcPos = 0; +- RINOK(ILookInStream_Seek(inStream, &startArcPos, SZ_SEEK_CUR)); ++ RINOK(ILookInStream_Seek(inStream, &startArcPos, SZ_SEEK_CUR)) + +- RINOK(LookInStream_Read2(inStream, header, k7zStartHeaderSize, SZ_ERROR_NO_ARCHIVE)); ++ RINOK(LookInStream_Read2(inStream, header, k7zStartHeaderSize, SZ_ERROR_NO_ARCHIVE)) + + if (!TestSignatureCandidate(header)) + return SZ_ERROR_NO_ARCHIVE; +@@ -1552,14 +1555,14 @@ static SRes SzArEx_Open2( + + { + Int64 pos = 0; +- RINOK(ILookInStream_Seek(inStream, &pos, SZ_SEEK_END)); ++ RINOK(ILookInStream_Seek(inStream, &pos, SZ_SEEK_END)) + if ((UInt64)pos < (UInt64)startArcPos + nextHeaderOffset || + (UInt64)pos < (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset || + (UInt64)pos < (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset + nextHeaderSize) + return SZ_ERROR_INPUT_EOF; + } + +- RINOK(LookInStream_SeekTo(inStream, (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset)); ++ RINOK(LookInStream_SeekTo(inStream, (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset)) + + if (!Buf_Create(&buf, nextHeaderSizeT, allocTemp)) + return SZ_ERROR_MEM; +@@ -1634,10 +1637,10 @@ static SRes SzArEx_Open2( + } + + +-SRes SzArEx_Open(CSzArEx *p, ILookInStream *inStream, ++SRes SzArEx_Open(CSzArEx *p, ILookInStreamPtr inStream, + ISzAllocPtr allocMain, ISzAllocPtr allocTemp) + { +- SRes res = SzArEx_Open2(p, inStream, allocMain, allocTemp); ++ const SRes res = SzArEx_Open2(p, inStream, allocMain, allocTemp); + if (res != SZ_OK) + SzArEx_Free(p, allocMain); + return res; +@@ -1646,7 +1649,7 @@ SRes SzArEx_Open(CSzArEx *p, ILookInStream *inStream, + + SRes SzArEx_Extract( + const CSzArEx *p, +- ILookInStream *inStream, ++ ILookInStreamPtr inStream, + UInt32 fileIndex, + UInt32 *blockIndex, + Byte **tempBuf, +@@ -1656,7 +1659,7 @@ SRes SzArEx_Extract( + ISzAllocPtr allocMain, + ISzAllocPtr allocTemp) + { +- UInt32 folderIndex = p->FileToFolder[fileIndex]; ++ const UInt32 folderIndex = p->FileToFolder[fileIndex]; + SRes res = SZ_OK; + + *offset = 0; +@@ -1673,13 +1676,13 @@ SRes SzArEx_Extract( + + if (*tempBuf == NULL || *blockIndex != folderIndex) + { +- UInt64 unpackSizeSpec = SzAr_GetFolderUnpackSize(&p->db, folderIndex); ++ const UInt64 unpackSizeSpec = SzAr_GetFolderUnpackSize(&p->db, folderIndex); + /* + UInt64 unpackSizeSpec = + p->UnpackPositions[p->FolderToFile[(size_t)folderIndex + 1]] - + p->UnpackPositions[p->FolderToFile[folderIndex]]; + */ +- size_t unpackSize = (size_t)unpackSizeSpec; ++ const size_t unpackSize = (size_t)unpackSizeSpec; + + if (unpackSize != unpackSizeSpec) + return SZ_ERROR_MEM; +@@ -1707,7 +1710,7 @@ SRes SzArEx_Extract( + + if (res == SZ_OK) + { +- UInt64 unpackPos = p->UnpackPositions[fileIndex]; ++ const UInt64 unpackPos = p->UnpackPositions[fileIndex]; + *offset = (size_t)(unpackPos - p->UnpackPositions[p->FolderToFile[folderIndex]]); + *outSizeProcessed = (size_t)(p->UnpackPositions[(size_t)fileIndex + 1] - unpackPos); + if (*offset + *outSizeProcessed > *outBufferSize) +@@ -1723,8 +1726,8 @@ SRes SzArEx_Extract( + + size_t SzArEx_GetFileNameUtf16(const CSzArEx *p, size_t fileIndex, UInt16 *dest) + { +- size_t offs = p->FileNameOffsets[fileIndex]; +- size_t len = p->FileNameOffsets[fileIndex + 1] - offs; ++ const size_t offs = p->FileNameOffsets[fileIndex]; ++ const size_t len = p->FileNameOffsets[fileIndex + 1] - offs; + if (dest != 0) + { + size_t i; +diff --git a/src/lzma/7zBuf.h b/src/lzma/7zBuf.h +index 81d1b5b64..c0ba8a7b6 100644 +--- a/src/lzma/7zBuf.h ++++ b/src/lzma/7zBuf.h +@@ -1,8 +1,8 @@ + /* 7zBuf.h -- Byte Buffer +-2017-04-03 : Igor Pavlov : Public domain */ ++2023-03-04 : Igor Pavlov : Public domain */ + +-#ifndef __7Z_BUF_H +-#define __7Z_BUF_H ++#ifndef ZIP7_INC_7Z_BUF_H ++#define ZIP7_INC_7Z_BUF_H + + #include "7zTypes.h" + +diff --git a/src/lzma/7zCrc.c b/src/lzma/7zCrc.c +index f186324dd..c995a8be4 100644 +--- a/src/lzma/7zCrc.c ++++ b/src/lzma/7zCrc.c +@@ -1,5 +1,5 @@ +-/* 7zCrc.c -- CRC32 init +-2021-04-01 : Igor Pavlov : Public domain */ ++/* 7zCrc.c -- CRC32 calculation and init ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -13,22 +13,20 @@ + #else + #define CRC_NUM_TABLES 9 + +- #define CRC_UINT32_SWAP(v) ((v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | (v << 24)) +- +- UInt32 MY_FAST_CALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table); +- UInt32 MY_FAST_CALL CrcUpdateT1_BeT8(UInt32 v, const void *data, size_t size, const UInt32 *table); ++ UInt32 Z7_FASTCALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table); ++ UInt32 Z7_FASTCALL CrcUpdateT1_BeT8(UInt32 v, const void *data, size_t size, const UInt32 *table); + #endif + + #ifndef MY_CPU_BE +- UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table); +- UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table); ++ UInt32 Z7_FASTCALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table); ++ UInt32 Z7_FASTCALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table); + #endif + +-typedef UInt32 (MY_FAST_CALL *CRC_FUNC)(UInt32 v, const void *data, size_t size, const UInt32 *table); +- ++/* + extern + CRC_FUNC g_CrcUpdateT4; + CRC_FUNC g_CrcUpdateT4; ++*/ + extern + CRC_FUNC g_CrcUpdateT8; + CRC_FUNC g_CrcUpdateT8; +@@ -44,20 +42,22 @@ CRC_FUNC g_CrcUpdate; + + UInt32 g_CrcTable[256 * CRC_NUM_TABLES]; + +-UInt32 MY_FAST_CALL CrcUpdate(UInt32 v, const void *data, size_t size) ++UInt32 Z7_FASTCALL CrcUpdate(UInt32 v, const void *data, size_t size) + { + return g_CrcUpdate(v, data, size, g_CrcTable); + } + +-UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size) ++UInt32 Z7_FASTCALL CrcCalc(const void *data, size_t size) + { + return g_CrcUpdate(CRC_INIT_VAL, data, size, g_CrcTable) ^ CRC_INIT_VAL; + } + ++#if CRC_NUM_TABLES < 4 \ ++ || (CRC_NUM_TABLES == 4 && defined(MY_CPU_BE)) \ ++ || (!defined(MY_CPU_LE) && !defined(MY_CPU_BE)) + #define CRC_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) +- +-UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table); +-UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table) ++UInt32 Z7_FASTCALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table); ++UInt32 Z7_FASTCALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table) + { + const Byte *p = (const Byte *)data; + const Byte *pEnd = p + size; +@@ -65,7 +65,7 @@ UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const U + v = CRC_UPDATE_BYTE_2(v, *p); + return v; + } +- ++#endif + + /* ---------- hardware CRC ---------- */ + +@@ -78,16 +78,29 @@ UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const U + #if defined(_MSC_VER) + #if defined(MY_CPU_ARM64) + #if (_MSC_VER >= 1910) ++ #ifndef __clang__ + #define USE_ARM64_CRC ++ #include ++ #endif + #endif + #endif + #elif (defined(__clang__) && (__clang_major__ >= 3)) \ + || (defined(__GNUC__) && (__GNUC__ > 4)) + #if !defined(__ARM_FEATURE_CRC32) + #define __ARM_FEATURE_CRC32 1 +- #if (!defined(__clang__) || (__clang_major__ > 3)) // fix these numbers ++ #if defined(__clang__) ++ #if defined(MY_CPU_ARM64) ++ #define ATTRIB_CRC __attribute__((__target__("crc"))) ++ #else ++ #define ATTRIB_CRC __attribute__((__target__("armv8-a,crc"))) ++ #endif ++ #else ++ #if defined(MY_CPU_ARM64) ++ #define ATTRIB_CRC __attribute__((__target__("+crc"))) ++ #else + #define ATTRIB_CRC __attribute__((__target__("arch=armv8-a+crc"))) + #endif ++ #endif + #endif + #if defined(__ARM_FEATURE_CRC32) + #define USE_ARM64_CRC +@@ -105,7 +118,7 @@ UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const U + + #pragma message("ARM64 CRC emulation") + +-MY_FORCE_INLINE ++Z7_FORCE_INLINE + UInt32 __crc32b(UInt32 v, UInt32 data) + { + const UInt32 *table = g_CrcTable; +@@ -113,7 +126,7 @@ UInt32 __crc32b(UInt32 v, UInt32 data) + return v; + } + +-MY_FORCE_INLINE ++Z7_FORCE_INLINE + UInt32 __crc32w(UInt32 v, UInt32 data) + { + const UInt32 *table = g_CrcTable; +@@ -124,7 +137,7 @@ UInt32 __crc32w(UInt32 v, UInt32 data) + return v; + } + +-MY_FORCE_INLINE ++Z7_FORCE_INLINE + UInt32 __crc32d(UInt32 v, UInt64 data) + { + const UInt32 *table = g_CrcTable; +@@ -156,9 +169,9 @@ UInt32 __crc32d(UInt32 v, UInt64 data) + // #pragma message("USE ARM HW CRC") + + ATTRIB_CRC +-UInt32 MY_FAST_CALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, const UInt32 *table); ++UInt32 Z7_FASTCALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, const UInt32 *table); + ATTRIB_CRC +-UInt32 MY_FAST_CALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, const UInt32 *table) ++UInt32 Z7_FASTCALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, const UInt32 *table) + { + const Byte *p = (const Byte *)data; + UNUSED_VAR(table); +@@ -188,9 +201,9 @@ UInt32 MY_FAST_CALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, cons + } + + ATTRIB_CRC +-UInt32 MY_FAST_CALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, const UInt32 *table); ++UInt32 Z7_FASTCALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, const UInt32 *table); + ATTRIB_CRC +-UInt32 MY_FAST_CALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, const UInt32 *table) ++UInt32 Z7_FASTCALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, const UInt32 *table) + { + const Byte *p = (const Byte *)data; + UNUSED_VAR(table); +@@ -219,6 +232,9 @@ UInt32 MY_FAST_CALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, cons + return v; + } + ++#undef T0_32_UNROLL_BYTES ++#undef T0_64_UNROLL_BYTES ++ + #endif // defined(USE_ARM64_CRC) || defined(USE_CRC_EMU) + + #endif // MY_CPU_LE +@@ -226,7 +242,7 @@ UInt32 MY_FAST_CALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, cons + + + +-void MY_FAST_CALL CrcGenerateTable() ++void Z7_FASTCALL CrcGenerateTable(void) + { + UInt32 i; + for (i = 0; i < 256; i++) +@@ -239,64 +255,62 @@ void MY_FAST_CALL CrcGenerateTable() + } + for (i = 256; i < 256 * CRC_NUM_TABLES; i++) + { +- UInt32 r = g_CrcTable[(size_t)i - 256]; ++ const UInt32 r = g_CrcTable[(size_t)i - 256]; + g_CrcTable[i] = g_CrcTable[r & 0xFF] ^ (r >> 8); + } + + #if CRC_NUM_TABLES < 4 +- +- g_CrcUpdate = CrcUpdateT1; +- +- #else +- +- #ifdef MY_CPU_LE +- +- g_CrcUpdateT4 = CrcUpdateT4; +- g_CrcUpdate = CrcUpdateT4; +- +- #if CRC_NUM_TABLES >= 8 ++ g_CrcUpdate = CrcUpdateT1; ++ #elif defined(MY_CPU_LE) ++ // g_CrcUpdateT4 = CrcUpdateT4; ++ #if CRC_NUM_TABLES < 8 ++ g_CrcUpdate = CrcUpdateT4; ++ #else // CRC_NUM_TABLES >= 8 + g_CrcUpdateT8 = CrcUpdateT8; +- ++ /* + #ifdef MY_CPU_X86_OR_AMD64 + if (!CPU_Is_InOrder()) + #endif +- g_CrcUpdate = CrcUpdateT8; ++ */ ++ g_CrcUpdate = CrcUpdateT8; + #endif +- + #else + { +- #ifndef MY_CPU_BE ++ #ifndef MY_CPU_BE + UInt32 k = 0x01020304; + const Byte *p = (const Byte *)&k; + if (p[0] == 4 && p[1] == 3) + { +- g_CrcUpdateT4 = CrcUpdateT4; +- g_CrcUpdate = CrcUpdateT4; +- #if CRC_NUM_TABLES >= 8 +- g_CrcUpdateT8 = CrcUpdateT8; +- g_CrcUpdate = CrcUpdateT8; ++ #if CRC_NUM_TABLES < 8 ++ // g_CrcUpdateT4 = CrcUpdateT4; ++ g_CrcUpdate = CrcUpdateT4; ++ #else // CRC_NUM_TABLES >= 8 ++ g_CrcUpdateT8 = CrcUpdateT8; ++ g_CrcUpdate = CrcUpdateT8; + #endif + } + else if (p[0] != 1 || p[1] != 2) + g_CrcUpdate = CrcUpdateT1; + else +- #endif ++ #endif // MY_CPU_BE + { + for (i = 256 * CRC_NUM_TABLES - 1; i >= 256; i--) + { +- UInt32 x = g_CrcTable[(size_t)i - 256]; +- g_CrcTable[i] = CRC_UINT32_SWAP(x); ++ const UInt32 x = g_CrcTable[(size_t)i - 256]; ++ g_CrcTable[i] = Z7_BSWAP32(x); + } +- g_CrcUpdateT4 = CrcUpdateT1_BeT4; +- g_CrcUpdate = CrcUpdateT1_BeT4; +- #if CRC_NUM_TABLES >= 8 +- g_CrcUpdateT8 = CrcUpdateT1_BeT8; +- g_CrcUpdate = CrcUpdateT1_BeT8; ++ #if CRC_NUM_TABLES <= 4 ++ g_CrcUpdate = CrcUpdateT1; ++ #elif CRC_NUM_TABLES <= 8 ++ // g_CrcUpdateT4 = CrcUpdateT1_BeT4; ++ g_CrcUpdate = CrcUpdateT1_BeT4; ++ #else // CRC_NUM_TABLES > 8 ++ g_CrcUpdateT8 = CrcUpdateT1_BeT8; ++ g_CrcUpdate = CrcUpdateT1_BeT8; + #endif + } + } +- #endif +- #endif ++ #endif // CRC_NUM_TABLES < 4 + + #ifdef MY_CPU_LE + #ifdef USE_ARM64_CRC +@@ -320,3 +334,7 @@ void MY_FAST_CALL CrcGenerateTable() + #endif + #endif + } ++ ++#undef kCrcPoly ++#undef CRC64_NUM_TABLES ++#undef CRC_UPDATE_BYTE_2 +diff --git a/src/lzma/7zCrc.h b/src/lzma/7zCrc.h +index 8fd579587..4afaeae4a 100644 +--- a/src/lzma/7zCrc.h ++++ b/src/lzma/7zCrc.h +@@ -1,8 +1,8 @@ + /* 7zCrc.h -- CRC32 calculation +-2013-01-18 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + +-#ifndef __7Z_CRC_H +-#define __7Z_CRC_H ++#ifndef ZIP7_INC_7Z_CRC_H ++#define ZIP7_INC_7Z_CRC_H + + #include "7zTypes.h" + +@@ -11,14 +11,16 @@ EXTERN_C_BEGIN + extern UInt32 g_CrcTable[]; + + /* Call CrcGenerateTable one time before other CRC functions */ +-void MY_FAST_CALL CrcGenerateTable(void); ++void Z7_FASTCALL CrcGenerateTable(void); + + #define CRC_INIT_VAL 0xFFFFFFFF + #define CRC_GET_DIGEST(crc) ((crc) ^ CRC_INIT_VAL) + #define CRC_UPDATE_BYTE(crc, b) (g_CrcTable[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) + +-UInt32 MY_FAST_CALL CrcUpdate(UInt32 crc, const void *data, size_t size); +-UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size); ++UInt32 Z7_FASTCALL CrcUpdate(UInt32 crc, const void *data, size_t size); ++UInt32 Z7_FASTCALL CrcCalc(const void *data, size_t size); ++ ++typedef UInt32 (Z7_FASTCALL *CRC_FUNC)(UInt32 v, const void *data, size_t size, const UInt32 *table); + + EXTERN_C_END + +diff --git a/src/lzma/7zCrcOpt.c b/src/lzma/7zCrcOpt.c +index 69fad9ca2..9c649290d 100644 +--- a/src/lzma/7zCrcOpt.c ++++ b/src/lzma/7zCrcOpt.c +@@ -1,5 +1,5 @@ + /* 7zCrcOpt.c -- CRC32 calculation +-2021-02-09 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -9,8 +9,8 @@ + + #define CRC_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) + +-UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table); +-UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table) ++UInt32 Z7_FASTCALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table); ++UInt32 Z7_FASTCALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table) + { + const Byte *p = (const Byte *)data; + for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++) +@@ -29,8 +29,8 @@ UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const U + return v; + } + +-UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table); +-UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table) ++UInt32 Z7_FASTCALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table); ++UInt32 Z7_FASTCALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table) + { + const Byte *p = (const Byte *)data; + for (; size > 0 && ((unsigned)(ptrdiff_t)p & 7) != 0; size--, p++) +@@ -61,11 +61,11 @@ UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const U + + #ifndef MY_CPU_LE + +-#define CRC_UINT32_SWAP(v) ((v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | (v << 24)) ++#define CRC_UINT32_SWAP(v) Z7_BSWAP32(v) + + #define CRC_UPDATE_BYTE_2_BE(crc, b) (table[(((crc) >> 24) ^ (b))] ^ ((crc) << 8)) + +-UInt32 MY_FAST_CALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table) ++UInt32 Z7_FASTCALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table) + { + const Byte *p = (const Byte *)data; + table += 0x100; +@@ -86,7 +86,7 @@ UInt32 MY_FAST_CALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, co + return CRC_UINT32_SWAP(v); + } + +-UInt32 MY_FAST_CALL CrcUpdateT1_BeT8(UInt32 v, const void *data, size_t size, const UInt32 *table) ++UInt32 Z7_FASTCALL CrcUpdateT1_BeT8(UInt32 v, const void *data, size_t size, const UInt32 *table) + { + const Byte *p = (const Byte *)data; + table += 0x100; +diff --git a/src/lzma/7zDec.c b/src/lzma/7zDec.c +index 94b676f89..380391c59 100644 +--- a/src/lzma/7zDec.c ++++ b/src/lzma/7zDec.c +@@ -1,11 +1,11 @@ + /* 7zDec.c -- Decoding from 7z folder +-2021-02-09 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + + #include + +-/* #define _7ZIP_PPMD_SUPPPORT */ ++/* #define Z7_PPMD_SUPPORT */ + + #include "7z.h" + #include "7zCrc.h" +@@ -16,27 +16,49 @@ + #include "Delta.h" + #include "LzmaDec.h" + #include "Lzma2Dec.h" +-#ifdef _7ZIP_PPMD_SUPPPORT ++#ifdef Z7_PPMD_SUPPORT + #include "Ppmd7.h" + #endif + + #define k_Copy 0 +-#ifndef _7Z_NO_METHOD_LZMA2 ++#ifndef Z7_NO_METHOD_LZMA2 + #define k_LZMA2 0x21 + #endif + #define k_LZMA 0x30101 + #define k_BCJ2 0x303011B +-#ifndef _7Z_NO_METHODS_FILTERS ++ ++#if !defined(Z7_NO_METHODS_FILTERS) ++#define Z7_USE_BRANCH_FILTER ++#endif ++ ++#if !defined(Z7_NO_METHODS_FILTERS) || \ ++ defined(Z7_USE_NATIVE_BRANCH_FILTER) && defined(MY_CPU_ARM64) ++#define Z7_USE_FILTER_ARM64 ++#ifndef Z7_USE_BRANCH_FILTER ++#define Z7_USE_BRANCH_FILTER ++#endif ++#define k_ARM64 0xa ++#endif ++ ++#if !defined(Z7_NO_METHODS_FILTERS) || \ ++ defined(Z7_USE_NATIVE_BRANCH_FILTER) && defined(MY_CPU_ARMT) ++#define Z7_USE_FILTER_ARMT ++#ifndef Z7_USE_BRANCH_FILTER ++#define Z7_USE_BRANCH_FILTER ++#endif ++#define k_ARMT 0x3030701 ++#endif ++ ++#ifndef Z7_NO_METHODS_FILTERS + #define k_Delta 3 + #define k_BCJ 0x3030103 + #define k_PPC 0x3030205 + #define k_IA64 0x3030401 + #define k_ARM 0x3030501 +-#define k_ARMT 0x3030701 + #define k_SPARC 0x3030805 + #endif + +-#ifdef _7ZIP_PPMD_SUPPPORT ++#ifdef Z7_PPMD_SUPPORT + + #define k_PPMD 0x30401 + +@@ -49,12 +71,12 @@ typedef struct + UInt64 processed; + BoolInt extra; + SRes res; +- const ILookInStream *inStream; ++ ILookInStreamPtr inStream; + } CByteInToLook; + +-static Byte ReadByte(const IByteIn *pp) ++static Byte ReadByte(IByteInPtr pp) + { +- CByteInToLook *p = CONTAINER_FROM_VTBL(pp, CByteInToLook, vt); ++ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CByteInToLook) + if (p->cur != p->end) + return *p->cur++; + if (p->res == SZ_OK) +@@ -67,13 +89,13 @@ static Byte ReadByte(const IByteIn *pp) + p->cur = p->begin; + p->end = p->begin + size; + if (size != 0) +- return *p->cur++;; ++ return *p->cur++; + } + p->extra = True7z; + return 0; + } + +-static SRes SzDecodePpmd(const Byte *props, unsigned propsSize, UInt64 inSize, const ILookInStream *inStream, ++static SRes SzDecodePpmd(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStreamPtr inStream, + Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain) + { + CPpmd7 ppmd; +@@ -138,14 +160,14 @@ static SRes SzDecodePpmd(const Byte *props, unsigned propsSize, UInt64 inSize, c + #endif + + +-static SRes SzDecodeLzma(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStream *inStream, ++static SRes SzDecodeLzma(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStreamPtr inStream, + Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain) + { + CLzmaDec state; + SRes res = SZ_OK; + +- LzmaDec_Construct(&state); +- RINOK(LzmaDec_AllocateProbs(&state, props, propsSize, allocMain)); ++ LzmaDec_CONSTRUCT(&state) ++ RINOK(LzmaDec_AllocateProbs(&state, props, propsSize, allocMain)) + state.dic = outBuffer; + state.dicBufSize = outSize; + LzmaDec_Init(&state); +@@ -196,18 +218,18 @@ static SRes SzDecodeLzma(const Byte *props, unsigned propsSize, UInt64 inSize, I + } + + +-#ifndef _7Z_NO_METHOD_LZMA2 ++#ifndef Z7_NO_METHOD_LZMA2 + +-static SRes SzDecodeLzma2(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStream *inStream, ++static SRes SzDecodeLzma2(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStreamPtr inStream, + Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain) + { + CLzma2Dec state; + SRes res = SZ_OK; + +- Lzma2Dec_Construct(&state); ++ Lzma2Dec_CONSTRUCT(&state) + if (propsSize != 1) + return SZ_ERROR_DATA; +- RINOK(Lzma2Dec_AllocateProbs(&state, props[0], allocMain)); ++ RINOK(Lzma2Dec_AllocateProbs(&state, props[0], allocMain)) + state.decoder.dic = outBuffer; + state.decoder.dicBufSize = outSize; + Lzma2Dec_Init(&state); +@@ -257,7 +279,7 @@ static SRes SzDecodeLzma2(const Byte *props, unsigned propsSize, UInt64 inSize, + #endif + + +-static SRes SzDecodeCopy(UInt64 inSize, ILookInStream *inStream, Byte *outBuffer) ++static SRes SzDecodeCopy(UInt64 inSize, ILookInStreamPtr inStream, Byte *outBuffer) + { + while (inSize > 0) + { +@@ -265,13 +287,13 @@ static SRes SzDecodeCopy(UInt64 inSize, ILookInStream *inStream, Byte *outBuffer + size_t curSize = (1 << 18); + if (curSize > inSize) + curSize = (size_t)inSize; +- RINOK(ILookInStream_Look(inStream, &inBuf, &curSize)); ++ RINOK(ILookInStream_Look(inStream, &inBuf, &curSize)) + if (curSize == 0) + return SZ_ERROR_INPUT_EOF; + memcpy(outBuffer, inBuf, curSize); + outBuffer += curSize; + inSize -= curSize; +- RINOK(ILookInStream_Skip(inStream, curSize)); ++ RINOK(ILookInStream_Skip(inStream, curSize)) + } + return SZ_OK; + } +@@ -282,12 +304,12 @@ static BoolInt IS_MAIN_METHOD(UInt32 m) + { + case k_Copy: + case k_LZMA: +- #ifndef _7Z_NO_METHOD_LZMA2 ++ #ifndef Z7_NO_METHOD_LZMA2 + case k_LZMA2: +- #endif +- #ifdef _7ZIP_PPMD_SUPPPORT ++ #endif ++ #ifdef Z7_PPMD_SUPPORT + case k_PPMD: +- #endif ++ #endif + return True7z; + } + return False7z; +@@ -317,7 +339,7 @@ static SRes CheckSupportedFolder(const CSzFolder *f) + } + + +- #ifndef _7Z_NO_METHODS_FILTERS ++ #if defined(Z7_USE_BRANCH_FILTER) + + if (f->NumCoders == 2) + { +@@ -333,13 +355,20 @@ static SRes CheckSupportedFolder(const CSzFolder *f) + return SZ_ERROR_UNSUPPORTED; + switch ((UInt32)c->MethodID) + { ++ #if !defined(Z7_NO_METHODS_FILTERS) + case k_Delta: + case k_BCJ: + case k_PPC: + case k_IA64: + case k_SPARC: + case k_ARM: ++ #endif ++ #ifdef Z7_USE_FILTER_ARM64 ++ case k_ARM64: ++ #endif ++ #ifdef Z7_USE_FILTER_ARMT + case k_ARMT: ++ #endif + break; + default: + return SZ_ERROR_UNSUPPORTED; +@@ -372,15 +401,16 @@ static SRes CheckSupportedFolder(const CSzFolder *f) + return SZ_ERROR_UNSUPPORTED; + } + +-#ifndef _7Z_NO_METHODS_FILTERS +-#define CASE_BRA_CONV(isa) case k_ ## isa: isa ## _Convert(outBuffer, outSize, 0, 0); break; +-#endif ++ ++ ++ ++ + + static SRes SzFolder_Decode2(const CSzFolder *folder, + const Byte *propsData, + const UInt64 *unpackSizes, + const UInt64 *packPositions, +- ILookInStream *inStream, UInt64 startPos, ++ ILookInStreamPtr inStream, UInt64 startPos, + Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain, + Byte *tempBuf[]) + { +@@ -389,7 +419,7 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, + SizeT tempSize3 = 0; + Byte *tempBuf3 = 0; + +- RINOK(CheckSupportedFolder(folder)); ++ RINOK(CheckSupportedFolder(folder)) + + for (ci = 0; ci < folder->NumCoders; ci++) + { +@@ -404,8 +434,8 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, + SizeT outSizeCur = outSize; + if (folder->NumCoders == 4) + { +- UInt32 indices[] = { 3, 2, 0 }; +- UInt64 unpackSize = unpackSizes[ci]; ++ const UInt32 indices[] = { 3, 2, 0 }; ++ const UInt64 unpackSize = unpackSizes[ci]; + si = indices[ci]; + if (ci < 2) + { +@@ -431,37 +461,37 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, + } + offset = packPositions[si]; + inSize = packPositions[(size_t)si + 1] - offset; +- RINOK(LookInStream_SeekTo(inStream, startPos + offset)); ++ RINOK(LookInStream_SeekTo(inStream, startPos + offset)) + + if (coder->MethodID == k_Copy) + { + if (inSize != outSizeCur) /* check it */ + return SZ_ERROR_DATA; +- RINOK(SzDecodeCopy(inSize, inStream, outBufCur)); ++ RINOK(SzDecodeCopy(inSize, inStream, outBufCur)) + } + else if (coder->MethodID == k_LZMA) + { +- RINOK(SzDecodeLzma(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)); ++ RINOK(SzDecodeLzma(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)) + } +- #ifndef _7Z_NO_METHOD_LZMA2 ++ #ifndef Z7_NO_METHOD_LZMA2 + else if (coder->MethodID == k_LZMA2) + { +- RINOK(SzDecodeLzma2(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)); ++ RINOK(SzDecodeLzma2(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)) + } +- #endif +- #ifdef _7ZIP_PPMD_SUPPPORT ++ #endif ++ #ifdef Z7_PPMD_SUPPORT + else if (coder->MethodID == k_PPMD) + { +- RINOK(SzDecodePpmd(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)); ++ RINOK(SzDecodePpmd(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)) + } +- #endif ++ #endif + else + return SZ_ERROR_UNSUPPORTED; + } + else if (coder->MethodID == k_BCJ2) + { +- UInt64 offset = packPositions[1]; +- UInt64 s3Size = packPositions[2] - offset; ++ const UInt64 offset = packPositions[1]; ++ const UInt64 s3Size = packPositions[2] - offset; + + if (ci != 3) + return SZ_ERROR_UNSUPPORTED; +@@ -473,8 +503,8 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, + if (!tempBuf[2] && tempSizes[2] != 0) + return SZ_ERROR_MEM; + +- RINOK(LookInStream_SeekTo(inStream, startPos + offset)); +- RINOK(SzDecodeCopy(s3Size, inStream, tempBuf[2])); ++ RINOK(LookInStream_SeekTo(inStream, startPos + offset)) ++ RINOK(SzDecodeCopy(s3Size, inStream, tempBuf[2])) + + if ((tempSizes[0] & 3) != 0 || + (tempSizes[1] & 3) != 0 || +@@ -493,26 +523,22 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, + p.destLim = outBuffer + outSize; + + Bcj2Dec_Init(&p); +- RINOK(Bcj2Dec_Decode(&p)); ++ RINOK(Bcj2Dec_Decode(&p)) + + { + unsigned i; + for (i = 0; i < 4; i++) + if (p.bufs[i] != p.lims[i]) + return SZ_ERROR_DATA; +- +- if (!Bcj2Dec_IsFinished(&p)) +- return SZ_ERROR_DATA; +- +- if (p.dest != p.destLim +- || p.state != BCJ2_STREAM_MAIN) ++ if (p.dest != p.destLim || !Bcj2Dec_IsMaybeFinished(&p)) + return SZ_ERROR_DATA; + } + } + } +- #ifndef _7Z_NO_METHODS_FILTERS ++ #if defined(Z7_USE_BRANCH_FILTER) + else if (ci == 1) + { ++ #if !defined(Z7_NO_METHODS_FILTERS) + if (coder->MethodID == k_Delta) + { + if (coder->PropsSize != 1) +@@ -522,31 +548,53 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, + Delta_Init(state); + Delta_Decode(state, (unsigned)(propsData[coder->PropsOffset]) + 1, outBuffer, outSize); + } ++ continue; + } +- else ++ #endif ++ ++ #ifdef Z7_USE_FILTER_ARM64 ++ if (coder->MethodID == k_ARM64) ++ { ++ UInt32 pc = 0; ++ if (coder->PropsSize == 4) ++ pc = GetUi32(propsData + coder->PropsOffset); ++ else if (coder->PropsSize != 0) ++ return SZ_ERROR_UNSUPPORTED; ++ z7_BranchConv_ARM64_Dec(outBuffer, outSize, pc); ++ continue; ++ } ++ #endif ++ ++ #if !defined(Z7_NO_METHODS_FILTERS) || defined(Z7_USE_FILTER_ARMT) + { + if (coder->PropsSize != 0) + return SZ_ERROR_UNSUPPORTED; ++ #define CASE_BRA_CONV(isa) case k_ ## isa: Z7_BRANCH_CONV_DEC(isa)(outBuffer, outSize, 0); break; // pc = 0; + switch (coder->MethodID) + { ++ #if !defined(Z7_NO_METHODS_FILTERS) + case k_BCJ: + { +- UInt32 state; +- x86_Convert_Init(state); +- x86_Convert(outBuffer, outSize, 0, &state, 0); ++ UInt32 state = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL; ++ z7_BranchConvSt_X86_Dec(outBuffer, outSize, 0, &state); // pc = 0 + break; + } + CASE_BRA_CONV(PPC) + CASE_BRA_CONV(IA64) + CASE_BRA_CONV(SPARC) + CASE_BRA_CONV(ARM) ++ #endif ++ #if !defined(Z7_NO_METHODS_FILTERS) || defined(Z7_USE_FILTER_ARMT) + CASE_BRA_CONV(ARMT) ++ #endif + default: + return SZ_ERROR_UNSUPPORTED; + } ++ continue; + } +- } +- #endif ++ #endif ++ } // (c == 1) ++ #endif + else + return SZ_ERROR_UNSUPPORTED; + } +@@ -556,7 +604,7 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, + + + SRes SzAr_DecodeFolder(const CSzAr *p, UInt32 folderIndex, +- ILookInStream *inStream, UInt64 startPos, ++ ILookInStreamPtr inStream, UInt64 startPos, + Byte *outBuffer, size_t outSize, + ISzAllocPtr allocMain) + { +diff --git a/src/lzma/7zFile.c b/src/lzma/7zFile.c +index 13d2efa47..ba5daa133 100644 +--- a/src/lzma/7zFile.c ++++ b/src/lzma/7zFile.c +@@ -1,5 +1,5 @@ + /* 7zFile.c -- File IO +-2021-04-29 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -268,7 +268,7 @@ WRes File_Write(CSzFile *p, const void *data, size_t *size) + return errno; + if (processed == 0) + break; +- data = (void *)((Byte *)data + (size_t)processed); ++ data = (const void *)((const Byte *)data + (size_t)processed); + originalSize -= (size_t)processed; + *size += (size_t)processed; + } +@@ -287,7 +287,8 @@ WRes File_Seek(CSzFile *p, Int64 *pos, ESzSeek origin) + DWORD moveMethod; + UInt32 low = (UInt32)*pos; + LONG high = (LONG)((UInt64)*pos >> 16 >> 16); /* for case when UInt64 is 32-bit only */ +- switch (origin) ++ // (int) to eliminate clang warning ++ switch ((int)origin) + { + case SZ_SEEK_SET: moveMethod = FILE_BEGIN; break; + case SZ_SEEK_CUR: moveMethod = FILE_CURRENT; break; +@@ -308,7 +309,7 @@ WRes File_Seek(CSzFile *p, Int64 *pos, ESzSeek origin) + + int moveMethod; // = origin; + +- switch (origin) ++ switch ((int)origin) + { + case SZ_SEEK_SET: moveMethod = SEEK_SET; break; + case SZ_SEEK_CUR: moveMethod = SEEK_CUR; break; +@@ -387,10 +388,10 @@ WRes File_GetLength(CSzFile *p, UInt64 *length) + + /* ---------- FileSeqInStream ---------- */ + +-static SRes FileSeqInStream_Read(const ISeqInStream *pp, void *buf, size_t *size) ++static SRes FileSeqInStream_Read(ISeqInStreamPtr pp, void *buf, size_t *size) + { +- CFileSeqInStream *p = CONTAINER_FROM_VTBL(pp, CFileSeqInStream, vt); +- WRes wres = File_Read(&p->file, buf, size); ++ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CFileSeqInStream) ++ const WRes wres = File_Read(&p->file, buf, size); + p->wres = wres; + return (wres == 0) ? SZ_OK : SZ_ERROR_READ; + } +@@ -403,18 +404,18 @@ void FileSeqInStream_CreateVTable(CFileSeqInStream *p) + + /* ---------- FileInStream ---------- */ + +-static SRes FileInStream_Read(const ISeekInStream *pp, void *buf, size_t *size) ++static SRes FileInStream_Read(ISeekInStreamPtr pp, void *buf, size_t *size) + { +- CFileInStream *p = CONTAINER_FROM_VTBL(pp, CFileInStream, vt); +- WRes wres = File_Read(&p->file, buf, size); ++ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CFileInStream) ++ const WRes wres = File_Read(&p->file, buf, size); + p->wres = wres; + return (wres == 0) ? SZ_OK : SZ_ERROR_READ; + } + +-static SRes FileInStream_Seek(const ISeekInStream *pp, Int64 *pos, ESzSeek origin) ++static SRes FileInStream_Seek(ISeekInStreamPtr pp, Int64 *pos, ESzSeek origin) + { +- CFileInStream *p = CONTAINER_FROM_VTBL(pp, CFileInStream, vt); +- WRes wres = File_Seek(&p->file, pos, origin); ++ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CFileInStream) ++ const WRes wres = File_Seek(&p->file, pos, origin); + p->wres = wres; + return (wres == 0) ? SZ_OK : SZ_ERROR_READ; + } +@@ -428,10 +429,10 @@ void FileInStream_CreateVTable(CFileInStream *p) + + /* ---------- FileOutStream ---------- */ + +-static size_t FileOutStream_Write(const ISeqOutStream *pp, const void *data, size_t size) ++static size_t FileOutStream_Write(ISeqOutStreamPtr pp, const void *data, size_t size) + { +- CFileOutStream *p = CONTAINER_FROM_VTBL(pp, CFileOutStream, vt); +- WRes wres = File_Write(&p->file, data, &size); ++ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CFileOutStream) ++ const WRes wres = File_Write(&p->file, data, &size); + p->wres = wres; + return size; + } +diff --git a/src/lzma/7zFile.h b/src/lzma/7zFile.h +index 788abb6b9..f5069cd9e 100644 +--- a/src/lzma/7zFile.h ++++ b/src/lzma/7zFile.h +@@ -1,8 +1,8 @@ + /* 7zFile.h -- File IO +-2021-02-15 : Igor Pavlov : Public domain */ ++2023-03-05 : Igor Pavlov : Public domain */ + +-#ifndef __7Z_FILE_H +-#define __7Z_FILE_H ++#ifndef ZIP7_INC_FILE_H ++#define ZIP7_INC_FILE_H + + #ifdef _WIN32 + #define USE_WINDOWS_FILE +@@ -10,7 +10,8 @@ + #endif + + #ifdef USE_WINDOWS_FILE +-#include ++#include "7zWindows.h" ++ + #else + // note: USE_FOPEN mode is limited to 32-bit file size + // #define USE_FOPEN +diff --git a/src/lzma/7zStream.c b/src/lzma/7zStream.c +index 28a14604f..74e75b65a 100644 +--- a/src/lzma/7zStream.c ++++ b/src/lzma/7zStream.c +@@ -1,5 +1,5 @@ + /* 7zStream.c -- 7z Stream functions +-2021-02-09 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -7,12 +7,33 @@ + + #include "7zTypes.h" + +-SRes SeqInStream_Read2(const ISeqInStream *stream, void *buf, size_t size, SRes errorType) ++ ++SRes SeqInStream_ReadMax(ISeqInStreamPtr stream, void *buf, size_t *processedSize) ++{ ++ size_t size = *processedSize; ++ *processedSize = 0; ++ while (size != 0) ++ { ++ size_t cur = size; ++ const SRes res = ISeqInStream_Read(stream, buf, &cur); ++ *processedSize += cur; ++ buf = (void *)((Byte *)buf + cur); ++ size -= cur; ++ if (res != SZ_OK) ++ return res; ++ if (cur == 0) ++ return SZ_OK; ++ } ++ return SZ_OK; ++} ++ ++/* ++SRes SeqInStream_Read2(ISeqInStreamPtr stream, void *buf, size_t size, SRes errorType) + { + while (size != 0) + { + size_t processed = size; +- RINOK(ISeqInStream_Read(stream, buf, &processed)); ++ RINOK(ISeqInStream_Read(stream, buf, &processed)) + if (processed == 0) + return errorType; + buf = (void *)((Byte *)buf + processed); +@@ -21,42 +42,44 @@ SRes SeqInStream_Read2(const ISeqInStream *stream, void *buf, size_t size, SRes + return SZ_OK; + } + +-SRes SeqInStream_Read(const ISeqInStream *stream, void *buf, size_t size) ++SRes SeqInStream_Read(ISeqInStreamPtr stream, void *buf, size_t size) + { + return SeqInStream_Read2(stream, buf, size, SZ_ERROR_INPUT_EOF); + } ++*/ ++ + +-SRes SeqInStream_ReadByte(const ISeqInStream *stream, Byte *buf) ++SRes SeqInStream_ReadByte(ISeqInStreamPtr stream, Byte *buf) + { + size_t processed = 1; +- RINOK(ISeqInStream_Read(stream, buf, &processed)); ++ RINOK(ISeqInStream_Read(stream, buf, &processed)) + return (processed == 1) ? SZ_OK : SZ_ERROR_INPUT_EOF; + } + + + +-SRes LookInStream_SeekTo(const ILookInStream *stream, UInt64 offset) ++SRes LookInStream_SeekTo(ILookInStreamPtr stream, UInt64 offset) + { + Int64 t = (Int64)offset; + return ILookInStream_Seek(stream, &t, SZ_SEEK_SET); + } + +-SRes LookInStream_LookRead(const ILookInStream *stream, void *buf, size_t *size) ++SRes LookInStream_LookRead(ILookInStreamPtr stream, void *buf, size_t *size) + { + const void *lookBuf; + if (*size == 0) + return SZ_OK; +- RINOK(ILookInStream_Look(stream, &lookBuf, size)); ++ RINOK(ILookInStream_Look(stream, &lookBuf, size)) + memcpy(buf, lookBuf, *size); + return ILookInStream_Skip(stream, *size); + } + +-SRes LookInStream_Read2(const ILookInStream *stream, void *buf, size_t size, SRes errorType) ++SRes LookInStream_Read2(ILookInStreamPtr stream, void *buf, size_t size, SRes errorType) + { + while (size != 0) + { + size_t processed = size; +- RINOK(ILookInStream_Read(stream, buf, &processed)); ++ RINOK(ILookInStream_Read(stream, buf, &processed)) + if (processed == 0) + return errorType; + buf = (void *)((Byte *)buf + processed); +@@ -65,16 +88,16 @@ SRes LookInStream_Read2(const ILookInStream *stream, void *buf, size_t size, SRe + return SZ_OK; + } + +-SRes LookInStream_Read(const ILookInStream *stream, void *buf, size_t size) ++SRes LookInStream_Read(ILookInStreamPtr stream, void *buf, size_t size) + { + return LookInStream_Read2(stream, buf, size, SZ_ERROR_INPUT_EOF); + } + + + +-#define GET_LookToRead2 CLookToRead2 *p = CONTAINER_FROM_VTBL(pp, CLookToRead2, vt); ++#define GET_LookToRead2 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CLookToRead2) + +-static SRes LookToRead2_Look_Lookahead(const ILookInStream *pp, const void **buf, size_t *size) ++static SRes LookToRead2_Look_Lookahead(ILookInStreamPtr pp, const void **buf, size_t *size) + { + SRes res = SZ_OK; + GET_LookToRead2 +@@ -93,7 +116,7 @@ static SRes LookToRead2_Look_Lookahead(const ILookInStream *pp, const void **buf + return res; + } + +-static SRes LookToRead2_Look_Exact(const ILookInStream *pp, const void **buf, size_t *size) ++static SRes LookToRead2_Look_Exact(ILookInStreamPtr pp, const void **buf, size_t *size) + { + SRes res = SZ_OK; + GET_LookToRead2 +@@ -113,14 +136,14 @@ static SRes LookToRead2_Look_Exact(const ILookInStream *pp, const void **buf, si + return res; + } + +-static SRes LookToRead2_Skip(const ILookInStream *pp, size_t offset) ++static SRes LookToRead2_Skip(ILookInStreamPtr pp, size_t offset) + { + GET_LookToRead2 + p->pos += offset; + return SZ_OK; + } + +-static SRes LookToRead2_Read(const ILookInStream *pp, void *buf, size_t *size) ++static SRes LookToRead2_Read(ILookInStreamPtr pp, void *buf, size_t *size) + { + GET_LookToRead2 + size_t rem = p->size - p->pos; +@@ -134,7 +157,7 @@ static SRes LookToRead2_Read(const ILookInStream *pp, void *buf, size_t *size) + return SZ_OK; + } + +-static SRes LookToRead2_Seek(const ILookInStream *pp, Int64 *pos, ESzSeek origin) ++static SRes LookToRead2_Seek(ILookInStreamPtr pp, Int64 *pos, ESzSeek origin) + { + GET_LookToRead2 + p->pos = p->size = 0; +@@ -153,9 +176,9 @@ void LookToRead2_CreateVTable(CLookToRead2 *p, int lookahead) + + + +-static SRes SecToLook_Read(const ISeqInStream *pp, void *buf, size_t *size) ++static SRes SecToLook_Read(ISeqInStreamPtr pp, void *buf, size_t *size) + { +- CSecToLook *p = CONTAINER_FROM_VTBL(pp, CSecToLook, vt); ++ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSecToLook) + return LookInStream_LookRead(p->realStream, buf, size); + } + +@@ -164,9 +187,9 @@ void SecToLook_CreateVTable(CSecToLook *p) + p->vt.Read = SecToLook_Read; + } + +-static SRes SecToRead_Read(const ISeqInStream *pp, void *buf, size_t *size) ++static SRes SecToRead_Read(ISeqInStreamPtr pp, void *buf, size_t *size) + { +- CSecToRead *p = CONTAINER_FROM_VTBL(pp, CSecToRead, vt); ++ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSecToRead) + return ILookInStream_Read(p->realStream, buf, size); + } + +diff --git a/src/lzma/7zTypes.h b/src/lzma/7zTypes.h +index 49291ce2a..e16175049 100644 +--- a/src/lzma/7zTypes.h ++++ b/src/lzma/7zTypes.h +@@ -1,8 +1,8 @@ + /* 7zTypes.h -- Basic types +-2021-12-25 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + +-#ifndef __7Z_TYPES_H +-#define __7Z_TYPES_H ++#ifndef ZIP7_7Z_TYPES_H ++#define ZIP7_7Z_TYPES_H + + #ifdef _WIN32 + /* #include */ +@@ -52,6 +52,11 @@ typedef int SRes; + #define MY_ALIGN(n) + #endif + #else ++ /* ++ // C11/C++11: ++ #include ++ #define MY_ALIGN(n) alignas(n) ++ */ + #define MY_ALIGN(n) __attribute__ ((aligned(n))) + #endif + +@@ -62,7 +67,7 @@ typedef int SRes; + typedef unsigned WRes; + #define MY_SRes_HRESULT_FROM_WRes(x) HRESULT_FROM_WIN32(x) + +-// #define MY_HRES_ERROR__INTERNAL_ERROR MY_SRes_HRESULT_FROM_WRes(ERROR_INTERNAL_ERROR) ++// #define MY_HRES_ERROR_INTERNAL_ERROR MY_SRes_HRESULT_FROM_WRes(ERROR_INTERNAL_ERROR) + + #else // _WIN32 + +@@ -70,13 +75,13 @@ typedef unsigned WRes; + typedef int WRes; + + // (FACILITY_ERRNO = 0x800) is 7zip's FACILITY constant to represent (errno) errors in HRESULT +-#define MY__FACILITY_ERRNO 0x800 +-#define MY__FACILITY_WIN32 7 +-#define MY__FACILITY__WRes MY__FACILITY_ERRNO ++#define MY_FACILITY_ERRNO 0x800 ++#define MY_FACILITY_WIN32 7 ++#define MY_FACILITY_WRes MY_FACILITY_ERRNO + + #define MY_HRESULT_FROM_errno_CONST_ERROR(x) ((HRESULT)( \ + ( (HRESULT)(x) & 0x0000FFFF) \ +- | (MY__FACILITY__WRes << 16) \ ++ | (MY_FACILITY_WRes << 16) \ + | (HRESULT)0x80000000 )) + + #define MY_SRes_HRESULT_FROM_WRes(x) \ +@@ -120,23 +125,19 @@ typedef int WRes; + #define ERROR_INVALID_REPARSE_DATA ((HRESULT)0x80071128L) + #define ERROR_REPARSE_TAG_INVALID ((HRESULT)0x80071129L) + +-// if (MY__FACILITY__WRes != FACILITY_WIN32), ++// if (MY_FACILITY_WRes != FACILITY_WIN32), + // we use FACILITY_WIN32 for COM errors: + #define E_OUTOFMEMORY ((HRESULT)0x8007000EL) + #define E_INVALIDARG ((HRESULT)0x80070057L) +-#define MY__E_ERROR_NEGATIVE_SEEK ((HRESULT)0x80070083L) ++#define MY_E_ERROR_NEGATIVE_SEEK ((HRESULT)0x80070083L) + + /* + // we can use FACILITY_ERRNO for some COM errors, that have errno equivalents: + #define E_OUTOFMEMORY MY_HRESULT_FROM_errno_CONST_ERROR(ENOMEM) + #define E_INVALIDARG MY_HRESULT_FROM_errno_CONST_ERROR(EINVAL) +-#define MY__E_ERROR_NEGATIVE_SEEK MY_HRESULT_FROM_errno_CONST_ERROR(EINVAL) ++#define MY_E_ERROR_NEGATIVE_SEEK MY_HRESULT_FROM_errno_CONST_ERROR(EINVAL) + */ + +-// gcc / clang : (sizeof(long) == sizeof(void*)) in 32/64 bits +-typedef long INT_PTR; +-typedef unsigned long UINT_PTR; +- + #define TEXT(quote) quote + + #define FILE_ATTRIBUTE_READONLY 0x0001 +@@ -160,18 +161,18 @@ typedef unsigned long UINT_PTR; + + + #ifndef RINOK +-#define RINOK(x) { int __result__ = (x); if (__result__ != 0) return __result__; } ++#define RINOK(x) { const int _result_ = (x); if (_result_ != 0) return _result_; } + #endif + + #ifndef RINOK_WRes +-#define RINOK_WRes(x) { WRes __result__ = (x); if (__result__ != 0) return __result__; } ++#define RINOK_WRes(x) { const WRes _result_ = (x); if (_result_ != 0) return _result_; } + #endif + + typedef unsigned char Byte; + typedef short Int16; + typedef unsigned short UInt16; + +-#ifdef _LZMA_UINT32_IS_ULONG ++#ifdef Z7_DECL_Int32_AS_long + typedef long Int32; + typedef unsigned long UInt32; + #else +@@ -210,37 +211,51 @@ typedef size_t SIZE_T; + #endif // _WIN32 + + +-#define MY_HRES_ERROR__INTERNAL_ERROR ((HRESULT)0x8007054FL) +- ++#define MY_HRES_ERROR_INTERNAL_ERROR ((HRESULT)0x8007054FL) + +-#ifdef _SZ_NO_INT_64 + +-/* define _SZ_NO_INT_64, if your compiler doesn't support 64-bit integers. +- NOTES: Some code will work incorrectly in that case! */ ++#ifdef Z7_DECL_Int64_AS_long + + typedef long Int64; + typedef unsigned long UInt64; + + #else + +-#if defined(_MSC_VER) || defined(__BORLANDC__) ++#if (defined(_MSC_VER) || defined(__BORLANDC__)) && !defined(__clang__) + typedef __int64 Int64; + typedef unsigned __int64 UInt64; +-#define UINT64_CONST(n) n ++#else ++#if defined(__clang__) || defined(__GNUC__) ++#include ++typedef int64_t Int64; ++typedef uint64_t UInt64; + #else + typedef long long int Int64; + typedef unsigned long long int UInt64; +-#define UINT64_CONST(n) n ## ULL ++// #define UINT64_CONST(n) n ## ULL ++#endif + #endif + + #endif + +-#ifdef _LZMA_NO_SYSTEM_SIZE_T +-typedef UInt32 SizeT; ++#define UINT64_CONST(n) n ++ ++ ++#ifdef Z7_DECL_SizeT_AS_unsigned_int ++typedef unsigned int SizeT; + #else + typedef size_t SizeT; + #endif + ++/* ++#if (defined(_MSC_VER) && _MSC_VER <= 1200) ++typedef size_t MY_uintptr_t; ++#else ++#include ++typedef uintptr_t MY_uintptr_t; ++#endif ++*/ ++ + typedef int BoolInt; + /* typedef BoolInt Bool; */ + #define True7z 1 +@@ -248,23 +263,23 @@ typedef int BoolInt; + + + #ifdef _WIN32 +-#define MY_STD_CALL __stdcall ++#define Z7_STDCALL __stdcall + #else +-#define MY_STD_CALL ++#define Z7_STDCALL + #endif + + #ifdef _MSC_VER + + #if _MSC_VER >= 1300 +-#define MY_NO_INLINE __declspec(noinline) ++#define Z7_NO_INLINE __declspec(noinline) + #else +-#define MY_NO_INLINE ++#define Z7_NO_INLINE + #endif + +-#define MY_FORCE_INLINE __forceinline ++#define Z7_FORCE_INLINE __forceinline + +-#define MY_CDECL __cdecl +-#define MY_FAST_CALL __fastcall ++#define Z7_CDECL __cdecl ++#define Z7_FASTCALL __fastcall + + #else // _MSC_VER + +@@ -272,27 +287,25 @@ typedef int BoolInt; + || (defined(__clang__) && (__clang_major__ >= 4)) \ + || defined(__INTEL_COMPILER) \ + || defined(__xlC__) +-#define MY_NO_INLINE __attribute__((noinline)) +-// #define MY_FORCE_INLINE __attribute__((always_inline)) inline ++#define Z7_NO_INLINE __attribute__((noinline)) ++#define Z7_FORCE_INLINE __attribute__((always_inline)) inline + #else +-#define MY_NO_INLINE ++#define Z7_NO_INLINE ++#define Z7_FORCE_INLINE + #endif + +-#define MY_FORCE_INLINE +- +- +-#define MY_CDECL ++#define Z7_CDECL + + #if defined(_M_IX86) \ + || defined(__i386__) +-// #define MY_FAST_CALL __attribute__((fastcall)) +-// #define MY_FAST_CALL __attribute__((cdecl)) +-#define MY_FAST_CALL ++// #define Z7_FASTCALL __attribute__((fastcall)) ++// #define Z7_FASTCALL __attribute__((cdecl)) ++#define Z7_FASTCALL + #elif defined(MY_CPU_AMD64) +-// #define MY_FAST_CALL __attribute__((ms_abi)) +-#define MY_FAST_CALL ++// #define Z7_FASTCALL __attribute__((ms_abi)) ++#define Z7_FASTCALL + #else +-#define MY_FAST_CALL ++#define Z7_FASTCALL + #endif + + #endif // _MSC_VER +@@ -300,41 +313,49 @@ typedef int BoolInt; + + /* The following interfaces use first parameter as pointer to structure */ + +-typedef struct IByteIn IByteIn; +-struct IByteIn ++// #define Z7_C_IFACE_CONST_QUAL ++#define Z7_C_IFACE_CONST_QUAL const ++ ++#define Z7_C_IFACE_DECL(a) \ ++ struct a ## _; \ ++ typedef Z7_C_IFACE_CONST_QUAL struct a ## _ * a ## Ptr; \ ++ typedef struct a ## _ a; \ ++ struct a ## _ ++ ++ ++Z7_C_IFACE_DECL (IByteIn) + { +- Byte (*Read)(const IByteIn *p); /* reads one byte, returns 0 in case of EOF or error */ ++ Byte (*Read)(IByteInPtr p); /* reads one byte, returns 0 in case of EOF or error */ + }; + #define IByteIn_Read(p) (p)->Read(p) + + +-typedef struct IByteOut IByteOut; +-struct IByteOut ++Z7_C_IFACE_DECL (IByteOut) + { +- void (*Write)(const IByteOut *p, Byte b); ++ void (*Write)(IByteOutPtr p, Byte b); + }; + #define IByteOut_Write(p, b) (p)->Write(p, b) + + +-typedef struct ISeqInStream ISeqInStream; +-struct ISeqInStream ++Z7_C_IFACE_DECL (ISeqInStream) + { +- SRes (*Read)(const ISeqInStream *p, void *buf, size_t *size); ++ SRes (*Read)(ISeqInStreamPtr p, void *buf, size_t *size); + /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. + (output(*size) < input(*size)) is allowed */ + }; + #define ISeqInStream_Read(p, buf, size) (p)->Read(p, buf, size) + ++/* try to read as much as avail in stream and limited by (*processedSize) */ ++SRes SeqInStream_ReadMax(ISeqInStreamPtr stream, void *buf, size_t *processedSize); + /* it can return SZ_ERROR_INPUT_EOF */ +-SRes SeqInStream_Read(const ISeqInStream *stream, void *buf, size_t size); +-SRes SeqInStream_Read2(const ISeqInStream *stream, void *buf, size_t size, SRes errorType); +-SRes SeqInStream_ReadByte(const ISeqInStream *stream, Byte *buf); ++// SRes SeqInStream_Read(ISeqInStreamPtr stream, void *buf, size_t size); ++// SRes SeqInStream_Read2(ISeqInStreamPtr stream, void *buf, size_t size, SRes errorType); ++SRes SeqInStream_ReadByte(ISeqInStreamPtr stream, Byte *buf); + + +-typedef struct ISeqOutStream ISeqOutStream; +-struct ISeqOutStream ++Z7_C_IFACE_DECL (ISeqOutStream) + { +- size_t (*Write)(const ISeqOutStream *p, const void *buf, size_t size); ++ size_t (*Write)(ISeqOutStreamPtr p, const void *buf, size_t size); + /* Returns: result - the number of actually written bytes. + (result < size) means error */ + }; +@@ -348,29 +369,26 @@ typedef enum + } ESzSeek; + + +-typedef struct ISeekInStream ISeekInStream; +-struct ISeekInStream ++Z7_C_IFACE_DECL (ISeekInStream) + { +- SRes (*Read)(const ISeekInStream *p, void *buf, size_t *size); /* same as ISeqInStream::Read */ +- SRes (*Seek)(const ISeekInStream *p, Int64 *pos, ESzSeek origin); ++ SRes (*Read)(ISeekInStreamPtr p, void *buf, size_t *size); /* same as ISeqInStream::Read */ ++ SRes (*Seek)(ISeekInStreamPtr p, Int64 *pos, ESzSeek origin); + }; + #define ISeekInStream_Read(p, buf, size) (p)->Read(p, buf, size) + #define ISeekInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin) + + +-typedef struct ILookInStream ILookInStream; +-struct ILookInStream ++Z7_C_IFACE_DECL (ILookInStream) + { +- SRes (*Look)(const ILookInStream *p, const void **buf, size_t *size); ++ SRes (*Look)(ILookInStreamPtr p, const void **buf, size_t *size); + /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. + (output(*size) > input(*size)) is not allowed + (output(*size) < input(*size)) is allowed */ +- SRes (*Skip)(const ILookInStream *p, size_t offset); ++ SRes (*Skip)(ILookInStreamPtr p, size_t offset); + /* offset must be <= output(*size) of Look */ +- +- SRes (*Read)(const ILookInStream *p, void *buf, size_t *size); ++ SRes (*Read)(ILookInStreamPtr p, void *buf, size_t *size); + /* reads directly (without buffer). It's same as ISeqInStream::Read */ +- SRes (*Seek)(const ILookInStream *p, Int64 *pos, ESzSeek origin); ++ SRes (*Seek)(ILookInStreamPtr p, Int64 *pos, ESzSeek origin); + }; + + #define ILookInStream_Look(p, buf, size) (p)->Look(p, buf, size) +@@ -379,19 +397,18 @@ struct ILookInStream + #define ILookInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin) + + +-SRes LookInStream_LookRead(const ILookInStream *stream, void *buf, size_t *size); +-SRes LookInStream_SeekTo(const ILookInStream *stream, UInt64 offset); ++SRes LookInStream_LookRead(ILookInStreamPtr stream, void *buf, size_t *size); ++SRes LookInStream_SeekTo(ILookInStreamPtr stream, UInt64 offset); + + /* reads via ILookInStream::Read */ +-SRes LookInStream_Read2(const ILookInStream *stream, void *buf, size_t size, SRes errorType); +-SRes LookInStream_Read(const ILookInStream *stream, void *buf, size_t size); +- ++SRes LookInStream_Read2(ILookInStreamPtr stream, void *buf, size_t size, SRes errorType); ++SRes LookInStream_Read(ILookInStreamPtr stream, void *buf, size_t size); + + + typedef struct + { + ILookInStream vt; +- const ISeekInStream *realStream; ++ ISeekInStreamPtr realStream; + + size_t pos; + size_t size; /* it's data size */ +@@ -403,13 +420,13 @@ typedef struct + + void LookToRead2_CreateVTable(CLookToRead2 *p, int lookahead); + +-#define LookToRead2_Init(p) { (p)->pos = (p)->size = 0; } ++#define LookToRead2_INIT(p) { (p)->pos = (p)->size = 0; } + + + typedef struct + { + ISeqInStream vt; +- const ILookInStream *realStream; ++ ILookInStreamPtr realStream; + } CSecToLook; + + void SecToLook_CreateVTable(CSecToLook *p); +@@ -419,20 +436,19 @@ void SecToLook_CreateVTable(CSecToLook *p); + typedef struct + { + ISeqInStream vt; +- const ILookInStream *realStream; ++ ILookInStreamPtr realStream; + } CSecToRead; + + void SecToRead_CreateVTable(CSecToRead *p); + + +-typedef struct ICompressProgress ICompressProgress; +- +-struct ICompressProgress ++Z7_C_IFACE_DECL (ICompressProgress) + { +- SRes (*Progress)(const ICompressProgress *p, UInt64 inSize, UInt64 outSize); ++ SRes (*Progress)(ICompressProgressPtr p, UInt64 inSize, UInt64 outSize); + /* Returns: result. (result != SZ_OK) means break. + Value (UInt64)(Int64)-1 for size means unknown value. */ + }; ++ + #define ICompressProgress_Progress(p, inSize, outSize) (p)->Progress(p, inSize, outSize) + + +@@ -470,13 +486,13 @@ struct ISzAlloc + + + +-#ifndef MY_container_of ++#ifndef Z7_container_of + + /* +-#define MY_container_of(ptr, type, m) container_of(ptr, type, m) +-#define MY_container_of(ptr, type, m) CONTAINING_RECORD(ptr, type, m) +-#define MY_container_of(ptr, type, m) ((type *)((char *)(ptr) - offsetof(type, m))) +-#define MY_container_of(ptr, type, m) (&((type *)0)->m == (ptr), ((type *)(((char *)(ptr)) - MY_offsetof(type, m)))) ++#define Z7_container_of(ptr, type, m) container_of(ptr, type, m) ++#define Z7_container_of(ptr, type, m) CONTAINING_RECORD(ptr, type, m) ++#define Z7_container_of(ptr, type, m) ((type *)((char *)(ptr) - offsetof(type, m))) ++#define Z7_container_of(ptr, type, m) (&((type *)0)->m == (ptr), ((type *)(((char *)(ptr)) - MY_offsetof(type, m)))) + */ + + /* +@@ -485,24 +501,64 @@ struct ISzAlloc + GCC 4.8.1 : classes with non-public variable members" + */ + +-#define MY_container_of(ptr, type, m) ((type *)(void *)((char *)(void *)(1 ? (ptr) : &((type *)0)->m) - MY_offsetof(type, m))) ++#define Z7_container_of(ptr, type, m) \ ++ ((type *)(void *)((char *)(void *) \ ++ (1 ? (ptr) : &((type *)NULL)->m) - MY_offsetof(type, m))) + +-#endif +- +-#define CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) ((type *)(void *)(ptr)) ++#define Z7_container_of_CONST(ptr, type, m) \ ++ ((const type *)(const void *)((const char *)(const void *) \ ++ (1 ? (ptr) : &((type *)NULL)->m) - MY_offsetof(type, m))) + + /* +-#define CONTAINER_FROM_VTBL(ptr, type, m) CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) ++#define Z7_container_of_NON_CONST_FROM_CONST(ptr, type, m) \ ++ ((type *)(void *)(const void *)((const char *)(const void *) \ ++ (1 ? (ptr) : &((type *)NULL)->m) - MY_offsetof(type, m))) + */ +-#define CONTAINER_FROM_VTBL(ptr, type, m) MY_container_of(ptr, type, m) + +-#define CONTAINER_FROM_VTBL_CLS(ptr, type, m) CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) ++#endif ++ ++#define Z7_CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) ((type *)(void *)(ptr)) ++ ++// #define Z7_CONTAINER_FROM_VTBL(ptr, type, m) Z7_CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) ++#define Z7_CONTAINER_FROM_VTBL(ptr, type, m) Z7_container_of(ptr, type, m) ++// #define Z7_CONTAINER_FROM_VTBL(ptr, type, m) Z7_container_of_NON_CONST_FROM_CONST(ptr, type, m) ++ ++#define Z7_CONTAINER_FROM_VTBL_CONST(ptr, type, m) Z7_container_of_CONST(ptr, type, m) ++ ++#define Z7_CONTAINER_FROM_VTBL_CLS(ptr, type, m) Z7_CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) + /* +-#define CONTAINER_FROM_VTBL_CLS(ptr, type, m) CONTAINER_FROM_VTBL(ptr, type, m) ++#define Z7_CONTAINER_FROM_VTBL_CLS(ptr, type, m) Z7_CONTAINER_FROM_VTBL(ptr, type, m) + */ ++#if defined (__clang__) || defined(__GNUC__) ++#define Z7_DIAGNOSCTIC_IGNORE_BEGIN_CAST_QUAL \ ++ _Pragma("GCC diagnostic push") \ ++ _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") ++#define Z7_DIAGNOSCTIC_IGNORE_END_CAST_QUAL \ ++ _Pragma("GCC diagnostic pop") ++#else ++#define Z7_DIAGNOSCTIC_IGNORE_BEGIN_CAST_QUAL ++#define Z7_DIAGNOSCTIC_IGNORE_END_CAST_QUAL ++#endif ++ ++#define Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR(ptr, type, m, p) \ ++ Z7_DIAGNOSCTIC_IGNORE_BEGIN_CAST_QUAL \ ++ type *p = Z7_CONTAINER_FROM_VTBL(ptr, type, m); \ ++ Z7_DIAGNOSCTIC_IGNORE_END_CAST_QUAL ++ ++#define Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(type) \ ++ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR(pp, type, vt, p) + + +-#define MY_memset_0_ARRAY(a) memset((a), 0, sizeof(a)) ++// #define ZIP7_DECLARE_HANDLE(name) typedef void *name; ++#define Z7_DECLARE_HANDLE(name) struct name##_dummy{int unused;}; typedef struct name##_dummy *name; ++ ++ ++#define Z7_memset_0_ARRAY(a) memset((a), 0, sizeof(a)) ++ ++#ifndef Z7_ARRAY_SIZE ++#define Z7_ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) ++#endif ++ + + #ifdef _WIN32 + +@@ -520,6 +576,22 @@ struct ISzAlloc + + #endif + ++#define k_PropVar_TimePrec_0 0 ++#define k_PropVar_TimePrec_Unix 1 ++#define k_PropVar_TimePrec_DOS 2 ++#define k_PropVar_TimePrec_HighPrec 3 ++#define k_PropVar_TimePrec_Base 16 ++#define k_PropVar_TimePrec_100ns (k_PropVar_TimePrec_Base + 7) ++#define k_PropVar_TimePrec_1ns (k_PropVar_TimePrec_Base + 9) ++ + EXTERN_C_END + + #endif ++ ++/* ++#ifndef Z7_ST ++#ifdef _7ZIP_ST ++#define Z7_ST ++#endif ++#endif ++*/ +diff --git a/src/lzma/7zVersion.h b/src/lzma/7zVersion.h +index e9363d37b..754923961 100644 +--- a/src/lzma/7zVersion.h ++++ b/src/lzma/7zVersion.h +@@ -1,7 +1,7 @@ +-#define MY_VER_MAJOR 21 +-#define MY_VER_MINOR 07 ++#define MY_VER_MAJOR 23 ++#define MY_VER_MINOR 01 + #define MY_VER_BUILD 0 +-#define MY_VERSION_NUMBERS "21.07" ++#define MY_VERSION_NUMBERS "23.01" + #define MY_VERSION MY_VERSION_NUMBERS + + #ifdef MY_CPU_NAME +@@ -10,12 +10,12 @@ + #define MY_VERSION_CPU MY_VERSION + #endif + +-#define MY_DATE "2021-12-26" ++#define MY_DATE "2023-06-20" + #undef MY_COPYRIGHT + #undef MY_VERSION_COPYRIGHT_DATE + #define MY_AUTHOR_NAME "Igor Pavlov" + #define MY_COPYRIGHT_PD "Igor Pavlov : Public domain" +-#define MY_COPYRIGHT_CR "Copyright (c) 1999-2021 Igor Pavlov" ++#define MY_COPYRIGHT_CR "Copyright (c) 1999-2023 Igor Pavlov" + + #ifdef USE_COPYRIGHT_CR + #define MY_COPYRIGHT MY_COPYRIGHT_CR +diff --git a/src/lzma/7zWindows.h b/src/lzma/7zWindows.h +new file mode 100644 +index 000000000..42c6db8bf +--- /dev/null ++++ b/src/lzma/7zWindows.h +@@ -0,0 +1,101 @@ ++/* 7zWindows.h -- StdAfx ++2023-04-02 : Igor Pavlov : Public domain */ ++ ++#ifndef ZIP7_INC_7Z_WINDOWS_H ++#define ZIP7_INC_7Z_WINDOWS_H ++ ++#ifdef _WIN32 ++ ++#if defined(__clang__) ++# pragma clang diagnostic push ++#endif ++ ++#if defined(_MSC_VER) ++ ++#pragma warning(push) ++#pragma warning(disable : 4668) // '_WIN32_WINNT' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' ++ ++#if _MSC_VER == 1900 ++// for old kit10 versions ++// #pragma warning(disable : 4255) // winuser.h(13979): warning C4255: 'GetThreadDpiAwarenessContext': ++#endif ++// win10 Windows Kit: ++#endif // _MSC_VER ++ ++#if defined(_MSC_VER) && _MSC_VER <= 1200 && !defined(_WIN64) ++// for msvc6 without sdk2003 ++#define RPC_NO_WINDOWS_H ++#endif ++ ++#if defined(__MINGW32__) || defined(__MINGW64__) ++// #if defined(__GNUC__) && !defined(__clang__) ++#include ++#else ++#include ++#endif ++// #include ++// #include ++ ++// but if precompiled with clang-cl then we need ++// #include ++#if defined(_MSC_VER) ++#pragma warning(pop) ++#endif ++ ++#if defined(__clang__) ++# pragma clang diagnostic pop ++#endif ++ ++#if defined(_MSC_VER) && _MSC_VER <= 1200 && !defined(_WIN64) ++#ifndef _W64 ++ ++typedef long LONG_PTR, *PLONG_PTR; ++typedef unsigned long ULONG_PTR, *PULONG_PTR; ++typedef ULONG_PTR DWORD_PTR, *PDWORD_PTR; ++ ++#define Z7_OLD_WIN_SDK ++#endif // _W64 ++#endif // _MSC_VER == 1200 ++ ++#ifdef Z7_OLD_WIN_SDK ++ ++#ifndef INVALID_FILE_ATTRIBUTES ++#define INVALID_FILE_ATTRIBUTES ((DWORD)-1) ++#endif ++#ifndef INVALID_SET_FILE_POINTER ++#define INVALID_SET_FILE_POINTER ((DWORD)-1) ++#endif ++#ifndef FILE_SPECIAL_ACCESS ++#define FILE_SPECIAL_ACCESS (FILE_ANY_ACCESS) ++#endif ++ ++// ShlObj.h: ++// #define BIF_NEWDIALOGSTYLE 0x0040 ++ ++#pragma warning(disable : 4201) ++// #pragma warning(disable : 4115) ++ ++#undef VARIANT_TRUE ++#define VARIANT_TRUE ((VARIANT_BOOL)-1) ++#endif ++ ++#endif // Z7_OLD_WIN_SDK ++ ++#ifdef UNDER_CE ++#undef VARIANT_TRUE ++#define VARIANT_TRUE ((VARIANT_BOOL)-1) ++#endif ++ ++ ++#if defined(_MSC_VER) ++#if _MSC_VER >= 1400 && _MSC_VER <= 1600 ++ // BaseTsd.h(148) : 'HandleToULong' : unreferenced inline function has been removed ++ // string.h ++ // #pragma warning(disable : 4514) ++#endif ++#endif ++ ++ ++/* #include "7zTypes.h" */ ++ ++#endif +diff --git a/src/lzma/Aes.c b/src/lzma/Aes.c +index 27e32e622..bcaafab11 100644 +--- a/src/lzma/Aes.c ++++ b/src/lzma/Aes.c +@@ -1,5 +1,5 @@ + /* Aes.c -- AES encryption / decryption +-2021-05-13 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -7,7 +7,7 @@ + #include "Aes.h" + + AES_CODE_FUNC g_AesCbc_Decode; +-#ifndef _SFX ++#ifndef Z7_SFX + AES_CODE_FUNC g_AesCbc_Encode; + AES_CODE_FUNC g_AesCtr_Code; + UInt32 g_Aes_SupportedFunctions_Flags; +@@ -51,7 +51,7 @@ static Byte InvS[256]; + #define DD(x) (D + (x << 8)) + + +-// #define _SHOW_AES_STATUS ++// #define Z7_SHOW_AES_STATUS + + #ifdef MY_CPU_X86_OR_AMD64 + #define USE_HW_AES +@@ -72,11 +72,11 @@ static Byte InvS[256]; + #endif + + #ifdef USE_HW_AES +-#ifdef _SHOW_AES_STATUS ++#ifdef Z7_SHOW_AES_STATUS + #include +-#define _PRF(x) x ++#define PRF(x) x + #else +-#define _PRF(x) ++#define PRF(x) + #endif + #endif + +@@ -90,23 +90,23 @@ void AesGenTables(void) + for (i = 0; i < 256; i++) + { + { +- UInt32 a1 = Sbox[i]; +- UInt32 a2 = xtime(a1); +- UInt32 a3 = a2 ^ a1; ++ const UInt32 a1 = Sbox[i]; ++ const UInt32 a2 = xtime(a1); ++ const UInt32 a3 = a2 ^ a1; + TT(0)[i] = Ui32(a2, a1, a1, a3); + TT(1)[i] = Ui32(a3, a2, a1, a1); + TT(2)[i] = Ui32(a1, a3, a2, a1); + TT(3)[i] = Ui32(a1, a1, a3, a2); + } + { +- UInt32 a1 = InvS[i]; +- UInt32 a2 = xtime(a1); +- UInt32 a4 = xtime(a2); +- UInt32 a8 = xtime(a4); +- UInt32 a9 = a8 ^ a1; +- UInt32 aB = a8 ^ a2 ^ a1; +- UInt32 aD = a8 ^ a4 ^ a1; +- UInt32 aE = a8 ^ a4 ^ a2; ++ const UInt32 a1 = InvS[i]; ++ const UInt32 a2 = xtime(a1); ++ const UInt32 a4 = xtime(a2); ++ const UInt32 a8 = xtime(a4); ++ const UInt32 a9 = a8 ^ a1; ++ const UInt32 aB = a8 ^ a2 ^ a1; ++ const UInt32 aD = a8 ^ a4 ^ a1; ++ const UInt32 aE = a8 ^ a4 ^ a2; + DD(0)[i] = Ui32(aE, a9, aD, aB); + DD(1)[i] = Ui32(aB, aE, a9, aD); + DD(2)[i] = Ui32(aD, aB, aE, a9); +@@ -116,7 +116,7 @@ void AesGenTables(void) + + { + AES_CODE_FUNC d = AesCbc_Decode; +- #ifndef _SFX ++ #ifndef Z7_SFX + AES_CODE_FUNC e = AesCbc_Encode; + AES_CODE_FUNC c = AesCtr_Code; + UInt32 flags = 0; +@@ -126,10 +126,10 @@ void AesGenTables(void) + if (CPU_IsSupported_AES()) + { + // #pragma message ("AES HW") +- _PRF(printf("\n===AES HW\n")); ++ PRF(printf("\n===AES HW\n")); + d = AesCbc_Decode_HW; + +- #ifndef _SFX ++ #ifndef Z7_SFX + e = AesCbc_Encode_HW; + c = AesCtr_Code_HW; + flags = k_Aes_SupportedFunctions_HW; +@@ -138,9 +138,9 @@ void AesGenTables(void) + #ifdef MY_CPU_X86_OR_AMD64 + if (CPU_IsSupported_VAES_AVX2()) + { +- _PRF(printf("\n===vaes avx2\n")); ++ PRF(printf("\n===vaes avx2\n")); + d = AesCbc_Decode_HW_256; +- #ifndef _SFX ++ #ifndef Z7_SFX + c = AesCtr_Code_HW_256; + flags |= k_Aes_SupportedFunctions_HW_256; + #endif +@@ -150,7 +150,7 @@ void AesGenTables(void) + #endif + + g_AesCbc_Decode = d; +- #ifndef _SFX ++ #ifndef Z7_SFX + g_AesCbc_Encode = e; + g_AesCtr_Code = c; + g_Aes_SupportedFunctions_Flags = flags; +@@ -194,7 +194,7 @@ void AesGenTables(void) + #define FD(i, x) InvS[gb(x, m[(i - x) & 3])] + #define FD4(i) dest[i] = Ui32(FD(i, 0), FD(i, 1), FD(i, 2), FD(i, 3)) ^ w[i]; + +-void MY_FAST_CALL Aes_SetKey_Enc(UInt32 *w, const Byte *key, unsigned keySize) ++void Z7_FASTCALL Aes_SetKey_Enc(UInt32 *w, const Byte *key, unsigned keySize) + { + unsigned i, m; + const UInt32 *wLim; +@@ -230,7 +230,7 @@ void MY_FAST_CALL Aes_SetKey_Enc(UInt32 *w, const Byte *key, unsigned keySize) + while (++w != wLim); + } + +-void MY_FAST_CALL Aes_SetKey_Dec(UInt32 *w, const Byte *key, unsigned keySize) ++void Z7_FASTCALL Aes_SetKey_Dec(UInt32 *w, const Byte *key, unsigned keySize) + { + unsigned i, num; + Aes_SetKey_Enc(w, key, keySize); +@@ -251,7 +251,7 @@ void MY_FAST_CALL Aes_SetKey_Dec(UInt32 *w, const Byte *key, unsigned keySize) + src and dest are pointers to 4 UInt32 words. + src and dest can point to same block */ + +-// MY_FORCE_INLINE ++// Z7_FORCE_INLINE + static void Aes_Encode(const UInt32 *w, UInt32 *dest, const UInt32 *src) + { + UInt32 s[4]; +@@ -265,17 +265,20 @@ static void Aes_Encode(const UInt32 *w, UInt32 *dest, const UInt32 *src) + w += 4; + for (;;) + { +- HT16(m, s, 0); ++ HT16(m, s, 0) + if (--numRounds2 == 0) + break; +- HT16(s, m, 4); ++ HT16(s, m, 4) + w += 8; + } + w += 4; +- FT4(0); FT4(1); FT4(2); FT4(3); ++ FT4(0) ++ FT4(1) ++ FT4(2) ++ FT4(3) + } + +-MY_FORCE_INLINE ++Z7_FORCE_INLINE + static void Aes_Decode(const UInt32 *w, UInt32 *dest, const UInt32 *src) + { + UInt32 s[4]; +@@ -289,12 +292,15 @@ static void Aes_Decode(const UInt32 *w, UInt32 *dest, const UInt32 *src) + for (;;) + { + w -= 8; +- HD16(m, s, 4); ++ HD16(m, s, 4) + if (--numRounds2 == 0) + break; +- HD16(s, m, 0); ++ HD16(s, m, 0) + } +- FD4(0); FD4(1); FD4(2); FD4(3); ++ FD4(0) ++ FD4(1) ++ FD4(2) ++ FD4(3) + } + + void AesCbc_Init(UInt32 *p, const Byte *iv) +@@ -304,7 +310,7 @@ void AesCbc_Init(UInt32 *p, const Byte *iv) + p[i] = GetUi32(iv + i * 4); + } + +-void MY_FAST_CALL AesCbc_Encode(UInt32 *p, Byte *data, size_t numBlocks) ++void Z7_FASTCALL AesCbc_Encode(UInt32 *p, Byte *data, size_t numBlocks) + { + for (; numBlocks != 0; numBlocks--, data += AES_BLOCK_SIZE) + { +@@ -315,14 +321,14 @@ void MY_FAST_CALL AesCbc_Encode(UInt32 *p, Byte *data, size_t numBlocks) + + Aes_Encode(p + 4, p, p); + +- SetUi32(data, p[0]); +- SetUi32(data + 4, p[1]); +- SetUi32(data + 8, p[2]); +- SetUi32(data + 12, p[3]); ++ SetUi32(data, p[0]) ++ SetUi32(data + 4, p[1]) ++ SetUi32(data + 8, p[2]) ++ SetUi32(data + 12, p[3]) + } + } + +-void MY_FAST_CALL AesCbc_Decode(UInt32 *p, Byte *data, size_t numBlocks) ++void Z7_FASTCALL AesCbc_Decode(UInt32 *p, Byte *data, size_t numBlocks) + { + UInt32 in[4], out[4]; + for (; numBlocks != 0; numBlocks--, data += AES_BLOCK_SIZE) +@@ -334,10 +340,10 @@ void MY_FAST_CALL AesCbc_Decode(UInt32 *p, Byte *data, size_t numBlocks) + + Aes_Decode(p + 4, out, in); + +- SetUi32(data, p[0] ^ out[0]); +- SetUi32(data + 4, p[1] ^ out[1]); +- SetUi32(data + 8, p[2] ^ out[2]); +- SetUi32(data + 12, p[3] ^ out[3]); ++ SetUi32(data, p[0] ^ out[0]) ++ SetUi32(data + 4, p[1] ^ out[1]) ++ SetUi32(data + 8, p[2] ^ out[2]) ++ SetUi32(data + 12, p[3] ^ out[3]) + + p[0] = in[0]; + p[1] = in[1]; +@@ -346,7 +352,7 @@ void MY_FAST_CALL AesCbc_Decode(UInt32 *p, Byte *data, size_t numBlocks) + } + } + +-void MY_FAST_CALL AesCtr_Code(UInt32 *p, Byte *data, size_t numBlocks) ++void Z7_FASTCALL AesCtr_Code(UInt32 *p, Byte *data, size_t numBlocks) + { + for (; numBlocks != 0; numBlocks--) + { +@@ -360,7 +366,7 @@ void MY_FAST_CALL AesCtr_Code(UInt32 *p, Byte *data, size_t numBlocks) + + for (i = 0; i < 4; i++, data += 4) + { +- UInt32 t = temp[i]; ++ const UInt32 t = temp[i]; + + #ifdef MY_CPU_LE_UNALIGN + *((UInt32 *)(void *)data) ^= t; +@@ -373,3 +379,15 @@ void MY_FAST_CALL AesCtr_Code(UInt32 *p, Byte *data, size_t numBlocks) + } + } + } ++ ++#undef xtime ++#undef Ui32 ++#undef gb0 ++#undef gb1 ++#undef gb2 ++#undef gb3 ++#undef gb ++#undef TT ++#undef DD ++#undef USE_HW_AES ++#undef PRF +diff --git a/src/lzma/Aes.h b/src/lzma/Aes.h +index 2aa225642..7f0182ac0 100644 +--- a/src/lzma/Aes.h ++++ b/src/lzma/Aes.h +@@ -1,8 +1,8 @@ + /* Aes.h -- AES encryption / decryption +-2018-04-28 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + +-#ifndef __AES_H +-#define __AES_H ++#ifndef ZIP7_INC_AES_H ++#define ZIP7_INC_AES_H + + #include "7zTypes.h" + +@@ -20,19 +20,19 @@ void AesGenTables(void); + + /* aes - 16-byte aligned pointer to keyMode+roundKeys sequence */ + /* keySize = 16 or 24 or 32 (bytes) */ +-typedef void (MY_FAST_CALL *AES_SET_KEY_FUNC)(UInt32 *aes, const Byte *key, unsigned keySize); +-void MY_FAST_CALL Aes_SetKey_Enc(UInt32 *aes, const Byte *key, unsigned keySize); +-void MY_FAST_CALL Aes_SetKey_Dec(UInt32 *aes, const Byte *key, unsigned keySize); ++typedef void (Z7_FASTCALL *AES_SET_KEY_FUNC)(UInt32 *aes, const Byte *key, unsigned keySize); ++void Z7_FASTCALL Aes_SetKey_Enc(UInt32 *aes, const Byte *key, unsigned keySize); ++void Z7_FASTCALL Aes_SetKey_Dec(UInt32 *aes, const Byte *key, unsigned keySize); + + /* ivAes - 16-byte aligned pointer to iv+keyMode+roundKeys sequence: UInt32[AES_NUM_IVMRK_WORDS] */ + void AesCbc_Init(UInt32 *ivAes, const Byte *iv); /* iv size is AES_BLOCK_SIZE */ + + /* data - 16-byte aligned pointer to data */ + /* numBlocks - the number of 16-byte blocks in data array */ +-typedef void (MY_FAST_CALL *AES_CODE_FUNC)(UInt32 *ivAes, Byte *data, size_t numBlocks); ++typedef void (Z7_FASTCALL *AES_CODE_FUNC)(UInt32 *ivAes, Byte *data, size_t numBlocks); + + extern AES_CODE_FUNC g_AesCbc_Decode; +-#ifndef _SFX ++#ifndef Z7_SFX + extern AES_CODE_FUNC g_AesCbc_Encode; + extern AES_CODE_FUNC g_AesCtr_Code; + #define k_Aes_SupportedFunctions_HW (1 << 2) +@@ -41,19 +41,19 @@ extern UInt32 g_Aes_SupportedFunctions_Flags; + #endif + + +-#define DECLARE__AES_CODE_FUNC(funcName) \ +- void MY_FAST_CALL funcName(UInt32 *ivAes, Byte *data, size_t numBlocks); ++#define Z7_DECLARE_AES_CODE_FUNC(funcName) \ ++ void Z7_FASTCALL funcName(UInt32 *ivAes, Byte *data, size_t numBlocks); + +-DECLARE__AES_CODE_FUNC (AesCbc_Encode) +-DECLARE__AES_CODE_FUNC (AesCbc_Decode) +-DECLARE__AES_CODE_FUNC (AesCtr_Code) ++Z7_DECLARE_AES_CODE_FUNC (AesCbc_Encode) ++Z7_DECLARE_AES_CODE_FUNC (AesCbc_Decode) ++Z7_DECLARE_AES_CODE_FUNC (AesCtr_Code) + +-DECLARE__AES_CODE_FUNC (AesCbc_Encode_HW) +-DECLARE__AES_CODE_FUNC (AesCbc_Decode_HW) +-DECLARE__AES_CODE_FUNC (AesCtr_Code_HW) ++Z7_DECLARE_AES_CODE_FUNC (AesCbc_Encode_HW) ++Z7_DECLARE_AES_CODE_FUNC (AesCbc_Decode_HW) ++Z7_DECLARE_AES_CODE_FUNC (AesCtr_Code_HW) + +-DECLARE__AES_CODE_FUNC (AesCbc_Decode_HW_256) +-DECLARE__AES_CODE_FUNC (AesCtr_Code_HW_256) ++Z7_DECLARE_AES_CODE_FUNC (AesCbc_Decode_HW_256) ++Z7_DECLARE_AES_CODE_FUNC (AesCtr_Code_HW_256) + + EXTERN_C_END + +diff --git a/src/lzma/AesOpt.c b/src/lzma/AesOpt.c +index 8be8ff69d..cfa6413f4 100644 +--- a/src/lzma/AesOpt.c ++++ b/src/lzma/AesOpt.c +@@ -1,39 +1,33 @@ + /* AesOpt.c -- AES optimized code for x86 AES hardware instructions +-2021-04-01 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + ++#include "Aes.h" + #include "CpuArch.h" + + #ifdef MY_CPU_X86_OR_AMD64 + +- #if defined(__clang__) +- #if __clang_major__ > 3 || (__clang_major__ == 3 && __clang_minor__ >= 8) +- #define USE_INTEL_AES +- #define ATTRIB_AES __attribute__((__target__("aes"))) +- #if (__clang_major__ >= 8) +- #define USE_INTEL_VAES +- #define ATTRIB_VAES __attribute__((__target__("aes,vaes,avx2"))) +- #endif +- #endif +- #elif defined(__GNUC__) +- #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4) +- #define USE_INTEL_AES +- #ifndef __AES__ +- #define ATTRIB_AES __attribute__((__target__("aes"))) +- #endif +- #if (__GNUC__ >= 8) +- #define USE_INTEL_VAES +- #define ATTRIB_VAES __attribute__((__target__("aes,vaes,avx2"))) +- #endif +- #endif +- #elif defined(__INTEL_COMPILER) ++ #if defined(__INTEL_COMPILER) + #if (__INTEL_COMPILER >= 1110) + #define USE_INTEL_AES + #if (__INTEL_COMPILER >= 1900) + #define USE_INTEL_VAES + #endif + #endif ++ #elif defined(__clang__) && (__clang_major__ > 3 || __clang_major__ == 3 && __clang_minor__ >= 8) \ ++ || defined(__GNUC__) && (__GNUC__ > 4 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4) ++ #define USE_INTEL_AES ++ #if !defined(__AES__) ++ #define ATTRIB_AES __attribute__((__target__("aes"))) ++ #endif ++ #if defined(__clang__) && (__clang_major__ >= 8) \ ++ || defined(__GNUC__) && (__GNUC__ >= 8) ++ #define USE_INTEL_VAES ++ #if !defined(__AES__) || !defined(__VAES__) || !defined(__AVX__) || !defined(__AVX2__) ++ #define ATTRIB_VAES __attribute__((__target__("aes,vaes,avx,avx2"))) ++ #endif ++ #endif + #elif defined(_MSC_VER) + #if (_MSC_VER > 1500) || (_MSC_FULL_VER >= 150030729) + #define USE_INTEL_AES +@@ -56,12 +50,15 @@ + #include + + #ifndef USE_INTEL_VAES +-#define AES_TYPE_keys __m128i +-#define AES_TYPE_data __m128i ++#define AES_TYPE_keys UInt32 ++#define AES_TYPE_data Byte ++// #define AES_TYPE_keys __m128i ++// #define AES_TYPE_data __m128i + #endif + + #define AES_FUNC_START(name) \ +- void MY_FAST_CALL name(__m128i *p, __m128i *data, size_t numBlocks) ++ void Z7_FASTCALL name(UInt32 *ivAes, Byte *data8, size_t numBlocks) ++ // void Z7_FASTCALL name(__m128i *p, __m128i *data, size_t numBlocks) + + #define AES_FUNC_START2(name) \ + AES_FUNC_START (name); \ +@@ -69,14 +66,16 @@ ATTRIB_AES \ + AES_FUNC_START (name) + + #define MM_OP(op, dest, src) dest = op(dest, src); +-#define MM_OP_m(op, src) MM_OP(op, m, src); ++#define MM_OP_m(op, src) MM_OP(op, m, src) + +-#define MM_XOR( dest, src) MM_OP(_mm_xor_si128, dest, src); +-#define AVX_XOR(dest, src) MM_OP(_mm256_xor_si256, dest, src); ++#define MM_XOR( dest, src) MM_OP(_mm_xor_si128, dest, src) ++#define AVX_XOR(dest, src) MM_OP(_mm256_xor_si256, dest, src) + + + AES_FUNC_START2 (AesCbc_Encode_HW) + { ++ __m128i *p = (__m128i *)(void *)ivAes; ++ __m128i *data = (__m128i *)(void *)data8; + __m128i m = *p; + const __m128i k0 = p[2]; + const __m128i k1 = p[3]; +@@ -86,17 +85,17 @@ AES_FUNC_START2 (AesCbc_Encode_HW) + UInt32 r = numRounds2; + const __m128i *w = p + 4; + __m128i temp = *data; +- MM_XOR (temp, k0); +- MM_XOR (m, temp); +- MM_OP_m (_mm_aesenc_si128, k1); ++ MM_XOR (temp, k0) ++ MM_XOR (m, temp) ++ MM_OP_m (_mm_aesenc_si128, k1) + do + { +- MM_OP_m (_mm_aesenc_si128, w[0]); +- MM_OP_m (_mm_aesenc_si128, w[1]); ++ MM_OP_m (_mm_aesenc_si128, w[0]) ++ MM_OP_m (_mm_aesenc_si128, w[1]) + w += 2; + } + while (--r); +- MM_OP_m (_mm_aesenclast_si128, w[0]); ++ MM_OP_m (_mm_aesenclast_si128, w[0]) + *data = m; + } + *p = m; +@@ -104,14 +103,14 @@ AES_FUNC_START2 (AesCbc_Encode_HW) + + + #define WOP_1(op) +-#define WOP_2(op) WOP_1 (op) op (m1, 1); +-#define WOP_3(op) WOP_2 (op) op (m2, 2); +-#define WOP_4(op) WOP_3 (op) op (m3, 3); ++#define WOP_2(op) WOP_1 (op) op (m1, 1) ++#define WOP_3(op) WOP_2 (op) op (m2, 2) ++#define WOP_4(op) WOP_3 (op) op (m3, 3) + #ifdef MY_CPU_AMD64 +-#define WOP_5(op) WOP_4 (op) op (m4, 4); +-#define WOP_6(op) WOP_5 (op) op (m5, 5); +-#define WOP_7(op) WOP_6 (op) op (m6, 6); +-#define WOP_8(op) WOP_7 (op) op (m7, 7); ++#define WOP_5(op) WOP_4 (op) op (m4, 4) ++#define WOP_6(op) WOP_5 (op) op (m5, 5) ++#define WOP_7(op) WOP_6 (op) op (m6, 6) ++#define WOP_8(op) WOP_7 (op) op (m7, 7) + #endif + /* + #define WOP_9(op) WOP_8 (op) op (m8, 8); +@@ -130,20 +129,20 @@ AES_FUNC_START2 (AesCbc_Encode_HW) + #define WOP_M1 WOP_4 + #endif + +-#define WOP(op) op (m0, 0); WOP_M1(op) ++#define WOP(op) op (m0, 0) WOP_M1(op) + + +-#define DECLARE_VAR(reg, ii) __m128i reg ++#define DECLARE_VAR(reg, ii) __m128i reg; + #define LOAD_data( reg, ii) reg = data[ii]; + #define STORE_data( reg, ii) data[ii] = reg; + #if (NUM_WAYS > 1) +-#define XOR_data_M1(reg, ii) MM_XOR (reg, data[ii- 1]); ++#define XOR_data_M1(reg, ii) MM_XOR (reg, data[ii- 1]) + #endif + +-#define AVX__DECLARE_VAR(reg, ii) __m256i reg +-#define AVX__LOAD_data( reg, ii) reg = ((const __m256i *)(const void *)data)[ii]; +-#define AVX__STORE_data( reg, ii) ((__m256i *)(void *)data)[ii] = reg; +-#define AVX__XOR_data_M1(reg, ii) AVX_XOR (reg, (((const __m256i *)(const void *)(data - 1))[ii])); ++#define AVX_DECLARE_VAR(reg, ii) __m256i reg; ++#define AVX_LOAD_data( reg, ii) reg = ((const __m256i *)(const void *)data)[ii]; ++#define AVX_STORE_data( reg, ii) ((__m256i *)(void *)data)[ii] = reg; ++#define AVX_XOR_data_M1(reg, ii) AVX_XOR (reg, (((const __m256i *)(const void *)(data - 1))[ii])) + + #define MM_OP_key(op, reg) MM_OP(op, reg, key); + +@@ -154,23 +153,23 @@ AES_FUNC_START2 (AesCbc_Encode_HW) + #define AES_XOR( reg, ii) MM_OP_key (_mm_xor_si128, reg) + + +-#define AVX__AES_DEC( reg, ii) MM_OP_key (_mm256_aesdec_epi128, reg) +-#define AVX__AES_DEC_LAST( reg, ii) MM_OP_key (_mm256_aesdeclast_epi128, reg) +-#define AVX__AES_ENC( reg, ii) MM_OP_key (_mm256_aesenc_epi128, reg) +-#define AVX__AES_ENC_LAST( reg, ii) MM_OP_key (_mm256_aesenclast_epi128, reg) +-#define AVX__AES_XOR( reg, ii) MM_OP_key (_mm256_xor_si256, reg) ++#define AVX_AES_DEC( reg, ii) MM_OP_key (_mm256_aesdec_epi128, reg) ++#define AVX_AES_DEC_LAST( reg, ii) MM_OP_key (_mm256_aesdeclast_epi128, reg) ++#define AVX_AES_ENC( reg, ii) MM_OP_key (_mm256_aesenc_epi128, reg) ++#define AVX_AES_ENC_LAST( reg, ii) MM_OP_key (_mm256_aesenclast_epi128, reg) ++#define AVX_AES_XOR( reg, ii) MM_OP_key (_mm256_xor_si256, reg) + +-#define CTR_START(reg, ii) MM_OP (_mm_add_epi64, ctr, one); reg = ctr; +-#define CTR_END( reg, ii) MM_XOR (data[ii], reg); ++#define CTR_START(reg, ii) MM_OP (_mm_add_epi64, ctr, one) reg = ctr; ++#define CTR_END( reg, ii) MM_XOR (data[ii], reg) + +-#define AVX__CTR_START(reg, ii) MM_OP (_mm256_add_epi64, ctr2, two); reg = _mm256_xor_si256(ctr2, key); +-#define AVX__CTR_END( reg, ii) AVX_XOR (((__m256i *)(void *)data)[ii], reg); ++#define AVX_CTR_START(reg, ii) MM_OP (_mm256_add_epi64, ctr2, two) reg = _mm256_xor_si256(ctr2, key); ++#define AVX_CTR_END( reg, ii) AVX_XOR (((__m256i *)(void *)data)[ii], reg) + + #define WOP_KEY(op, n) { \ + const __m128i key = w[n]; \ + WOP(op); } + +-#define AVX__WOP_KEY(op, n) { \ ++#define AVX_WOP_KEY(op, n) { \ + const __m256i key = w[n]; \ + WOP(op); } + +@@ -218,6 +217,8 @@ AES_FUNC_START2 (AesCbc_Encode_HW) + + AES_FUNC_START2 (AesCbc_Decode_HW) + { ++ __m128i *p = (__m128i *)(void *)ivAes; ++ __m128i *data = (__m128i *)(void *)data8; + __m128i iv = *p; + const __m128i *wStart = p + *(const UInt32 *)(p + 1) * 2 + 2 - 1; + const __m128i *dataEnd; +@@ -228,7 +229,7 @@ AES_FUNC_START2 (AesCbc_Decode_HW) + const __m128i *w = wStart; + + WOP (DECLARE_VAR) +- WOP (LOAD_data); ++ WOP (LOAD_data) + WOP_KEY (AES_XOR, 1) + + do +@@ -239,10 +240,10 @@ AES_FUNC_START2 (AesCbc_Decode_HW) + while (w != p); + WOP_KEY (AES_DEC_LAST, 0) + +- MM_XOR (m0, iv); ++ MM_XOR (m0, iv) + WOP_M1 (XOR_data_M1) + iv = data[NUM_WAYS - 1]; +- WOP (STORE_data); ++ WOP (STORE_data) + } + WIDE_LOOP_END + +@@ -252,15 +253,15 @@ AES_FUNC_START2 (AesCbc_Decode_HW) + __m128i m = _mm_xor_si128 (w[2], *data); + do + { +- MM_OP_m (_mm_aesdec_si128, w[1]); +- MM_OP_m (_mm_aesdec_si128, w[0]); ++ MM_OP_m (_mm_aesdec_si128, w[1]) ++ MM_OP_m (_mm_aesdec_si128, w[0]) + w -= 2; + } + while (w != p); +- MM_OP_m (_mm_aesdec_si128, w[1]); +- MM_OP_m (_mm_aesdeclast_si128, w[0]); ++ MM_OP_m (_mm_aesdec_si128, w[1]) ++ MM_OP_m (_mm_aesdeclast_si128, w[0]) + +- MM_XOR (m, iv); ++ MM_XOR (m, iv) + iv = *data; + *data = m; + } +@@ -271,6 +272,8 @@ AES_FUNC_START2 (AesCbc_Decode_HW) + + AES_FUNC_START2 (AesCtr_Code_HW) + { ++ __m128i *p = (__m128i *)(void *)ivAes; ++ __m128i *data = (__m128i *)(void *)data8; + __m128i ctr = *p; + UInt32 numRoundsMinus2 = *(const UInt32 *)(p + 1) * 2 - 1; + const __m128i *dataEnd; +@@ -283,7 +286,7 @@ AES_FUNC_START2 (AesCtr_Code_HW) + const __m128i *w = p; + UInt32 r = numRoundsMinus2; + WOP (DECLARE_VAR) +- WOP (CTR_START); ++ WOP (CTR_START) + WOP_KEY (AES_XOR, 0) + w += 1; + do +@@ -294,7 +297,7 @@ AES_FUNC_START2 (AesCtr_Code_HW) + while (--r); + WOP_KEY (AES_ENC_LAST, 0) + +- WOP (CTR_END); ++ WOP (CTR_END) + } + WIDE_LOOP_END + +@@ -303,19 +306,19 @@ AES_FUNC_START2 (AesCtr_Code_HW) + UInt32 numRounds2 = *(const UInt32 *)(p - 2 + 1) - 1; + const __m128i *w = p; + __m128i m; +- MM_OP (_mm_add_epi64, ctr, one); ++ MM_OP (_mm_add_epi64, ctr, one) + m = _mm_xor_si128 (ctr, p[0]); + w += 1; + do + { +- MM_OP_m (_mm_aesenc_si128, w[0]); +- MM_OP_m (_mm_aesenc_si128, w[1]); ++ MM_OP_m (_mm_aesenc_si128, w[0]) ++ MM_OP_m (_mm_aesenc_si128, w[1]) + w += 2; + } + while (--numRounds2); +- MM_OP_m (_mm_aesenc_si128, w[0]); +- MM_OP_m (_mm_aesenclast_si128, w[1]); +- MM_XOR (*data, m); ++ MM_OP_m (_mm_aesenc_si128, w[0]) ++ MM_OP_m (_mm_aesenclast_si128, w[1]) ++ MM_XOR (*data, m) + } + + p[-2] = ctr; +@@ -325,17 +328,58 @@ AES_FUNC_START2 (AesCtr_Code_HW) + + #ifdef USE_INTEL_VAES + ++/* ++GCC before 2013-Jun: ++ : ++ #ifdef __AVX__ ++ #include ++ #endif ++GCC after 2013-Jun: ++ : ++ #include ++CLANG 3.8+: ++{ ++ : ++ #if !defined(_MSC_VER) || defined(__AVX__) ++ #include ++ #endif ++ ++ if (the compiler is clang for Windows and if global arch is not set for __AVX__) ++ [ if (defined(_MSC_VER) && !defined(__AVX__)) ] ++ { ++ doesn't include ++ and we have 2 ways to fix it: ++ 1) we can define required __AVX__ before ++ or ++ 2) we can include after ++ } ++} ++ ++If we include manually for GCC/CLANG, it's ++required that must be included before . ++*/ ++ ++/* + #if defined(__clang__) && defined(_MSC_VER) +-#define __SSE4_2__ +-#define __AES__ + #define __AVX__ + #define __AVX2__ + #define __VAES__ +-#define __AVX512F__ +-#define __AVX512VL__ + #endif ++*/ + + #include ++#if defined(__clang__) && defined(_MSC_VER) ++ #if !defined(__AVX__) ++ #include ++ #endif ++ #if !defined(__AVX2__) ++ #include ++ #endif ++ #if !defined(__VAES__) ++ #include ++ #endif ++#endif // __clang__ && _MSC_VER ++ + + #define VAES_FUNC_START2(name) \ + AES_FUNC_START (name); \ +@@ -344,6 +388,8 @@ AES_FUNC_START (name) + + VAES_FUNC_START2 (AesCbc_Decode_HW_256) + { ++ __m128i *p = (__m128i *)(void *)ivAes; ++ __m128i *data = (__m128i *)(void *)data8; + __m128i iv = *p; + const __m128i *dataEnd; + UInt32 numRounds = *(const UInt32 *)(p + 1) * 2 + 1; +@@ -353,22 +399,22 @@ VAES_FUNC_START2 (AesCbc_Decode_HW_256) + { + const __m256i *w = keys + numRounds - 2; + +- WOP (AVX__DECLARE_VAR) +- WOP (AVX__LOAD_data); +- AVX__WOP_KEY (AVX__AES_XOR, 1) ++ WOP (AVX_DECLARE_VAR) ++ WOP (AVX_LOAD_data) ++ AVX_WOP_KEY (AVX_AES_XOR, 1) + + do + { +- AVX__WOP_KEY (AVX__AES_DEC, 0) ++ AVX_WOP_KEY (AVX_AES_DEC, 0) + w--; + } + while (w != keys); +- AVX__WOP_KEY (AVX__AES_DEC_LAST, 0) ++ AVX_WOP_KEY (AVX_AES_DEC_LAST, 0) + +- AVX_XOR (m0, _mm256_setr_m128i(iv, data[0])); +- WOP_M1 (AVX__XOR_data_M1) ++ AVX_XOR (m0, _mm256_setr_m128i(iv, data[0])) ++ WOP_M1 (AVX_XOR_data_M1) + iv = data[NUM_WAYS * 2 - 1]; +- WOP (AVX__STORE_data); ++ WOP (AVX_STORE_data) + } + WIDE_LOOP_END_AVX(;) + +@@ -378,15 +424,15 @@ VAES_FUNC_START2 (AesCbc_Decode_HW_256) + __m128i m = _mm_xor_si128 (w[2], *data); + do + { +- MM_OP_m (_mm_aesdec_si128, w[1]); +- MM_OP_m (_mm_aesdec_si128, w[0]); ++ MM_OP_m (_mm_aesdec_si128, w[1]) ++ MM_OP_m (_mm_aesdec_si128, w[0]) + w -= 2; + } + while (w != p); +- MM_OP_m (_mm_aesdec_si128, w[1]); +- MM_OP_m (_mm_aesdeclast_si128, w[0]); ++ MM_OP_m (_mm_aesdec_si128, w[1]) ++ MM_OP_m (_mm_aesdeclast_si128, w[0]) + +- MM_XOR (m, iv); ++ MM_XOR (m, iv) + iv = *data; + *data = m; + } +@@ -403,18 +449,20 @@ AVX2: _mm256_add_epi64 : vpaddq ymm, ymm, ymm + _mm256_broadcastsi128_si256 : vbroadcasti128 + */ + +-#define AVX__CTR_LOOP_START \ ++#define AVX_CTR_LOOP_START \ + ctr2 = _mm256_setr_m128i(_mm_sub_epi64(ctr, one), ctr); \ + two = _mm256_setr_m128i(one, one); \ + two = _mm256_add_epi64(two, two); \ + + // two = _mm256_setr_epi64x(2, 0, 2, 0); + +-#define AVX__CTR_LOOP_ENC \ ++#define AVX_CTR_LOOP_ENC \ + ctr = _mm256_extracti128_si256 (ctr2, 1); \ + + VAES_FUNC_START2 (AesCtr_Code_HW_256) + { ++ __m128i *p = (__m128i *)(void *)ivAes; ++ __m128i *data = (__m128i *)(void *)data8; + __m128i ctr = *p; + UInt32 numRounds = *(const UInt32 *)(p + 1) * 2 + 1; + const __m128i *dataEnd; +@@ -422,44 +470,44 @@ VAES_FUNC_START2 (AesCtr_Code_HW_256) + __m256i ctr2, two; + p += 2; + +- WIDE_LOOP_START_AVX (AVX__CTR_LOOP_START) ++ WIDE_LOOP_START_AVX (AVX_CTR_LOOP_START) + { + const __m256i *w = keys; + UInt32 r = numRounds - 2; +- WOP (AVX__DECLARE_VAR) +- AVX__WOP_KEY (AVX__CTR_START, 0); ++ WOP (AVX_DECLARE_VAR) ++ AVX_WOP_KEY (AVX_CTR_START, 0) + + w += 1; + do + { +- AVX__WOP_KEY (AVX__AES_ENC, 0) ++ AVX_WOP_KEY (AVX_AES_ENC, 0) + w += 1; + } + while (--r); +- AVX__WOP_KEY (AVX__AES_ENC_LAST, 0) ++ AVX_WOP_KEY (AVX_AES_ENC_LAST, 0) + +- WOP (AVX__CTR_END); ++ WOP (AVX_CTR_END) + } +- WIDE_LOOP_END_AVX (AVX__CTR_LOOP_ENC) ++ WIDE_LOOP_END_AVX (AVX_CTR_LOOP_ENC) + + SINGLE_LOOP + { + UInt32 numRounds2 = *(const UInt32 *)(p - 2 + 1) - 1; + const __m128i *w = p; + __m128i m; +- MM_OP (_mm_add_epi64, ctr, one); ++ MM_OP (_mm_add_epi64, ctr, one) + m = _mm_xor_si128 (ctr, p[0]); + w += 1; + do + { +- MM_OP_m (_mm_aesenc_si128, w[0]); +- MM_OP_m (_mm_aesenc_si128, w[1]); ++ MM_OP_m (_mm_aesenc_si128, w[0]) ++ MM_OP_m (_mm_aesenc_si128, w[1]) + w += 2; + } + while (--numRounds2); +- MM_OP_m (_mm_aesenc_si128, w[0]); +- MM_OP_m (_mm_aesenclast_si128, w[1]); +- MM_XOR (*data, m); ++ MM_OP_m (_mm_aesenc_si128, w[0]) ++ MM_OP_m (_mm_aesenclast_si128, w[1]) ++ MM_XOR (*data, m) + } + + p[-2] = ctr; +@@ -477,7 +525,7 @@ VAES_FUNC_START2 (AesCtr_Code_HW_256) + #define AES_TYPE_data Byte + + #define AES_FUNC_START(name) \ +- void MY_FAST_CALL name(UInt32 *p, Byte *data, size_t numBlocks) \ ++ void Z7_FASTCALL name(UInt32 *p, Byte *data, size_t numBlocks) \ + + #define AES_COMPAT_STUB(name) \ + AES_FUNC_START(name); \ +@@ -496,8 +544,8 @@ AES_COMPAT_STUB (AesCtr_Code) + #pragma message("VAES HW_SW stub was used") + + #define VAES_COMPAT_STUB(name) \ +- void MY_FAST_CALL name ## _256(UInt32 *p, Byte *data, size_t numBlocks); \ +- void MY_FAST_CALL name ## _256(UInt32 *p, Byte *data, size_t numBlocks) \ ++ void Z7_FASTCALL name ## _256(UInt32 *p, Byte *data, size_t numBlocks); \ ++ void Z7_FASTCALL name ## _256(UInt32 *p, Byte *data, size_t numBlocks) \ + { name((AES_TYPE_keys *)(void *)p, (AES_TYPE_data *)(void *)data, numBlocks); } + + VAES_COMPAT_STUB (AesCbc_Decode_HW) +@@ -551,7 +599,8 @@ VAES_COMPAT_STUB (AesCtr_Code_HW) + typedef uint8x16_t v128; + + #define AES_FUNC_START(name) \ +- void MY_FAST_CALL name(v128 *p, v128 *data, size_t numBlocks) ++ void Z7_FASTCALL name(UInt32 *ivAes, Byte *data8, size_t numBlocks) ++ // void Z7_FASTCALL name(v128 *p, v128 *data, size_t numBlocks) + + #define AES_FUNC_START2(name) \ + AES_FUNC_START (name); \ +@@ -559,18 +608,20 @@ ATTRIB_AES \ + AES_FUNC_START (name) + + #define MM_OP(op, dest, src) dest = op(dest, src); +-#define MM_OP_m(op, src) MM_OP(op, m, src); ++#define MM_OP_m(op, src) MM_OP(op, m, src) + #define MM_OP1_m(op) m = op(m); + +-#define MM_XOR( dest, src) MM_OP(veorq_u8, dest, src); +-#define MM_XOR_m( src) MM_XOR(m, src); ++#define MM_XOR( dest, src) MM_OP(veorq_u8, dest, src) ++#define MM_XOR_m( src) MM_XOR(m, src) + +-#define AES_E_m(k) MM_OP_m (vaeseq_u8, k); +-#define AES_E_MC_m(k) AES_E_m (k); MM_OP1_m(vaesmcq_u8); ++#define AES_E_m(k) MM_OP_m (vaeseq_u8, k) ++#define AES_E_MC_m(k) AES_E_m (k) MM_OP1_m(vaesmcq_u8) + + + AES_FUNC_START2 (AesCbc_Encode_HW) + { ++ v128 *p = (v128*)(void*)ivAes; ++ v128 *data = (v128*)(void*)data8; + v128 m = *p; + const v128 k0 = p[2]; + const v128 k1 = p[3]; +@@ -608,7 +659,7 @@ AES_FUNC_START2 (AesCbc_Encode_HW) + AES_E_MC_m (p[14]) + } + } +- AES_E_m (k_z1); ++ AES_E_m (k_z1) + MM_XOR_m (k_z0); + *data = m; + } +@@ -617,44 +668,44 @@ AES_FUNC_START2 (AesCbc_Encode_HW) + + + #define WOP_1(op) +-#define WOP_2(op) WOP_1 (op) op (m1, 1); +-#define WOP_3(op) WOP_2 (op) op (m2, 2); +-#define WOP_4(op) WOP_3 (op) op (m3, 3); +-#define WOP_5(op) WOP_4 (op) op (m4, 4); +-#define WOP_6(op) WOP_5 (op) op (m5, 5); +-#define WOP_7(op) WOP_6 (op) op (m6, 6); +-#define WOP_8(op) WOP_7 (op) op (m7, 7); ++#define WOP_2(op) WOP_1 (op) op (m1, 1) ++#define WOP_3(op) WOP_2 (op) op (m2, 2) ++#define WOP_4(op) WOP_3 (op) op (m3, 3) ++#define WOP_5(op) WOP_4 (op) op (m4, 4) ++#define WOP_6(op) WOP_5 (op) op (m5, 5) ++#define WOP_7(op) WOP_6 (op) op (m6, 6) ++#define WOP_8(op) WOP_7 (op) op (m7, 7) + + #define NUM_WAYS 8 + #define WOP_M1 WOP_8 + +-#define WOP(op) op (m0, 0); WOP_M1(op) ++#define WOP(op) op (m0, 0) WOP_M1(op) + +-#define DECLARE_VAR(reg, ii) v128 reg ++#define DECLARE_VAR(reg, ii) v128 reg; + #define LOAD_data( reg, ii) reg = data[ii]; + #define STORE_data( reg, ii) data[ii] = reg; + #if (NUM_WAYS > 1) +-#define XOR_data_M1(reg, ii) MM_XOR (reg, data[ii- 1]); ++#define XOR_data_M1(reg, ii) MM_XOR (reg, data[ii- 1]) + #endif + +-#define MM_OP_key(op, reg) MM_OP (op, reg, key); ++#define MM_OP_key(op, reg) MM_OP (op, reg, key) + +-#define AES_D_m(k) MM_OP_m (vaesdq_u8, k); +-#define AES_D_IMC_m(k) AES_D_m (k); MM_OP1_m (vaesimcq_u8); ++#define AES_D_m(k) MM_OP_m (vaesdq_u8, k) ++#define AES_D_IMC_m(k) AES_D_m (k) MM_OP1_m (vaesimcq_u8) + + #define AES_XOR( reg, ii) MM_OP_key (veorq_u8, reg) + #define AES_D( reg, ii) MM_OP_key (vaesdq_u8, reg) + #define AES_E( reg, ii) MM_OP_key (vaeseq_u8, reg) + +-#define AES_D_IMC( reg, ii) AES_D (reg, ii); reg = vaesimcq_u8(reg) +-#define AES_E_MC( reg, ii) AES_E (reg, ii); reg = vaesmcq_u8(reg) ++#define AES_D_IMC( reg, ii) AES_D (reg, ii) reg = vaesimcq_u8(reg); ++#define AES_E_MC( reg, ii) AES_E (reg, ii) reg = vaesmcq_u8(reg); + +-#define CTR_START(reg, ii) MM_OP (vaddq_u64, ctr, one); reg = vreinterpretq_u8_u64(ctr); +-#define CTR_END( reg, ii) MM_XOR (data[ii], reg); ++#define CTR_START(reg, ii) MM_OP (vaddq_u64, ctr, one) reg = vreinterpretq_u8_u64(ctr); ++#define CTR_END( reg, ii) MM_XOR (data[ii], reg) + + #define WOP_KEY(op, n) { \ + const v128 key = w[n]; \ +- WOP(op); } ++ WOP(op) } + + #define WIDE_LOOP_START \ + dataEnd = data + numBlocks; \ +@@ -672,6 +723,8 @@ AES_FUNC_START2 (AesCbc_Encode_HW) + + AES_FUNC_START2 (AesCbc_Decode_HW) + { ++ v128 *p = (v128*)(void*)ivAes; ++ v128 *data = (v128*)(void*)data8; + v128 iv = *p; + const v128 *wStart = p + ((size_t)*(const UInt32 *)(p + 1)) * 2; + const v128 *dataEnd; +@@ -681,7 +734,7 @@ AES_FUNC_START2 (AesCbc_Decode_HW) + { + const v128 *w = wStart; + WOP (DECLARE_VAR) +- WOP (LOAD_data); ++ WOP (LOAD_data) + WOP_KEY (AES_D_IMC, 2) + do + { +@@ -695,7 +748,7 @@ AES_FUNC_START2 (AesCbc_Decode_HW) + MM_XOR (m0, iv); + WOP_M1 (XOR_data_M1) + iv = data[NUM_WAYS - 1]; +- WOP (STORE_data); ++ WOP (STORE_data) + } + WIDE_LOOP_END + +@@ -724,6 +777,8 @@ AES_FUNC_START2 (AesCbc_Decode_HW) + + AES_FUNC_START2 (AesCtr_Code_HW) + { ++ v128 *p = (v128*)(void*)ivAes; ++ v128 *data = (v128*)(void*)data8; + uint64x2_t ctr = vreinterpretq_u64_u8(*p); + const v128 *wEnd = p + ((size_t)*(const UInt32 *)(p + 1)) * 2; + const v128 *dataEnd; +@@ -735,7 +790,7 @@ AES_FUNC_START2 (AesCtr_Code_HW) + { + const v128 *w = p; + WOP (DECLARE_VAR) +- WOP (CTR_START); ++ WOP (CTR_START) + do + { + WOP_KEY (AES_E_MC, 0) +@@ -746,7 +801,7 @@ AES_FUNC_START2 (AesCtr_Code_HW) + WOP_KEY (AES_E_MC, 0) + WOP_KEY (AES_E, 1) + WOP_KEY (AES_XOR, 2) +- WOP (CTR_END); ++ WOP (CTR_END) + } + WIDE_LOOP_END + +@@ -762,10 +817,10 @@ AES_FUNC_START2 (AesCtr_Code_HW) + w += 2; + } + while (w != wEnd); +- AES_E_MC_m (w[0]); +- AES_E_m (w[1]); +- MM_XOR_m (w[2]); +- CTR_END (m, 0); ++ AES_E_MC_m (w[0]) ++ AES_E_m (w[1]) ++ MM_XOR_m (w[2]) ++ CTR_END (m, 0) + } + + p[-2] = vreinterpretq_u8_u64(ctr); +@@ -774,3 +829,12 @@ AES_FUNC_START2 (AesCtr_Code_HW) + #endif // USE_HW_AES + + #endif // MY_CPU_ARM_OR_ARM64 ++ ++#undef NUM_WAYS ++#undef WOP_M1 ++#undef WOP ++#undef DECLARE_VAR ++#undef LOAD_data ++#undef STORE_data ++#undef USE_INTEL_AES ++#undef USE_HW_AES +diff --git a/src/lzma/Alloc.c b/src/lzma/Alloc.c +index d1af76c5c..d841bf20a 100644 +--- a/src/lzma/Alloc.c ++++ b/src/lzma/Alloc.c +@@ -1,38 +1,54 @@ + /* Alloc.c -- Memory allocation functions +-2021-07-13 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +-#include +- + #ifdef _WIN32 +-#include ++#include "7zWindows.h" + #endif + #include + + #include "Alloc.h" + +-/* #define _SZ_ALLOC_DEBUG */ ++#ifdef _WIN32 ++#ifdef Z7_LARGE_PAGES ++#if defined(__clang__) || defined(__GNUC__) ++typedef void (*Z7_voidFunction)(void); ++#define MY_CAST_FUNC (Z7_voidFunction) ++#elif defined(_MSC_VER) && _MSC_VER > 1920 ++#define MY_CAST_FUNC (void *) ++// #pragma warning(disable : 4191) // 'type cast': unsafe conversion from 'FARPROC' to 'void (__cdecl *)()' ++#else ++#define MY_CAST_FUNC ++#endif ++#endif // Z7_LARGE_PAGES ++#endif // _WIN32 ++ ++// #define SZ_ALLOC_DEBUG ++/* #define SZ_ALLOC_DEBUG */ + +-/* use _SZ_ALLOC_DEBUG to debug alloc/free operations */ +-#ifdef _SZ_ALLOC_DEBUG ++/* use SZ_ALLOC_DEBUG to debug alloc/free operations */ ++#ifdef SZ_ALLOC_DEBUG + ++#include + #include +-int g_allocCount = 0; +-int g_allocCountMid = 0; +-int g_allocCountBig = 0; ++static int g_allocCount = 0; ++#ifdef _WIN32 ++static int g_allocCountMid = 0; ++static int g_allocCountBig = 0; ++#endif + + + #define CONVERT_INT_TO_STR(charType, tempSize) \ +- unsigned char temp[tempSize]; unsigned i = 0; \ +- while (val >= 10) { temp[i++] = (unsigned char)('0' + (unsigned)(val % 10)); val /= 10; } \ ++ char temp[tempSize]; unsigned i = 0; \ ++ while (val >= 10) { temp[i++] = (char)('0' + (unsigned)(val % 10)); val /= 10; } \ + *s++ = (charType)('0' + (unsigned)val); \ + while (i != 0) { i--; *s++ = temp[i]; } \ + *s = 0; + + static void ConvertUInt64ToString(UInt64 val, char *s) + { +- CONVERT_INT_TO_STR(char, 24); ++ CONVERT_INT_TO_STR(char, 24) + } + + #define GET_HEX_CHAR(t) ((char)(((t < 10) ? ('0' + t) : ('A' + (t - 10))))) +@@ -77,7 +93,7 @@ static void PrintAligned(const char *s, size_t align) + Print(s); + } + +-static void PrintLn() ++static void PrintLn(void) + { + Print("\n"); + } +@@ -89,10 +105,10 @@ static void PrintHex(UInt64 v, size_t align) + PrintAligned(s, align); + } + +-static void PrintDec(UInt64 v, size_t align) ++static void PrintDec(int v, size_t align) + { + char s[32]; +- ConvertUInt64ToString(v, s); ++ ConvertUInt64ToString((unsigned)v, s); + PrintAligned(s, align); + } + +@@ -102,12 +118,19 @@ static void PrintAddr(void *p) + } + + +-#define PRINT_ALLOC(name, cnt, size, ptr) \ ++#define PRINT_REALLOC(name, cnt, size, ptr) { \ ++ Print(name " "); \ ++ if (!ptr) PrintDec(cnt++, 10); \ ++ PrintHex(size, 10); \ ++ PrintAddr(ptr); \ ++ PrintLn(); } ++ ++#define PRINT_ALLOC(name, cnt, size, ptr) { \ + Print(name " "); \ + PrintDec(cnt++, 10); \ + PrintHex(size, 10); \ + PrintAddr(ptr); \ +- PrintLn(); ++ PrintLn(); } + + #define PRINT_FREE(name, cnt, ptr) if (ptr) { \ + Print(name " "); \ +@@ -117,7 +140,9 @@ static void PrintAddr(void *p) + + #else + ++#ifdef _WIN32 + #define PRINT_ALLOC(name, cnt, size, ptr) ++#endif + #define PRINT_FREE(name, cnt, ptr) + #define Print(s) + #define PrintLn() +@@ -127,16 +152,31 @@ static void PrintAddr(void *p) + #endif + + ++/* ++by specification: ++ malloc(non_NULL, 0) : returns NULL or a unique pointer value that can later be successfully passed to free() ++ realloc(NULL, size) : the call is equivalent to malloc(size) ++ realloc(non_NULL, 0) : the call is equivalent to free(ptr) ++ ++in main compilers: ++ malloc(0) : returns non_NULL ++ realloc(NULL, 0) : returns non_NULL ++ realloc(non_NULL, 0) : returns NULL ++*/ ++ + + void *MyAlloc(size_t size) + { + if (size == 0) + return NULL; +- PRINT_ALLOC("Alloc ", g_allocCount, size, NULL); +- #ifdef _SZ_ALLOC_DEBUG ++ // PRINT_ALLOC("Alloc ", g_allocCount, size, NULL) ++ #ifdef SZ_ALLOC_DEBUG + { + void *p = malloc(size); +- // PRINT_ALLOC("Alloc ", g_allocCount, size, p); ++ if (p) ++ { ++ PRINT_ALLOC("Alloc ", g_allocCount, size, p) ++ } + return p; + } + #else +@@ -146,33 +186,64 @@ void *MyAlloc(size_t size) + + void MyFree(void *address) + { +- PRINT_FREE("Free ", g_allocCount, address); ++ PRINT_FREE("Free ", g_allocCount, address) + + free(address); + } + ++void *MyRealloc(void *address, size_t size) ++{ ++ if (size == 0) ++ { ++ MyFree(address); ++ return NULL; ++ } ++ // PRINT_REALLOC("Realloc ", g_allocCount, size, address) ++ #ifdef SZ_ALLOC_DEBUG ++ { ++ void *p = realloc(address, size); ++ if (p) ++ { ++ PRINT_REALLOC("Realloc ", g_allocCount, size, address) ++ } ++ return p; ++ } ++ #else ++ return realloc(address, size); ++ #endif ++} ++ ++ + #ifdef _WIN32 + + void *MidAlloc(size_t size) + { + if (size == 0) + return NULL; +- +- PRINT_ALLOC("Alloc-Mid", g_allocCountMid, size, NULL); +- ++ #ifdef SZ_ALLOC_DEBUG ++ { ++ void *p = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE); ++ if (p) ++ { ++ PRINT_ALLOC("Alloc-Mid", g_allocCountMid, size, p) ++ } ++ return p; ++ } ++ #else + return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE); ++ #endif + } + + void MidFree(void *address) + { +- PRINT_FREE("Free-Mid", g_allocCountMid, address); ++ PRINT_FREE("Free-Mid", g_allocCountMid, address) + + if (!address) + return; + VirtualFree(address, 0, MEM_RELEASE); + } + +-#ifdef _7ZIP_LARGE_PAGES ++#ifdef Z7_LARGE_PAGES + + #ifdef MEM_LARGE_PAGES + #define MY__MEM_LARGE_PAGES MEM_LARGE_PAGES +@@ -183,34 +254,35 @@ void MidFree(void *address) + extern + SIZE_T g_LargePageSize; + SIZE_T g_LargePageSize = 0; +-typedef SIZE_T (WINAPI *GetLargePageMinimumP)(VOID); ++typedef SIZE_T (WINAPI *Func_GetLargePageMinimum)(VOID); + +-#endif // _7ZIP_LARGE_PAGES +- +-void SetLargePageSize() ++void SetLargePageSize(void) + { +- #ifdef _7ZIP_LARGE_PAGES ++ #ifdef Z7_LARGE_PAGES + SIZE_T size; +- GetLargePageMinimumP largePageMinimum = (GetLargePageMinimumP) +- GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetLargePageMinimum"); +- if (!largePageMinimum) ++ const ++ Func_GetLargePageMinimum fn = ++ (Func_GetLargePageMinimum) MY_CAST_FUNC GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), ++ "GetLargePageMinimum"); ++ if (!fn) + return; +- size = largePageMinimum(); ++ size = fn(); + if (size == 0 || (size & (size - 1)) != 0) + return; + g_LargePageSize = size; + #endif + } + ++#endif // Z7_LARGE_PAGES + + void *BigAlloc(size_t size) + { + if (size == 0) + return NULL; + +- PRINT_ALLOC("Alloc-Big", g_allocCountBig, size, NULL); +- +- #ifdef _7ZIP_LARGE_PAGES ++ PRINT_ALLOC("Alloc-Big", g_allocCountBig, size, NULL) ++ ++ #ifdef Z7_LARGE_PAGES + { + SIZE_T ps = g_LargePageSize; + if (ps != 0 && ps <= (1 << 30) && size > (ps / 2)) +@@ -220,38 +292,38 @@ void *BigAlloc(size_t size) + size2 = (size + ps) & ~ps; + if (size2 >= size) + { +- void *res = VirtualAlloc(NULL, size2, MEM_COMMIT | MY__MEM_LARGE_PAGES, PAGE_READWRITE); +- if (res) +- return res; ++ void *p = VirtualAlloc(NULL, size2, MEM_COMMIT | MY__MEM_LARGE_PAGES, PAGE_READWRITE); ++ if (p) ++ { ++ PRINT_ALLOC("Alloc-BM ", g_allocCountMid, size2, p) ++ return p; ++ } + } + } + } + #endif + +- return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE); ++ return MidAlloc(size); + } + + void BigFree(void *address) + { +- PRINT_FREE("Free-Big", g_allocCountBig, address); +- +- if (!address) +- return; +- VirtualFree(address, 0, MEM_RELEASE); ++ PRINT_FREE("Free-Big", g_allocCountBig, address) ++ MidFree(address); + } + +-#endif ++#endif // _WIN32 + + +-static void *SzAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p); return MyAlloc(size); } +-static void SzFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p); MyFree(address); } ++static void *SzAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p) return MyAlloc(size); } ++static void SzFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p) MyFree(address); } + const ISzAlloc g_Alloc = { SzAlloc, SzFree }; + + #ifdef _WIN32 +-static void *SzMidAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p); return MidAlloc(size); } +-static void SzMidFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p); MidFree(address); } +-static void *SzBigAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p); return BigAlloc(size); } +-static void SzBigFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p); BigFree(address); } ++static void *SzMidAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p) return MidAlloc(size); } ++static void SzMidFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p) MidFree(address); } ++static void *SzBigAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p) return BigAlloc(size); } ++static void SzBigFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p) BigFree(address); } + const ISzAlloc g_MidAlloc = { SzMidAlloc, SzMidFree }; + const ISzAlloc g_BigAlloc = { SzBigAlloc, SzBigFree }; + #endif +@@ -334,7 +406,7 @@ static void *SzAlignedAlloc(ISzAllocPtr pp, size_t size) + void *p; + void *pAligned; + size_t newSize; +- UNUSED_VAR(pp); ++ UNUSED_VAR(pp) + + /* also we can allocate additional dummy ALLOC_ALIGN_SIZE bytes after aligned + block to prevent cache line sharing with another allocated blocks */ +@@ -362,7 +434,7 @@ static void *SzAlignedAlloc(ISzAllocPtr pp, size_t size) + #else + + void *p; +- UNUSED_VAR(pp); ++ UNUSED_VAR(pp) + if (posix_memalign(&p, ALLOC_ALIGN_SIZE, size)) + return NULL; + +@@ -377,7 +449,7 @@ static void *SzAlignedAlloc(ISzAllocPtr pp, size_t size) + + static void SzAlignedFree(ISzAllocPtr pp, void *address) + { +- UNUSED_VAR(pp); ++ UNUSED_VAR(pp) + #ifndef USE_posix_memalign + if (address) + MyFree(((void **)address)[-1]); +@@ -401,7 +473,7 @@ const ISzAlloc g_AlignedAlloc = { SzAlignedAlloc, SzAlignedFree }; + + static void *AlignOffsetAlloc_Alloc(ISzAllocPtr pp, size_t size) + { +- CAlignOffsetAlloc *p = CONTAINER_FROM_VTBL(pp, CAlignOffsetAlloc, vt); ++ const CAlignOffsetAlloc *p = Z7_CONTAINER_FROM_VTBL_CONST(pp, CAlignOffsetAlloc, vt); + void *adr; + void *pAligned; + size_t newSize; +@@ -447,7 +519,7 @@ static void AlignOffsetAlloc_Free(ISzAllocPtr pp, void *address) + { + if (address) + { +- CAlignOffsetAlloc *p = CONTAINER_FROM_VTBL(pp, CAlignOffsetAlloc, vt); ++ const CAlignOffsetAlloc *p = Z7_CONTAINER_FROM_VTBL_CONST(pp, CAlignOffsetAlloc, vt); + PrintLn(); + Print("- Aligned Free: "); + PrintLn(); +diff --git a/src/lzma/Alloc.h b/src/lzma/Alloc.h +index 3be2041eb..fac5b62fb 100644 +--- a/src/lzma/Alloc.h ++++ b/src/lzma/Alloc.h +@@ -1,19 +1,32 @@ + /* Alloc.h -- Memory allocation functions +-2021-07-13 : Igor Pavlov : Public domain */ ++2023-03-04 : Igor Pavlov : Public domain */ + +-#ifndef __COMMON_ALLOC_H +-#define __COMMON_ALLOC_H ++#ifndef ZIP7_INC_ALLOC_H ++#define ZIP7_INC_ALLOC_H + + #include "7zTypes.h" + + EXTERN_C_BEGIN + ++/* ++ MyFree(NULL) : is allowed, as free(NULL) ++ MyAlloc(0) : returns NULL : but malloc(0) is allowed to return NULL or non_NULL ++ MyRealloc(NULL, 0) : returns NULL : but realloc(NULL, 0) is allowed to return NULL or non_NULL ++MyRealloc() is similar to realloc() for the following cases: ++ MyRealloc(non_NULL, 0) : returns NULL and always calls MyFree(ptr) ++ MyRealloc(NULL, non_ZERO) : returns NULL, if allocation failed ++ MyRealloc(non_NULL, non_ZERO) : returns NULL, if reallocation failed ++*/ ++ + void *MyAlloc(size_t size); + void MyFree(void *address); ++void *MyRealloc(void *address, size_t size); + + #ifdef _WIN32 + ++#ifdef Z7_LARGE_PAGES + void SetLargePageSize(void); ++#endif + + void *MidAlloc(size_t size); + void MidFree(void *address); +diff --git a/src/lzma/Bcj2.c b/src/lzma/Bcj2.c +index c7b956708..7cb57ad62 100644 +--- a/src/lzma/Bcj2.c ++++ b/src/lzma/Bcj2.c +@@ -1,29 +1,24 @@ + /* Bcj2.c -- BCJ2 Decoder (Converter for x86 code) +-2021-02-09 : Igor Pavlov : Public domain */ ++2023-03-01 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + + #include "Bcj2.h" + #include "CpuArch.h" + +-#define CProb UInt16 +- + #define kTopValue ((UInt32)1 << 24) +-#define kNumModelBits 11 +-#define kBitModelTotal (1 << kNumModelBits) ++#define kNumBitModelTotalBits 11 ++#define kBitModelTotal (1 << kNumBitModelTotalBits) + #define kNumMoveBits 5 + +-#define _IF_BIT_0 ttt = *prob; bound = (p->range >> kNumModelBits) * ttt; if (p->code < bound) +-#define _UPDATE_0 p->range = bound; *prob = (CProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); +-#define _UPDATE_1 p->range -= bound; p->code -= bound; *prob = (CProb)(ttt - (ttt >> kNumMoveBits)); ++// UInt32 bcj2_stats[256 + 2][2]; + + void Bcj2Dec_Init(CBcj2Dec *p) + { + unsigned i; +- +- p->state = BCJ2_DEC_STATE_OK; ++ p->state = BCJ2_STREAM_RC; // BCJ2_DEC_STATE_OK; + p->ip = 0; +- p->temp[3] = 0; ++ p->temp = 0; + p->range = 0; + p->code = 0; + for (i = 0; i < sizeof(p->probs) / sizeof(p->probs[0]); i++) +@@ -32,217 +27,248 @@ void Bcj2Dec_Init(CBcj2Dec *p) + + SRes Bcj2Dec_Decode(CBcj2Dec *p) + { ++ UInt32 v = p->temp; ++ // const Byte *src; + if (p->range <= 5) + { +- p->state = BCJ2_DEC_STATE_OK; ++ UInt32 code = p->code; ++ p->state = BCJ2_DEC_STATE_ERROR; /* for case if we return SZ_ERROR_DATA; */ + for (; p->range != 5; p->range++) + { +- if (p->range == 1 && p->code != 0) ++ if (p->range == 1 && code != 0) + return SZ_ERROR_DATA; +- + if (p->bufs[BCJ2_STREAM_RC] == p->lims[BCJ2_STREAM_RC]) + { + p->state = BCJ2_STREAM_RC; + return SZ_OK; + } +- +- p->code = (p->code << 8) | *(p->bufs[BCJ2_STREAM_RC])++; ++ code = (code << 8) | *(p->bufs[BCJ2_STREAM_RC])++; ++ p->code = code; + } +- +- if (p->code == 0xFFFFFFFF) ++ if (code == 0xffffffff) + return SZ_ERROR_DATA; +- +- p->range = 0xFFFFFFFF; ++ p->range = 0xffffffff; + } +- else if (p->state >= BCJ2_DEC_STATE_ORIG_0) ++ // else + { +- while (p->state <= BCJ2_DEC_STATE_ORIG_3) ++ unsigned state = p->state; ++ // we check BCJ2_IS_32BIT_STREAM() here instead of check in the main loop ++ if (BCJ2_IS_32BIT_STREAM(state)) + { +- Byte *dest = p->dest; +- if (dest == p->destLim) ++ const Byte *cur = p->bufs[state]; ++ if (cur == p->lims[state]) + return SZ_OK; +- *dest = p->temp[(size_t)p->state - BCJ2_DEC_STATE_ORIG_0]; +- p->state++; +- p->dest = dest + 1; ++ p->bufs[state] = cur + 4; ++ { ++ const UInt32 ip = p->ip + 4; ++ v = GetBe32a(cur) - ip; ++ p->ip = ip; ++ } ++ state = BCJ2_DEC_STATE_ORIG_0; + } +- } +- +- /* +- if (BCJ2_IS_32BIT_STREAM(p->state)) +- { +- const Byte *cur = p->bufs[p->state]; +- if (cur == p->lims[p->state]) +- return SZ_OK; +- p->bufs[p->state] = cur + 4; +- ++ if ((unsigned)(state - BCJ2_DEC_STATE_ORIG_0) < 4) + { +- UInt32 val; +- Byte *dest; +- SizeT rem; +- +- p->ip += 4; +- val = GetBe32(cur) - p->ip; +- dest = p->dest; +- rem = p->destLim - dest; +- if (rem < 4) ++ Byte *dest = p->dest; ++ for (;;) + { +- SizeT i; +- SetUi32(p->temp, val); +- for (i = 0; i < rem; i++) +- dest[i] = p->temp[i]; +- p->dest = dest + rem; +- p->state = BCJ2_DEC_STATE_ORIG_0 + (unsigned)rem; +- return SZ_OK; ++ if (dest == p->destLim) ++ { ++ p->state = state; ++ p->temp = v; ++ return SZ_OK; ++ } ++ *dest++ = (Byte)v; ++ p->dest = dest; ++ if (++state == BCJ2_DEC_STATE_ORIG_3 + 1) ++ break; ++ v >>= 8; + } +- SetUi32(dest, val); +- p->temp[3] = (Byte)(val >> 24); +- p->dest = dest + 4; +- p->state = BCJ2_DEC_STATE_OK; + } + } +- */ + ++ // src = p->bufs[BCJ2_STREAM_MAIN]; + for (;;) + { ++ /* + if (BCJ2_IS_32BIT_STREAM(p->state)) + p->state = BCJ2_DEC_STATE_OK; + else ++ */ + { + if (p->range < kTopValue) + { + if (p->bufs[BCJ2_STREAM_RC] == p->lims[BCJ2_STREAM_RC]) + { + p->state = BCJ2_STREAM_RC; ++ p->temp = v; + return SZ_OK; + } + p->range <<= 8; + p->code = (p->code << 8) | *(p->bufs[BCJ2_STREAM_RC])++; + } +- + { + const Byte *src = p->bufs[BCJ2_STREAM_MAIN]; + const Byte *srcLim; +- Byte *dest; +- SizeT num = (SizeT)(p->lims[BCJ2_STREAM_MAIN] - src); +- +- if (num == 0) ++ Byte *dest = p->dest; + { +- p->state = BCJ2_STREAM_MAIN; +- return SZ_OK; ++ const SizeT rem = (SizeT)(p->lims[BCJ2_STREAM_MAIN] - src); ++ SizeT num = (SizeT)(p->destLim - dest); ++ if (num >= rem) ++ num = rem; ++ #define NUM_ITERS 4 ++ #if (NUM_ITERS & (NUM_ITERS - 1)) == 0 ++ num &= ~((SizeT)NUM_ITERS - 1); // if (NUM_ITERS == (1 << x)) ++ #else ++ num -= num % NUM_ITERS; // if (NUM_ITERS != (1 << x)) ++ #endif ++ srcLim = src + num; + } +- +- dest = p->dest; +- if (num > (SizeT)(p->destLim - dest)) ++ ++ #define NUM_SHIFT_BITS 24 ++ #define ONE_ITER(indx) { \ ++ const unsigned b = src[indx]; \ ++ *dest++ = (Byte)b; \ ++ v = (v << NUM_SHIFT_BITS) | b; \ ++ if (((b + (0x100 - 0xe8)) & 0xfe) == 0) break; \ ++ if (((v - (((UInt32)0x0f << (NUM_SHIFT_BITS)) + 0x80)) & \ ++ ((((UInt32)1 << (4 + NUM_SHIFT_BITS)) - 0x1) << 4)) == 0) break; \ ++ /* ++dest */; /* v = b; */ } ++ ++ if (src != srcLim) ++ for (;;) + { +- num = (SizeT)(p->destLim - dest); +- if (num == 0) +- { +- p->state = BCJ2_DEC_STATE_ORIG; +- return SZ_OK; +- } ++ /* The dependency chain of 2-cycle for (v) calculation is not big problem here. ++ But we can remove dependency chain with v = b in the end of loop. */ ++ ONE_ITER(0) ++ #if (NUM_ITERS > 1) ++ ONE_ITER(1) ++ #if (NUM_ITERS > 2) ++ ONE_ITER(2) ++ #if (NUM_ITERS > 3) ++ ONE_ITER(3) ++ #if (NUM_ITERS > 4) ++ ONE_ITER(4) ++ #if (NUM_ITERS > 5) ++ ONE_ITER(5) ++ #if (NUM_ITERS > 6) ++ ONE_ITER(6) ++ #if (NUM_ITERS > 7) ++ ONE_ITER(7) ++ #endif ++ #endif ++ #endif ++ #endif ++ #endif ++ #endif ++ #endif ++ ++ src += NUM_ITERS; ++ if (src == srcLim) ++ break; + } +- +- srcLim = src + num; + +- if (p->temp[3] == 0x0F && (src[0] & 0xF0) == 0x80) +- *dest = src[0]; +- else for (;;) ++ if (src == srcLim) ++ #if (NUM_ITERS > 1) ++ for (;;) ++ #endif + { +- Byte b = *src; +- *dest = b; +- if (b != 0x0F) ++ #if (NUM_ITERS > 1) ++ if (src == p->lims[BCJ2_STREAM_MAIN] || dest == p->destLim) ++ #endif + { +- if ((b & 0xFE) == 0xE8) +- break; +- dest++; +- if (++src != srcLim) +- continue; +- break; ++ const SizeT num = (SizeT)(src - p->bufs[BCJ2_STREAM_MAIN]); ++ p->bufs[BCJ2_STREAM_MAIN] = src; ++ p->dest = dest; ++ p->ip += (UInt32)num; ++ /* state BCJ2_STREAM_MAIN has more priority than BCJ2_STATE_ORIG */ ++ p->state = ++ src == p->lims[BCJ2_STREAM_MAIN] ? ++ (unsigned)BCJ2_STREAM_MAIN : ++ (unsigned)BCJ2_DEC_STATE_ORIG; ++ p->temp = v; ++ return SZ_OK; + } +- dest++; +- if (++src == srcLim) +- break; +- if ((*src & 0xF0) != 0x80) +- continue; +- *dest = *src; +- break; ++ #if (NUM_ITERS > 1) ++ ONE_ITER(0) ++ src++; ++ #endif + } +- +- num = (SizeT)(src - p->bufs[BCJ2_STREAM_MAIN]); +- +- if (src == srcLim) ++ + { +- p->temp[3] = src[-1]; +- p->bufs[BCJ2_STREAM_MAIN] = src; ++ const SizeT num = (SizeT)(dest - p->dest); ++ p->dest = dest; // p->dest += num; ++ p->bufs[BCJ2_STREAM_MAIN] += num; // = src; + p->ip += (UInt32)num; +- p->dest += num; +- p->state = +- p->bufs[BCJ2_STREAM_MAIN] == +- p->lims[BCJ2_STREAM_MAIN] ? +- (unsigned)BCJ2_STREAM_MAIN : +- (unsigned)BCJ2_DEC_STATE_ORIG; +- return SZ_OK; + } +- + { + UInt32 bound, ttt; +- CProb *prob; +- Byte b = src[0]; +- Byte prev = (Byte)(num == 0 ? p->temp[3] : src[-1]); +- +- p->temp[3] = b; +- p->bufs[BCJ2_STREAM_MAIN] = src + 1; +- num++; +- p->ip += (UInt32)num; +- p->dest += num; +- +- prob = p->probs + (unsigned)(b == 0xE8 ? 2 + (unsigned)prev : (b == 0xE9 ? 1 : 0)); +- +- _IF_BIT_0 ++ CBcj2Prob *prob; // unsigned index; ++ /* ++ prob = p->probs + (unsigned)((Byte)v == 0xe8 ? ++ 2 + (Byte)(v >> 8) : ++ ((v >> 5) & 1)); // ((Byte)v < 0xe8 ? 0 : 1)); ++ */ + { +- _UPDATE_0 ++ const unsigned c = ((v + 0x17) >> 6) & 1; ++ prob = p->probs + (unsigned) ++ (((0 - c) & (Byte)(v >> NUM_SHIFT_BITS)) + c + ((v >> 5) & 1)); ++ // (Byte) ++ // 8x->0 : e9->1 : xxe8->xx+2 ++ // 8x->0x100 : e9->0x101 : xxe8->xx ++ // (((0x100 - (e & ~v)) & (0x100 | (v >> 8))) + (e & v)); ++ // (((0x101 + (~e | v)) & (0x100 | (v >> 8))) + (e & v)); ++ } ++ ttt = *prob; ++ bound = (p->range >> kNumBitModelTotalBits) * ttt; ++ if (p->code < bound) ++ { ++ // bcj2_stats[prob - p->probs][0]++; ++ p->range = bound; ++ *prob = (CBcj2Prob)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); + continue; + } +- _UPDATE_1 +- ++ { ++ // bcj2_stats[prob - p->probs][1]++; ++ p->range -= bound; ++ p->code -= bound; ++ *prob = (CBcj2Prob)(ttt - (ttt >> kNumMoveBits)); ++ } + } + } + } +- + { +- UInt32 val; +- unsigned cj = (p->temp[3] == 0xE8) ? BCJ2_STREAM_CALL : BCJ2_STREAM_JUMP; ++ /* (v == 0xe8 ? 0 : 1) uses setcc instruction with additional zero register usage in x64 MSVC. */ ++ // const unsigned cj = ((Byte)v == 0xe8) ? BCJ2_STREAM_CALL : BCJ2_STREAM_JUMP; ++ const unsigned cj = (((v + 0x57) >> 6) & 1) + BCJ2_STREAM_CALL; + const Byte *cur = p->bufs[cj]; + Byte *dest; + SizeT rem; +- + if (cur == p->lims[cj]) + { + p->state = cj; + break; + } +- +- val = GetBe32(cur); ++ v = GetBe32a(cur); + p->bufs[cj] = cur + 4; +- +- p->ip += 4; +- val -= p->ip; ++ { ++ const UInt32 ip = p->ip + 4; ++ v -= ip; ++ p->ip = ip; ++ } + dest = p->dest; + rem = (SizeT)(p->destLim - dest); +- + if (rem < 4) + { +- p->temp[0] = (Byte)val; if (rem > 0) dest[0] = (Byte)val; val >>= 8; +- p->temp[1] = (Byte)val; if (rem > 1) dest[1] = (Byte)val; val >>= 8; +- p->temp[2] = (Byte)val; if (rem > 2) dest[2] = (Byte)val; val >>= 8; +- p->temp[3] = (Byte)val; ++ if ((unsigned)rem > 0) { dest[0] = (Byte)v; v >>= 8; ++ if ((unsigned)rem > 1) { dest[1] = (Byte)v; v >>= 8; ++ if ((unsigned)rem > 2) { dest[2] = (Byte)v; v >>= 8; }}} ++ p->temp = v; + p->dest = dest + rem; + p->state = BCJ2_DEC_STATE_ORIG_0 + (unsigned)rem; + break; + } +- +- SetUi32(dest, val); +- p->temp[3] = (Byte)(val >> 24); ++ SetUi32(dest, v) ++ v >>= 24; + p->dest = dest + 4; + } + } +@@ -252,6 +278,13 @@ SRes Bcj2Dec_Decode(CBcj2Dec *p) + p->range <<= 8; + p->code = (p->code << 8) | *(p->bufs[BCJ2_STREAM_RC])++; + } +- + return SZ_OK; + } ++ ++#undef NUM_ITERS ++#undef ONE_ITER ++#undef NUM_SHIFT_BITS ++#undef kTopValue ++#undef kNumBitModelTotalBits ++#undef kBitModelTotal ++#undef kNumMoveBits +diff --git a/src/lzma/Bcj2.h b/src/lzma/Bcj2.h +index 8824080ac..4575545b6 100644 +--- a/src/lzma/Bcj2.h ++++ b/src/lzma/Bcj2.h +@@ -1,8 +1,8 @@ +-/* Bcj2.h -- BCJ2 Converter for x86 code +-2014-11-10 : Igor Pavlov : Public domain */ ++/* Bcj2.h -- BCJ2 converter for x86 code (Branch CALL/JUMP variant2) ++2023-03-02 : Igor Pavlov : Public domain */ + +-#ifndef __BCJ2_H +-#define __BCJ2_H ++#ifndef ZIP7_INC_BCJ2_H ++#define ZIP7_INC_BCJ2_H + + #include "7zTypes.h" + +@@ -26,37 +26,68 @@ enum + BCJ2_DEC_STATE_ORIG_3, + + BCJ2_DEC_STATE_ORIG, +- BCJ2_DEC_STATE_OK ++ BCJ2_DEC_STATE_ERROR /* after detected data error */ + }; + + enum + { + BCJ2_ENC_STATE_ORIG = BCJ2_NUM_STREAMS, +- BCJ2_ENC_STATE_OK ++ BCJ2_ENC_STATE_FINISHED /* it's state after fully encoded stream */ + }; + + +-#define BCJ2_IS_32BIT_STREAM(s) ((s) == BCJ2_STREAM_CALL || (s) == BCJ2_STREAM_JUMP) ++/* #define BCJ2_IS_32BIT_STREAM(s) ((s) == BCJ2_STREAM_CALL || (s) == BCJ2_STREAM_JUMP) */ ++#define BCJ2_IS_32BIT_STREAM(s) ((unsigned)((unsigned)(s) - (unsigned)BCJ2_STREAM_CALL) < 2) + + /* + CBcj2Dec / CBcj2Enc + bufs sizes: + BUF_SIZE(n) = lims[n] - bufs[n] +-bufs sizes for BCJ2_STREAM_CALL and BCJ2_STREAM_JUMP must be mutliply of 4: ++bufs sizes for BCJ2_STREAM_CALL and BCJ2_STREAM_JUMP must be multiply of 4: + (BUF_SIZE(BCJ2_STREAM_CALL) & 3) == 0 + (BUF_SIZE(BCJ2_STREAM_JUMP) & 3) == 0 + */ + ++// typedef UInt32 CBcj2Prob; ++typedef UInt16 CBcj2Prob; ++ ++/* ++BCJ2 encoder / decoder internal requirements: ++ - If last bytes of stream contain marker (e8/e8/0f8x), then ++ there is also encoded symbol (0 : no conversion) in RC stream. ++ - One case of overlapped instructions is supported, ++ if last byte of converted instruction is (0f) and next byte is (8x): ++ marker [xx xx xx 0f] 8x ++ then the pair (0f 8x) is treated as marker. ++*/ ++ ++/* ---------- BCJ2 Decoder ---------- */ ++ + /* + CBcj2Dec: +-dest is allowed to overlap with bufs[BCJ2_STREAM_MAIN], with the following conditions: ++(dest) is allowed to overlap with bufs[BCJ2_STREAM_MAIN], with the following conditions: + bufs[BCJ2_STREAM_MAIN] >= dest && +- bufs[BCJ2_STREAM_MAIN] - dest >= tempReserv + ++ bufs[BCJ2_STREAM_MAIN] - dest >= + BUF_SIZE(BCJ2_STREAM_CALL) + + BUF_SIZE(BCJ2_STREAM_JUMP) +- tempReserv = 0 : for first call of Bcj2Dec_Decode +- tempReserv = 4 : for any other calls of Bcj2Dec_Decode +- overlap with offset = 1 is not allowed ++ reserve = bufs[BCJ2_STREAM_MAIN] - dest - ++ ( BUF_SIZE(BCJ2_STREAM_CALL) + ++ BUF_SIZE(BCJ2_STREAM_JUMP) ) ++ and additional conditions: ++ if (it's first call of Bcj2Dec_Decode() after Bcj2Dec_Init()) ++ { ++ (reserve != 1) : if (ver < v23.00) ++ } ++ else // if there are more than one calls of Bcj2Dec_Decode() after Bcj2Dec_Init()) ++ { ++ (reserve >= 6) : if (ver < v23.00) ++ (reserve >= 4) : if (ver >= v23.00) ++ We need that (reserve) because after first call of Bcj2Dec_Decode(), ++ CBcj2Dec::temp can contain up to 4 bytes for writing to (dest). ++ } ++ (reserve == 0) is allowed, if we decode full stream via single call of Bcj2Dec_Decode(). ++ (reserve == 0) also is allowed in case of multi-call, if we use fixed buffers, ++ and (reserve) is calculated from full (final) sizes of all streams before first call. + */ + + typedef struct +@@ -68,21 +99,65 @@ typedef struct + + unsigned state; /* BCJ2_STREAM_MAIN has more priority than BCJ2_STATE_ORIG */ + +- UInt32 ip; +- Byte temp[4]; ++ UInt32 ip; /* property of starting base for decoding */ ++ UInt32 temp; /* Byte temp[4]; */ + UInt32 range; + UInt32 code; +- UInt16 probs[2 + 256]; ++ CBcj2Prob probs[2 + 256]; + } CBcj2Dec; + ++ ++/* Note: ++ Bcj2Dec_Init() sets (CBcj2Dec::ip = 0) ++ if (ip != 0) property is required, the caller must set CBcj2Dec::ip after Bcj2Dec_Init() ++*/ + void Bcj2Dec_Init(CBcj2Dec *p); + +-/* Returns: SZ_OK or SZ_ERROR_DATA */ ++ ++/* Bcj2Dec_Decode(): ++ returns: ++ SZ_OK ++ SZ_ERROR_DATA : if data in 5 starting bytes of BCJ2_STREAM_RC stream are not correct ++*/ + SRes Bcj2Dec_Decode(CBcj2Dec *p); + +-#define Bcj2Dec_IsFinished(_p_) ((_p_)->code == 0) ++/* To check that decoding was finished you can compare ++ sizes of processed streams with sizes known from another sources. ++ You must do at least one mandatory check from the two following options: ++ - the check for size of processed output (ORIG) stream. ++ - the check for size of processed input (MAIN) stream. ++ additional optional checks: ++ - the checks for processed sizes of all input streams (MAIN, CALL, JUMP, RC) ++ - the checks Bcj2Dec_IsMaybeFinished*() ++ also before actual decoding you can check that the ++ following condition is met for stream sizes: ++ ( size(ORIG) == size(MAIN) + size(CALL) + size(JUMP) ) ++*/ + ++/* (state == BCJ2_STREAM_MAIN) means that decoder is ready for ++ additional input data in BCJ2_STREAM_MAIN stream. ++ Note that (state == BCJ2_STREAM_MAIN) is allowed for non-finished decoding. ++*/ ++#define Bcj2Dec_IsMaybeFinished_state_MAIN(_p_) ((_p_)->state == BCJ2_STREAM_MAIN) + ++/* if the stream decoding was finished correctly, then range decoder ++ part of CBcj2Dec also was finished, and then (CBcj2Dec::code == 0). ++ Note that (CBcj2Dec::code == 0) is allowed for non-finished decoding. ++*/ ++#define Bcj2Dec_IsMaybeFinished_code(_p_) ((_p_)->code == 0) ++ ++/* use Bcj2Dec_IsMaybeFinished() only as additional check ++ after at least one mandatory check from the two following options: ++ - the check for size of processed output (ORIG) stream. ++ - the check for size of processed input (MAIN) stream. ++*/ ++#define Bcj2Dec_IsMaybeFinished(_p_) ( \ ++ Bcj2Dec_IsMaybeFinished_state_MAIN(_p_) && \ ++ Bcj2Dec_IsMaybeFinished_code(_p_)) ++ ++ ++ ++/* ---------- BCJ2 Encoder ---------- */ + + typedef enum + { +@@ -91,6 +166,91 @@ typedef enum + BCJ2_ENC_FINISH_MODE_END_STREAM + } EBcj2Enc_FinishMode; + ++/* ++ BCJ2_ENC_FINISH_MODE_CONTINUE: ++ process non finished encoding. ++ It notifies the encoder that additional further calls ++ can provide more input data (src) than provided by current call. ++ In that case the CBcj2Enc encoder still can move (src) pointer ++ up to (srcLim), but CBcj2Enc encoder can store some of the last ++ processed bytes (up to 4 bytes) from src to internal CBcj2Enc::temp[] buffer. ++ at return: ++ (CBcj2Enc::src will point to position that includes ++ processed data and data copied to (temp[]) buffer) ++ That data from (temp[]) buffer will be used in further calls. ++ ++ BCJ2_ENC_FINISH_MODE_END_BLOCK: ++ finish encoding of current block (ended at srcLim) without RC flushing. ++ at return: if (CBcj2Enc::state == BCJ2_ENC_STATE_ORIG) && ++ CBcj2Enc::src == CBcj2Enc::srcLim) ++ : it shows that block encoding was finished. And the encoder is ++ ready for new (src) data or for stream finish operation. ++ finished block means ++ { ++ CBcj2Enc has completed block encoding up to (srcLim). ++ (1 + 4 bytes) or (2 + 4 bytes) CALL/JUMP cortages will ++ not cross block boundary at (srcLim). ++ temporary CBcj2Enc buffer for (ORIG) src data is empty. ++ 3 output uncompressed streams (MAIN, CALL, JUMP) were flushed. ++ RC stream was not flushed. And RC stream will cross block boundary. ++ } ++ Note: some possible implementation of BCJ2 encoder could ++ write branch marker (e8/e8/0f8x) in one call of Bcj2Enc_Encode(), ++ and it could calculate symbol for RC in another call of Bcj2Enc_Encode(). ++ BCJ2 encoder uses ip/fileIp/fileSize/relatLimit values to calculate RC symbol. ++ And these CBcj2Enc variables can have different values in different Bcj2Enc_Encode() calls. ++ So caller must finish each block with BCJ2_ENC_FINISH_MODE_END_BLOCK ++ to ensure that RC symbol is calculated and written in proper block. ++ ++ BCJ2_ENC_FINISH_MODE_END_STREAM ++ finish encoding of stream (ended at srcLim) fully including RC flushing. ++ at return: if (CBcj2Enc::state == BCJ2_ENC_STATE_FINISHED) ++ : it shows that stream encoding was finished fully, ++ and all output streams were flushed fully. ++ also Bcj2Enc_IsFinished() can be called. ++*/ ++ ++ ++/* ++ 32-bit relative offset in JUMP/CALL commands is ++ - (mod 4 GiB) for 32-bit x86 code ++ - signed Int32 for 64-bit x86-64 code ++ BCJ2 encoder also does internal relative to absolute address conversions. ++ And there are 2 possible ways to do it: ++ before v23: we used 32-bit variables and (mod 4 GiB) conversion ++ since v23: we use 64-bit variables and (signed Int32 offset) conversion. ++ The absolute address condition for conversion in v23: ++ ((UInt64)((Int64)ip64 - (Int64)fileIp64 + 5 + (Int32)offset) < (UInt64)fileSize64) ++ note that if (fileSize64 > 2 GiB). there is difference between ++ old (mod 4 GiB) way (v22) and new (signed Int32 offset) way (v23). ++ And new (v23) way is more suitable to encode 64-bit x86-64 code for (fileSize64 > 2 GiB) cases. ++*/ ++ ++/* ++// for old (v22) way for conversion: ++typedef UInt32 CBcj2Enc_ip_unsigned; ++typedef Int32 CBcj2Enc_ip_signed; ++#define BCJ2_ENC_FileSize_MAX ((UInt32)1 << 31) ++*/ ++typedef UInt64 CBcj2Enc_ip_unsigned; ++typedef Int64 CBcj2Enc_ip_signed; ++ ++/* maximum size of file that can be used for conversion condition */ ++#define BCJ2_ENC_FileSize_MAX ((CBcj2Enc_ip_unsigned)0 - 2) ++ ++/* default value of fileSize64_minus1 variable that means ++ that absolute address limitation will not be used */ ++#define BCJ2_ENC_FileSizeField_UNLIMITED ((CBcj2Enc_ip_unsigned)0 - 1) ++ ++/* calculate value that later can be set to CBcj2Enc::fileSize64_minus1 */ ++#define BCJ2_ENC_GET_FileSizeField_VAL_FROM_FileSize(fileSize) \ ++ ((CBcj2Enc_ip_unsigned)(fileSize) - 1) ++ ++/* set CBcj2Enc::fileSize64_minus1 variable from size of file */ ++#define Bcj2Enc_SET_FileSize(p, fileSize) \ ++ (p)->fileSize64_minus1 = BCJ2_ENC_GET_FileSizeField_VAL_FROM_FileSize(fileSize); ++ ++ + typedef struct + { + Byte *bufs[BCJ2_NUM_STREAMS]; +@@ -101,45 +261,71 @@ typedef struct + unsigned state; + EBcj2Enc_FinishMode finishMode; + +- Byte prevByte; ++ Byte context; ++ Byte flushRem; ++ Byte isFlushState; + + Byte cache; + UInt32 range; + UInt64 low; + UInt64 cacheSize; ++ ++ // UInt32 context; // for marker version, it can include marker flag. + +- UInt32 ip; +- +- /* 32-bit ralative offset in JUMP/CALL commands is +- - (mod 4 GB) in 32-bit mode +- - signed Int32 in 64-bit mode +- We use (mod 4 GB) check for fileSize. +- Use fileSize up to 2 GB, if you want to support 32-bit and 64-bit code conversion. */ +- UInt32 fileIp; +- UInt32 fileSize; /* (fileSize <= ((UInt32)1 << 31)), 0 means no_limit */ +- UInt32 relatLimit; /* (relatLimit <= ((UInt32)1 << 31)), 0 means desable_conversion */ ++ /* (ip64) and (fileIp64) correspond to virtual source stream position ++ that doesn't include data in temp[] */ ++ CBcj2Enc_ip_unsigned ip64; /* current (ip) position */ ++ CBcj2Enc_ip_unsigned fileIp64; /* start (ip) position of current file */ ++ CBcj2Enc_ip_unsigned fileSize64_minus1; /* size of current file (for conversion limitation) */ ++ UInt32 relatLimit; /* (relatLimit <= ((UInt32)1 << 31)) : 0 means disable_conversion */ ++ // UInt32 relatExcludeBits; + + UInt32 tempTarget; +- unsigned tempPos; +- Byte temp[4 * 2]; +- +- unsigned flushPos; +- +- UInt16 probs[2 + 256]; ++ unsigned tempPos; /* the number of bytes that were copied to temp[] buffer ++ (tempPos <= 4) outside of Bcj2Enc_Encode() */ ++ // Byte temp[4]; // for marker version ++ Byte temp[8]; ++ CBcj2Prob probs[2 + 256]; + } CBcj2Enc; + + void Bcj2Enc_Init(CBcj2Enc *p); +-void Bcj2Enc_Encode(CBcj2Enc *p); + +-#define Bcj2Enc_Get_InputData_Size(p) ((SizeT)((p)->srcLim - (p)->src) + (p)->tempPos) +-#define Bcj2Enc_IsFinished(p) ((p)->flushPos == 5) + ++/* ++Bcj2Enc_Encode(): at exit: ++ p->State < BCJ2_NUM_STREAMS : we need more buffer space for output stream ++ (bufs[p->State] == lims[p->State]) ++ p->State == BCJ2_ENC_STATE_ORIG : we need more data in input src stream ++ (src == srcLim) ++ p->State == BCJ2_ENC_STATE_FINISHED : after fully encoded stream ++*/ ++void Bcj2Enc_Encode(CBcj2Enc *p); + +-#define BCJ2_RELAT_LIMIT_NUM_BITS 26 +-#define BCJ2_RELAT_LIMIT ((UInt32)1 << BCJ2_RELAT_LIMIT_NUM_BITS) ++/* Bcj2Enc encoder can look ahead for up 4 bytes of source stream. ++ CBcj2Enc::tempPos : is the number of bytes that were copied from input stream to temp[] buffer. ++ (CBcj2Enc::src) after Bcj2Enc_Encode() is starting position after ++ fully processed data and after data copied to temp buffer. ++ So if the caller needs to get real number of fully processed input ++ bytes (without look ahead data in temp buffer), ++ the caller must subtruct (CBcj2Enc::tempPos) value from processed size ++ value that is calculated based on current (CBcj2Enc::src): ++ cur_processed_pos = Calc_Big_Processed_Pos(enc.src)) - ++ Bcj2Enc_Get_AvailInputSize_in_Temp(&enc); ++*/ ++/* get the size of input data that was stored in temp[] buffer: */ ++#define Bcj2Enc_Get_AvailInputSize_in_Temp(p) ((p)->tempPos) + +-/* limit for CBcj2Enc::fileSize variable */ +-#define BCJ2_FileSize_MAX ((UInt32)1 << 31) ++#define Bcj2Enc_IsFinished(p) ((p)->flushRem == 0) ++ ++/* Note : the decoder supports overlapping of marker (0f 80). ++ But we can eliminate such overlapping cases by setting ++ the limit for relative offset conversion as ++ CBcj2Enc::relatLimit <= (0x0f << 24) == (240 MiB) ++*/ ++/* default value for CBcj2Enc::relatLimit */ ++#define BCJ2_ENC_RELAT_LIMIT_DEFAULT ((UInt32)0x0f << 24) ++#define BCJ2_ENC_RELAT_LIMIT_MAX ((UInt32)1 << 31) ++// #define BCJ2_RELAT_EXCLUDE_NUM_BITS 5 + + EXTERN_C_END + +diff --git a/src/lzma/Bcj2Enc.c b/src/lzma/Bcj2Enc.c +index 666303b90..9654d1d81 100644 +--- a/src/lzma/Bcj2Enc.c ++++ b/src/lzma/Bcj2Enc.c +@@ -1,60 +1,62 @@ +-/* Bcj2Enc.c -- BCJ2 Encoder (Converter for x86 code) +-2021-02-09 : Igor Pavlov : Public domain */ ++/* Bcj2Enc.c -- BCJ2 Encoder converter for x86 code (Branch CALL/JUMP variant2) ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + + /* #define SHOW_STAT */ +- + #ifdef SHOW_STAT + #include +-#define PRF(x) x ++#define PRF2(s) printf("%s ip=%8x tempPos=%d src= %8x\n", s, (unsigned)p->ip64, p->tempPos, (unsigned)(p->srcLim - p->src)); + #else +-#define PRF(x) ++#define PRF2(s) + #endif + +-#include +- + #include "Bcj2.h" + #include "CpuArch.h" + +-#define CProb UInt16 +- + #define kTopValue ((UInt32)1 << 24) +-#define kNumModelBits 11 +-#define kBitModelTotal (1 << kNumModelBits) ++#define kNumBitModelTotalBits 11 ++#define kBitModelTotal (1 << kNumBitModelTotalBits) + #define kNumMoveBits 5 + + void Bcj2Enc_Init(CBcj2Enc *p) + { + unsigned i; +- +- p->state = BCJ2_ENC_STATE_OK; ++ p->state = BCJ2_ENC_STATE_ORIG; + p->finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE; +- +- p->prevByte = 0; +- ++ p->context = 0; ++ p->flushRem = 5; ++ p->isFlushState = 0; + p->cache = 0; +- p->range = 0xFFFFFFFF; ++ p->range = 0xffffffff; + p->low = 0; + p->cacheSize = 1; +- +- p->ip = 0; +- +- p->fileIp = 0; +- p->fileSize = 0; +- p->relatLimit = BCJ2_RELAT_LIMIT; +- ++ p->ip64 = 0; ++ p->fileIp64 = 0; ++ p->fileSize64_minus1 = BCJ2_ENC_FileSizeField_UNLIMITED; ++ p->relatLimit = BCJ2_ENC_RELAT_LIMIT_DEFAULT; ++ // p->relatExcludeBits = 0; + p->tempPos = 0; +- +- p->flushPos = 0; +- + for (i = 0; i < sizeof(p->probs) / sizeof(p->probs[0]); i++) + p->probs[i] = kBitModelTotal >> 1; + } + +-static BoolInt MY_FAST_CALL RangeEnc_ShiftLow(CBcj2Enc *p) ++// Z7_NO_INLINE ++Z7_FORCE_INLINE ++static BoolInt Bcj2_RangeEnc_ShiftLow(CBcj2Enc *p) + { +- if ((UInt32)p->low < (UInt32)0xFF000000 || (UInt32)(p->low >> 32) != 0) ++ const UInt32 low = (UInt32)p->low; ++ const unsigned high = (unsigned) ++ #if defined(Z7_MSC_VER_ORIGINAL) \ ++ && defined(MY_CPU_X86) \ ++ && defined(MY_CPU_LE) \ ++ && !defined(MY_CPU_64BIT) ++ // we try to rid of __aullshr() call in MSVS-x86 ++ (((const UInt32 *)&p->low)[1]); // [1] : for little-endian only ++ #else ++ (p->low >> 32); ++ #endif ++ if (low < (UInt32)0xff000000 || high != 0) + { + Byte *buf = p->bufs[BCJ2_STREAM_RC]; + do +@@ -65,247 +67,440 @@ static BoolInt MY_FAST_CALL RangeEnc_ShiftLow(CBcj2Enc *p) + p->bufs[BCJ2_STREAM_RC] = buf; + return True7z; + } +- *buf++ = (Byte)(p->cache + (Byte)(p->low >> 32)); +- p->cache = 0xFF; ++ *buf++ = (Byte)(p->cache + high); ++ p->cache = 0xff; + } + while (--p->cacheSize); + p->bufs[BCJ2_STREAM_RC] = buf; +- p->cache = (Byte)((UInt32)p->low >> 24); ++ p->cache = (Byte)(low >> 24); + } + p->cacheSize++; +- p->low = (UInt32)p->low << 8; ++ p->low = low << 8; + return False7z; + } + +-static void Bcj2Enc_Encode_2(CBcj2Enc *p) +-{ +- if (BCJ2_IS_32BIT_STREAM(p->state)) ++ ++/* ++We can use 2 alternative versions of code: ++1) non-marker version: ++ Byte CBcj2Enc::context ++ Byte temp[8]; ++ Last byte of marker (e8/e9/[0f]8x) can be written to temp[] buffer. ++ Encoder writes last byte of marker (e8/e9/[0f]8x) to dest, only in conjunction ++ with writing branch symbol to range coder in same Bcj2Enc_Encode_2() call. ++ ++2) marker version: ++ UInt32 CBcj2Enc::context ++ Byte CBcj2Enc::temp[4]; ++ MARKER_FLAG in CBcj2Enc::context shows that CBcj2Enc::context contains finded marker. ++ it's allowed that ++ one call of Bcj2Enc_Encode_2() writes last byte of marker (e8/e9/[0f]8x) to dest, ++ and another call of Bcj2Enc_Encode_2() does offset conversion. ++ So different values of (fileIp) and (fileSize) are possible ++ in these different Bcj2Enc_Encode_2() calls. ++ ++Also marker version requires additional if((v & MARKER_FLAG) == 0) check in main loop. ++So we use non-marker version. ++*/ ++ ++/* ++ Corner cases with overlap in multi-block. ++ before v23: there was one corner case, where converted instruction ++ could start in one sub-stream and finish in next sub-stream. ++ If multi-block (solid) encoding is used, ++ and BCJ2_ENC_FINISH_MODE_END_BLOCK is used for each sub-stream. ++ and (0f) is last byte of previous sub-stream ++ and (8x) is first byte of current sub-stream ++ then (0f 8x) pair is treated as marker by BCJ2 encoder and decoder. ++ BCJ2 encoder can converts 32-bit offset for that (0f 8x) cortage, ++ if that offset meets limit requirements. ++ If encoder allows 32-bit offset conversion for such overlap case, ++ then the data in 3 uncompressed BCJ2 streams for some sub-stream ++ can depend from data of previous sub-stream. ++ That corner case is not big problem, and it's rare case. ++ Since v23.00 we do additional check to prevent conversions in such overlap cases. ++*/ ++ ++/* ++ Bcj2Enc_Encode_2() output variables at exit: + { +- Byte *cur = p->bufs[p->state]; +- if (cur == p->lims[p->state]) +- return; +- SetBe32(cur, p->tempTarget); +- p->bufs[p->state] = cur + 4; ++ if (Bcj2Enc_Encode_2() exits with (p->state == BCJ2_ENC_STATE_ORIG)) ++ { ++ it means that encoder needs more input data. ++ if (p->srcLim == p->src) at exit, then ++ { ++ (p->finishMode != BCJ2_ENC_FINISH_MODE_END_STREAM) ++ all input data were read and processed, and we are ready for ++ new input data. ++ } ++ else ++ { ++ (p->srcLim != p->src) ++ (p->finishMode == BCJ2_ENC_FINISH_MODE_CONTINUE) ++ The encoder have found e8/e9/0f_8x marker, ++ and p->src points to last byte of that marker, ++ Bcj2Enc_Encode_2() needs more input data to get totally ++ 5 bytes (last byte of marker and 32-bit branch offset) ++ as continuous array starting from p->src. ++ (p->srcLim - p->src < 5) requirement is met after exit. ++ So non-processed resedue from p->src to p->srcLim is always less than 5 bytes. ++ } ++ } + } ++*/ + +- p->state = BCJ2_ENC_STATE_ORIG; +- +- for (;;) ++Z7_NO_INLINE ++static void Bcj2Enc_Encode_2(CBcj2Enc *p) ++{ ++ if (!p->isFlushState) + { +- if (p->range < kTopValue) ++ const Byte *src; ++ UInt32 v; + { +- if (RangeEnc_ShiftLow(p)) +- return; +- p->range <<= 8; ++ const unsigned state = p->state; ++ if (BCJ2_IS_32BIT_STREAM(state)) ++ { ++ Byte *cur = p->bufs[state]; ++ if (cur == p->lims[state]) ++ return; ++ SetBe32a(cur, p->tempTarget) ++ p->bufs[state] = cur + 4; ++ } + } ++ p->state = BCJ2_ENC_STATE_ORIG; // for main reason of exit ++ src = p->src; ++ v = p->context; ++ ++ // #define WRITE_CONTEXT p->context = v; // for marker version ++ #define WRITE_CONTEXT p->context = (Byte)v; ++ #define WRITE_CONTEXT_AND_SRC p->src = src; WRITE_CONTEXT + ++ for (;;) + { ++ // const Byte *src; ++ // UInt32 v; ++ CBcj2Enc_ip_unsigned ip; ++ if (p->range < kTopValue) ++ { ++ // to reduce register pressure and code size: we save and restore local variables. ++ WRITE_CONTEXT_AND_SRC ++ if (Bcj2_RangeEnc_ShiftLow(p)) ++ return; ++ p->range <<= 8; ++ src = p->src; ++ v = p->context; ++ } ++ // src = p->src; ++ // #define MARKER_FLAG ((UInt32)1 << 17) ++ // if ((v & MARKER_FLAG) == 0) // for marker version + { +- const Byte *src = p->src; + const Byte *srcLim; +- Byte *dest; +- SizeT num = (SizeT)(p->srcLim - src); +- +- if (p->finishMode == BCJ2_ENC_FINISH_MODE_CONTINUE) ++ Byte *dest = p->bufs[BCJ2_STREAM_MAIN]; + { +- if (num <= 4) +- return; +- num -= 4; ++ const SizeT remSrc = (SizeT)(p->srcLim - src); ++ SizeT rem = (SizeT)(p->lims[BCJ2_STREAM_MAIN] - dest); ++ if (rem >= remSrc) ++ rem = remSrc; ++ srcLim = src + rem; + } +- else if (num == 0) +- break; +- +- dest = p->bufs[BCJ2_STREAM_MAIN]; +- if (num > (SizeT)(p->lims[BCJ2_STREAM_MAIN] - dest)) ++ /* p->context contains context of previous byte: ++ bits [0 : 7] : src[-1], if (src) was changed in this call ++ bits [8 : 31] : are undefined for non-marker version ++ */ ++ // v = p->context; ++ #define NUM_SHIFT_BITS 24 ++ #define CONV_FLAG ((UInt32)1 << 16) ++ #define ONE_ITER { \ ++ b = src[0]; \ ++ *dest++ = (Byte)b; \ ++ v = (v << NUM_SHIFT_BITS) | b; \ ++ if (((b + (0x100 - 0xe8)) & 0xfe) == 0) break; \ ++ if (((v - (((UInt32)0x0f << (NUM_SHIFT_BITS)) + 0x80)) & \ ++ ((((UInt32)1 << (4 + NUM_SHIFT_BITS)) - 0x1) << 4)) == 0) break; \ ++ src++; if (src == srcLim) { break; } } ++ ++ if (src != srcLim) ++ for (;;) + { +- num = (SizeT)(p->lims[BCJ2_STREAM_MAIN] - dest); +- if (num == 0) +- { +- p->state = BCJ2_STREAM_MAIN; +- return; +- } ++ /* clang can generate ineffective code with setne instead of two jcc instructions. ++ we can use 2 iterations and external (unsigned b) to avoid that ineffective code genaration. */ ++ unsigned b; ++ ONE_ITER ++ ONE_ITER + } +- +- srcLim = src + num; ++ ++ ip = p->ip64 + (CBcj2Enc_ip_unsigned)(SizeT)(dest - p->bufs[BCJ2_STREAM_MAIN]); ++ p->bufs[BCJ2_STREAM_MAIN] = dest; ++ p->ip64 = ip; + +- if (p->prevByte == 0x0F && (src[0] & 0xF0) == 0x80) +- *dest = src[0]; +- else for (;;) ++ if (src == srcLim) + { +- Byte b = *src; +- *dest = b; +- if (b != 0x0F) ++ WRITE_CONTEXT_AND_SRC ++ if (src != p->srcLim) + { +- if ((b & 0xFE) == 0xE8) +- break; +- dest++; +- if (++src != srcLim) +- continue; +- break; ++ p->state = BCJ2_STREAM_MAIN; ++ return; + } +- dest++; +- if (++src == srcLim) +- break; +- if ((*src & 0xF0) != 0x80) +- continue; +- *dest = *src; ++ /* (p->src == p->srcLim) ++ (p->state == BCJ2_ENC_STATE_ORIG) */ ++ if (p->finishMode != BCJ2_ENC_FINISH_MODE_END_STREAM) ++ return; ++ /* (p->finishMode == BCJ2_ENC_FINISH_MODE_END_STREAM */ ++ // (p->flushRem == 5); ++ p->isFlushState = 1; + break; + } +- +- num = (SizeT)(src - p->src); +- +- if (src == srcLim) +- { +- p->prevByte = src[-1]; +- p->bufs[BCJ2_STREAM_MAIN] = dest; +- p->src = src; +- p->ip += (UInt32)num; +- continue; +- } +- ++ src++; ++ // p->src = src; ++ } ++ // ip = p->ip; // for marker version ++ /* marker was found */ ++ /* (v) contains marker that was found: ++ bits [NUM_SHIFT_BITS : NUM_SHIFT_BITS + 7] ++ : value of src[-2] : xx/xx/0f ++ bits [0 : 7] : value of src[-1] : e8/e9/8x ++ */ ++ { + { +- Byte context = (Byte)(num == 0 ? p->prevByte : src[-1]); +- BoolInt needConvert; +- +- p->bufs[BCJ2_STREAM_MAIN] = dest + 1; +- p->ip += (UInt32)num + 1; +- src++; +- +- needConvert = False7z; +- ++ #if NUM_SHIFT_BITS != 24 ++ v &= ~(UInt32)CONV_FLAG; ++ #endif ++ // UInt32 relat = 0; + if ((SizeT)(p->srcLim - src) >= 4) + { +- UInt32 relatVal = GetUi32(src); +- if ((p->fileSize == 0 || (UInt32)(p->ip + 4 + relatVal - p->fileIp) < p->fileSize) +- && ((relatVal + p->relatLimit) >> 1) < p->relatLimit) +- needConvert = True7z; ++ /* ++ if (relat != 0 || (Byte)v != 0xe8) ++ BoolInt isBigOffset = True7z; ++ */ ++ const UInt32 relat = GetUi32(src); ++ /* ++ #define EXCLUDE_FLAG ((UInt32)1 << 4) ++ #define NEED_CONVERT(rel) ((((rel) + EXCLUDE_FLAG) & (0 - EXCLUDE_FLAG * 2)) != 0) ++ if (p->relatExcludeBits != 0) ++ { ++ const UInt32 flag = (UInt32)1 << (p->relatExcludeBits - 1); ++ isBigOffset = (((relat + flag) & (0 - flag * 2)) != 0); ++ } ++ // isBigOffset = False7z; // for debug ++ */ ++ ip -= p->fileIp64; ++ // Use the following if check, if (ip) is 64-bit: ++ if (ip > (((v + 0x20) >> 5) & 1)) // 23.00 : we eliminate milti-block overlap for (Of 80) and (e8/e9) ++ if ((CBcj2Enc_ip_unsigned)((CBcj2Enc_ip_signed)ip + 4 + (Int32)relat) <= p->fileSize64_minus1) ++ if (((UInt32)(relat + p->relatLimit) >> 1) < p->relatLimit) ++ v |= CONV_FLAG; + } +- ++ else if (p->finishMode == BCJ2_ENC_FINISH_MODE_CONTINUE) + { +- UInt32 bound; +- unsigned ttt; +- Byte b = src[-1]; +- CProb *prob = p->probs + (unsigned)(b == 0xE8 ? 2 + (unsigned)context : (b == 0xE9 ? 1 : 0)); +- +- ttt = *prob; +- bound = (p->range >> kNumModelBits) * ttt; +- +- if (!needConvert) ++ // (p->srcLim - src < 4) ++ // /* ++ // for non-marker version ++ p->ip64--; // p->ip = ip - 1; ++ p->bufs[BCJ2_STREAM_MAIN]--; ++ src--; ++ v >>= NUM_SHIFT_BITS; ++ // (0 < p->srcLim - p->src <= 4) ++ // */ ++ // v |= MARKER_FLAG; // for marker version ++ /* (p->state == BCJ2_ENC_STATE_ORIG) */ ++ WRITE_CONTEXT_AND_SRC ++ return; ++ } ++ { ++ const unsigned c = ((v + 0x17) >> 6) & 1; ++ CBcj2Prob *prob = p->probs + (unsigned) ++ (((0 - c) & (Byte)(v >> NUM_SHIFT_BITS)) + c + ((v >> 5) & 1)); ++ /* ++ ((Byte)v == 0xe8 ? 2 + ((Byte)(v >> 8)) : ++ ((Byte)v < 0xe8 ? 0 : 1)); // ((v >> 5) & 1)); ++ */ ++ const unsigned ttt = *prob; ++ const UInt32 bound = (p->range >> kNumBitModelTotalBits) * ttt; ++ if ((v & CONV_FLAG) == 0) + { ++ // static int yyy = 0; yyy++; printf("\n!needConvert = %d\n", yyy); ++ // v = (Byte)v; // for marker version + p->range = bound; +- *prob = (CProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); +- p->src = src; +- p->prevByte = b; ++ *prob = (CBcj2Prob)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); ++ // WRITE_CONTEXT_AND_SRC + continue; + } +- + p->low += bound; + p->range -= bound; +- *prob = (CProb)(ttt - (ttt >> kNumMoveBits)); +- ++ *prob = (CBcj2Prob)(ttt - (ttt >> kNumMoveBits)); ++ } ++ // p->context = src[3]; ++ { ++ // const unsigned cj = ((Byte)v == 0xe8 ? BCJ2_STREAM_CALL : BCJ2_STREAM_JUMP); ++ const unsigned cj = (((v + 0x57) >> 6) & 1) + BCJ2_STREAM_CALL; ++ ip = p->ip64; ++ v = GetUi32(src); // relat ++ ip += 4; ++ p->ip64 = ip; ++ src += 4; ++ // p->src = src; + { +- UInt32 relatVal = GetUi32(src); +- UInt32 absVal; +- p->ip += 4; +- absVal = p->ip + relatVal; +- p->prevByte = src[3]; +- src += 4; +- p->src = src; ++ const UInt32 absol = (UInt32)ip + v; ++ Byte *cur = p->bufs[cj]; ++ v >>= 24; ++ // WRITE_CONTEXT ++ if (cur == p->lims[cj]) + { +- unsigned cj = (b == 0xE8) ? BCJ2_STREAM_CALL : BCJ2_STREAM_JUMP; +- Byte *cur = p->bufs[cj]; +- if (cur == p->lims[cj]) +- { +- p->state = cj; +- p->tempTarget = absVal; +- return; +- } +- SetBe32(cur, absVal); +- p->bufs[cj] = cur + 4; ++ p->state = cj; ++ p->tempTarget = absol; ++ WRITE_CONTEXT_AND_SRC ++ return; + } ++ SetBe32a(cur, absol) ++ p->bufs[cj] = cur + 4; + } + } + } + } +- } ++ } // end of loop + } + +- if (p->finishMode != BCJ2_ENC_FINISH_MODE_END_STREAM) +- return; +- +- for (; p->flushPos < 5; p->flushPos++) +- if (RangeEnc_ShiftLow(p)) ++ for (; p->flushRem != 0; p->flushRem--) ++ if (Bcj2_RangeEnc_ShiftLow(p)) + return; +- p->state = BCJ2_ENC_STATE_OK; ++ p->state = BCJ2_ENC_STATE_FINISHED; + } + + ++/* ++BCJ2 encoder needs look ahead for up to 4 bytes in (src) buffer. ++So base function Bcj2Enc_Encode_2() ++ in BCJ2_ENC_FINISH_MODE_CONTINUE mode can return with ++ (p->state == BCJ2_ENC_STATE_ORIG && p->src < p->srcLim) ++Bcj2Enc_Encode() solves that look ahead problem by using p->temp[] buffer. ++ so if (p->state == BCJ2_ENC_STATE_ORIG) after Bcj2Enc_Encode(), ++ then (p->src == p->srcLim). ++ And the caller's code is simpler with Bcj2Enc_Encode(). ++*/ ++ ++Z7_NO_INLINE + void Bcj2Enc_Encode(CBcj2Enc *p) + { +- PRF(printf("\n")); +- PRF(printf("---- ip = %8d tempPos = %8d src = %8d\n", p->ip, p->tempPos, p->srcLim - p->src)); +- ++ PRF2("\n----") + if (p->tempPos != 0) + { ++ /* extra: number of bytes that were copied from (src) to (temp) buffer in this call */ + unsigned extra = 0; +- ++ /* We will touch only minimal required number of bytes in input (src) stream. ++ So we will add input bytes from (src) stream to temp[] with step of 1 byte. ++ We don't add new bytes to temp[] before Bcj2Enc_Encode_2() call ++ in first loop iteration because ++ - previous call of Bcj2Enc_Encode() could use another (finishMode), ++ - previous call could finish with (p->state != BCJ2_ENC_STATE_ORIG). ++ the case with full temp[] buffer (p->tempPos == 4) is possible here. ++ */ + for (;;) + { ++ // (0 < p->tempPos <= 5) // in non-marker version ++ /* p->src : the current src data position including extra bytes ++ that were copied to temp[] buffer in this call */ + const Byte *src = p->src; + const Byte *srcLim = p->srcLim; +- EBcj2Enc_FinishMode finishMode = p->finishMode; +- +- p->src = p->temp; +- p->srcLim = p->temp + p->tempPos; ++ const EBcj2Enc_FinishMode finishMode = p->finishMode; + if (src != srcLim) ++ { ++ /* if there are some src data after the data copied to temp[], ++ then we use MODE_CONTINUE for temp data */ + p->finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE; +- +- PRF(printf(" ip = %8d tempPos = %8d src = %8d\n", p->ip, p->tempPos, p->srcLim - p->src)); +- ++ } ++ p->src = p->temp; ++ p->srcLim = p->temp + p->tempPos; ++ PRF2(" ") + Bcj2Enc_Encode_2(p); +- + { +- unsigned num = (unsigned)(p->src - p->temp); +- unsigned tempPos = p->tempPos - num; ++ const unsigned num = (unsigned)(p->src - p->temp); ++ const unsigned tempPos = p->tempPos - num; + unsigned i; + p->tempPos = tempPos; + for (i = 0; i < tempPos; i++) +- p->temp[i] = p->temp[(size_t)i + num]; +- ++ p->temp[i] = p->temp[(SizeT)i + num]; ++ // tempPos : number of bytes in temp buffer + p->src = src; + p->srcLim = srcLim; + p->finishMode = finishMode; +- +- if (p->state != BCJ2_ENC_STATE_ORIG || src == srcLim) ++ if (p->state != BCJ2_ENC_STATE_ORIG) ++ { ++ // (p->tempPos <= 4) // in non-marker version ++ /* if (the reason of exit from Bcj2Enc_Encode_2() ++ is not BCJ2_ENC_STATE_ORIG), ++ then we exit from Bcj2Enc_Encode() with same reason */ ++ // optional code begin : we rollback (src) and tempPos, if it's possible: ++ if (extra >= tempPos) ++ extra = tempPos; ++ p->src = src - extra; ++ p->tempPos = tempPos - extra; ++ // optional code end : rollback of (src) and tempPos + return; +- ++ } ++ /* (p->tempPos <= 4) ++ (p->state == BCJ2_ENC_STATE_ORIG) ++ so encoder needs more data than in temp[] */ ++ if (src == srcLim) ++ return; // src buffer has no more input data. ++ /* (src != srcLim) ++ so we can provide more input data from src for Bcj2Enc_Encode_2() */ + if (extra >= tempPos) + { +- p->src = src - tempPos; ++ /* (extra >= tempPos) means that temp buffer contains ++ only data from src buffer of this call. ++ So now we can encode without temp buffer */ ++ p->src = src - tempPos; // rollback (src) + p->tempPos = 0; + break; + } +- +- p->temp[tempPos] = src[0]; ++ // we append one additional extra byte from (src) to temp[] buffer: ++ p->temp[tempPos] = *src; + p->tempPos = tempPos + 1; ++ // (0 < p->tempPos <= 5) // in non-marker version + p->src = src + 1; + extra++; + } + } + } + +- PRF(printf("++++ ip = %8d tempPos = %8d src = %8d\n", p->ip, p->tempPos, p->srcLim - p->src)); +- ++ PRF2("++++") ++ // (p->tempPos == 0) + Bcj2Enc_Encode_2(p); ++ PRF2("====") + + if (p->state == BCJ2_ENC_STATE_ORIG) + { + const Byte *src = p->src; +- unsigned rem = (unsigned)(p->srcLim - src); +- unsigned i; +- for (i = 0; i < rem; i++) +- p->temp[i] = src[i]; +- p->tempPos = rem; +- p->src = src + rem; ++ const Byte *srcLim = p->srcLim; ++ const unsigned rem = (unsigned)(srcLim - src); ++ /* (rem <= 4) here. ++ if (p->src != p->srcLim), then ++ - we copy non-processed bytes from (p->src) to temp[] buffer, ++ - we set p->src equal to p->srcLim. ++ */ ++ if (rem) ++ { ++ unsigned i = 0; ++ p->src = srcLim; ++ p->tempPos = rem; ++ // (0 < p->tempPos <= 4) ++ do ++ p->temp[i] = src[i]; ++ while (++i != rem); ++ } ++ // (p->tempPos <= 4) ++ // (p->src == p->srcLim) + } + } ++ ++#undef PRF2 ++#undef CONV_FLAG ++#undef MARKER_FLAG ++#undef WRITE_CONTEXT ++#undef WRITE_CONTEXT_AND_SRC ++#undef ONE_ITER ++#undef NUM_SHIFT_BITS ++#undef kTopValue ++#undef kNumBitModelTotalBits ++#undef kBitModelTotal ++#undef kNumMoveBits +diff --git a/src/lzma/Bra.c b/src/lzma/Bra.c +index 3b854d9ca..22e0e478e 100644 +--- a/src/lzma/Bra.c ++++ b/src/lzma/Bra.c +@@ -1,230 +1,420 @@ +-/* Bra.c -- Converters for RISC code +-2021-02-09 : Igor Pavlov : Public domain */ ++/* Bra.c -- Branch converters for RISC code ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +-#include "CpuArch.h" + #include "Bra.h" ++#include "CpuArch.h" ++#include "RotateDefs.h" ++ ++#if defined(MY_CPU_SIZEOF_POINTER) \ ++ && ( MY_CPU_SIZEOF_POINTER == 4 \ ++ || MY_CPU_SIZEOF_POINTER == 8) ++ #define BR_CONV_USE_OPT_PC_PTR ++#endif ++ ++#ifdef BR_CONV_USE_OPT_PC_PTR ++#define BR_PC_INIT pc -= (UInt32)(SizeT)p; ++#define BR_PC_GET (pc + (UInt32)(SizeT)p) ++#else ++#define BR_PC_INIT pc += (UInt32)size; ++#define BR_PC_GET (pc - (UInt32)(SizeT)(lim - p)) ++// #define BR_PC_INIT ++// #define BR_PC_GET (pc + (UInt32)(SizeT)(p - data)) ++#endif ++ ++#define BR_CONVERT_VAL(v, c) if (encoding) v += c; else v -= c; ++// #define BR_CONVERT_VAL(v, c) if (!encoding) c = (UInt32)0 - c; v += c; ++ ++#define Z7_BRANCH_CONV(name) z7_BranchConv_ ## name ++ ++#define Z7_BRANCH_FUNC_MAIN(name) \ ++static \ ++Z7_FORCE_INLINE \ ++Z7_ATTRIB_NO_VECTOR \ ++Byte *Z7_BRANCH_CONV(name)(Byte *p, SizeT size, UInt32 pc, int encoding) + +-SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) ++#define Z7_BRANCH_FUNC_IMP(name, m, encoding) \ ++Z7_NO_INLINE \ ++Z7_ATTRIB_NO_VECTOR \ ++Byte *m(name)(Byte *data, SizeT size, UInt32 pc) \ ++ { return Z7_BRANCH_CONV(name)(data, size, pc, encoding); } \ ++ ++#ifdef Z7_EXTRACT_ONLY ++#define Z7_BRANCH_FUNCS_IMP(name) \ ++ Z7_BRANCH_FUNC_IMP(name, Z7_BRANCH_CONV_DEC, 0) ++#else ++#define Z7_BRANCH_FUNCS_IMP(name) \ ++ Z7_BRANCH_FUNC_IMP(name, Z7_BRANCH_CONV_DEC, 0) \ ++ Z7_BRANCH_FUNC_IMP(name, Z7_BRANCH_CONV_ENC, 1) ++#endif ++ ++#if defined(__clang__) ++#define BR_EXTERNAL_FOR ++#define BR_NEXT_ITERATION continue; ++#else ++#define BR_EXTERNAL_FOR for (;;) ++#define BR_NEXT_ITERATION break; ++#endif ++ ++#if defined(__clang__) && (__clang_major__ >= 8) \ ++ || defined(__GNUC__) && (__GNUC__ >= 1000) \ ++ // GCC is not good for __builtin_expect() here ++ /* || defined(_MSC_VER) && (_MSC_VER >= 1920) */ ++ // #define Z7_unlikely [[unlikely]] ++ // #define Z7_LIKELY(x) (__builtin_expect((x), 1)) ++ #define Z7_UNLIKELY(x) (__builtin_expect((x), 0)) ++ // #define Z7_likely [[likely]] ++#else ++ // #define Z7_LIKELY(x) (x) ++ #define Z7_UNLIKELY(x) (x) ++ // #define Z7_likely ++#endif ++ ++ ++Z7_BRANCH_FUNC_MAIN(ARM64) + { +- Byte *p; ++ // Byte *p = data; + const Byte *lim; +- size &= ~(size_t)3; +- ip += 4; +- p = data; +- lim = data + size; ++ const UInt32 flag = (UInt32)1 << (24 - 4); ++ const UInt32 mask = ((UInt32)1 << 24) - (flag << 1); ++ size &= ~(SizeT)3; ++ // if (size == 0) return p; ++ lim = p + size; ++ BR_PC_INIT ++ pc -= 4; // because (p) will point to next instruction ++ ++ BR_EXTERNAL_FOR ++ { ++ // Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE ++ for (;;) ++ { ++ UInt32 v; ++ if Z7_UNLIKELY(p == lim) ++ return p; ++ v = GetUi32a(p); ++ p += 4; ++ if Z7_UNLIKELY(((v - 0x94000000) & 0xfc000000) == 0) ++ { ++ UInt32 c = BR_PC_GET >> 2; ++ BR_CONVERT_VAL(v, c) ++ v &= 0x03ffffff; ++ v |= 0x94000000; ++ SetUi32a(p - 4, v) ++ BR_NEXT_ITERATION ++ } ++ // v = rotlFixed(v, 8); v += (flag << 8) - 0x90; if Z7_UNLIKELY((v & ((mask << 8) + 0x9f)) == 0) ++ v -= 0x90000000; if Z7_UNLIKELY((v & 0x9f000000) == 0) ++ { ++ UInt32 z, c; ++ // v = rotrFixed(v, 8); ++ v += flag; if Z7_UNLIKELY(v & mask) continue; ++ z = (v & 0xffffffe0) | (v >> 26); ++ c = (BR_PC_GET >> (12 - 3)) & ~(UInt32)7; ++ BR_CONVERT_VAL(z, c) ++ v &= 0x1f; ++ v |= 0x90000000; ++ v |= z << 26; ++ v |= 0x00ffffe0 & ((z & (((flag << 1) - 1))) - flag); ++ SetUi32a(p - 4, v) ++ } ++ } ++ } ++} ++Z7_BRANCH_FUNCS_IMP(ARM64) + +- if (encoding) + ++Z7_BRANCH_FUNC_MAIN(ARM) ++{ ++ // Byte *p = data; ++ const Byte *lim; ++ size &= ~(SizeT)3; ++ lim = p + size; ++ BR_PC_INIT ++ /* in ARM: branch offset is relative to the +2 instructions from current instruction. ++ (p) will point to next instruction */ ++ pc += 8 - 4; ++ + for (;;) + { + for (;;) + { +- if (p >= lim) +- return (SizeT)(p - data); +- p += 4; +- if (p[-1] == 0xEB) +- break; ++ if Z7_UNLIKELY(p >= lim) { return p; } p += 4; if Z7_UNLIKELY(p[-1] == 0xeb) break; ++ if Z7_UNLIKELY(p >= lim) { return p; } p += 4; if Z7_UNLIKELY(p[-1] == 0xeb) break; + } + { +- UInt32 v = GetUi32(p - 4); +- v <<= 2; +- v += ip + (UInt32)(p - data); +- v >>= 2; +- v &= 0x00FFFFFF; +- v |= 0xEB000000; +- SetUi32(p - 4, v); ++ UInt32 v = GetUi32a(p - 4); ++ UInt32 c = BR_PC_GET >> 2; ++ BR_CONVERT_VAL(v, c) ++ v &= 0x00ffffff; ++ v |= 0xeb000000; ++ SetUi32a(p - 4, v) + } + } ++} ++Z7_BRANCH_FUNCS_IMP(ARM) ++ + ++Z7_BRANCH_FUNC_MAIN(PPC) ++{ ++ // Byte *p = data; ++ const Byte *lim; ++ size &= ~(SizeT)3; ++ lim = p + size; ++ BR_PC_INIT ++ pc -= 4; // because (p) will point to next instruction ++ + for (;;) + { ++ UInt32 v; + for (;;) + { +- if (p >= lim) +- return (SizeT)(p - data); ++ if Z7_UNLIKELY(p == lim) ++ return p; ++ // v = GetBe32a(p); ++ v = *(UInt32 *)(void *)p; + p += 4; +- if (p[-1] == 0xEB) +- break; ++ // if ((v & 0xfc000003) == 0x48000001) break; ++ // if ((p[-4] & 0xFC) == 0x48 && (p[-1] & 3) == 1) break; ++ if Z7_UNLIKELY( ++ ((v - Z7_CONV_BE_TO_NATIVE_CONST32(0x48000001)) ++ & Z7_CONV_BE_TO_NATIVE_CONST32(0xfc000003)) == 0) break; + } + { +- UInt32 v = GetUi32(p - 4); +- v <<= 2; +- v -= ip + (UInt32)(p - data); +- v >>= 2; +- v &= 0x00FFFFFF; +- v |= 0xEB000000; +- SetUi32(p - 4, v); ++ v = Z7_CONV_NATIVE_TO_BE_32(v); ++ { ++ UInt32 c = BR_PC_GET; ++ BR_CONVERT_VAL(v, c) ++ } ++ v &= 0x03ffffff; ++ v |= 0x48000000; ++ SetBe32a(p - 4, v) + } + } + } ++Z7_BRANCH_FUNCS_IMP(PPC) + + +-SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) ++#ifdef Z7_CPU_FAST_ROTATE_SUPPORTED ++#define BR_SPARC_USE_ROTATE ++#endif ++ ++Z7_BRANCH_FUNC_MAIN(SPARC) + { +- Byte *p; ++ // Byte *p = data; + const Byte *lim; +- size &= ~(size_t)1; +- p = data; +- lim = data + size - 4; +- +- if (encoding) +- ++ const UInt32 flag = (UInt32)1 << 22; ++ size &= ~(SizeT)3; ++ lim = p + size; ++ BR_PC_INIT ++ pc -= 4; // because (p) will point to next instruction + for (;;) + { +- UInt32 b1; ++ UInt32 v; + for (;;) + { +- UInt32 b3; +- if (p > lim) +- return (SizeT)(p - data); +- b1 = p[1]; +- b3 = p[3]; +- p += 2; +- b1 ^= 8; +- if ((b3 & b1) >= 0xF8) ++ if Z7_UNLIKELY(p == lim) ++ return p; ++ /* // the code without GetBe32a(): ++ { const UInt32 v = GetUi16a(p) & 0xc0ff; p += 4; if (v == 0x40 || v == 0xc07f) break; } ++ */ ++ v = GetBe32a(p); ++ p += 4; ++ #ifdef BR_SPARC_USE_ROTATE ++ v = rotlFixed(v, 2); ++ v += (flag << 2) - 1; ++ if Z7_UNLIKELY((v & (3 - (flag << 3))) == 0) ++ #else ++ v += (UInt32)5 << 29; ++ v ^= (UInt32)7 << 29; ++ v += flag; ++ if Z7_UNLIKELY((v & (0 - (flag << 1))) == 0) ++ #endif + break; + } + { +- UInt32 v = +- ((UInt32)b1 << 19) +- + (((UInt32)p[1] & 0x7) << 8) +- + (((UInt32)p[-2] << 11)) +- + (p[0]); +- +- p += 2; ++ // UInt32 v = GetBe32a(p - 4); ++ #ifndef BR_SPARC_USE_ROTATE ++ v <<= 2; ++ #endif + { +- UInt32 cur = (ip + (UInt32)(p - data)) >> 1; +- v += cur; ++ UInt32 c = BR_PC_GET; ++ BR_CONVERT_VAL(v, c) + } +- +- p[-4] = (Byte)(v >> 11); +- p[-3] = (Byte)(0xF0 | ((v >> 19) & 0x7)); +- p[-2] = (Byte)v; +- p[-1] = (Byte)(0xF8 | (v >> 8)); ++ v &= (flag << 3) - 1; ++ #ifdef BR_SPARC_USE_ROTATE ++ v -= (flag << 2) - 1; ++ v = rotrFixed(v, 2); ++ #else ++ v -= (flag << 2); ++ v >>= 2; ++ v |= (UInt32)1 << 30; ++ #endif ++ SetBe32a(p - 4, v) + } + } ++} ++Z7_BRANCH_FUNCS_IMP(SPARC) ++ ++ ++Z7_BRANCH_FUNC_MAIN(ARMT) ++{ ++ // Byte *p = data; ++ Byte *lim; ++ size &= ~(SizeT)1; ++ // if (size == 0) return p; ++ if (size <= 2) return p; ++ size -= 2; ++ lim = p + size; ++ BR_PC_INIT ++ /* in ARM: branch offset is relative to the +2 instructions from current instruction. ++ (p) will point to the +2 instructions from current instruction */ ++ // pc += 4 - 4; ++ // if (encoding) pc -= 0xf800 << 1; else pc += 0xf800 << 1; ++ // #define ARMT_TAIL_PROC { goto armt_tail; } ++ #define ARMT_TAIL_PROC { return p; } + +- for (;;) ++ do + { +- UInt32 b1; ++ /* in MSVC 32-bit x86 compilers: ++ UInt32 version : it loads value from memory with movzx ++ Byte version : it loads value to 8-bit register (AL/CL) ++ movzx version is slightly faster in some cpus ++ */ ++ unsigned b1; ++ // Byte / unsigned ++ b1 = p[1]; ++ // optimized version to reduce one (p >= lim) check: ++ // unsigned a1 = p[1]; b1 = p[3]; p += 2; if Z7_LIKELY((b1 & (a1 ^ 8)) < 0xf8) + for (;;) + { +- UInt32 b3; +- if (p > lim) +- return (SizeT)(p - data); +- b1 = p[1]; +- b3 = p[3]; +- p += 2; +- b1 ^= 8; +- if ((b3 & b1) >= 0xF8) +- break; ++ unsigned b3; // Byte / UInt32 ++ /* (Byte)(b3) normalization can use low byte computations in MSVC. ++ It gives smaller code, and no loss of speed in some compilers/cpus. ++ But new MSVC 32-bit x86 compilers use more slow load ++ from memory to low byte register in that case. ++ So we try to use full 32-bit computations for faster code. ++ */ ++ // if (p >= lim) { ARMT_TAIL_PROC } b3 = b1 + 8; b1 = p[3]; p += 2; if ((b3 & b1) >= 0xf8) break; ++ if Z7_UNLIKELY(p >= lim) { ARMT_TAIL_PROC } b3 = p[3]; p += 2; if Z7_UNLIKELY((b3 & (b1 ^ 8)) >= 0xf8) break; ++ if Z7_UNLIKELY(p >= lim) { ARMT_TAIL_PROC } b1 = p[3]; p += 2; if Z7_UNLIKELY((b1 & (b3 ^ 8)) >= 0xf8) break; + } + { ++ /* we can adjust pc for (0xf800) to rid of (& 0x7FF) operation. ++ But gcc/clang for arm64 can use bfi instruction for full code here */ + UInt32 v = +- ((UInt32)b1 << 19) ++ ((UInt32)GetUi16a(p - 2) << 11) | ++ ((UInt32)GetUi16a(p) & 0x7FF); ++ /* ++ UInt32 v = ++ ((UInt32)p[1 - 2] << 19) + + (((UInt32)p[1] & 0x7) << 8) + + (((UInt32)p[-2] << 11)) + + (p[0]); +- ++ */ + p += 2; + { +- UInt32 cur = (ip + (UInt32)(p - data)) >> 1; +- v -= cur; ++ UInt32 c = BR_PC_GET >> 1; ++ BR_CONVERT_VAL(v, c) + } +- ++ SetUi16a(p - 4, (UInt16)(((v >> 11) & 0x7ff) | 0xf000)) ++ SetUi16a(p - 2, (UInt16)(v | 0xf800)) + /* +- SetUi16(p - 4, (UInt16)(((v >> 11) & 0x7FF) | 0xF000)); +- SetUi16(p - 2, (UInt16)(v | 0xF800)); +- */ +- + p[-4] = (Byte)(v >> 11); +- p[-3] = (Byte)(0xF0 | ((v >> 19) & 0x7)); ++ p[-3] = (Byte)(0xf0 | ((v >> 19) & 0x7)); + p[-2] = (Byte)v; +- p[-1] = (Byte)(0xF8 | (v >> 8)); ++ p[-1] = (Byte)(0xf8 | (v >> 8)); ++ */ + } + } ++ while (p < lim); ++ return p; ++ // armt_tail: ++ // if ((Byte)((lim[1] & 0xf8)) != 0xf0) { lim += 2; } return lim; ++ // return (Byte *)(lim + ((Byte)((lim[1] ^ 0xf0) & 0xf8) == 0 ? 0 : 2)); ++ // return (Byte *)(lim + (((lim[1] ^ ~0xfu) & ~7u) == 0 ? 0 : 2)); ++ // return (Byte *)(lim + 2 - (((((unsigned)lim[1] ^ 8) + 8) >> 7) & 2)); + } ++Z7_BRANCH_FUNCS_IMP(ARMT) + + +-SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) +-{ +- Byte *p; +- const Byte *lim; +- size &= ~(size_t)3; +- ip -= 4; +- p = data; +- lim = data + size; +- +- for (;;) +- { +- for (;;) +- { +- if (p >= lim) +- return (SizeT)(p - data); +- p += 4; +- /* if ((v & 0xFC000003) == 0x48000001) */ +- if ((p[-4] & 0xFC) == 0x48 && (p[-1] & 3) == 1) +- break; +- } +- { +- UInt32 v = GetBe32(p - 4); +- if (encoding) +- v += ip + (UInt32)(p - data); +- else +- v -= ip + (UInt32)(p - data); +- v &= 0x03FFFFFF; +- v |= 0x48000000; +- SetBe32(p - 4, v); +- } +- } +-} +- ++// #define BR_IA64_NO_INLINE + +-SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) ++Z7_BRANCH_FUNC_MAIN(IA64) + { +- Byte *p; ++ // Byte *p = data; + const Byte *lim; +- size &= ~(size_t)3; +- ip -= 4; +- p = data; +- lim = data + size; +- ++ size &= ~(SizeT)15; ++ lim = p + size; ++ pc -= 1 << 4; ++ pc >>= 4 - 1; ++ // pc -= 1 << 1; ++ + for (;;) + { ++ unsigned m; + for (;;) + { +- if (p >= lim) +- return (SizeT)(p - data); +- /* +- v = GetBe32(p); +- p += 4; +- m = v + ((UInt32)5 << 29); +- m ^= (UInt32)7 << 29; +- m += (UInt32)1 << 22; +- if ((m & ((UInt32)0x1FF << 23)) == 0) +- break; +- */ +- p += 4; +- if ((p[-4] == 0x40 && (p[-3] & 0xC0) == 0) || +- (p[-4] == 0x7F && (p[-3] >= 0xC0))) ++ if Z7_UNLIKELY(p == lim) ++ return p; ++ m = (unsigned)((UInt32)0x334b0000 >> (*p & 0x1e)); ++ p += 16; ++ pc += 1 << 1; ++ if (m &= 3) + break; + } + { +- UInt32 v = GetBe32(p - 4); +- v <<= 2; +- if (encoding) +- v += ip + (UInt32)(p - data); +- else +- v -= ip + (UInt32)(p - data); +- +- v &= 0x01FFFFFF; +- v -= (UInt32)1 << 24; +- v ^= 0xFF000000; +- v >>= 2; +- v |= 0x40000000; +- SetBe32(p - 4, v); ++ p += (ptrdiff_t)m * 5 - 20; // negative value is expected here. ++ do ++ { ++ const UInt32 t = ++ #if defined(MY_CPU_X86_OR_AMD64) ++ // we use 32-bit load here to reduce code size on x86: ++ GetUi32(p); ++ #else ++ GetUi16(p); ++ #endif ++ UInt32 z = GetUi32(p + 1) >> m; ++ p += 5; ++ if (((t >> m) & (0x70 << 1)) == 0 ++ && ((z - (0x5000000 << 1)) & (0xf000000 << 1)) == 0) ++ { ++ UInt32 v = (UInt32)((0x8fffff << 1) | 1) & z; ++ z ^= v; ++ #ifdef BR_IA64_NO_INLINE ++ v |= (v & ((UInt32)1 << (23 + 1))) >> 3; ++ { ++ UInt32 c = pc; ++ BR_CONVERT_VAL(v, c) ++ } ++ v &= (0x1fffff << 1) | 1; ++ #else ++ { ++ if (encoding) ++ { ++ // pc &= ~(0xc00000 << 1); // we just need to clear at least 2 bits ++ pc &= (0x1fffff << 1) | 1; ++ v += pc; ++ } ++ else ++ { ++ // pc |= 0xc00000 << 1; // we need to set at least 2 bits ++ pc |= ~(UInt32)((0x1fffff << 1) | 1); ++ v -= pc; ++ } ++ } ++ v &= ~(UInt32)(0x600000 << 1); ++ #endif ++ v += (0x700000 << 1); ++ v &= (0x8fffff << 1) | 1; ++ z |= v; ++ z <<= m; ++ SetUi32(p + 1 - 5, z) ++ } ++ m++; ++ } ++ while (m &= 3); // while (m < 4); + } + } + } ++Z7_BRANCH_FUNCS_IMP(IA64) +diff --git a/src/lzma/Bra.h b/src/lzma/Bra.h +index 855e37a6b..a4ee568e2 100644 +--- a/src/lzma/Bra.h ++++ b/src/lzma/Bra.h +@@ -1,64 +1,99 @@ + /* Bra.h -- Branch converters for executables +-2013-01-18 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + +-#ifndef __BRA_H +-#define __BRA_H ++#ifndef ZIP7_INC_BRA_H ++#define ZIP7_INC_BRA_H + + #include "7zTypes.h" + + EXTERN_C_BEGIN + ++#define Z7_BRANCH_CONV_DEC(name) z7_BranchConv_ ## name ## _Dec ++#define Z7_BRANCH_CONV_ENC(name) z7_BranchConv_ ## name ## _Enc ++#define Z7_BRANCH_CONV_ST_DEC(name) z7_BranchConvSt_ ## name ## _Dec ++#define Z7_BRANCH_CONV_ST_ENC(name) z7_BranchConvSt_ ## name ## _Enc ++ ++#define Z7_BRANCH_CONV_DECL(name) Byte * name(Byte *data, SizeT size, UInt32 pc) ++#define Z7_BRANCH_CONV_ST_DECL(name) Byte * name(Byte *data, SizeT size, UInt32 pc, UInt32 *state) ++ ++typedef Z7_BRANCH_CONV_DECL( (*z7_Func_BranchConv)); ++typedef Z7_BRANCH_CONV_ST_DECL((*z7_Func_BranchConvSt)); ++ ++#define Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL 0 ++Z7_BRANCH_CONV_ST_DECL(Z7_BRANCH_CONV_ST_DEC(X86)); ++Z7_BRANCH_CONV_ST_DECL(Z7_BRANCH_CONV_ST_ENC(X86)); ++ ++#define Z7_BRANCH_FUNCS_DECL(name) \ ++Z7_BRANCH_CONV_DECL(Z7_BRANCH_CONV_DEC(name)); \ ++Z7_BRANCH_CONV_DECL(Z7_BRANCH_CONV_ENC(name)); ++ ++Z7_BRANCH_FUNCS_DECL(ARM64) ++Z7_BRANCH_FUNCS_DECL(ARM) ++Z7_BRANCH_FUNCS_DECL(ARMT) ++Z7_BRANCH_FUNCS_DECL(PPC) ++Z7_BRANCH_FUNCS_DECL(SPARC) ++Z7_BRANCH_FUNCS_DECL(IA64) ++ + /* +-These functions convert relative addresses to absolute addresses +-in CALL instructions to increase the compression ratio. +- +- In: +- data - data buffer +- size - size of data +- ip - current virtual Instruction Pinter (IP) value +- state - state variable for x86 converter +- encoding - 0 (for decoding), 1 (for encoding) +- +- Out: +- state - state variable for x86 converter ++These functions convert data that contain CPU instructions. ++Each such function converts relative addresses to absolute addresses in some ++branch instructions: CALL (in all converters) and JUMP (X86 converter only). ++Such conversion allows to increase compression ratio, if we compress that data. ++ ++There are 2 types of converters: ++ Byte * Conv_RISC (Byte *data, SizeT size, UInt32 pc); ++ Byte * ConvSt_X86(Byte *data, SizeT size, UInt32 pc, UInt32 *state); ++Each Converter supports 2 versions: one for encoding ++and one for decoding (_Enc/_Dec postfixes in function name). + +- Returns: +- The number of processed bytes. If you call these functions with multiple calls, +- you must start next call with first byte after block of processed bytes. ++In params: ++ data : data buffer ++ size : size of data ++ pc : current virtual Program Counter (Instruction Pinter) value ++In/Out param: ++ state : pointer to state variable (for X86 converter only) ++ ++Return: ++ The pointer to position in (data) buffer after last byte that was processed. ++ If the caller calls converter again, it must call it starting with that position. ++ But the caller is allowed to move data in buffer. so pointer to ++ current processed position also will be changed for next call. ++ Also the caller must increase internal (pc) value for next call. + ++Each converter has some characteristics: Endian, Alignment, LookAhead. + Type Endian Alignment LookAhead + +- x86 little 1 4 ++ X86 little 1 4 + ARMT little 2 2 + ARM little 4 0 ++ ARM64 little 4 0 + PPC big 4 0 + SPARC big 4 0 + IA64 little 16 0 + +- size must be >= Alignment + LookAhead, if it's not last block. +- If (size < Alignment + LookAhead), converter returns 0. +- +- Example: ++ (data) must be aligned for (Alignment). ++ processed size can be calculated as: ++ SizeT processed = Conv(data, size, pc) - data; ++ if (processed == 0) ++ it means that converter needs more data for processing. ++ If (size < Alignment + LookAhead) ++ then (processed == 0) is allowed. + +- UInt32 ip = 0; +- for () +- { +- ; size must be >= Alignment + LookAhead, if it's not last block +- SizeT processed = Convert(data, size, ip, 1); +- data += processed; +- size -= processed; +- ip += processed; +- } ++Example code for conversion in loop: ++ UInt32 pc = 0; ++ size = 0; ++ for (;;) ++ { ++ size += Load_more_input_data(data + size); ++ SizeT processed = Conv(data, size, pc) - data; ++ if (processed == 0 && no_more_input_data_after_size) ++ break; // we stop convert loop ++ data += processed; ++ size -= processed; ++ pc += processed; ++ } + */ + +-#define x86_Convert_Init(state) { state = 0; } +-SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding); +-SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); +-SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); +-SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); +-SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); +-SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); +- + EXTERN_C_END + + #endif +diff --git a/src/lzma/Bra86.c b/src/lzma/Bra86.c +index 10a0fbd16..d81f392ae 100644 +--- a/src/lzma/Bra86.c ++++ b/src/lzma/Bra86.c +@@ -1,82 +1,187 @@ +-/* Bra86.c -- Converter for x86 code (BCJ) +-2021-02-09 : Igor Pavlov : Public domain */ ++/* Bra86.c -- Branch converter for X86 code (BCJ) ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + + #include "Bra.h" ++#include "CpuArch.h" + +-#define Test86MSByte(b) ((((b) + 1) & 0xFE) == 0) + +-SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding) ++#if defined(MY_CPU_SIZEOF_POINTER) \ ++ && ( MY_CPU_SIZEOF_POINTER == 4 \ ++ || MY_CPU_SIZEOF_POINTER == 8) ++ #define BR_CONV_USE_OPT_PC_PTR ++#endif ++ ++#ifdef BR_CONV_USE_OPT_PC_PTR ++#define BR_PC_INIT pc -= (UInt32)(SizeT)p; // (MY_uintptr_t) ++#define BR_PC_GET (pc + (UInt32)(SizeT)p) ++#else ++#define BR_PC_INIT pc += (UInt32)size; ++#define BR_PC_GET (pc - (UInt32)(SizeT)(lim - p)) ++// #define BR_PC_INIT ++// #define BR_PC_GET (pc + (UInt32)(SizeT)(p - data)) ++#endif ++ ++#define BR_CONVERT_VAL(v, c) if (encoding) v += c; else v -= c; ++// #define BR_CONVERT_VAL(v, c) if (!encoding) c = (UInt32)0 - c; v += c; ++ ++#define Z7_BRANCH_CONV_ST(name) z7_BranchConvSt_ ## name ++ ++#define BR86_NEED_CONV_FOR_MS_BYTE(b) ((((b) + 1) & 0xfe) == 0) ++ ++#ifdef MY_CPU_LE_UNALIGN ++ #define BR86_PREPARE_BCJ_SCAN const UInt32 v = GetUi32(p) ^ 0xe8e8e8e8; ++ #define BR86_IS_BCJ_BYTE(n) ((v & ((UInt32)0xfe << (n) * 8)) == 0) ++#else ++ #define BR86_PREPARE_BCJ_SCAN ++ // bad for MSVC X86 (partial write to byte reg): ++ #define BR86_IS_BCJ_BYTE(n) ((p[n - 4] & 0xfe) == 0xe8) ++ // bad for old MSVC (partial write to byte reg): ++ // #define BR86_IS_BCJ_BYTE(n) (((*p ^ 0xe8) & 0xfe) == 0) ++#endif ++ ++static ++Z7_FORCE_INLINE ++Z7_ATTRIB_NO_VECTOR ++Byte *Z7_BRANCH_CONV_ST(X86)(Byte *p, SizeT size, UInt32 pc, UInt32 *state, int encoding) + { +- SizeT pos = 0; +- UInt32 mask = *state & 7; + if (size < 5) +- return 0; +- size -= 4; +- ip += 5; ++ return p; ++ { ++ // Byte *p = data; ++ const Byte *lim = p + size - 4; ++ unsigned mask = (unsigned)*state; // & 7; ++#ifdef BR_CONV_USE_OPT_PC_PTR ++ /* if BR_CONV_USE_OPT_PC_PTR is defined: we need to adjust (pc) for (+4), ++ because call/jump offset is relative to the next instruction. ++ if BR_CONV_USE_OPT_PC_PTR is not defined : we don't need to adjust (pc) for (+4), ++ because BR_PC_GET uses (pc - (lim - p)), and lim was adjusted for (-4) before. ++ */ ++ pc += 4; ++#endif ++ BR_PC_INIT ++ goto start; + +- for (;;) ++ for (;; mask |= 4) + { +- Byte *p = data + pos; +- const Byte *limit = data + size; +- for (; p < limit; p++) +- if ((*p & 0xFE) == 0xE8) +- break; +- ++ // cont: mask |= 4; ++ start: ++ if (p >= lim) ++ goto fin; + { +- SizeT d = (SizeT)(p - data) - pos; +- pos = (SizeT)(p - data); +- if (p >= limit) +- { +- *state = (d > 2 ? 0 : mask >> (unsigned)d); +- return pos; +- } +- if (d > 2) +- mask = 0; +- else +- { +- mask >>= (unsigned)d; +- if (mask != 0 && (mask > 4 || mask == 3 || Test86MSByte(p[(size_t)(mask >> 1) + 1]))) +- { +- mask = (mask >> 1) | 4; +- pos++; +- continue; +- } +- } ++ BR86_PREPARE_BCJ_SCAN ++ p += 4; ++ if (BR86_IS_BCJ_BYTE(0)) { goto m0; } mask >>= 1; ++ if (BR86_IS_BCJ_BYTE(1)) { goto m1; } mask >>= 1; ++ if (BR86_IS_BCJ_BYTE(2)) { goto m2; } mask = 0; ++ if (BR86_IS_BCJ_BYTE(3)) { goto a3; } + } ++ goto main_loop; + +- if (Test86MSByte(p[4])) ++ m0: p--; ++ m1: p--; ++ m2: p--; ++ if (mask == 0) ++ goto a3; ++ if (p > lim) ++ goto fin_p; ++ ++ // if (((0x17u >> mask) & 1) == 0) ++ if (mask > 4 || mask == 3) ++ { ++ mask >>= 1; ++ continue; // goto cont; ++ } ++ mask >>= 1; ++ if (BR86_NEED_CONV_FOR_MS_BYTE(p[mask])) ++ continue; // goto cont; ++ // if (!BR86_NEED_CONV_FOR_MS_BYTE(p[3])) continue; // goto cont; + { +- UInt32 v = ((UInt32)p[4] << 24) | ((UInt32)p[3] << 16) | ((UInt32)p[2] << 8) | ((UInt32)p[1]); +- UInt32 cur = ip + (UInt32)pos; +- pos += 5; +- if (encoding) +- v += cur; +- else +- v -= cur; +- if (mask != 0) ++ UInt32 v = GetUi32(p); ++ UInt32 c; ++ v += (1 << 24); if (v & 0xfe000000) continue; // goto cont; ++ c = BR_PC_GET; ++ BR_CONVERT_VAL(v, c) + { +- unsigned sh = (mask & 6) << 2; +- if (Test86MSByte((Byte)(v >> sh))) ++ mask <<= 3; ++ if (BR86_NEED_CONV_FOR_MS_BYTE(v >> mask)) + { +- v ^= (((UInt32)0x100 << sh) - 1); +- if (encoding) +- v += cur; +- else +- v -= cur; ++ v ^= (((UInt32)0x100 << mask) - 1); ++ #ifdef MY_CPU_X86 ++ // for X86 : we can recalculate (c) to reduce register pressure ++ c = BR_PC_GET; ++ #endif ++ BR_CONVERT_VAL(v, c) + } + mask = 0; + } +- p[1] = (Byte)v; +- p[2] = (Byte)(v >> 8); +- p[3] = (Byte)(v >> 16); +- p[4] = (Byte)(0 - ((v >> 24) & 1)); ++ // v = (v & ((1 << 24) - 1)) - (v & (1 << 24)); ++ v &= (1 << 25) - 1; v -= (1 << 24); ++ SetUi32(p, v) ++ p += 4; ++ goto main_loop; + } +- else ++ ++ main_loop: ++ if (p >= lim) ++ goto fin; ++ for (;;) + { +- mask = (mask >> 1) | 4; +- pos++; ++ BR86_PREPARE_BCJ_SCAN ++ p += 4; ++ if (BR86_IS_BCJ_BYTE(0)) { goto a0; } ++ if (BR86_IS_BCJ_BYTE(1)) { goto a1; } ++ if (BR86_IS_BCJ_BYTE(2)) { goto a2; } ++ if (BR86_IS_BCJ_BYTE(3)) { goto a3; } ++ if (p >= lim) ++ goto fin; ++ } ++ ++ a0: p--; ++ a1: p--; ++ a2: p--; ++ a3: ++ if (p > lim) ++ goto fin_p; ++ // if (!BR86_NEED_CONV_FOR_MS_BYTE(p[3])) continue; // goto cont; ++ { ++ UInt32 v = GetUi32(p); ++ UInt32 c; ++ v += (1 << 24); if (v & 0xfe000000) continue; // goto cont; ++ c = BR_PC_GET; ++ BR_CONVERT_VAL(v, c) ++ // v = (v & ((1 << 24) - 1)) - (v & (1 << 24)); ++ v &= (1 << 25) - 1; v -= (1 << 24); ++ SetUi32(p, v) ++ p += 4; ++ goto main_loop; + } + } ++ ++fin_p: ++ p--; ++fin: ++ // the following processing for tail is optional and can be commented ++ /* ++ lim += 4; ++ for (; p < lim; p++, mask >>= 1) ++ if ((*p & 0xfe) == 0xe8) ++ break; ++ */ ++ *state = (UInt32)mask; ++ return p; ++ } + } ++ ++ ++#define Z7_BRANCH_CONV_ST_FUNC_IMP(name, m, encoding) \ ++Z7_NO_INLINE \ ++Z7_ATTRIB_NO_VECTOR \ ++Byte *m(name)(Byte *data, SizeT size, UInt32 pc, UInt32 *state) \ ++ { return Z7_BRANCH_CONV_ST(name)(data, size, pc, state, encoding); } ++ ++Z7_BRANCH_CONV_ST_FUNC_IMP(X86, Z7_BRANCH_CONV_ST_DEC, 0) ++#ifndef Z7_EXTRACT_ONLY ++Z7_BRANCH_CONV_ST_FUNC_IMP(X86, Z7_BRANCH_CONV_ST_ENC, 1) ++#endif +diff --git a/src/lzma/BraIA64.c b/src/lzma/BraIA64.c +index d1dbc62c5..9dfe3e289 100644 +--- a/src/lzma/BraIA64.c ++++ b/src/lzma/BraIA64.c +@@ -1,53 +1,14 @@ + /* BraIA64.c -- Converter for IA-64 code +-2017-01-26 : Igor Pavlov : Public domain */ ++2023-02-20 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +-#include "CpuArch.h" +-#include "Bra.h" ++// the code was moved to Bra.c + +-SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) +-{ +- SizeT i; +- if (size < 16) +- return 0; +- size -= 16; +- i = 0; +- do +- { +- unsigned m = ((UInt32)0x334B0000 >> (data[i] & 0x1E)) & 3; +- if (m) +- { +- m++; +- do +- { +- Byte *p = data + (i + (size_t)m * 5 - 8); +- if (((p[3] >> m) & 15) == 5 +- && (((p[-1] | ((UInt32)p[0] << 8)) >> m) & 0x70) == 0) +- { +- unsigned raw = GetUi32(p); +- unsigned v = raw >> m; +- v = (v & 0xFFFFF) | ((v & (1 << 23)) >> 3); +- +- v <<= 4; +- if (encoding) +- v += ip + (UInt32)i; +- else +- v -= ip + (UInt32)i; +- v >>= 4; +- +- v &= 0x1FFFFF; +- v += 0x700000; +- v &= 0x8FFFFF; +- raw &= ~((UInt32)0x8FFFFF << m); +- raw |= (v << m); +- SetUi32(p, raw); +- } +- } +- while (++m <= 4); +- } +- i += 16; +- } +- while (i <= size); +- return i; +-} ++#ifdef _MSC_VER ++#pragma warning(disable : 4206) // nonstandard extension used : translation unit is empty ++#endif ++ ++#if defined(__clang__) ++#pragma GCC diagnostic ignored "-Wempty-translation-unit" ++#endif +diff --git a/src/lzma/Compiler.h b/src/lzma/Compiler.h +index a9816fa5a..185a52deb 100644 +--- a/src/lzma/Compiler.h ++++ b/src/lzma/Compiler.h +@@ -1,12 +1,37 @@ +-/* Compiler.h +-2021-01-05 : Igor Pavlov : Public domain */ ++/* Compiler.h : Compiler specific defines and pragmas ++2023-04-02 : Igor Pavlov : Public domain */ + +-#ifndef __7Z_COMPILER_H +-#define __7Z_COMPILER_H ++#ifndef ZIP7_INC_COMPILER_H ++#define ZIP7_INC_COMPILER_H ++ ++#if defined(__clang__) ++# define Z7_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) ++#endif ++#if defined(__clang__) && defined(__apple_build_version__) ++# define Z7_APPLE_CLANG_VERSION Z7_CLANG_VERSION ++#elif defined(__clang__) ++# define Z7_LLVM_CLANG_VERSION Z7_CLANG_VERSION ++#elif defined(__GNUC__) ++# define Z7_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) ++#endif ++ ++#ifdef _MSC_VER ++#if !defined(__clang__) && !defined(__GNUC__) ++#define Z7_MSC_VER_ORIGINAL _MSC_VER ++#endif ++#endif ++ ++#if defined(__MINGW32__) || defined(__MINGW64__) ++#define Z7_MINGW ++#endif ++ ++// #pragma GCC diagnostic ignored "-Wunknown-pragmas" ++ ++#ifdef __clang__ ++// padding size of '' with 4 bytes to alignment boundary ++#pragma GCC diagnostic ignored "-Wpadded" ++#endif + +- #ifdef __clang__ +- #pragma clang diagnostic ignored "-Wunused-private-field" +- #endif + + #ifdef _MSC_VER + +@@ -17,24 +42,115 @@ + #pragma warning(disable : 4214) // nonstandard extension used : bit field types other than int + #endif + +- #if _MSC_VER >= 1300 +- #pragma warning(disable : 4996) // This function or variable may be unsafe +- #else +- #pragma warning(disable : 4511) // copy constructor could not be generated +- #pragma warning(disable : 4512) // assignment operator could not be generated +- #pragma warning(disable : 4514) // unreferenced inline function has been removed +- #pragma warning(disable : 4702) // unreachable code +- #pragma warning(disable : 4710) // not inlined +- #pragma warning(disable : 4714) // function marked as __forceinline not inlined +- #pragma warning(disable : 4786) // identifier was truncated to '255' characters in the debug information +- #endif ++#if defined(_MSC_VER) && _MSC_VER >= 1800 ++#pragma warning(disable : 4464) // relative include path contains '..' ++#endif ++ ++// == 1200 : -O1 : for __forceinline ++// >= 1900 : -O1 : for printf ++#pragma warning(disable : 4710) // function not inlined ++ ++#if _MSC_VER < 1900 ++// winnt.h: 'Int64ShllMod32' ++#pragma warning(disable : 4514) // unreferenced inline function has been removed ++#endif ++ ++#if _MSC_VER < 1300 ++// #pragma warning(disable : 4702) // unreachable code ++// Bra.c : -O1: ++#pragma warning(disable : 4714) // function marked as __forceinline not inlined ++#endif ++ ++/* ++#if _MSC_VER > 1400 && _MSC_VER <= 1900 ++// strcat: This function or variable may be unsafe ++// sysinfoapi.h: kit10: GetVersion was declared deprecated ++#pragma warning(disable : 4996) ++#endif ++*/ ++ ++#if _MSC_VER > 1200 ++// -Wall warnings ++ ++#pragma warning(disable : 4711) // function selected for automatic inline expansion ++#pragma warning(disable : 4820) // '2' bytes padding added after data member ++ ++#if _MSC_VER >= 1400 && _MSC_VER < 1920 ++// 1400: string.h: _DBG_MEMCPY_INLINE_ ++// 1600 - 191x : smmintrin.h __cplusplus' ++// is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' ++#pragma warning(disable : 4668) ++ ++// 1400 - 1600 : WinDef.h : 'FARPROC' : ++// 1900 - 191x : immintrin.h: _readfsbase_u32 ++// no function prototype given : converting '()' to '(void)' ++#pragma warning(disable : 4255) ++#endif ++ ++#if _MSC_VER >= 1914 ++// Compiler will insert Spectre mitigation for memory load if /Qspectre switch specified ++#pragma warning(disable : 5045) ++#endif ++ ++#endif // _MSC_VER > 1200 ++#endif // _MSC_VER ++ ++ ++#if defined(__clang__) && (__clang_major__ >= 4) ++ #define Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE \ ++ _Pragma("clang loop unroll(disable)") \ ++ _Pragma("clang loop vectorize(disable)") ++ #define Z7_ATTRIB_NO_VECTORIZE ++#elif defined(__GNUC__) && (__GNUC__ >= 5) ++ #define Z7_ATTRIB_NO_VECTORIZE __attribute__((optimize("no-tree-vectorize"))) ++ // __attribute__((optimize("no-unroll-loops"))); ++ #define Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE ++#elif defined(_MSC_VER) && (_MSC_VER >= 1920) ++ #define Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE \ ++ _Pragma("loop( no_vector )") ++ #define Z7_ATTRIB_NO_VECTORIZE ++#else ++ #define Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE ++ #define Z7_ATTRIB_NO_VECTORIZE ++#endif ++ ++#if defined(MY_CPU_X86_OR_AMD64) && ( \ ++ defined(__clang__) && (__clang_major__ >= 4) \ ++ || defined(__GNUC__) && (__GNUC__ >= 5)) ++ #define Z7_ATTRIB_NO_SSE __attribute__((__target__("no-sse"))) ++#else ++ #define Z7_ATTRIB_NO_SSE ++#endif ++ ++#define Z7_ATTRIB_NO_VECTOR \ ++ Z7_ATTRIB_NO_VECTORIZE \ ++ Z7_ATTRIB_NO_SSE ++ ++ ++#if defined(__clang__) && (__clang_major__ >= 8) \ ++ || defined(__GNUC__) && (__GNUC__ >= 1000) \ ++ /* || defined(_MSC_VER) && (_MSC_VER >= 1920) */ ++ // GCC is not good for __builtin_expect() ++ #define Z7_LIKELY(x) (__builtin_expect((x), 1)) ++ #define Z7_UNLIKELY(x) (__builtin_expect((x), 0)) ++ // #define Z7_unlikely [[unlikely]] ++ // #define Z7_likely [[likely]] ++#else ++ #define Z7_LIKELY(x) (x) ++ #define Z7_UNLIKELY(x) (x) ++ // #define Z7_likely ++#endif + +- #ifdef __clang__ +- #pragma clang diagnostic ignored "-Wdeprecated-declarations" +- #pragma clang diagnostic ignored "-Wmicrosoft-exception-spec" +- // #pragma clang diagnostic ignored "-Wreserved-id-macro" +- #endif + ++#if (defined(Z7_CLANG_VERSION) && (Z7_CLANG_VERSION >= 36000)) ++#define Z7_DIAGNOSCTIC_IGNORE_BEGIN_RESERVED_MACRO_IDENTIFIER \ ++ _Pragma("GCC diagnostic push") \ ++ _Pragma("GCC diagnostic ignored \"-Wreserved-macro-identifier\"") ++#define Z7_DIAGNOSCTIC_IGNORE_END_RESERVED_MACRO_IDENTIFIER \ ++ _Pragma("GCC diagnostic pop") ++#else ++#define Z7_DIAGNOSCTIC_IGNORE_BEGIN_RESERVED_MACRO_IDENTIFIER ++#define Z7_DIAGNOSCTIC_IGNORE_END_RESERVED_MACRO_IDENTIFIER + #endif + + #define UNUSED_VAR(x) (void)x; +diff --git a/src/lzma/CpuArch.c b/src/lzma/CpuArch.c +index 1a1facf54..4e2af7707 100644 +--- a/src/lzma/CpuArch.c ++++ b/src/lzma/CpuArch.c +@@ -1,187 +1,318 @@ + /* CpuArch.c -- CPU specific code +-2021-07-13 : Igor Pavlov : Public domain */ ++2023-05-18 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + ++// #include ++ + #include "CpuArch.h" + + #ifdef MY_CPU_X86_OR_AMD64 + +-#if (defined(_MSC_VER) && !defined(MY_CPU_AMD64)) || defined(__GNUC__) +-#define USE_ASM ++#undef NEED_CHECK_FOR_CPUID ++#if !defined(MY_CPU_AMD64) ++#define NEED_CHECK_FOR_CPUID + #endif + +-#if !defined(USE_ASM) && _MSC_VER >= 1500 +-#include ++/* ++ cpuid instruction supports (subFunction) parameter in ECX, ++ that is used only with some specific (function) parameter values. ++ But we always use only (subFunction==0). ++*/ ++/* ++ __cpuid(): MSVC and GCC/CLANG use same function/macro name ++ but parameters are different. ++ We use MSVC __cpuid() parameters style for our z7_x86_cpuid() function. ++*/ ++ ++#if defined(__GNUC__) /* && (__GNUC__ >= 10) */ \ ++ || defined(__clang__) /* && (__clang_major__ >= 10) */ ++ ++/* there was some CLANG/GCC compilers that have issues with ++ rbx(ebx) handling in asm blocks in -fPIC mode (__PIC__ is defined). ++ compiler's contains the macro __cpuid() that is similar to our code. ++ The history of __cpuid() changes in CLANG/GCC: ++ GCC: ++ 2007: it preserved ebx for (__PIC__ && __i386__) ++ 2013: it preserved rbx and ebx for __PIC__ ++ 2014: it doesn't preserves rbx and ebx anymore ++ we suppose that (__GNUC__ >= 5) fixed that __PIC__ ebx/rbx problem. ++ CLANG: ++ 2014+: it preserves rbx, but only for 64-bit code. No __PIC__ check. ++ Why CLANG cares about 64-bit mode only, and doesn't care about ebx (in 32-bit)? ++ Do we need __PIC__ test for CLANG or we must care about rbx even if ++ __PIC__ is not defined? ++*/ ++ ++#define ASM_LN "\n" ++ ++#if defined(MY_CPU_AMD64) && defined(__PIC__) \ ++ && ((defined (__GNUC__) && (__GNUC__ < 5)) || defined(__clang__)) ++ ++#define x86_cpuid_MACRO(p, func) { \ ++ __asm__ __volatile__ ( \ ++ ASM_LN "mov %%rbx, %q1" \ ++ ASM_LN "cpuid" \ ++ ASM_LN "xchg %%rbx, %q1" \ ++ : "=a" ((p)[0]), "=&r" ((p)[1]), "=c" ((p)[2]), "=d" ((p)[3]) : "0" (func), "2"(0)); } ++ ++ /* "=&r" selects free register. It can select even rbx, if that register is free. ++ "=&D" for (RDI) also works, but the code can be larger with "=&D" ++ "2"(0) means (subFunction = 0), ++ 2 is (zero-based) index in the output constraint list "=c" (ECX). */ ++ ++#elif defined(MY_CPU_X86) && defined(__PIC__) \ ++ && ((defined (__GNUC__) && (__GNUC__ < 5)) || defined(__clang__)) ++ ++#define x86_cpuid_MACRO(p, func) { \ ++ __asm__ __volatile__ ( \ ++ ASM_LN "mov %%ebx, %k1" \ ++ ASM_LN "cpuid" \ ++ ASM_LN "xchg %%ebx, %k1" \ ++ : "=a" ((p)[0]), "=&r" ((p)[1]), "=c" ((p)[2]), "=d" ((p)[3]) : "0" (func), "2"(0)); } ++ ++#else ++ ++#define x86_cpuid_MACRO(p, func) { \ ++ __asm__ __volatile__ ( \ ++ ASM_LN "cpuid" \ ++ : "=a" ((p)[0]), "=b" ((p)[1]), "=c" ((p)[2]), "=d" ((p)[3]) : "0" (func), "2"(0)); } ++ + #endif + +-#if defined(USE_ASM) && !defined(MY_CPU_AMD64) +-static UInt32 CheckFlag(UInt32 flag) +-{ +- #ifdef _MSC_VER +- __asm pushfd; +- __asm pop EAX; +- __asm mov EDX, EAX; +- __asm xor EAX, flag; +- __asm push EAX; +- __asm popfd; +- __asm pushfd; +- __asm pop EAX; +- __asm xor EAX, EDX; +- __asm push EDX; +- __asm popfd; +- __asm and flag, EAX; +- #else ++ ++void Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func) ++{ ++ x86_cpuid_MACRO(p, func) ++} ++ ++ ++Z7_NO_INLINE ++UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void) ++{ ++ #if defined(NEED_CHECK_FOR_CPUID) ++ #define EFALGS_CPUID_BIT 21 ++ UInt32 a; + __asm__ __volatile__ ( +- "pushf\n\t" +- "pop %%EAX\n\t" +- "movl %%EAX,%%EDX\n\t" +- "xorl %0,%%EAX\n\t" +- "push %%EAX\n\t" +- "popf\n\t" +- "pushf\n\t" +- "pop %%EAX\n\t" +- "xorl %%EDX,%%EAX\n\t" +- "push %%EDX\n\t" +- "popf\n\t" +- "andl %%EAX, %0\n\t": +- "=c" (flag) : "c" (flag) : +- "%eax", "%edx"); ++ ASM_LN "pushf" ++ ASM_LN "pushf" ++ ASM_LN "pop %0" ++ // ASM_LN "movl %0, %1" ++ // ASM_LN "xorl $0x200000, %0" ++ ASM_LN "btc %1, %0" ++ ASM_LN "push %0" ++ ASM_LN "popf" ++ ASM_LN "pushf" ++ ASM_LN "pop %0" ++ ASM_LN "xorl (%%esp), %0" ++ ++ ASM_LN "popf" ++ ASM_LN ++ : "=&r" (a) // "=a" ++ : "i" (EFALGS_CPUID_BIT) ++ ); ++ if ((a & (1 << EFALGS_CPUID_BIT)) == 0) ++ return 0; ++ #endif ++ { ++ UInt32 p[4]; ++ x86_cpuid_MACRO(p, 0) ++ return p[0]; ++ } ++} ++ ++#undef ASM_LN ++ ++#elif !defined(_MSC_VER) ++ ++/* ++// for gcc/clang and other: we can try to use __cpuid macro: ++#include ++void Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func) ++{ ++ __cpuid(func, p[0], p[1], p[2], p[3]); ++} ++UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void) ++{ ++ return (UInt32)__get_cpuid_max(0, NULL); ++} ++*/ ++// for unsupported cpuid: ++void Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func) ++{ ++ UNUSED_VAR(func) ++ p[0] = p[1] = p[2] = p[3] = 0; ++} ++UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void) ++{ ++ return 0; ++} ++ ++#else // _MSC_VER ++ ++#if !defined(MY_CPU_AMD64) ++ ++UInt32 __declspec(naked) Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void) ++{ ++ #if defined(NEED_CHECK_FOR_CPUID) ++ #define EFALGS_CPUID_BIT 21 ++ __asm pushfd ++ __asm pushfd ++ /* ++ __asm pop eax ++ // __asm mov edx, eax ++ __asm btc eax, EFALGS_CPUID_BIT ++ __asm push eax ++ */ ++ __asm btc dword ptr [esp], EFALGS_CPUID_BIT ++ __asm popfd ++ __asm pushfd ++ __asm pop eax ++ // __asm xor eax, edx ++ __asm xor eax, [esp] ++ // __asm push edx ++ __asm popfd ++ __asm and eax, (1 shl EFALGS_CPUID_BIT) ++ __asm jz end_func ++ #endif ++ __asm push ebx ++ __asm xor eax, eax // func ++ __asm xor ecx, ecx // subFunction (optional) for (func == 0) ++ __asm cpuid ++ __asm pop ebx ++ #if defined(NEED_CHECK_FOR_CPUID) ++ end_func: + #endif +- return flag; ++ __asm ret 0 + } +-#define CHECK_CPUID_IS_SUPPORTED if (CheckFlag(1 << 18) == 0 || CheckFlag(1 << 21) == 0) return False7z; +-#else +-#define CHECK_CPUID_IS_SUPPORTED +-#endif + +-#ifndef USE_ASM +- #ifdef _MSC_VER ++void __declspec(naked) Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func) ++{ ++ UNUSED_VAR(p) ++ UNUSED_VAR(func) ++ __asm push ebx ++ __asm push edi ++ __asm mov edi, ecx // p ++ __asm mov eax, edx // func ++ __asm xor ecx, ecx // subfunction (optional) for (func == 0) ++ __asm cpuid ++ __asm mov [edi ], eax ++ __asm mov [edi + 4], ebx ++ __asm mov [edi + 8], ecx ++ __asm mov [edi + 12], edx ++ __asm pop edi ++ __asm pop ebx ++ __asm ret 0 ++} ++ ++#else // MY_CPU_AMD64 ++ + #if _MSC_VER >= 1600 +- #define MY__cpuidex __cpuidex ++ #include ++ #define MY_cpuidex __cpuidex + #else +- + /* +- __cpuid (function == 4) requires subfunction number in ECX. ++ __cpuid (func == (0 or 7)) requires subfunction number in ECX. + MSDN: The __cpuid intrinsic clears the ECX register before calling the cpuid instruction. + __cpuid() in new MSVC clears ECX. +- __cpuid() in old MSVC (14.00) doesn't clear ECX +- We still can use __cpuid for low (function) values that don't require ECX, +- but __cpuid() in old MSVC will be incorrect for some function values: (function == 4). ++ __cpuid() in old MSVC (14.00) x64 doesn't clear ECX ++ We still can use __cpuid for low (func) values that don't require ECX, ++ but __cpuid() in old MSVC will be incorrect for some func values: (func == 7). + So here we use the hack for old MSVC to send (subFunction) in ECX register to cpuid instruction, +- where ECX value is first parameter for FAST_CALL / NO_INLINE function, +- So the caller of MY__cpuidex_HACK() sets ECX as subFunction, and ++ where ECX value is first parameter for FASTCALL / NO_INLINE func, ++ So the caller of MY_cpuidex_HACK() sets ECX as subFunction, and + old MSVC for __cpuid() doesn't change ECX and cpuid instruction gets (subFunction) value. + +- DON'T remove MY_NO_INLINE and MY_FAST_CALL for MY__cpuidex_HACK() !!! ++DON'T remove Z7_NO_INLINE and Z7_FASTCALL for MY_cpuidex_HACK(): !!! + */ +- + static +-MY_NO_INLINE +-void MY_FAST_CALL MY__cpuidex_HACK(UInt32 subFunction, int *CPUInfo, UInt32 function) ++Z7_NO_INLINE void Z7_FASTCALL MY_cpuidex_HACK(UInt32 subFunction, UInt32 func, int *CPUInfo) + { +- UNUSED_VAR(subFunction); +- __cpuid(CPUInfo, function); ++ UNUSED_VAR(subFunction) ++ __cpuid(CPUInfo, func); + } +- +- #define MY__cpuidex(info, func, func2) MY__cpuidex_HACK(func2, info, func) +- #pragma message("======== MY__cpuidex_HACK WAS USED ========") +- #endif +- #else +- #define MY__cpuidex(info, func, func2) __cpuid(info, func) +- #pragma message("======== (INCORRECT ?) cpuid WAS USED ========") +- #endif ++ #define MY_cpuidex(info, func, func2) MY_cpuidex_HACK(func2, func, info) ++ #pragma message("======== MY_cpuidex_HACK WAS USED ========") ++ #endif // _MSC_VER >= 1600 ++ ++#if !defined(MY_CPU_AMD64) ++/* inlining for __cpuid() in MSVC x86 (32-bit) produces big ineffective code, ++ so we disable inlining here */ ++Z7_NO_INLINE + #endif +- +- +- +- +-void MyCPUID(UInt32 function, UInt32 *a, UInt32 *b, UInt32 *c, UInt32 *d) ++void Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func) + { +- #ifdef USE_ASM +- +- #ifdef _MSC_VER +- +- UInt32 a2, b2, c2, d2; +- __asm xor EBX, EBX; +- __asm xor ECX, ECX; +- __asm xor EDX, EDX; +- __asm mov EAX, function; +- __asm cpuid; +- __asm mov a2, EAX; +- __asm mov b2, EBX; +- __asm mov c2, ECX; +- __asm mov d2, EDX; +- +- *a = a2; +- *b = b2; +- *c = c2; +- *d = d2; +- +- #else +- +- __asm__ __volatile__ ( +- #if defined(MY_CPU_AMD64) && defined(__PIC__) +- "mov %%rbx, %%rdi;" +- "cpuid;" +- "xchg %%rbx, %%rdi;" +- : "=a" (*a) , +- "=D" (*b) , +- #elif defined(MY_CPU_X86) && defined(__PIC__) +- "mov %%ebx, %%edi;" +- "cpuid;" +- "xchgl %%ebx, %%edi;" +- : "=a" (*a) , +- "=D" (*b) , +- #else +- "cpuid" +- : "=a" (*a) , +- "=b" (*b) , +- #endif +- "=c" (*c) , +- "=d" (*d) +- : "0" (function), "c"(0) ) ; +- +- #endif +- +- #else ++ MY_cpuidex((int *)p, (int)func, 0); ++} + +- int CPUInfo[4]; ++Z7_NO_INLINE ++UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void) ++{ ++ int a[4]; ++ MY_cpuidex(a, 0, 0); ++ return a[0]; ++} + +- MY__cpuidex(CPUInfo, (int)function, 0); ++#endif // MY_CPU_AMD64 ++#endif // _MSC_VER + +- *a = (UInt32)CPUInfo[0]; +- *b = (UInt32)CPUInfo[1]; +- *c = (UInt32)CPUInfo[2]; +- *d = (UInt32)CPUInfo[3]; ++#if defined(NEED_CHECK_FOR_CPUID) ++#define CHECK_CPUID_IS_SUPPORTED { if (z7_x86_cpuid_GetMaxFunc() == 0) return 0; } ++#else ++#define CHECK_CPUID_IS_SUPPORTED ++#endif ++#undef NEED_CHECK_FOR_CPUID + +- #endif +-} + +-BoolInt x86cpuid_CheckAndRead(Cx86cpuid *p) ++static ++BoolInt x86cpuid_Func_1(UInt32 *p) + { + CHECK_CPUID_IS_SUPPORTED +- MyCPUID(0, &p->maxFunc, &p->vendor[0], &p->vendor[2], &p->vendor[1]); +- MyCPUID(1, &p->ver, &p->b, &p->c, &p->d); ++ z7_x86_cpuid(p, 1); + return True7z; + } + +-static const UInt32 kVendors[][3] = ++/* ++static const UInt32 kVendors[][1] = + { +- { 0x756E6547, 0x49656E69, 0x6C65746E}, +- { 0x68747541, 0x69746E65, 0x444D4163}, +- { 0x746E6543, 0x48727561, 0x736C7561} ++ { 0x756E6547 }, // , 0x49656E69, 0x6C65746E }, ++ { 0x68747541 }, // , 0x69746E65, 0x444D4163 }, ++ { 0x746E6543 } // , 0x48727561, 0x736C7561 } + }; ++*/ ++ ++/* ++typedef struct ++{ ++ UInt32 maxFunc; ++ UInt32 vendor[3]; ++ UInt32 ver; ++ UInt32 b; ++ UInt32 c; ++ UInt32 d; ++} Cx86cpuid; ++ ++enum ++{ ++ CPU_FIRM_INTEL, ++ CPU_FIRM_AMD, ++ CPU_FIRM_VIA ++}; ++int x86cpuid_GetFirm(const Cx86cpuid *p); ++#define x86cpuid_ver_GetFamily(ver) (((ver >> 16) & 0xff0) | ((ver >> 8) & 0xf)) ++#define x86cpuid_ver_GetModel(ver) (((ver >> 12) & 0xf0) | ((ver >> 4) & 0xf)) ++#define x86cpuid_ver_GetStepping(ver) (ver & 0xf) + + int x86cpuid_GetFirm(const Cx86cpuid *p) + { + unsigned i; +- for (i = 0; i < sizeof(kVendors) / sizeof(kVendors[i]); i++) ++ for (i = 0; i < sizeof(kVendors) / sizeof(kVendors[0]); i++) + { + const UInt32 *v = kVendors[i]; +- if (v[0] == p->vendor[0] && +- v[1] == p->vendor[1] && +- v[2] == p->vendor[2]) ++ if (v[0] == p->vendor[0] ++ // && v[1] == p->vendor[1] ++ // && v[2] == p->vendor[2] ++ ) + return (int)i; + } + return -1; +@@ -190,41 +321,55 @@ int x86cpuid_GetFirm(const Cx86cpuid *p) + BoolInt CPU_Is_InOrder() + { + Cx86cpuid p; +- int firm; + UInt32 family, model; + if (!x86cpuid_CheckAndRead(&p)) + return True7z; + +- family = x86cpuid_GetFamily(p.ver); +- model = x86cpuid_GetModel(p.ver); +- +- firm = x86cpuid_GetFirm(&p); ++ family = x86cpuid_ver_GetFamily(p.ver); ++ model = x86cpuid_ver_GetModel(p.ver); + +- switch (firm) ++ switch (x86cpuid_GetFirm(&p)) + { + case CPU_FIRM_INTEL: return (family < 6 || (family == 6 && ( +- /* In-Order Atom CPU */ +- model == 0x1C /* 45 nm, N4xx, D4xx, N5xx, D5xx, 230, 330 */ +- || model == 0x26 /* 45 nm, Z6xx */ +- || model == 0x27 /* 32 nm, Z2460 */ +- || model == 0x35 /* 32 nm, Z2760 */ +- || model == 0x36 /* 32 nm, N2xxx, D2xxx */ ++ // In-Order Atom CPU ++ model == 0x1C // 45 nm, N4xx, D4xx, N5xx, D5xx, 230, 330 ++ || model == 0x26 // 45 nm, Z6xx ++ || model == 0x27 // 32 nm, Z2460 ++ || model == 0x35 // 32 nm, Z2760 ++ || model == 0x36 // 32 nm, N2xxx, D2xxx + ))); + case CPU_FIRM_AMD: return (family < 5 || (family == 5 && (model < 6 || model == 0xA))); + case CPU_FIRM_VIA: return (family < 6 || (family == 6 && model < 0xF)); + } +- return True7z; ++ return False7z; // v23 : unknown processors are not In-Order + } ++*/ ++ ++#ifdef _WIN32 ++#include "7zWindows.h" ++#endif + + #if !defined(MY_CPU_AMD64) && defined(_WIN32) +-#include +-static BoolInt CPU_Sys_Is_SSE_Supported() ++ ++/* for legacy SSE ia32: there is no user-space cpu instruction to check ++ that OS supports SSE register storing/restoring on context switches. ++ So we need some OS-specific function to check that it's safe to use SSE registers. ++*/ ++ ++Z7_FORCE_INLINE ++static BoolInt CPU_Sys_Is_SSE_Supported(void) + { +- OSVERSIONINFO vi; +- vi.dwOSVersionInfoSize = sizeof(vi); +- if (!GetVersionEx(&vi)) +- return False7z; +- return (vi.dwMajorVersion >= 5); ++#ifdef _MSC_VER ++ #pragma warning(push) ++ #pragma warning(disable : 4996) // `GetVersion': was declared deprecated ++#endif ++ /* low byte is major version of Windows ++ We suppose that any Windows version since ++ Windows2000 (major == 5) supports SSE registers */ ++ return (Byte)GetVersion() >= 5; ++#if defined(_MSC_VER) ++ #pragma warning(pop) ++#endif + } + #define CHECK_SYS_SSE_SUPPORT if (!CPU_Sys_Is_SSE_Supported()) return False7z; + #else +@@ -232,94 +377,300 @@ static BoolInt CPU_Sys_Is_SSE_Supported() + #endif + + +-static UInt32 X86_CPUID_ECX_Get_Flags() ++#if !defined(MY_CPU_AMD64) ++ ++BoolInt CPU_IsSupported_CMOV(void) + { +- Cx86cpuid p; ++ UInt32 a[4]; ++ if (!x86cpuid_Func_1(&a[0])) ++ return 0; ++ return (a[3] >> 15) & 1; ++} ++ ++BoolInt CPU_IsSupported_SSE(void) ++{ ++ UInt32 a[4]; + CHECK_SYS_SSE_SUPPORT +- if (!x86cpuid_CheckAndRead(&p)) ++ if (!x86cpuid_Func_1(&a[0])) ++ return 0; ++ return (a[3] >> 25) & 1; ++} ++ ++BoolInt CPU_IsSupported_SSE2(void) ++{ ++ UInt32 a[4]; ++ CHECK_SYS_SSE_SUPPORT ++ if (!x86cpuid_Func_1(&a[0])) ++ return 0; ++ return (a[3] >> 26) & 1; ++} ++ ++#endif ++ ++ ++static UInt32 x86cpuid_Func_1_ECX(void) ++{ ++ UInt32 a[4]; ++ CHECK_SYS_SSE_SUPPORT ++ if (!x86cpuid_Func_1(&a[0])) + return 0; +- return p.c; ++ return a[2]; + } + +-BoolInt CPU_IsSupported_AES() ++BoolInt CPU_IsSupported_AES(void) + { +- return (X86_CPUID_ECX_Get_Flags() >> 25) & 1; ++ return (x86cpuid_Func_1_ECX() >> 25) & 1; + } + +-BoolInt CPU_IsSupported_SSSE3() ++BoolInt CPU_IsSupported_SSSE3(void) + { +- return (X86_CPUID_ECX_Get_Flags() >> 9) & 1; ++ return (x86cpuid_Func_1_ECX() >> 9) & 1; + } + +-BoolInt CPU_IsSupported_SSE41() ++BoolInt CPU_IsSupported_SSE41(void) + { +- return (X86_CPUID_ECX_Get_Flags() >> 19) & 1; ++ return (x86cpuid_Func_1_ECX() >> 19) & 1; + } + +-BoolInt CPU_IsSupported_SHA() ++BoolInt CPU_IsSupported_SHA(void) + { +- Cx86cpuid p; + CHECK_SYS_SSE_SUPPORT +- if (!x86cpuid_CheckAndRead(&p)) +- return False7z; + +- if (p.maxFunc < 7) ++ if (z7_x86_cpuid_GetMaxFunc() < 7) + return False7z; + { +- UInt32 d[4] = { 0 }; +- MyCPUID(7, &d[0], &d[1], &d[2], &d[3]); ++ UInt32 d[4]; ++ z7_x86_cpuid(d, 7); + return (d[1] >> 29) & 1; + } + } + +-// #include ++/* ++MSVC: _xgetbv() intrinsic is available since VS2010SP1. ++ MSVC also defines (_XCR_XFEATURE_ENABLED_MASK) macro in ++ that we can use or check. ++ For any 32-bit x86 we can use asm code in MSVC, ++ but MSVC asm code is huge after compilation. ++ So _xgetbv() is better ++ ++ICC: _xgetbv() intrinsic is available (in what version of ICC?) ++ ICC defines (__GNUC___) and it supports gnu assembler ++ also ICC supports MASM style code with -use-msasm switch. ++ but ICC doesn't support __attribute__((__target__)) ++ ++GCC/CLANG 9: ++ _xgetbv() is macro that works via __builtin_ia32_xgetbv() ++ and we need __attribute__((__target__("xsave")). ++ But with __target__("xsave") the function will be not ++ inlined to function that has no __target__("xsave") attribute. ++ If we want _xgetbv() call inlining, then we should use asm version ++ instead of calling _xgetbv(). ++ Note:intrinsic is broke before GCC 8.2: ++ https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85684 ++*/ + +-#ifdef _WIN32 +-#include ++#if defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1100) \ ++ || defined(_MSC_VER) && (_MSC_VER >= 1600) && (_MSC_FULL_VER >= 160040219) \ ++ || defined(__GNUC__) && (__GNUC__ >= 9) \ ++ || defined(__clang__) && (__clang_major__ >= 9) ++// we define ATTRIB_XGETBV, if we want to use predefined _xgetbv() from compiler ++#if defined(__INTEL_COMPILER) ++#define ATTRIB_XGETBV ++#elif defined(__GNUC__) || defined(__clang__) ++// we don't define ATTRIB_XGETBV here, because asm version is better for inlining. ++// #define ATTRIB_XGETBV __attribute__((__target__("xsave"))) ++#else ++#define ATTRIB_XGETBV ++#endif ++#endif ++ ++#if defined(ATTRIB_XGETBV) ++#include + #endif + +-BoolInt CPU_IsSupported_AVX2() ++ ++// XFEATURE_ENABLED_MASK/XCR0 ++#define MY_XCR_XFEATURE_ENABLED_MASK 0 ++ ++#if defined(ATTRIB_XGETBV) ++ATTRIB_XGETBV ++#endif ++static UInt64 x86_xgetbv_0(UInt32 num) + { +- Cx86cpuid p; +- CHECK_SYS_SSE_SUPPORT ++#if defined(ATTRIB_XGETBV) ++ { ++ return ++ #if (defined(_MSC_VER)) ++ _xgetbv(num); ++ #else ++ __builtin_ia32_xgetbv( ++ #if !defined(__clang__) ++ (int) ++ #endif ++ num); ++ #endif ++ } ++ ++#elif defined(__GNUC__) || defined(__clang__) || defined(__SUNPRO_CC) ++ ++ UInt32 a, d; ++ #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) ++ __asm__ ++ ( ++ "xgetbv" ++ : "=a"(a), "=d"(d) : "c"(num) : "cc" ++ ); ++ #else // is old gcc ++ __asm__ ++ ( ++ ".byte 0x0f, 0x01, 0xd0" "\n\t" ++ : "=a"(a), "=d"(d) : "c"(num) : "cc" ++ ); ++ #endif ++ return ((UInt64)d << 32) | a; ++ // return a; ++ ++#elif defined(_MSC_VER) && !defined(MY_CPU_AMD64) ++ ++ UInt32 a, d; ++ __asm { ++ push eax ++ push edx ++ push ecx ++ mov ecx, num; ++ // xor ecx, ecx // = MY_XCR_XFEATURE_ENABLED_MASK ++ _emit 0x0f ++ _emit 0x01 ++ _emit 0xd0 ++ mov a, eax ++ mov d, edx ++ pop ecx ++ pop edx ++ pop eax ++ } ++ return ((UInt64)d << 32) | a; ++ // return a; ++ ++#else // it's unknown compiler ++ // #error "Need xgetbv function" ++ UNUSED_VAR(num) ++ // for MSVC-X64 we could call external function from external file. ++ /* Actually we had checked OSXSAVE/AVX in cpuid before. ++ So it's expected that OS supports at least AVX and below. */ ++ // if (num != MY_XCR_XFEATURE_ENABLED_MASK) return 0; // if not XCR0 ++ return ++ // (1 << 0) | // x87 ++ (1 << 1) // SSE ++ | (1 << 2); // AVX ++ ++#endif ++} + ++#ifdef _WIN32 ++/* ++ Windows versions do not know about new ISA extensions that ++ can be introduced. But we still can use new extensions, ++ even if Windows doesn't report about supporting them, ++ But we can use new extensions, only if Windows knows about new ISA extension ++ that changes the number or size of registers: SSE, AVX/XSAVE, AVX512 ++ So it's enough to check ++ MY_PF_AVX_INSTRUCTIONS_AVAILABLE ++ instead of ++ MY_PF_AVX2_INSTRUCTIONS_AVAILABLE ++*/ ++#define MY_PF_XSAVE_ENABLED 17 ++// #define MY_PF_SSSE3_INSTRUCTIONS_AVAILABLE 36 ++// #define MY_PF_SSE4_1_INSTRUCTIONS_AVAILABLE 37 ++// #define MY_PF_SSE4_2_INSTRUCTIONS_AVAILABLE 38 ++// #define MY_PF_AVX_INSTRUCTIONS_AVAILABLE 39 ++// #define MY_PF_AVX2_INSTRUCTIONS_AVAILABLE 40 ++// #define MY_PF_AVX512F_INSTRUCTIONS_AVAILABLE 41 ++#endif ++ ++BoolInt CPU_IsSupported_AVX(void) ++{ + #ifdef _WIN32 +- #define MY__PF_XSAVE_ENABLED 17 +- if (!IsProcessorFeaturePresent(MY__PF_XSAVE_ENABLED)) ++ if (!IsProcessorFeaturePresent(MY_PF_XSAVE_ENABLED)) + return False7z; ++ /* PF_AVX_INSTRUCTIONS_AVAILABLE probably is supported starting from ++ some latest Win10 revisions. But we need AVX in older Windows also. ++ So we don't use the following check: */ ++ /* ++ if (!IsProcessorFeaturePresent(MY_PF_AVX_INSTRUCTIONS_AVAILABLE)) ++ return False7z; ++ */ + #endif + +- if (!x86cpuid_CheckAndRead(&p)) ++ /* ++ OS must use new special XSAVE/XRSTOR instructions to save ++ AVX registers when it required for context switching. ++ At OS statring: ++ OS sets CR4.OSXSAVE flag to signal the processor that OS supports the XSAVE extensions. ++ Also OS sets bitmask in XCR0 register that defines what ++ registers will be processed by XSAVE instruction: ++ XCR0.SSE[bit 0] - x87 registers and state ++ XCR0.SSE[bit 1] - SSE registers and state ++ XCR0.AVX[bit 2] - AVX registers and state ++ CR4.OSXSAVE is reflected to CPUID.1:ECX.OSXSAVE[bit 27]. ++ So we can read that bit in user-space. ++ XCR0 is available for reading in user-space by new XGETBV instruction. ++ */ ++ { ++ const UInt32 c = x86cpuid_Func_1_ECX(); ++ if (0 == (1 ++ & (c >> 28) // AVX instructions are supported by hardware ++ & (c >> 27))) // OSXSAVE bit: XSAVE and related instructions are enabled by OS. ++ return False7z; ++ } ++ ++ /* also we can check ++ CPUID.1:ECX.XSAVE [bit 26] : that shows that ++ XSAVE, XRESTOR, XSETBV, XGETBV instructions are supported by hardware. ++ But that check is redundant, because if OSXSAVE bit is set, then XSAVE is also set */ ++ ++ /* If OS have enabled XSAVE extension instructions (OSXSAVE == 1), ++ in most cases we expect that OS also will support storing/restoring ++ for AVX and SSE states at least. ++ But to be ensure for that we call user-space instruction ++ XGETBV(0) to get XCR0 value that contains bitmask that defines ++ what exact states(registers) OS have enabled for storing/restoring. ++ */ ++ ++ { ++ const UInt32 bm = (UInt32)x86_xgetbv_0(MY_XCR_XFEATURE_ENABLED_MASK); ++ // printf("\n=== XGetBV=%d\n", bm); ++ return 1 ++ & (bm >> 1) // SSE state is supported (set by OS) for storing/restoring ++ & (bm >> 2); // AVX state is supported (set by OS) for storing/restoring ++ } ++ // since Win7SP1: we can use GetEnabledXStateFeatures(); ++} ++ ++ ++BoolInt CPU_IsSupported_AVX2(void) ++{ ++ if (!CPU_IsSupported_AVX()) + return False7z; +- if (p.maxFunc < 7) ++ if (z7_x86_cpuid_GetMaxFunc() < 7) + return False7z; + { +- UInt32 d[4] = { 0 }; +- MyCPUID(7, &d[0], &d[1], &d[2], &d[3]); ++ UInt32 d[4]; ++ z7_x86_cpuid(d, 7); + // printf("\ncpuid(7): ebx=%8x ecx=%8x\n", d[1], d[2]); + return 1 + & (d[1] >> 5); // avx2 + } + } + +-BoolInt CPU_IsSupported_VAES_AVX2() ++BoolInt CPU_IsSupported_VAES_AVX2(void) + { +- Cx86cpuid p; +- CHECK_SYS_SSE_SUPPORT +- +- #ifdef _WIN32 +- #define MY__PF_XSAVE_ENABLED 17 +- if (!IsProcessorFeaturePresent(MY__PF_XSAVE_ENABLED)) ++ if (!CPU_IsSupported_AVX()) + return False7z; +- #endif +- +- if (!x86cpuid_CheckAndRead(&p)) +- return False7z; +- if (p.maxFunc < 7) ++ if (z7_x86_cpuid_GetMaxFunc() < 7) + return False7z; + { +- UInt32 d[4] = { 0 }; +- MyCPUID(7, &d[0], &d[1], &d[2], &d[3]); ++ UInt32 d[4]; ++ z7_x86_cpuid(d, 7); + // printf("\ncpuid(7): ebx=%8x ecx=%8x\n", d[1], d[2]); + return 1 + & (d[1] >> 5) // avx2 +@@ -328,20 +679,15 @@ BoolInt CPU_IsSupported_VAES_AVX2() + } + } + +-BoolInt CPU_IsSupported_PageGB() ++BoolInt CPU_IsSupported_PageGB(void) + { +- Cx86cpuid cpuid; +- if (!x86cpuid_CheckAndRead(&cpuid)) +- return False7z; ++ CHECK_CPUID_IS_SUPPORTED + { +- UInt32 d[4] = { 0 }; +- MyCPUID(0x80000000, &d[0], &d[1], &d[2], &d[3]); ++ UInt32 d[4]; ++ z7_x86_cpuid(d, 0x80000000); + if (d[0] < 0x80000001) + return False7z; +- } +- { +- UInt32 d[4] = { 0 }; +- MyCPUID(0x80000001, &d[0], &d[1], &d[2], &d[3]); ++ z7_x86_cpuid(d, 0x80000001); + return (d[3] >> 26) & 1; + } + } +@@ -351,11 +697,11 @@ BoolInt CPU_IsSupported_PageGB() + + #ifdef _WIN32 + +-#include ++#include "7zWindows.h" + +-BoolInt CPU_IsSupported_CRC32() { return IsProcessorFeaturePresent(PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } +-BoolInt CPU_IsSupported_CRYPTO() { return IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } +-BoolInt CPU_IsSupported_NEON() { return IsProcessorFeaturePresent(PF_ARM_NEON_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } ++BoolInt CPU_IsSupported_CRC32(void) { return IsProcessorFeaturePresent(PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } ++BoolInt CPU_IsSupported_CRYPTO(void) { return IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } ++BoolInt CPU_IsSupported_NEON(void) { return IsProcessorFeaturePresent(PF_ARM_NEON_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } + + #else + +@@ -378,28 +724,27 @@ static void Print_sysctlbyname(const char *name) + } + } + */ ++/* ++ Print_sysctlbyname("hw.pagesize"); ++ Print_sysctlbyname("machdep.cpu.brand_string"); ++*/ + +-static BoolInt My_sysctlbyname_Get_BoolInt(const char *name) ++static BoolInt z7_sysctlbyname_Get_BoolInt(const char *name) + { + UInt32 val = 0; +- if (My_sysctlbyname_Get_UInt32(name, &val) == 0 && val == 1) ++ if (z7_sysctlbyname_Get_UInt32(name, &val) == 0 && val == 1) + return 1; + return 0; + } + +- /* +- Print_sysctlbyname("hw.pagesize"); +- Print_sysctlbyname("machdep.cpu.brand_string"); +- */ +- + BoolInt CPU_IsSupported_CRC32(void) + { +- return My_sysctlbyname_Get_BoolInt("hw.optional.armv8_crc32"); ++ return z7_sysctlbyname_Get_BoolInt("hw.optional.armv8_crc32"); + } + + BoolInt CPU_IsSupported_NEON(void) + { +- return My_sysctlbyname_Get_BoolInt("hw.optional.neon"); ++ return z7_sysctlbyname_Get_BoolInt("hw.optional.neon"); + } + + #ifdef MY_CPU_ARM64 +@@ -461,15 +806,15 @@ MY_HWCAP_CHECK_FUNC (AES) + + #include + +-int My_sysctlbyname_Get(const char *name, void *buf, size_t *bufSize) ++int z7_sysctlbyname_Get(const char *name, void *buf, size_t *bufSize) + { + return sysctlbyname(name, buf, bufSize, NULL, 0); + } + +-int My_sysctlbyname_Get_UInt32(const char *name, UInt32 *val) ++int z7_sysctlbyname_Get_UInt32(const char *name, UInt32 *val) + { + size_t bufSize = sizeof(*val); +- int res = My_sysctlbyname_Get(name, val, &bufSize); ++ const int res = z7_sysctlbyname_Get(name, val, &bufSize); + if (res == 0 && bufSize != sizeof(*val)) + return EFAULT; + return res; +diff --git a/src/lzma/CpuArch.h b/src/lzma/CpuArch.h +index 529d3a502..8e5d8a543 100644 +--- a/src/lzma/CpuArch.h ++++ b/src/lzma/CpuArch.h +@@ -1,8 +1,8 @@ + /* CpuArch.h -- CPU specific code +-2021-07-13 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + +-#ifndef __CPU_ARCH_H +-#define __CPU_ARCH_H ++#ifndef ZIP7_INC_CPU_ARCH_H ++#define ZIP7_INC_CPU_ARCH_H + + #include "7zTypes.h" + +@@ -51,7 +51,13 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. + || defined(__AARCH64EB__) \ + || defined(__aarch64__) + #define MY_CPU_ARM64 +- #define MY_CPU_NAME "arm64" ++ #ifdef __ILP32__ ++ #define MY_CPU_NAME "arm64-32" ++ #define MY_CPU_SIZEOF_POINTER 4 ++ #else ++ #define MY_CPU_NAME "arm64" ++ #define MY_CPU_SIZEOF_POINTER 8 ++ #endif + #define MY_CPU_64BIT + #endif + +@@ -68,8 +74,10 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. + #define MY_CPU_ARM + + #if defined(__thumb__) || defined(__THUMBEL__) || defined(_M_ARMT) ++ #define MY_CPU_ARMT + #define MY_CPU_NAME "armt" + #else ++ #define MY_CPU_ARM32 + #define MY_CPU_NAME "arm" + #endif + /* #define MY_CPU_32BIT */ +@@ -103,6 +111,8 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. + || defined(__PPC__) \ + || defined(_POWER) + ++#define MY_CPU_PPC_OR_PPC64 ++ + #if defined(__ppc64__) \ + || defined(__powerpc64__) \ + || defined(_LP64) \ +@@ -123,12 +133,15 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. + #endif + + +-#if defined(__sparc64__) +- #define MY_CPU_NAME "sparc64" +- #define MY_CPU_64BIT +-#elif defined(__sparc__) +- #define MY_CPU_NAME "sparc" +- /* #define MY_CPU_32BIT */ ++#if defined(__riscv) \ ++ || defined(__riscv__) ++ #if __riscv_xlen == 32 ++ #define MY_CPU_NAME "riscv32" ++ #elif __riscv_xlen == 64 ++ #define MY_CPU_NAME "riscv64" ++ #else ++ #define MY_CPU_NAME "riscv" ++ #endif + #endif + + +@@ -194,6 +207,9 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. + #error Stop_Compiling_Bad_Endian + #endif + ++#if !defined(MY_CPU_LE) && !defined(MY_CPU_BE) ++ #error Stop_Compiling_CPU_ENDIAN_must_be_detected_at_compile_time ++#endif + + #if defined(MY_CPU_32BIT) && defined(MY_CPU_64BIT) + #error Stop_Compiling_Bad_32_64_BIT +@@ -250,6 +266,67 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. + + + ++#ifdef __has_builtin ++ #define Z7_has_builtin(x) __has_builtin(x) ++#else ++ #define Z7_has_builtin(x) 0 ++#endif ++ ++ ++#define Z7_BSWAP32_CONST(v) \ ++ ( (((UInt32)(v) << 24) ) \ ++ | (((UInt32)(v) << 8) & (UInt32)0xff0000) \ ++ | (((UInt32)(v) >> 8) & (UInt32)0xff00 ) \ ++ | (((UInt32)(v) >> 24) )) ++ ++ ++#if defined(_MSC_VER) && (_MSC_VER >= 1300) ++ ++#include ++ ++/* Note: these macros will use bswap instruction (486), that is unsupported in 386 cpu */ ++ ++#pragma intrinsic(_byteswap_ushort) ++#pragma intrinsic(_byteswap_ulong) ++#pragma intrinsic(_byteswap_uint64) ++ ++#define Z7_BSWAP16(v) _byteswap_ushort(v) ++#define Z7_BSWAP32(v) _byteswap_ulong (v) ++#define Z7_BSWAP64(v) _byteswap_uint64(v) ++#define Z7_CPU_FAST_BSWAP_SUPPORTED ++ ++#elif (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) \ ++ || (defined(__clang__) && Z7_has_builtin(__builtin_bswap16)) ++ ++#define Z7_BSWAP16(v) __builtin_bswap16(v) ++#define Z7_BSWAP32(v) __builtin_bswap32(v) ++#define Z7_BSWAP64(v) __builtin_bswap64(v) ++#define Z7_CPU_FAST_BSWAP_SUPPORTED ++ ++#else ++ ++#define Z7_BSWAP16(v) ((UInt16) \ ++ ( ((UInt32)(v) << 8) \ ++ | ((UInt32)(v) >> 8) \ ++ )) ++ ++#define Z7_BSWAP32(v) Z7_BSWAP32_CONST(v) ++ ++#define Z7_BSWAP64(v) \ ++ ( ( ( (UInt64)(v) ) << 8 * 7 ) \ ++ | ( ( (UInt64)(v) & ((UInt32)0xff << 8 * 1) ) << 8 * 5 ) \ ++ | ( ( (UInt64)(v) & ((UInt32)0xff << 8 * 2) ) << 8 * 3 ) \ ++ | ( ( (UInt64)(v) & ((UInt32)0xff << 8 * 3) ) << 8 * 1 ) \ ++ | ( ( (UInt64)(v) >> 8 * 1 ) & ((UInt32)0xff << 8 * 3) ) \ ++ | ( ( (UInt64)(v) >> 8 * 3 ) & ((UInt32)0xff << 8 * 2) ) \ ++ | ( ( (UInt64)(v) >> 8 * 5 ) & ((UInt32)0xff << 8 * 1) ) \ ++ | ( ( (UInt64)(v) >> 8 * 7 ) ) \ ++ ) ++ ++#endif ++ ++ ++ + #ifdef MY_CPU_LE + #if defined(MY_CPU_X86_OR_AMD64) \ + || defined(MY_CPU_ARM64) +@@ -269,13 +346,11 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. + #define GetUi32(p) (*(const UInt32 *)(const void *)(p)) + #ifdef MY_CPU_LE_UNALIGN_64 + #define GetUi64(p) (*(const UInt64 *)(const void *)(p)) ++#define SetUi64(p, v) { *(UInt64 *)(void *)(p) = (v); } + #endif + + #define SetUi16(p, v) { *(UInt16 *)(void *)(p) = (v); } + #define SetUi32(p, v) { *(UInt32 *)(void *)(p) = (v); } +-#ifdef MY_CPU_LE_UNALIGN_64 +-#define SetUi64(p, v) { *(UInt64 *)(void *)(p) = (v); } +-#endif + + #else + +@@ -302,51 +377,26 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. + #endif + + +-#ifndef MY_CPU_LE_UNALIGN_64 +- ++#ifndef GetUi64 + #define GetUi64(p) (GetUi32(p) | ((UInt64)GetUi32(((const Byte *)(p)) + 4) << 32)) ++#endif + ++#ifndef SetUi64 + #define SetUi64(p, v) { Byte *_ppp2_ = (Byte *)(p); UInt64 _vvv2_ = (v); \ +- SetUi32(_ppp2_ , (UInt32)_vvv2_); \ +- SetUi32(_ppp2_ + 4, (UInt32)(_vvv2_ >> 32)); } +- ++ SetUi32(_ppp2_ , (UInt32)_vvv2_) \ ++ SetUi32(_ppp2_ + 4, (UInt32)(_vvv2_ >> 32)) } + #endif + + ++#if defined(MY_CPU_LE_UNALIGN) && defined(Z7_CPU_FAST_BSWAP_SUPPORTED) + ++#define GetBe32(p) Z7_BSWAP32 (*(const UInt32 *)(const void *)(p)) ++#define SetBe32(p, v) { (*(UInt32 *)(void *)(p)) = Z7_BSWAP32(v); } + +-#ifdef __has_builtin +- #define MY__has_builtin(x) __has_builtin(x) +-#else +- #define MY__has_builtin(x) 0 ++#if defined(MY_CPU_LE_UNALIGN_64) ++#define GetBe64(p) Z7_BSWAP64 (*(const UInt64 *)(const void *)(p)) + #endif + +-#if defined(MY_CPU_LE_UNALIGN) && /* defined(_WIN64) && */ defined(_MSC_VER) && (_MSC_VER >= 1300) +- +-/* Note: we use bswap instruction, that is unsupported in 386 cpu */ +- +-#include +- +-#pragma intrinsic(_byteswap_ushort) +-#pragma intrinsic(_byteswap_ulong) +-#pragma intrinsic(_byteswap_uint64) +- +-/* #define GetBe16(p) _byteswap_ushort(*(const UInt16 *)(const Byte *)(p)) */ +-#define GetBe32(p) _byteswap_ulong (*(const UInt32 *)(const void *)(p)) +-#define GetBe64(p) _byteswap_uint64(*(const UInt64 *)(const void *)(p)) +- +-#define SetBe32(p, v) (*(UInt32 *)(void *)(p)) = _byteswap_ulong(v) +- +-#elif defined(MY_CPU_LE_UNALIGN) && ( \ +- (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) \ +- || (defined(__clang__) && MY__has_builtin(__builtin_bswap16)) ) +- +-/* #define GetBe16(p) __builtin_bswap16(*(const UInt16 *)(const void *)(p)) */ +-#define GetBe32(p) __builtin_bswap32(*(const UInt32 *)(const void *)(p)) +-#define GetBe64(p) __builtin_bswap64(*(const UInt64 *)(const void *)(p)) +- +-#define SetBe32(p, v) (*(UInt32 *)(void *)(p)) = __builtin_bswap32(v) +- + #else + + #define GetBe32(p) ( \ +@@ -355,8 +405,6 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. + ((UInt32)((const Byte *)(p))[2] << 8) | \ + ((const Byte *)(p))[3] ) + +-#define GetBe64(p) (((UInt64)GetBe32(p) << 32) | GetBe32(((const Byte *)(p)) + 4)) +- + #define SetBe32(p, v) { Byte *_ppp_ = (Byte *)(p); UInt32 _vvv_ = (v); \ + _ppp_[0] = (Byte)(_vvv_ >> 24); \ + _ppp_[1] = (Byte)(_vvv_ >> 16); \ +@@ -365,50 +413,83 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. + + #endif + ++#ifndef GetBe64 ++#define GetBe64(p) (((UInt64)GetBe32(p) << 32) | GetBe32(((const Byte *)(p)) + 4)) ++#endif + + #ifndef GetBe16 +- + #define GetBe16(p) ( (UInt16) ( \ + ((UInt16)((const Byte *)(p))[0] << 8) | \ + ((const Byte *)(p))[1] )) ++#endif + ++ ++#if defined(MY_CPU_BE) ++#define Z7_CONV_BE_TO_NATIVE_CONST32(v) (v) ++#define Z7_CONV_LE_TO_NATIVE_CONST32(v) Z7_BSWAP32_CONST(v) ++#define Z7_CONV_NATIVE_TO_BE_32(v) (v) ++#elif defined(MY_CPU_LE) ++#define Z7_CONV_BE_TO_NATIVE_CONST32(v) Z7_BSWAP32_CONST(v) ++#define Z7_CONV_LE_TO_NATIVE_CONST32(v) (v) ++#define Z7_CONV_NATIVE_TO_BE_32(v) Z7_BSWAP32(v) ++#else ++#error Stop_Compiling_Unknown_Endian_CONV + #endif + + ++#if defined(MY_CPU_BE) + +-#ifdef MY_CPU_X86_OR_AMD64 ++#define GetBe32a(p) (*(const UInt32 *)(const void *)(p)) ++#define GetBe16a(p) (*(const UInt16 *)(const void *)(p)) ++#define SetBe32a(p, v) { *(UInt32 *)(void *)(p) = (v); } ++#define SetBe16a(p, v) { *(UInt16 *)(void *)(p) = (v); } + +-typedef struct +-{ +- UInt32 maxFunc; +- UInt32 vendor[3]; +- UInt32 ver; +- UInt32 b; +- UInt32 c; +- UInt32 d; +-} Cx86cpuid; ++#define GetUi32a(p) GetUi32(p) ++#define GetUi16a(p) GetUi16(p) ++#define SetUi32a(p, v) SetUi32(p, v) ++#define SetUi16a(p, v) SetUi16(p, v) + +-enum +-{ +- CPU_FIRM_INTEL, +- CPU_FIRM_AMD, +- CPU_FIRM_VIA +-}; ++#elif defined(MY_CPU_LE) + +-void MyCPUID(UInt32 function, UInt32 *a, UInt32 *b, UInt32 *c, UInt32 *d); ++#define GetUi32a(p) (*(const UInt32 *)(const void *)(p)) ++#define GetUi16a(p) (*(const UInt16 *)(const void *)(p)) ++#define SetUi32a(p, v) { *(UInt32 *)(void *)(p) = (v); } ++#define SetUi16a(p, v) { *(UInt16 *)(void *)(p) = (v); } + +-BoolInt x86cpuid_CheckAndRead(Cx86cpuid *p); +-int x86cpuid_GetFirm(const Cx86cpuid *p); ++#define GetBe32a(p) GetBe32(p) ++#define GetBe16a(p) GetBe16(p) ++#define SetBe32a(p, v) SetBe32(p, v) ++#define SetBe16a(p, v) SetBe16(p, v) + +-#define x86cpuid_GetFamily(ver) (((ver >> 16) & 0xFF0) | ((ver >> 8) & 0xF)) +-#define x86cpuid_GetModel(ver) (((ver >> 12) & 0xF0) | ((ver >> 4) & 0xF)) +-#define x86cpuid_GetStepping(ver) (ver & 0xF) ++#else ++#error Stop_Compiling_Unknown_Endian_CPU_a ++#endif + +-BoolInt CPU_Is_InOrder(void); ++ ++#if defined(MY_CPU_X86_OR_AMD64) \ ++ || defined(MY_CPU_ARM_OR_ARM64) \ ++ || defined(MY_CPU_PPC_OR_PPC64) ++ #define Z7_CPU_FAST_ROTATE_SUPPORTED ++#endif ++ ++ ++#ifdef MY_CPU_X86_OR_AMD64 ++ ++void Z7_FASTCALL z7_x86_cpuid(UInt32 a[4], UInt32 function); ++UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void); ++#if defined(MY_CPU_AMD64) ++#define Z7_IF_X86_CPUID_SUPPORTED ++#else ++#define Z7_IF_X86_CPUID_SUPPORTED if (z7_x86_cpuid_GetMaxFunc()) ++#endif + + BoolInt CPU_IsSupported_AES(void); ++BoolInt CPU_IsSupported_AVX(void); + BoolInt CPU_IsSupported_AVX2(void); + BoolInt CPU_IsSupported_VAES_AVX2(void); ++BoolInt CPU_IsSupported_CMOV(void); ++BoolInt CPU_IsSupported_SSE(void); ++BoolInt CPU_IsSupported_SSE2(void); + BoolInt CPU_IsSupported_SSSE3(void); + BoolInt CPU_IsSupported_SSE41(void); + BoolInt CPU_IsSupported_SHA(void); +@@ -433,8 +514,8 @@ BoolInt CPU_IsSupported_AES(void); + #endif + + #if defined(__APPLE__) +-int My_sysctlbyname_Get(const char *name, void *buf, size_t *bufSize); +-int My_sysctlbyname_Get_UInt32(const char *name, UInt32 *val); ++int z7_sysctlbyname_Get(const char *name, void *buf, size_t *bufSize); ++int z7_sysctlbyname_Get_UInt32(const char *name, UInt32 *val); + #endif + + EXTERN_C_END +diff --git a/src/lzma/Delta.h b/src/lzma/Delta.h +index 2fa54ad67..706095417 100644 +--- a/src/lzma/Delta.h ++++ b/src/lzma/Delta.h +@@ -1,8 +1,8 @@ + /* Delta.h -- Delta converter +-2013-01-18 : Igor Pavlov : Public domain */ ++2023-03-03 : Igor Pavlov : Public domain */ + +-#ifndef __DELTA_H +-#define __DELTA_H ++#ifndef ZIP7_INC_DELTA_H ++#define ZIP7_INC_DELTA_H + + #include "7zTypes.h" + +diff --git a/src/lzma/DllSecur.c b/src/lzma/DllSecur.c +index d81508c0b..02a0f977e 100644 +--- a/src/lzma/DllSecur.c ++++ b/src/lzma/DllSecur.c +@@ -1,110 +1,111 @@ + /* DllSecur.c -- DLL loading security +-2021-12-25 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + + #ifdef _WIN32 + +-#include ++#include "7zWindows.h" + + #include "DllSecur.h" + + #ifndef UNDER_CE + ++#if (defined(__GNUC__) && (__GNUC__ >= 8)) || defined(__clang__) ++ // #pragma GCC diagnostic ignored "-Wcast-function-type" ++#endif ++ ++#if defined(__clang__) || defined(__GNUC__) ++typedef void (*Z7_voidFunction)(void); ++#define MY_CAST_FUNC (Z7_voidFunction) ++#elif defined(_MSC_VER) && _MSC_VER > 1920 ++#define MY_CAST_FUNC (void *) ++// #pragma warning(disable : 4191) // 'type cast': unsafe conversion from 'FARPROC' to 'void (__cdecl *)()' ++#else ++#define MY_CAST_FUNC ++#endif ++ + typedef BOOL (WINAPI *Func_SetDefaultDllDirectories)(DWORD DirectoryFlags); + + #define MY_LOAD_LIBRARY_SEARCH_USER_DIRS 0x400 + #define MY_LOAD_LIBRARY_SEARCH_SYSTEM32 0x800 + ++#define DELIM "\0" ++ + static const char * const g_Dlls = ++ "userenv" ++ DELIM "setupapi" ++ DELIM "apphelp" ++ DELIM "propsys" ++ DELIM "dwmapi" ++ DELIM "cryptbase" ++ DELIM "oleacc" ++ DELIM "clbcatq" ++ DELIM "version" + #ifndef _CONSOLE +- "UXTHEME\0" ++ DELIM "uxtheme" + #endif +- "USERENV\0" +- "SETUPAPI\0" +- "APPHELP\0" +- "PROPSYS\0" +- "DWMAPI\0" +- "CRYPTBASE\0" +- "OLEACC\0" +- "CLBCATQ\0" +- "VERSION\0" +- ; ++ DELIM; ++ ++#endif + ++#ifdef __clang__ ++ #pragma GCC diagnostic ignored "-Wdeprecated-declarations" ++#endif ++#if defined (_MSC_VER) && _MSC_VER >= 1900 ++// sysinfoapi.h: kit10: GetVersion was declared deprecated ++#pragma warning(disable : 4996) + #endif + +-// #define MY_CAST_FUNC (void(*)()) +-#define MY_CAST_FUNC ++#define IF_NON_VISTA_SET_DLL_DIRS_AND_RETURN \ ++ if ((UInt16)GetVersion() != 6) { \ ++ const \ ++ Func_SetDefaultDllDirectories setDllDirs = \ ++ (Func_SetDefaultDllDirectories) MY_CAST_FUNC GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), \ ++ "SetDefaultDllDirectories"); \ ++ if (setDllDirs) if (setDllDirs(MY_LOAD_LIBRARY_SEARCH_SYSTEM32 | MY_LOAD_LIBRARY_SEARCH_USER_DIRS)) return; } + +-void My_SetDefaultDllDirectories() ++void My_SetDefaultDllDirectories(void) + { + #ifndef UNDER_CE +- +- OSVERSIONINFO vi; +- vi.dwOSVersionInfoSize = sizeof(vi); +- if (!GetVersionEx(&vi) || vi.dwMajorVersion != 6 || vi.dwMinorVersion != 0) +- { +- Func_SetDefaultDllDirectories setDllDirs = (Func_SetDefaultDllDirectories) +- MY_CAST_FUNC GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "SetDefaultDllDirectories"); +- if (setDllDirs) +- if (setDllDirs(MY_LOAD_LIBRARY_SEARCH_SYSTEM32 | MY_LOAD_LIBRARY_SEARCH_USER_DIRS)) +- return; +- } +- ++ IF_NON_VISTA_SET_DLL_DIRS_AND_RETURN + #endif + } + + +-void LoadSecurityDlls() ++void LoadSecurityDlls(void) + { + #ifndef UNDER_CE +- +- wchar_t buf[MAX_PATH + 100]; +- +- { +- // at Vista (ver 6.0) : CoCreateInstance(CLSID_ShellLink, ...) doesn't work after SetDefaultDllDirectories() : Check it ??? +- OSVERSIONINFO vi; +- vi.dwOSVersionInfoSize = sizeof(vi); +- if (!GetVersionEx(&vi) || vi.dwMajorVersion != 6 || vi.dwMinorVersion != 0) +- { +- Func_SetDefaultDllDirectories setDllDirs = (Func_SetDefaultDllDirectories) +- MY_CAST_FUNC GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "SetDefaultDllDirectories"); +- if (setDllDirs) +- if (setDllDirs(MY_LOAD_LIBRARY_SEARCH_SYSTEM32 | MY_LOAD_LIBRARY_SEARCH_USER_DIRS)) +- return; +- } +- } +- +- { +- unsigned len = GetSystemDirectoryW(buf, MAX_PATH + 2); +- if (len == 0 || len > MAX_PATH) +- return; +- } ++ // at Vista (ver 6.0) : CoCreateInstance(CLSID_ShellLink, ...) doesn't work after SetDefaultDllDirectories() : Check it ??? ++ IF_NON_VISTA_SET_DLL_DIRS_AND_RETURN + { ++ wchar_t buf[MAX_PATH + 100]; + const char *dll; +- unsigned pos = (unsigned)lstrlenW(buf); +- ++ unsigned pos = GetSystemDirectoryW(buf, MAX_PATH + 2); ++ if (pos == 0 || pos > MAX_PATH) ++ return; + if (buf[pos - 1] != '\\') + buf[pos++] = '\\'; +- +- for (dll = g_Dlls; dll[0] != 0;) ++ for (dll = g_Dlls; *dll != 0;) + { +- unsigned k = 0; ++ wchar_t *dest = &buf[pos]; + for (;;) + { +- char c = *dll++; +- buf[pos + k] = (Byte)c; +- k++; ++ const char c = *dll++; + if (c == 0) + break; ++ *dest++ = (Byte)c; + } +- +- lstrcatW(buf, L".dll"); ++ dest[0] = '.'; ++ dest[1] = 'd'; ++ dest[2] = 'l'; ++ dest[3] = 'l'; ++ dest[4] = 0; ++ // lstrcatW(buf, L".dll"); + LoadLibraryExW(buf, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); + } + } +- + #endif + } + +-#endif ++#endif // _WIN32 +diff --git a/src/lzma/DllSecur.h b/src/lzma/DllSecur.h +index 64ff26cd9..9fa415382 100644 +--- a/src/lzma/DllSecur.h ++++ b/src/lzma/DllSecur.h +@@ -1,8 +1,8 @@ + /* DllSecur.h -- DLL loading for security +-2018-02-19 : Igor Pavlov : Public domain */ ++2023-03-03 : Igor Pavlov : Public domain */ + +-#ifndef __DLL_SECUR_H +-#define __DLL_SECUR_H ++#ifndef ZIP7_INC_DLL_SECUR_H ++#define ZIP7_INC_DLL_SECUR_H + + #include "7zTypes.h" + +diff --git a/src/lzma/LzFind.c b/src/lzma/LzFind.c +index 1b73c2848..0fbd5aae5 100644 +--- a/src/lzma/LzFind.c ++++ b/src/lzma/LzFind.c +@@ -1,5 +1,5 @@ + /* LzFind.c -- Match finder for LZ algorithms +-2021-11-29 : Igor Pavlov : Public domain */ ++2023-03-14 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -17,7 +17,7 @@ + #define kEmptyHashValue 0 + + #define kMaxValForNormalize ((UInt32)0) +-// #define kMaxValForNormalize ((UInt32)(1 << 20) + 0xFFF) // for debug ++// #define kMaxValForNormalize ((UInt32)(1 << 20) + 0xfff) // for debug + + // #define kNormalizeAlign (1 << 7) // alignment for speculated accesses + +@@ -67,10 +67,10 @@ + + static void LzInWindow_Free(CMatchFinder *p, ISzAllocPtr alloc) + { +- if (!p->directInput) ++ // if (!p->directInput) + { +- ISzAlloc_Free(alloc, p->bufferBase); +- p->bufferBase = NULL; ++ ISzAlloc_Free(alloc, p->bufBase); ++ p->bufBase = NULL; + } + } + +@@ -79,7 +79,7 @@ static int LzInWindow_Create2(CMatchFinder *p, UInt32 blockSize, ISzAllocPtr all + { + if (blockSize == 0) + return 0; +- if (!p->bufferBase || p->blockSize != blockSize) ++ if (!p->bufBase || p->blockSize != blockSize) + { + // size_t blockSizeT; + LzInWindow_Free(p, alloc); +@@ -101,11 +101,11 @@ static int LzInWindow_Create2(CMatchFinder *p, UInt32 blockSize, ISzAllocPtr all + #endif + */ + +- p->bufferBase = (Byte *)ISzAlloc_Alloc(alloc, blockSize); +- // printf("\nbufferBase = %p\n", p->bufferBase); ++ p->bufBase = (Byte *)ISzAlloc_Alloc(alloc, blockSize); ++ // printf("\nbufferBase = %p\n", p->bufBase); + // return 0; // for debug + } +- return (p->bufferBase != NULL); ++ return (p->bufBase != NULL); + } + + static const Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p) { return p->buffer; } +@@ -113,7 +113,7 @@ static const Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p) { return + static UInt32 MatchFinder_GetNumAvailableBytes(CMatchFinder *p) { return GET_AVAIL_BYTES(p); } + + +-MY_NO_INLINE ++Z7_NO_INLINE + static void MatchFinder_ReadBlock(CMatchFinder *p) + { + if (p->streamEndWasReached || p->result != SZ_OK) +@@ -127,8 +127,8 @@ static void MatchFinder_ReadBlock(CMatchFinder *p) + UInt32 curSize = 0xFFFFFFFF - GET_AVAIL_BYTES(p); + if (curSize > p->directInputRem) + curSize = (UInt32)p->directInputRem; +- p->directInputRem -= curSize; + p->streamPos += curSize; ++ p->directInputRem -= curSize; + if (p->directInputRem == 0) + p->streamEndWasReached = 1; + return; +@@ -136,8 +136,8 @@ static void MatchFinder_ReadBlock(CMatchFinder *p) + + for (;;) + { +- Byte *dest = p->buffer + GET_AVAIL_BYTES(p); +- size_t size = (size_t)(p->bufferBase + p->blockSize - dest); ++ const Byte *dest = p->buffer + GET_AVAIL_BYTES(p); ++ size_t size = (size_t)(p->bufBase + p->blockSize - dest); + if (size == 0) + { + /* we call ReadBlock() after NeedMove() and MoveBlock(). +@@ -153,7 +153,14 @@ static void MatchFinder_ReadBlock(CMatchFinder *p) + // #define kRead 3 + // if (size > kRead) size = kRead; // for debug + +- p->result = ISeqInStream_Read(p->stream, dest, &size); ++ /* ++ // we need cast (Byte *)dest. ++ #ifdef __clang__ ++ #pragma GCC diagnostic ignored "-Wcast-qual" ++ #endif ++ */ ++ p->result = ISeqInStream_Read(p->stream, ++ p->bufBase + (dest - p->bufBase), &size); + if (p->result != SZ_OK) + return; + if (size == 0) +@@ -173,14 +180,14 @@ static void MatchFinder_ReadBlock(CMatchFinder *p) + + + +-MY_NO_INLINE ++Z7_NO_INLINE + void MatchFinder_MoveBlock(CMatchFinder *p) + { +- const size_t offset = (size_t)(p->buffer - p->bufferBase) - p->keepSizeBefore; ++ const size_t offset = (size_t)(p->buffer - p->bufBase) - p->keepSizeBefore; + const size_t keepBefore = (offset & (kBlockMoveAlign - 1)) + p->keepSizeBefore; +- p->buffer = p->bufferBase + keepBefore; +- memmove(p->bufferBase, +- p->bufferBase + (offset & ~((size_t)kBlockMoveAlign - 1)), ++ p->buffer = p->bufBase + keepBefore; ++ memmove(p->bufBase, ++ p->bufBase + (offset & ~((size_t)kBlockMoveAlign - 1)), + keepBefore + (size_t)GET_AVAIL_BYTES(p)); + } + +@@ -198,7 +205,7 @@ int MatchFinder_NeedMove(CMatchFinder *p) + return 0; + if (p->streamEndWasReached || p->result != SZ_OK) + return 0; +- return ((size_t)(p->bufferBase + p->blockSize - p->buffer) <= p->keepSizeAfter); ++ return ((size_t)(p->bufBase + p->blockSize - p->buffer) <= p->keepSizeAfter); + } + + void MatchFinder_ReadIfRequired(CMatchFinder *p) +@@ -214,6 +221,8 @@ static void MatchFinder_SetDefaultSettings(CMatchFinder *p) + p->cutValue = 32; + p->btMode = 1; + p->numHashBytes = 4; ++ p->numHashBytes_Min = 2; ++ p->numHashOutBits = 0; + p->bigHash = 0; + } + +@@ -222,8 +231,10 @@ static void MatchFinder_SetDefaultSettings(CMatchFinder *p) + void MatchFinder_Construct(CMatchFinder *p) + { + unsigned i; +- p->bufferBase = NULL; ++ p->buffer = NULL; ++ p->bufBase = NULL; + p->directInput = 0; ++ p->stream = NULL; + p->hash = NULL; + p->expectedDataSize = (UInt64)(Int64)-1; + MatchFinder_SetDefaultSettings(p); +@@ -238,6 +249,8 @@ void MatchFinder_Construct(CMatchFinder *p) + } + } + ++#undef kCrcPoly ++ + static void MatchFinder_FreeThisClassMemory(CMatchFinder *p, ISzAllocPtr alloc) + { + ISzAlloc_Free(alloc, p->hash); +@@ -252,7 +265,7 @@ void MatchFinder_Free(CMatchFinder *p, ISzAllocPtr alloc) + + static CLzRef* AllocRefs(size_t num, ISzAllocPtr alloc) + { +- size_t sizeInBytes = (size_t)num * sizeof(CLzRef); ++ const size_t sizeInBytes = (size_t)num * sizeof(CLzRef); + if (sizeInBytes / sizeof(CLzRef) != num) + return NULL; + return (CLzRef *)ISzAlloc_Alloc(alloc, sizeInBytes); +@@ -298,6 +311,62 @@ static UInt32 GetBlockSize(CMatchFinder *p, UInt32 historySize) + } + + ++// input is historySize ++static UInt32 MatchFinder_GetHashMask2(CMatchFinder *p, UInt32 hs) ++{ ++ if (p->numHashBytes == 2) ++ return (1 << 16) - 1; ++ if (hs != 0) ++ hs--; ++ hs |= (hs >> 1); ++ hs |= (hs >> 2); ++ hs |= (hs >> 4); ++ hs |= (hs >> 8); ++ // we propagated 16 bits in (hs). Low 16 bits must be set later ++ if (hs >= (1 << 24)) ++ { ++ if (p->numHashBytes == 3) ++ hs = (1 << 24) - 1; ++ /* if (bigHash) mode, GetHeads4b() in LzFindMt.c needs (hs >= ((1 << 24) - 1))) */ ++ } ++ // (hash_size >= (1 << 16)) : Required for (numHashBytes > 2) ++ hs |= (1 << 16) - 1; /* don't change it! */ ++ // bt5: we adjust the size with recommended minimum size ++ if (p->numHashBytes >= 5) ++ hs |= (256 << kLzHash_CrcShift_2) - 1; ++ return hs; ++} ++ ++// input is historySize ++static UInt32 MatchFinder_GetHashMask(CMatchFinder *p, UInt32 hs) ++{ ++ if (p->numHashBytes == 2) ++ return (1 << 16) - 1; ++ if (hs != 0) ++ hs--; ++ hs |= (hs >> 1); ++ hs |= (hs >> 2); ++ hs |= (hs >> 4); ++ hs |= (hs >> 8); ++ // we propagated 16 bits in (hs). Low 16 bits must be set later ++ hs >>= 1; ++ if (hs >= (1 << 24)) ++ { ++ if (p->numHashBytes == 3) ++ hs = (1 << 24) - 1; ++ else ++ hs >>= 1; ++ /* if (bigHash) mode, GetHeads4b() in LzFindMt.c needs (hs >= ((1 << 24) - 1))) */ ++ } ++ // (hash_size >= (1 << 16)) : Required for (numHashBytes > 2) ++ hs |= (1 << 16) - 1; /* don't change it! */ ++ // bt5: we adjust the size with recommended minimum size ++ if (p->numHashBytes >= 5) ++ hs |= (256 << kLzHash_CrcShift_2) - 1; ++ return hs; ++} ++ ++ + int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, + UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, + ISzAllocPtr alloc) +@@ -318,78 +387,91 @@ int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, + p->blockSize = 0; + if (p->directInput || LzInWindow_Create2(p, GetBlockSize(p, historySize), alloc)) + { +- const UInt32 newCyclicBufferSize = historySize + 1; // do not change it +- UInt32 hs; +- p->matchMaxLen = matchMaxLen; ++ size_t hashSizeSum; + { +- // UInt32 hs4; +- p->fixedHashSize = 0; +- hs = (1 << 16) - 1; +- if (p->numHashBytes != 2) ++ UInt32 hs; ++ UInt32 hsCur; ++ ++ if (p->numHashOutBits != 0) + { +- hs = historySize; +- if (hs > p->expectedDataSize) +- hs = (UInt32)p->expectedDataSize; +- if (hs != 0) +- hs--; +- hs |= (hs >> 1); +- hs |= (hs >> 2); +- hs |= (hs >> 4); +- hs |= (hs >> 8); +- // we propagated 16 bits in (hs). Low 16 bits must be set later +- hs >>= 1; +- if (hs >= (1 << 24)) +- { +- if (p->numHashBytes == 3) +- hs = (1 << 24) - 1; +- else +- hs >>= 1; +- /* if (bigHash) mode, GetHeads4b() in LzFindMt.c needs (hs >= ((1 << 24) - 1))) */ +- } +- +- // hs = ((UInt32)1 << 25) - 1; // for test +- ++ unsigned numBits = p->numHashOutBits; ++ const unsigned nbMax = ++ (p->numHashBytes == 2 ? 16 : ++ (p->numHashBytes == 3 ? 24 : 32)); ++ if (numBits > nbMax) ++ numBits = nbMax; ++ if (numBits >= 32) ++ hs = (UInt32)0 - 1; ++ else ++ hs = ((UInt32)1 << numBits) - 1; + // (hash_size >= (1 << 16)) : Required for (numHashBytes > 2) + hs |= (1 << 16) - 1; /* don't change it! */ +- +- // bt5: we adjust the size with recommended minimum size + if (p->numHashBytes >= 5) + hs |= (256 << kLzHash_CrcShift_2) - 1; ++ { ++ const UInt32 hs2 = MatchFinder_GetHashMask2(p, historySize); ++ if (hs > hs2) ++ hs = hs2; ++ } ++ hsCur = hs; ++ if (p->expectedDataSize < historySize) ++ { ++ const UInt32 hs2 = MatchFinder_GetHashMask2(p, (UInt32)p->expectedDataSize); ++ if (hsCur > hs2) ++ hsCur = hs2; ++ } + } +- p->hashMask = hs; +- hs++; +- +- /* +- hs4 = (1 << 20); +- if (hs4 > hs) +- hs4 = hs; +- // hs4 = (1 << 16); // for test +- p->hash4Mask = hs4 - 1; +- */ ++ else ++ { ++ hs = MatchFinder_GetHashMask(p, historySize); ++ hsCur = hs; ++ if (p->expectedDataSize < historySize) ++ { ++ hsCur = MatchFinder_GetHashMask(p, (UInt32)p->expectedDataSize); ++ if (hsCur > hs) // is it possible? ++ hsCur = hs; ++ } ++ } ++ ++ p->hashMask = hsCur; + +- if (p->numHashBytes > 2) p->fixedHashSize += kHash2Size; +- if (p->numHashBytes > 3) p->fixedHashSize += kHash3Size; +- // if (p->numHashBytes > 4) p->fixedHashSize += hs4; // kHash4Size; +- hs += p->fixedHashSize; ++ hashSizeSum = hs; ++ hashSizeSum++; ++ if (hashSizeSum < hs) ++ return 0; ++ { ++ UInt32 fixedHashSize = 0; ++ if (p->numHashBytes > 2 && p->numHashBytes_Min <= 2) fixedHashSize += kHash2Size; ++ if (p->numHashBytes > 3 && p->numHashBytes_Min <= 3) fixedHashSize += kHash3Size; ++ // if (p->numHashBytes > 4) p->fixedHashSize += hs4; // kHash4Size; ++ hashSizeSum += fixedHashSize; ++ p->fixedHashSize = fixedHashSize; ++ } + } + ++ p->matchMaxLen = matchMaxLen; ++ + { + size_t newSize; + size_t numSons; ++ const UInt32 newCyclicBufferSize = historySize + 1; // do not change it + p->historySize = historySize; +- p->hashSizeSum = hs; + p->cyclicBufferSize = newCyclicBufferSize; // it must be = (historySize + 1) + + numSons = newCyclicBufferSize; + if (p->btMode) + numSons <<= 1; +- newSize = hs + numSons; ++ newSize = hashSizeSum + numSons; ++ ++ if (numSons < newCyclicBufferSize || newSize < numSons) ++ return 0; + + // aligned size is not required here, but it can be better for some loops + #define NUM_REFS_ALIGN_MASK 0xF + newSize = (newSize + NUM_REFS_ALIGN_MASK) & ~(size_t)NUM_REFS_ALIGN_MASK; + +- if (p->hash && p->numRefs == newSize) ++ // 22.02: we don't reallocate buffer, if old size is enough ++ if (p->hash && p->numRefs >= newSize) + return 1; + + MatchFinder_FreeThisClassMemory(p, alloc); +@@ -398,7 +480,7 @@ int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, + + if (p->hash) + { +- p->son = p->hash + p->hashSizeSum; ++ p->son = p->hash + hashSizeSum; + return 1; + } + } +@@ -470,7 +552,8 @@ void MatchFinder_Init_HighHash(CMatchFinder *p) + + void MatchFinder_Init_4(CMatchFinder *p) + { +- p->buffer = p->bufferBase; ++ if (!p->directInput) ++ p->buffer = p->bufBase; + { + /* kEmptyHashValue = 0 (Zero) is used in hash tables as NO-VALUE marker. + the code in CMatchFinderMt expects (pos = 1) */ +@@ -507,20 +590,20 @@ void MatchFinder_Init(CMatchFinder *p) + + + #ifdef MY_CPU_X86_OR_AMD64 +- #if defined(__clang__) && (__clang_major__ >= 8) \ +- || defined(__GNUC__) && (__GNUC__ >= 8) \ +- || defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1900) +- #define USE_SATUR_SUB_128 +- #define USE_AVX2 +- #define ATTRIB_SSE41 __attribute__((__target__("sse4.1"))) +- #define ATTRIB_AVX2 __attribute__((__target__("avx2"))) ++ #if defined(__clang__) && (__clang_major__ >= 4) \ ++ || defined(Z7_GCC_VERSION) && (Z7_GCC_VERSION >= 40701) ++ // || defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1900) ++ ++ #define USE_LZFIND_SATUR_SUB_128 ++ #define USE_LZFIND_SATUR_SUB_256 ++ #define LZFIND_ATTRIB_SSE41 __attribute__((__target__("sse4.1"))) ++ #define LZFIND_ATTRIB_AVX2 __attribute__((__target__("avx2"))) + #elif defined(_MSC_VER) + #if (_MSC_VER >= 1600) +- #define USE_SATUR_SUB_128 +- #if (_MSC_VER >= 1900) +- #define USE_AVX2 +- #include // avx +- #endif ++ #define USE_LZFIND_SATUR_SUB_128 ++ #endif ++ #if (_MSC_VER >= 1900) ++ #define USE_LZFIND_SATUR_SUB_256 + #endif + #endif + +@@ -529,16 +612,16 @@ void MatchFinder_Init(CMatchFinder *p) + + #if defined(__clang__) && (__clang_major__ >= 8) \ + || defined(__GNUC__) && (__GNUC__ >= 8) +- #define USE_SATUR_SUB_128 ++ #define USE_LZFIND_SATUR_SUB_128 + #ifdef MY_CPU_ARM64 +- // #define ATTRIB_SSE41 __attribute__((__target__(""))) ++ // #define LZFIND_ATTRIB_SSE41 __attribute__((__target__(""))) + #else +- // #define ATTRIB_SSE41 __attribute__((__target__("fpu=crypto-neon-fp-armv8"))) ++ // #define LZFIND_ATTRIB_SSE41 __attribute__((__target__("fpu=crypto-neon-fp-armv8"))) + #endif + + #elif defined(_MSC_VER) + #if (_MSC_VER >= 1910) +- #define USE_SATUR_SUB_128 ++ #define USE_LZFIND_SATUR_SUB_128 + #endif + #endif + +@@ -550,121 +633,130 @@ void MatchFinder_Init(CMatchFinder *p) + + #endif + +-/* +-#ifndef ATTRIB_SSE41 +- #define ATTRIB_SSE41 +-#endif +-#ifndef ATTRIB_AVX2 +- #define ATTRIB_AVX2 +-#endif +-*/ + +-#ifdef USE_SATUR_SUB_128 ++#ifdef USE_LZFIND_SATUR_SUB_128 + +-// #define _SHOW_HW_STATUS ++// #define Z7_SHOW_HW_STATUS + +-#ifdef _SHOW_HW_STATUS ++#ifdef Z7_SHOW_HW_STATUS + #include +-#define _PRF(x) x +-_PRF(;) ++#define PRF(x) x ++PRF(;) + #else +-#define _PRF(x) ++#define PRF(x) + #endif + ++ + #ifdef MY_CPU_ARM_OR_ARM64 + + #ifdef MY_CPU_ARM64 +-// #define FORCE_SATUR_SUB_128 ++// #define FORCE_LZFIND_SATUR_SUB_128 + #endif ++typedef uint32x4_t LzFind_v128; ++#define SASUB_128_V(v, s) \ ++ vsubq_u32(vmaxq_u32(v, s), s) + +-typedef uint32x4_t v128; +-#define SASUB_128(i) \ +- *(v128 *)(void *)(items + (i) * 4) = \ +- vsubq_u32(vmaxq_u32(*(const v128 *)(const void *)(items + (i) * 4), sub2), sub2); +- +-#else ++#else // MY_CPU_ARM_OR_ARM64 + + #include // sse4.1 + +-typedef __m128i v128; +-#define SASUB_128(i) \ +- *(v128 *)(void *)(items + (i) * 4) = \ +- _mm_sub_epi32(_mm_max_epu32(*(const v128 *)(const void *)(items + (i) * 4), sub2), sub2); // SSE 4.1 ++typedef __m128i LzFind_v128; ++// SSE 4.1 ++#define SASUB_128_V(v, s) \ ++ _mm_sub_epi32(_mm_max_epu32(v, s), s) + +-#endif ++#endif // MY_CPU_ARM_OR_ARM64 + + ++#define SASUB_128(i) \ ++ *( LzFind_v128 *)( void *)(items + (i) * 4) = SASUB_128_V( \ ++ *(const LzFind_v128 *)(const void *)(items + (i) * 4), sub2); ++ + +-MY_NO_INLINE ++Z7_NO_INLINE + static +-#ifdef ATTRIB_SSE41 +-ATTRIB_SSE41 ++#ifdef LZFIND_ATTRIB_SSE41 ++LZFIND_ATTRIB_SSE41 + #endif + void +-MY_FAST_CALL ++Z7_FASTCALL + LzFind_SaturSub_128(UInt32 subValue, CLzRef *items, const CLzRef *lim) + { +- v128 sub2 = ++ const LzFind_v128 sub2 = + #ifdef MY_CPU_ARM_OR_ARM64 + vdupq_n_u32(subValue); + #else + _mm_set_epi32((Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue); + #endif ++ Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + do + { +- SASUB_128(0) +- SASUB_128(1) +- SASUB_128(2) +- SASUB_128(3) +- items += 4 * 4; ++ SASUB_128(0) SASUB_128(1) items += 2 * 4; ++ SASUB_128(0) SASUB_128(1) items += 2 * 4; + } + while (items != lim); + } + + + +-#ifdef USE_AVX2 ++#ifdef USE_LZFIND_SATUR_SUB_256 + + #include // avx ++/* ++clang :immintrin.h uses ++#if !(defined(_MSC_VER) || defined(__SCE__)) || __has_feature(modules) || \ ++ defined(__AVX2__) ++#include ++#endif ++so we need for clang-cl */ + +-#define SASUB_256(i) *(__m256i *)(void *)(items + (i) * 8) = _mm256_sub_epi32(_mm256_max_epu32(*(const __m256i *)(const void *)(items + (i) * 8), sub2), sub2); // AVX2 ++#if defined(__clang__) ++#include ++#include ++#endif + +-MY_NO_INLINE ++// AVX2: ++#define SASUB_256(i) \ ++ *( __m256i *)( void *)(items + (i) * 8) = \ ++ _mm256_sub_epi32(_mm256_max_epu32( \ ++ *(const __m256i *)(const void *)(items + (i) * 8), sub2), sub2); ++ ++Z7_NO_INLINE + static +-#ifdef ATTRIB_AVX2 +-ATTRIB_AVX2 ++#ifdef LZFIND_ATTRIB_AVX2 ++LZFIND_ATTRIB_AVX2 + #endif + void +-MY_FAST_CALL ++Z7_FASTCALL + LzFind_SaturSub_256(UInt32 subValue, CLzRef *items, const CLzRef *lim) + { +- __m256i sub2 = _mm256_set_epi32( ++ const __m256i sub2 = _mm256_set_epi32( + (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue, + (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue); ++ Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + do + { +- SASUB_256(0) +- SASUB_256(1) +- items += 2 * 8; ++ SASUB_256(0) SASUB_256(1) items += 2 * 8; ++ SASUB_256(0) SASUB_256(1) items += 2 * 8; + } + while (items != lim); + } +-#endif // USE_AVX2 ++#endif // USE_LZFIND_SATUR_SUB_256 + +-#ifndef FORCE_SATUR_SUB_128 +-typedef void (MY_FAST_CALL *LZFIND_SATUR_SUB_CODE_FUNC)( ++#ifndef FORCE_LZFIND_SATUR_SUB_128 ++typedef void (Z7_FASTCALL *LZFIND_SATUR_SUB_CODE_FUNC)( + UInt32 subValue, CLzRef *items, const CLzRef *lim); + static LZFIND_SATUR_SUB_CODE_FUNC g_LzFind_SaturSub; +-#endif // FORCE_SATUR_SUB_128 ++#endif // FORCE_LZFIND_SATUR_SUB_128 + +-#endif // USE_SATUR_SUB_128 ++#endif // USE_LZFIND_SATUR_SUB_128 + + + // kEmptyHashValue must be zero +-// #define SASUB_32(i) v = items[i]; m = v - subValue; if (v < subValue) m = kEmptyHashValue; items[i] = m; +-#define SASUB_32(i) v = items[i]; if (v < subValue) v = subValue; items[i] = v - subValue; ++// #define SASUB_32(i) { UInt32 v = items[i]; UInt32 m = v - subValue; if (v < subValue) m = kEmptyHashValue; items[i] = m; } ++#define SASUB_32(i) { UInt32 v = items[i]; if (v < subValue) v = subValue; items[i] = v - subValue; } + +-#ifdef FORCE_SATUR_SUB_128 ++#ifdef FORCE_LZFIND_SATUR_SUB_128 + + #define DEFAULT_SaturSub LzFind_SaturSub_128 + +@@ -672,24 +764,19 @@ static LZFIND_SATUR_SUB_CODE_FUNC g_LzFind_SaturSub; + + #define DEFAULT_SaturSub LzFind_SaturSub_32 + +-MY_NO_INLINE ++Z7_NO_INLINE + static + void +-MY_FAST_CALL ++Z7_FASTCALL + LzFind_SaturSub_32(UInt32 subValue, CLzRef *items, const CLzRef *lim) + { ++ Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + do + { +- UInt32 v; +- SASUB_32(0) +- SASUB_32(1) +- SASUB_32(2) +- SASUB_32(3) +- SASUB_32(4) +- SASUB_32(5) +- SASUB_32(6) +- SASUB_32(7) +- items += 8; ++ SASUB_32(0) SASUB_32(1) items += 2; ++ SASUB_32(0) SASUB_32(1) items += 2; ++ SASUB_32(0) SASUB_32(1) items += 2; ++ SASUB_32(0) SASUB_32(1) items += 2; + } + while (items != lim); + } +@@ -697,27 +784,23 @@ LzFind_SaturSub_32(UInt32 subValue, CLzRef *items, const CLzRef *lim) + #endif + + +-MY_NO_INLINE ++Z7_NO_INLINE + void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems) + { +- #define K_NORM_ALIGN_BLOCK_SIZE (1 << 6) +- +- CLzRef *lim; +- +- for (; numItems != 0 && ((unsigned)(ptrdiff_t)items & (K_NORM_ALIGN_BLOCK_SIZE - 1)) != 0; numItems--) ++ #define LZFIND_NORM_ALIGN_BLOCK_SIZE (1 << 7) ++ Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE ++ for (; numItems != 0 && ((unsigned)(ptrdiff_t)items & (LZFIND_NORM_ALIGN_BLOCK_SIZE - 1)) != 0; numItems--) + { +- UInt32 v; +- SASUB_32(0); ++ SASUB_32(0) + items++; + } +- + { +- #define K_NORM_ALIGN_MASK (K_NORM_ALIGN_BLOCK_SIZE / 4 - 1) +- lim = items + (numItems & ~(size_t)K_NORM_ALIGN_MASK); +- numItems &= K_NORM_ALIGN_MASK; ++ const size_t k_Align_Mask = (LZFIND_NORM_ALIGN_BLOCK_SIZE / 4 - 1); ++ CLzRef *lim = items + (numItems & ~(size_t)k_Align_Mask); ++ numItems &= k_Align_Mask; + if (items != lim) + { +- #if defined(USE_SATUR_SUB_128) && !defined(FORCE_SATUR_SUB_128) ++ #if defined(USE_LZFIND_SATUR_SUB_128) && !defined(FORCE_LZFIND_SATUR_SUB_128) + if (g_LzFind_SaturSub) + g_LzFind_SaturSub(subValue, items, lim); + else +@@ -726,12 +809,10 @@ void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems) + } + items = lim; + } +- +- ++ Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + for (; numItems != 0; numItems--) + { +- UInt32 v; +- SASUB_32(0); ++ SASUB_32(0) + items++; + } + } +@@ -740,7 +821,7 @@ void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems) + + // call MatchFinder_CheckLimits() only after (p->pos++) update + +-MY_NO_INLINE ++Z7_NO_INLINE + static void MatchFinder_CheckLimits(CMatchFinder *p) + { + if (// !p->streamEndWasReached && p->result == SZ_OK && +@@ -768,11 +849,14 @@ static void MatchFinder_CheckLimits(CMatchFinder *p) + const UInt32 subValue = (p->pos - p->historySize - 1) /* & ~(UInt32)(kNormalizeAlign - 1) */; + // const UInt32 subValue = (1 << 15); // for debug + // printf("\nMatchFinder_Normalize() subValue == 0x%x\n", subValue); +- size_t numSonRefs = p->cyclicBufferSize; +- if (p->btMode) +- numSonRefs <<= 1; +- Inline_MatchFinder_ReduceOffsets(p, subValue); +- MatchFinder_Normalize3(subValue, p->hash, (size_t)p->hashSizeSum + numSonRefs); ++ MatchFinder_REDUCE_OFFSETS(p, subValue) ++ MatchFinder_Normalize3(subValue, p->hash, (size_t)p->hashMask + 1 + p->fixedHashSize); ++ { ++ size_t numSonRefs = p->cyclicBufferSize; ++ if (p->btMode) ++ numSonRefs <<= 1; ++ MatchFinder_Normalize3(subValue, p->son, numSonRefs); ++ } + } + + if (p->cyclicBufferPos == p->cyclicBufferSize) +@@ -785,7 +869,7 @@ static void MatchFinder_CheckLimits(CMatchFinder *p) + /* + (lenLimit > maxLen) + */ +-MY_FORCE_INLINE ++Z7_FORCE_INLINE + static UInt32 * Hc_GetMatchesSpec(size_t lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, + size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, + UInt32 *d, unsigned maxLen) +@@ -867,7 +951,7 @@ static UInt32 * Hc_GetMatchesSpec(size_t lenLimit, UInt32 curMatch, UInt32 pos, + } + + +-MY_FORCE_INLINE ++Z7_FORCE_INLINE + UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, + size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, + UInt32 *d, UInt32 maxLen) +@@ -1004,7 +1088,7 @@ static void SkipMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const + + #define MOVE_POS_RET MOVE_POS return distances; + +-MY_NO_INLINE ++Z7_NO_INLINE + static void MatchFinder_MovePos(CMatchFinder *p) + { + /* we go here at the end of stream data, when (avail < num_hash_bytes) +@@ -1015,11 +1099,11 @@ static void MatchFinder_MovePos(CMatchFinder *p) + if (p->btMode) + p->sons[(p->cyclicBufferPos << p->btMode) + 1] = 0; // kEmptyHashValue + */ +- MOVE_POS; ++ MOVE_POS + } + + #define GET_MATCHES_HEADER2(minLen, ret_op) \ +- unsigned lenLimit; UInt32 hv; Byte *cur; UInt32 curMatch; \ ++ unsigned lenLimit; UInt32 hv; const Byte *cur; UInt32 curMatch; \ + lenLimit = (unsigned)p->lenLimit; { if (lenLimit < minLen) { MatchFinder_MovePos(p); ret_op; }} \ + cur = p->buffer; + +@@ -1028,11 +1112,11 @@ static void MatchFinder_MovePos(CMatchFinder *p) + + #define MF_PARAMS(p) lenLimit, curMatch, p->pos, p->buffer, p->son, p->cyclicBufferPos, p->cyclicBufferSize, p->cutValue + +-#define SKIP_FOOTER SkipMatchesSpec(MF_PARAMS(p)); MOVE_POS; } while (--num); ++#define SKIP_FOOTER SkipMatchesSpec(MF_PARAMS(p)); MOVE_POS } while (--num); + + #define GET_MATCHES_FOOTER_BASE(_maxLen_, func) \ + distances = func(MF_PARAMS(p), \ +- distances, (UInt32)_maxLen_); MOVE_POS_RET; ++ distances, (UInt32)_maxLen_); MOVE_POS_RET + + #define GET_MATCHES_FOOTER_BT(_maxLen_) \ + GET_MATCHES_FOOTER_BASE(_maxLen_, GetMatchesSpec1) +@@ -1052,7 +1136,7 @@ static void MatchFinder_MovePos(CMatchFinder *p) + static UInt32* Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) + { + GET_MATCHES_HEADER(2) +- HASH2_CALC; ++ HASH2_CALC + curMatch = p->hash[hv]; + p->hash[hv] = p->pos; + GET_MATCHES_FOOTER_BT(1) +@@ -1061,7 +1145,7 @@ static UInt32* Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) + UInt32* Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) + { + GET_MATCHES_HEADER(3) +- HASH_ZIP_CALC; ++ HASH_ZIP_CALC + curMatch = p->hash[hv]; + p->hash[hv] = p->pos; + GET_MATCHES_FOOTER_BT(2) +@@ -1082,7 +1166,7 @@ static UInt32* Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) + UInt32 *hash; + GET_MATCHES_HEADER(3) + +- HASH3_CALC; ++ HASH3_CALC + + hash = p->hash; + pos = p->pos; +@@ -1107,7 +1191,7 @@ static UInt32* Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) + if (maxLen == lenLimit) + { + SkipMatchesSpec(MF_PARAMS(p)); +- MOVE_POS_RET; ++ MOVE_POS_RET + } + } + +@@ -1123,7 +1207,7 @@ static UInt32* Bt4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) + UInt32 *hash; + GET_MATCHES_HEADER(4) + +- HASH4_CALC; ++ HASH4_CALC + + hash = p->hash; + pos = p->pos; +@@ -1190,7 +1274,7 @@ static UInt32* Bt5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) + UInt32 *hash; + GET_MATCHES_HEADER(5) + +- HASH5_CALC; ++ HASH5_CALC + + hash = p->hash; + pos = p->pos; +@@ -1246,7 +1330,7 @@ static UInt32* Bt5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) + if (maxLen == lenLimit) + { + SkipMatchesSpec(MF_PARAMS(p)); +- MOVE_POS_RET; ++ MOVE_POS_RET + } + break; + } +@@ -1263,7 +1347,7 @@ static UInt32* Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) + UInt32 *hash; + GET_MATCHES_HEADER(4) + +- HASH4_CALC; ++ HASH4_CALC + + hash = p->hash; + pos = p->pos; +@@ -1314,12 +1398,12 @@ static UInt32* Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) + if (maxLen == lenLimit) + { + p->son[p->cyclicBufferPos] = curMatch; +- MOVE_POS_RET; ++ MOVE_POS_RET + } + break; + } + +- GET_MATCHES_FOOTER_HC(maxLen); ++ GET_MATCHES_FOOTER_HC(maxLen) + } + + +@@ -1330,7 +1414,7 @@ static UInt32 * Hc5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) + UInt32 *hash; + GET_MATCHES_HEADER(5) + +- HASH5_CALC; ++ HASH5_CALC + + hash = p->hash; + pos = p->pos; +@@ -1386,19 +1470,19 @@ static UInt32 * Hc5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) + if (maxLen == lenLimit) + { + p->son[p->cyclicBufferPos] = curMatch; +- MOVE_POS_RET; ++ MOVE_POS_RET + } + break; + } + +- GET_MATCHES_FOOTER_HC(maxLen); ++ GET_MATCHES_FOOTER_HC(maxLen) + } + + + UInt32* Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) + { + GET_MATCHES_HEADER(3) +- HASH_ZIP_CALC; ++ HASH_ZIP_CALC + curMatch = p->hash[hv]; + p->hash[hv] = p->pos; + GET_MATCHES_FOOTER_HC(2) +@@ -1409,7 +1493,7 @@ static void Bt2_MatchFinder_Skip(CMatchFinder *p, UInt32 num) + { + SKIP_HEADER(2) + { +- HASH2_CALC; ++ HASH2_CALC + curMatch = p->hash[hv]; + p->hash[hv] = p->pos; + } +@@ -1420,7 +1504,7 @@ void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num) + { + SKIP_HEADER(3) + { +- HASH_ZIP_CALC; ++ HASH_ZIP_CALC + curMatch = p->hash[hv]; + p->hash[hv] = p->pos; + } +@@ -1433,7 +1517,7 @@ static void Bt3_MatchFinder_Skip(CMatchFinder *p, UInt32 num) + { + UInt32 h2; + UInt32 *hash; +- HASH3_CALC; ++ HASH3_CALC + hash = p->hash; + curMatch = (hash + kFix3HashSize)[hv]; + hash[h2] = +@@ -1448,7 +1532,7 @@ static void Bt4_MatchFinder_Skip(CMatchFinder *p, UInt32 num) + { + UInt32 h2, h3; + UInt32 *hash; +- HASH4_CALC; ++ HASH4_CALC + hash = p->hash; + curMatch = (hash + kFix4HashSize)[hv]; + hash [h2] = +@@ -1464,7 +1548,7 @@ static void Bt5_MatchFinder_Skip(CMatchFinder *p, UInt32 num) + { + UInt32 h2, h3; + UInt32 *hash; +- HASH5_CALC; ++ HASH5_CALC + hash = p->hash; + curMatch = (hash + kFix5HashSize)[hv]; + hash [h2] = +@@ -1478,7 +1562,7 @@ static void Bt5_MatchFinder_Skip(CMatchFinder *p, UInt32 num) + + #define HC_SKIP_HEADER(minLen) \ + do { if (p->lenLimit < minLen) { MatchFinder_MovePos(p); num--; continue; } { \ +- Byte *cur; \ ++ const Byte *cur; \ + UInt32 *hash; \ + UInt32 *son; \ + UInt32 pos = p->pos; \ +@@ -1510,7 +1594,7 @@ static void Hc4_MatchFinder_Skip(CMatchFinder *p, UInt32 num) + HC_SKIP_HEADER(4) + + UInt32 h2, h3; +- HASH4_CALC; ++ HASH4_CALC + curMatch = (hash + kFix4HashSize)[hv]; + hash [h2] = + (hash + kFix3HashSize)[h3] = +@@ -1540,7 +1624,7 @@ void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num) + { + HC_SKIP_HEADER(3) + +- HASH_ZIP_CALC; ++ HASH_ZIP_CALC + curMatch = hash[hv]; + hash[hv] = pos; + +@@ -1590,17 +1674,17 @@ void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder2 *vTable) + + + +-void LzFindPrepare() ++void LzFindPrepare(void) + { +- #ifndef FORCE_SATUR_SUB_128 +- #ifdef USE_SATUR_SUB_128 ++ #ifndef FORCE_LZFIND_SATUR_SUB_128 ++ #ifdef USE_LZFIND_SATUR_SUB_128 + LZFIND_SATUR_SUB_CODE_FUNC f = NULL; + #ifdef MY_CPU_ARM_OR_ARM64 + { + if (CPU_IsSupported_NEON()) + { + // #pragma message ("=== LzFind NEON") +- _PRF(printf("\n=== LzFind NEON\n")); ++ PRF(printf("\n=== LzFind NEON\n")); + f = LzFind_SaturSub_128; + } + // f = 0; // for debug +@@ -1609,20 +1693,25 @@ void LzFindPrepare() + if (CPU_IsSupported_SSE41()) + { + // #pragma message ("=== LzFind SSE41") +- _PRF(printf("\n=== LzFind SSE41\n")); ++ PRF(printf("\n=== LzFind SSE41\n")); + f = LzFind_SaturSub_128; + +- #ifdef USE_AVX2 ++ #ifdef USE_LZFIND_SATUR_SUB_256 + if (CPU_IsSupported_AVX2()) + { + // #pragma message ("=== LzFind AVX2") +- _PRF(printf("\n=== LzFind AVX2\n")); ++ PRF(printf("\n=== LzFind AVX2\n")); + f = LzFind_SaturSub_256; + } + #endif + } + #endif // MY_CPU_ARM_OR_ARM64 + g_LzFind_SaturSub = f; +- #endif // USE_SATUR_SUB_128 +- #endif // FORCE_SATUR_SUB_128 ++ #endif // USE_LZFIND_SATUR_SUB_128 ++ #endif // FORCE_LZFIND_SATUR_SUB_128 + } ++ ++ ++#undef MOVE_POS ++#undef MOVE_POS_RET ++#undef PRF +diff --git a/src/lzma/LzFind.h b/src/lzma/LzFind.h +index eea873ff6..a3f72c987 100644 +--- a/src/lzma/LzFind.h ++++ b/src/lzma/LzFind.h +@@ -1,8 +1,8 @@ + /* LzFind.h -- Match finder for LZ algorithms +-2021-07-13 : Igor Pavlov : Public domain */ ++2023-03-04 : Igor Pavlov : Public domain */ + +-#ifndef __LZ_FIND_H +-#define __LZ_FIND_H ++#ifndef ZIP7_INC_LZ_FIND_H ++#define ZIP7_INC_LZ_FIND_H + + #include "7zTypes.h" + +@@ -10,9 +10,9 @@ EXTERN_C_BEGIN + + typedef UInt32 CLzRef; + +-typedef struct _CMatchFinder ++typedef struct + { +- Byte *buffer; ++ const Byte *buffer; + UInt32 pos; + UInt32 posLimit; + UInt32 streamPos; /* wrap over Zero is allowed (streamPos < pos). Use (UInt32)(streamPos - pos) */ +@@ -32,8 +32,8 @@ typedef struct _CMatchFinder + UInt32 hashMask; + UInt32 cutValue; + +- Byte *bufferBase; +- ISeqInStream *stream; ++ Byte *bufBase; ++ ISeqInStreamPtr stream; + + UInt32 blockSize; + UInt32 keepSizeBefore; +@@ -43,7 +43,9 @@ typedef struct _CMatchFinder + size_t directInputRem; + UInt32 historySize; + UInt32 fixedHashSize; +- UInt32 hashSizeSum; ++ Byte numHashBytes_Min; ++ Byte numHashOutBits; ++ Byte _pad2_[2]; + SRes result; + UInt32 crc[256]; + size_t numRefs; +@@ -69,24 +71,45 @@ void MatchFinder_ReadIfRequired(CMatchFinder *p); + + void MatchFinder_Construct(CMatchFinder *p); + +-/* Conditions: +- historySize <= 3 GB +- keepAddBufferBefore + matchMaxLen + keepAddBufferAfter < 511MB ++/* (directInput = 0) is default value. ++ It's required to provide correct (directInput) value ++ before calling MatchFinder_Create(). ++ You can set (directInput) by any of the following calls: ++ - MatchFinder_SET_DIRECT_INPUT_BUF() ++ - MatchFinder_SET_STREAM() ++ - MatchFinder_SET_STREAM_MODE() + */ ++ ++#define MatchFinder_SET_DIRECT_INPUT_BUF(p, _src_, _srcLen_) { \ ++ (p)->stream = NULL; \ ++ (p)->directInput = 1; \ ++ (p)->buffer = (_src_); \ ++ (p)->directInputRem = (_srcLen_); } ++ ++/* ++#define MatchFinder_SET_STREAM_MODE(p) { \ ++ (p)->directInput = 0; } ++*/ ++ ++#define MatchFinder_SET_STREAM(p, _stream_) { \ ++ (p)->stream = _stream_; \ ++ (p)->directInput = 0; } ++ ++ + int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, + UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, + ISzAllocPtr alloc); + void MatchFinder_Free(CMatchFinder *p, ISzAllocPtr alloc); + void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems); +-// void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue); + + /* +-#define Inline_MatchFinder_InitPos(p, val) \ ++#define MatchFinder_INIT_POS(p, val) \ + (p)->pos = (val); \ + (p)->streamPos = (val); + */ + +-#define Inline_MatchFinder_ReduceOffsets(p, subValue) \ ++// void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue); ++#define MatchFinder_REDUCE_OFFSETS(p, subValue) \ + (p)->pos -= (subValue); \ + (p)->streamPos -= (subValue); + +@@ -107,7 +130,7 @@ 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 ++typedef struct + { + Mf_Init_Func Init; + Mf_GetNumAvailableBytes_Func GetNumAvailableBytes; +diff --git a/src/lzma/LzFindMt.c b/src/lzma/LzFindMt.c +index 1e0bfc87b..776be3ac6 100644 +--- a/src/lzma/LzFindMt.c ++++ b/src/lzma/LzFindMt.c +@@ -1,5 +1,5 @@ + /* LzFindMt.c -- multithreaded Match finder for LZ algorithms +-2021-12-21 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -69,7 +69,7 @@ extern UInt64 g_NumIters_Bytes; + UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ + h3 = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); } + +-#define __MT_HASH4_CALC { \ ++#define MT_HASH4_CALC { \ + UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ + h2 = temp & (kHash2Size - 1); \ + temp ^= ((UInt32)cur[2] << 8); \ +@@ -79,14 +79,14 @@ extern UInt64 g_NumIters_Bytes; + */ + + +-MY_NO_INLINE ++Z7_NO_INLINE + static void MtSync_Construct(CMtSync *p) + { + p->affinity = 0; + p->wasCreated = False7z; + p->csWasInitialized = False7z; + p->csWasEntered = False7z; +- Thread_Construct(&p->thread); ++ Thread_CONSTRUCT(&p->thread) + Event_Construct(&p->canStart); + Event_Construct(&p->wasStopped); + Semaphore_Construct(&p->freeSemaphore); +@@ -116,7 +116,7 @@ static void MtSync_Construct(CMtSync *p) + (p)->csWasEntered = False7z; } + + +-MY_NO_INLINE ++Z7_NO_INLINE + static UInt32 MtSync_GetNextBlock(CMtSync *p) + { + UInt32 numBlocks = 0; +@@ -140,14 +140,14 @@ static UInt32 MtSync_GetNextBlock(CMtSync *p) + + // buffer is UNLOCKED here + Semaphore_Wait(&p->filledSemaphore); +- LOCK_BUFFER(p); ++ LOCK_BUFFER(p) + return numBlocks; + } + + + /* if Writing (Processing) thread was started, we must call MtSync_StopWriting() */ + +-MY_NO_INLINE ++Z7_NO_INLINE + static void MtSync_StopWriting(CMtSync *p) + { + if (!Thread_WasCreated(&p->thread) || p->needStart) +@@ -185,7 +185,7 @@ static void MtSync_StopWriting(CMtSync *p) + } + + +-MY_NO_INLINE ++Z7_NO_INLINE + static void MtSync_Destruct(CMtSync *p) + { + PRF(printf("\nMtSync_Destruct %p\n", p)); +@@ -220,11 +220,11 @@ static void MtSync_Destruct(CMtSync *p) + + // #define RINOK_THREAD(x) { if ((x) != 0) return SZ_ERROR_THREAD; } + // we want to get real system error codes here instead of SZ_ERROR_THREAD +-#define RINOK_THREAD(x) RINOK(x) ++#define RINOK_THREAD(x) RINOK_WRes(x) + + + // call it before each new file (when new starting is required): +-MY_NO_INLINE ++Z7_NO_INLINE + static SRes MtSync_Init(CMtSync *p, UInt32 numBlocks) + { + WRes wres; +@@ -245,12 +245,12 @@ static WRes MtSync_Create_WRes(CMtSync *p, THREAD_FUNC_TYPE startAddress, void * + if (p->wasCreated) + return SZ_OK; + +- RINOK_THREAD(CriticalSection_Init(&p->cs)); ++ RINOK_THREAD(CriticalSection_Init(&p->cs)) + p->csWasInitialized = True7z; + p->csWasEntered = False7z; + +- RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->canStart)); +- RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->wasStopped)); ++ RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->canStart)) ++ RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->wasStopped)) + + p->needStart = True7z; + p->exit = True7z; /* p->exit is unused before (canStart) Event. +@@ -264,13 +264,13 @@ static WRes MtSync_Create_WRes(CMtSync *p, THREAD_FUNC_TYPE startAddress, void * + else + wres = Thread_Create(&p->thread, startAddress, obj); + +- RINOK_THREAD(wres); ++ RINOK_THREAD(wres) + p->wasCreated = True7z; + return SZ_OK; + } + + +-MY_NO_INLINE ++Z7_NO_INLINE + static SRes MtSync_Create(CMtSync *p, THREAD_FUNC_TYPE startAddress, void *obj) + { + const WRes wres = MtSync_Create_WRes(p, startAddress, obj); +@@ -519,7 +519,7 @@ static void HashThreadFunc(CMatchFinderMt *mt) + if (mf->pos > (UInt32)kMtMaxValForNormalize - num) + { + const UInt32 subValue = (mf->pos - mf->historySize - 1); // & ~(UInt32)(kNormalizeAlign - 1); +- Inline_MatchFinder_ReduceOffsets(mf, subValue); ++ MatchFinder_REDUCE_OFFSETS(mf, subValue) + MatchFinder_Normalize3(subValue, mf->hash + mf->fixedHashSize, (size_t)mf->hashMask + 1); + } + +@@ -560,7 +560,7 @@ static void HashThreadFunc(CMatchFinderMt *mt) + */ + + +-UInt32 * MY_FAST_CALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, ++UInt32 * Z7_FASTCALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, + UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, + size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, + UInt32 *posRes); +@@ -749,7 +749,7 @@ static void BtFillBlock(CMatchFinderMt *p, UInt32 globalBlockIndex) + } + + +-MY_NO_INLINE ++Z7_NO_INLINE + static void BtThreadFunc(CMatchFinderMt *mt) + { + CMtSync *p = &mt->btSync; +@@ -864,15 +864,15 @@ SRes MatchFinderMt_Create(CMatchFinderMt *p, UInt32 historySize, UInt32 keepAddB + if (!MatchFinder_Create(mf, historySize, keepAddBufferBefore, matchMaxLen, keepAddBufferAfter, alloc)) + return SZ_ERROR_MEM; + +- RINOK(MtSync_Create(&p->hashSync, HashThreadFunc2, p)); +- RINOK(MtSync_Create(&p->btSync, BtThreadFunc2, p)); ++ RINOK(MtSync_Create(&p->hashSync, HashThreadFunc2, p)) ++ RINOK(MtSync_Create(&p->btSync, BtThreadFunc2, p)) + return SZ_OK; + } + + + SRes MatchFinderMt_InitMt(CMatchFinderMt *p) + { +- RINOK(MtSync_Init(&p->hashSync, kMtHashNumBlocks)); ++ RINOK(MtSync_Init(&p->hashSync, kMtHashNumBlocks)) + return MtSync_Init(&p->btSync, kMtBtNumBlocks); + } + +@@ -941,7 +941,7 @@ void MatchFinderMt_ReleaseStream(CMatchFinderMt *p) + } + + +-MY_NO_INLINE ++Z7_NO_INLINE + static UInt32 MatchFinderMt_GetNextBlock_Bt(CMatchFinderMt *p) + { + if (p->failure_LZ_BT) +@@ -1163,7 +1163,7 @@ UInt32* MatchFinderMt_GetMatches_Bt4(CMatchFinderMt *p, UInt32 *d) + */ + + +-static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) ++static UInt32 * MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) + { + UInt32 h2, h3, /* h4, */ c2, c3 /* , c4 */; + UInt32 *hash = p->hash; +@@ -1179,9 +1179,8 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) + (hash + kFix3HashSize)[h3] = m; + // (hash + kFix4HashSize)[h4] = m; + +- #define _USE_H2 +- +- #ifdef _USE_H2 ++ // #define BT5_USE_H2 ++ // #ifdef BT5_USE_H2 + if (c2 >= matchMinPos && cur[(ptrdiff_t)c2 - (ptrdiff_t)m] == cur[0]) + { + d[1] = m - c2 - 1; +@@ -1197,8 +1196,8 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) + } + d[0] = 3; + d += 2; +- +- #ifdef _USE_H4 ++ ++ #ifdef BT5_USE_H4 + if (c4 >= matchMinPos) + if ( + cur[(ptrdiff_t)c4 - (ptrdiff_t)m] == cur[0] && +@@ -1214,7 +1213,7 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) + d[0] = 2; + d += 2; + } +- #endif ++ // #endif + + if (c3 >= matchMinPos && cur[(ptrdiff_t)c3 - (ptrdiff_t)m] == cur[0]) + { +@@ -1228,7 +1227,7 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) + d += 2; + } + +- #ifdef _USE_H4 ++ #ifdef BT5_USE_H4 + if (c4 >= matchMinPos) + if ( + cur[(ptrdiff_t)c4 - (ptrdiff_t)m] == cur[0] && +@@ -1244,7 +1243,7 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) + } + + +-static UInt32* MatchFinderMt2_GetMatches(CMatchFinderMt *p, UInt32 *d) ++static UInt32 * MatchFinderMt2_GetMatches(CMatchFinderMt *p, UInt32 *d) + { + const UInt32 *bt = p->btBufPos; + const UInt32 len = *bt++; +@@ -1268,7 +1267,7 @@ static UInt32* MatchFinderMt2_GetMatches(CMatchFinderMt *p, UInt32 *d) + + + +-static UInt32* MatchFinderMt_GetMatches(CMatchFinderMt *p, UInt32 *d) ++static UInt32 * MatchFinderMt_GetMatches(CMatchFinderMt *p, UInt32 *d) + { + const UInt32 *bt = p->btBufPos; + UInt32 len = *bt++; +@@ -1398,3 +1397,10 @@ void MatchFinderMt_CreateVTable(CMatchFinderMt *p, IMatchFinder2 *vTable) + break; + } + } ++ ++#undef RINOK_THREAD ++#undef PRF ++#undef MF ++#undef GetUi24hi_from32 ++#undef LOCK_BUFFER ++#undef UNLOCK_BUFFER +diff --git a/src/lzma/LzFindMt.h b/src/lzma/LzFindMt.h +index 660b7244d..db5923ea0 100644 +--- a/src/lzma/LzFindMt.h ++++ b/src/lzma/LzFindMt.h +@@ -1,15 +1,15 @@ + /* LzFindMt.h -- multithreaded Match finder for LZ algorithms +-2021-07-12 : Igor Pavlov : Public domain */ ++2023-03-05 : Igor Pavlov : Public domain */ + +-#ifndef __LZ_FIND_MT_H +-#define __LZ_FIND_MT_H ++#ifndef ZIP7_INC_LZ_FIND_MT_H ++#define ZIP7_INC_LZ_FIND_MT_H + + #include "LzFind.h" + #include "Threads.h" + + EXTERN_C_BEGIN + +-typedef struct _CMtSync ++typedef struct + { + UInt32 numProcessedBlocks; + CThread thread; +@@ -39,7 +39,7 @@ typedef UInt32 * (*Mf_Mix_Matches)(void *p, UInt32 matchMinPos, UInt32 *distance + typedef void (*Mf_GetHeads)(const Byte *buffer, UInt32 pos, + UInt32 *hash, UInt32 hashMask, UInt32 *heads, UInt32 numHeads, const UInt32 *crc); + +-typedef struct _CMatchFinderMt ++typedef struct + { + /* LZ */ + const Byte *pointerToCurPos; +diff --git a/src/lzma/LzFindOpt.c b/src/lzma/LzFindOpt.c +index 8ff006e07..85bdc136d 100644 +--- a/src/lzma/LzFindOpt.c ++++ b/src/lzma/LzFindOpt.c +@@ -1,5 +1,5 @@ + /* LzFindOpt.c -- multithreaded Match finder for LZ algorithms +-2021-07-13 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -41,8 +41,8 @@ UInt64 g_NumIters_Bytes; + // #define CYC_TO_POS_OFFSET 1 // for debug + + /* +-MY_NO_INLINE +-UInt32 * MY_FAST_CALL GetMatchesSpecN_1(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, ++Z7_NO_INLINE ++UInt32 * Z7_FASTCALL GetMatchesSpecN_1(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, + UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, UInt32 *posRes) + { + do +@@ -214,13 +214,13 @@ else + to eliminate "movsx" BUG in old MSVC x64 compiler. + */ + +-UInt32 * MY_FAST_CALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, ++UInt32 * Z7_FASTCALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, + UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, + size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, + UInt32 *posRes); + +-MY_NO_INLINE +-UInt32 * MY_FAST_CALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, ++Z7_NO_INLINE ++UInt32 * Z7_FASTCALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, + UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, + size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, + UInt32 *posRes) +@@ -404,7 +404,7 @@ else + /* + typedef UInt32 uint32plus; // size_t + +-UInt32 * MY_FAST_CALL GetMatchesSpecN_3(uint32plus lenLimit, size_t pos, const Byte *cur, CLzRef *son, ++UInt32 * Z7_FASTCALL GetMatchesSpecN_3(uint32plus lenLimit, size_t pos, const Byte *cur, CLzRef *son, + UInt32 _cutValue, UInt32 *d, uint32plus _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, + size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, + UInt32 *posRes) +diff --git a/src/lzma/LzHash.h b/src/lzma/LzHash.h +index 77b898cfa..2b6290b64 100644 +--- a/src/lzma/LzHash.h ++++ b/src/lzma/LzHash.h +@@ -1,8 +1,8 @@ +-/* LzHash.h -- HASH functions for LZ algorithms +-2019-10-30 : Igor Pavlov : Public domain */ ++/* LzHash.h -- HASH constants for LZ algorithms ++2023-03-05 : Igor Pavlov : Public domain */ + +-#ifndef __LZ_HASH_H +-#define __LZ_HASH_H ++#ifndef ZIP7_INC_LZ_HASH_H ++#define ZIP7_INC_LZ_HASH_H + + /* + (kHash2Size >= (1 << 8)) : Required +diff --git a/src/lzma/Lzma2Dec.c b/src/lzma/Lzma2Dec.c +index 3f4ca29ea..8c4d464c0 100644 +--- a/src/lzma/Lzma2Dec.c ++++ b/src/lzma/Lzma2Dec.c +@@ -1,5 +1,5 @@ + /* Lzma2Dec.c -- LZMA2 Decoder +-2021-02-09 : Igor Pavlov : Public domain */ ++2023-03-03 : Igor Pavlov : Public domain */ + + /* #define SHOW_DEBUG_INFO */ + +@@ -71,14 +71,14 @@ static SRes Lzma2Dec_GetOldProps(Byte prop, Byte *props) + SRes Lzma2Dec_AllocateProbs(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc) + { + Byte props[LZMA_PROPS_SIZE]; +- RINOK(Lzma2Dec_GetOldProps(prop, props)); ++ RINOK(Lzma2Dec_GetOldProps(prop, props)) + return LzmaDec_AllocateProbs(&p->decoder, props, LZMA_PROPS_SIZE, alloc); + } + + SRes Lzma2Dec_Allocate(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc) + { + Byte props[LZMA_PROPS_SIZE]; +- RINOK(Lzma2Dec_GetOldProps(prop, props)); ++ RINOK(Lzma2Dec_GetOldProps(prop, props)) + return LzmaDec_Allocate(&p->decoder, props, LZMA_PROPS_SIZE, alloc); + } + +@@ -474,8 +474,8 @@ SRes Lzma2Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, + SizeT outSize = *destLen, inSize = *srcLen; + *destLen = *srcLen = 0; + *status = LZMA_STATUS_NOT_SPECIFIED; +- Lzma2Dec_Construct(&p); +- RINOK(Lzma2Dec_AllocateProbs(&p, prop, alloc)); ++ Lzma2Dec_CONSTRUCT(&p) ++ RINOK(Lzma2Dec_AllocateProbs(&p, prop, alloc)) + p.decoder.dic = dest; + p.decoder.dicBufSize = outSize; + Lzma2Dec_Init(&p); +@@ -487,3 +487,5 @@ SRes Lzma2Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, + Lzma2Dec_FreeProbs(&p, alloc); + return res; + } ++ ++#undef PRF +diff --git a/src/lzma/Lzma2Dec.h b/src/lzma/Lzma2Dec.h +index b8ddeac89..1f5233a72 100644 +--- a/src/lzma/Lzma2Dec.h ++++ b/src/lzma/Lzma2Dec.h +@@ -1,8 +1,8 @@ + /* Lzma2Dec.h -- LZMA2 Decoder +-2018-02-19 : Igor Pavlov : Public domain */ ++2023-03-03 : Igor Pavlov : Public domain */ + +-#ifndef __LZMA2_DEC_H +-#define __LZMA2_DEC_H ++#ifndef ZIP7_INC_LZMA2_DEC_H ++#define ZIP7_INC_LZMA2_DEC_H + + #include "LzmaDec.h" + +@@ -22,9 +22,10 @@ typedef struct + CLzmaDec decoder; + } CLzma2Dec; + +-#define Lzma2Dec_Construct(p) LzmaDec_Construct(&(p)->decoder) +-#define Lzma2Dec_FreeProbs(p, alloc) LzmaDec_FreeProbs(&(p)->decoder, alloc) +-#define Lzma2Dec_Free(p, alloc) LzmaDec_Free(&(p)->decoder, alloc) ++#define Lzma2Dec_CONSTRUCT(p) LzmaDec_CONSTRUCT(&(p)->decoder) ++#define Lzma2Dec_Construct(p) Lzma2Dec_CONSTRUCT(p) ++#define Lzma2Dec_FreeProbs(p, alloc) LzmaDec_FreeProbs(&(p)->decoder, alloc) ++#define Lzma2Dec_Free(p, alloc) LzmaDec_Free(&(p)->decoder, alloc) + + SRes Lzma2Dec_AllocateProbs(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc); + SRes Lzma2Dec_Allocate(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc); +@@ -90,7 +91,7 @@ Lzma2Dec_GetUnpackExtra() returns the value that shows + at current input positon. + */ + +-#define Lzma2Dec_GetUnpackExtra(p) ((p)->isExtraMode ? (p)->unpackSize : 0); ++#define Lzma2Dec_GetUnpackExtra(p) ((p)->isExtraMode ? (p)->unpackSize : 0) + + + /* ---------- One Call Interface ---------- */ +diff --git a/src/lzma/Lzma2DecMt.c b/src/lzma/Lzma2DecMt.c +index 51a237a85..9ada455bf 100644 +--- a/src/lzma/Lzma2DecMt.c ++++ b/src/lzma/Lzma2DecMt.c +@@ -1,44 +1,44 @@ + /* Lzma2DecMt.c -- LZMA2 Decoder Multi-thread +-2021-04-01 : Igor Pavlov : Public domain */ ++2023-04-13 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + + // #define SHOW_DEBUG_INFO +- +-// #define _7ZIP_ST ++// #define Z7_ST + + #ifdef SHOW_DEBUG_INFO + #include + #endif + +-#ifndef _7ZIP_ST +-#ifdef SHOW_DEBUG_INFO +-#define PRF(x) x +-#else +-#define PRF(x) +-#endif +-#define PRF_STR(s) PRF(printf("\n" s "\n")) +-#define PRF_STR_INT_2(s, d1, d2) PRF(printf("\n" s " %d %d\n", (unsigned)d1, (unsigned)d2)) +-#endif +- + #include "Alloc.h" + + #include "Lzma2Dec.h" + #include "Lzma2DecMt.h" + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + #include "MtDec.h" + + #define LZMA2DECMT_OUT_BLOCK_MAX_DEFAULT (1 << 28) + #endif + + ++#ifndef Z7_ST ++#ifdef SHOW_DEBUG_INFO ++#define PRF(x) x ++#else ++#define PRF(x) ++#endif ++#define PRF_STR(s) PRF(printf("\n" s "\n");) ++#define PRF_STR_INT_2(s, d1, d2) PRF(printf("\n" s " %d %d\n", (unsigned)d1, (unsigned)d2);) ++#endif ++ ++ + void Lzma2DecMtProps_Init(CLzma2DecMtProps *p) + { + p->inBufSize_ST = 1 << 20; + p->outStep_ST = 1 << 20; + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + p->numThreads = 1; + p->inBufSize_MT = 1 << 18; + p->outBlockMax = LZMA2DECMT_OUT_BLOCK_MAX_DEFAULT; +@@ -48,7 +48,7 @@ void Lzma2DecMtProps_Init(CLzma2DecMtProps *p) + + + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + + /* ---------- CLzma2DecMtThread ---------- */ + +@@ -81,7 +81,7 @@ typedef struct + + /* ---------- CLzma2DecMt ---------- */ + +-typedef struct ++struct CLzma2DecMt + { + // ISzAllocPtr alloc; + ISzAllocPtr allocMid; +@@ -90,9 +90,9 @@ typedef struct + CLzma2DecMtProps props; + Byte prop; + +- ISeqInStream *inStream; +- ISeqOutStream *outStream; +- ICompressProgress *progress; ++ ISeqInStreamPtr inStream; ++ ISeqOutStreamPtr outStream; ++ ICompressProgressPtr progress; + + BoolInt finishMode; + BoolInt outSize_Defined; +@@ -111,14 +111,13 @@ typedef struct + size_t inPos; + size_t inLim; + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + UInt64 outProcessed_Parse; + BoolInt mtc_WasConstructed; + CMtDec mtc; +- CLzma2DecMtThread coders[MTDEC__THREADS_MAX]; ++ CLzma2DecMtThread coders[MTDEC_THREADS_MAX]; + #endif +- +-} CLzma2DecMt; ++}; + + + +@@ -142,11 +141,11 @@ CLzma2DecMtHandle Lzma2DecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid) + + // Lzma2DecMtProps_Init(&p->props); + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + p->mtc_WasConstructed = False7z; + { + unsigned i; +- for (i = 0; i < MTDEC__THREADS_MAX; i++) ++ for (i = 0; i < MTDEC_THREADS_MAX; i++) + { + CLzma2DecMtThread *t = &p->coders[i]; + t->dec_created = False7z; +@@ -156,16 +155,16 @@ CLzma2DecMtHandle Lzma2DecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid) + } + #endif + +- return p; ++ return (CLzma2DecMtHandle)(void *)p; + } + + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + + static void Lzma2DecMt_FreeOutBufs(CLzma2DecMt *p) + { + unsigned i; +- for (i = 0; i < MTDEC__THREADS_MAX; i++) ++ for (i = 0; i < MTDEC_THREADS_MAX; i++) + { + CLzma2DecMtThread *t = &p->coders[i]; + if (t->outBuf) +@@ -196,13 +195,15 @@ static void Lzma2DecMt_FreeSt(CLzma2DecMt *p) + } + + +-void Lzma2DecMt_Destroy(CLzma2DecMtHandle pp) ++// #define GET_CLzma2DecMt_p CLzma2DecMt *p = (CLzma2DecMt *)(void *)pp; ++ ++void Lzma2DecMt_Destroy(CLzma2DecMtHandle p) + { +- CLzma2DecMt *p = (CLzma2DecMt *)pp; ++ // GET_CLzma2DecMt_p + + Lzma2DecMt_FreeSt(p); + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + + if (p->mtc_WasConstructed) + { +@@ -211,7 +212,7 @@ void Lzma2DecMt_Destroy(CLzma2DecMtHandle pp) + } + { + unsigned i; +- for (i = 0; i < MTDEC__THREADS_MAX; i++) ++ for (i = 0; i < MTDEC_THREADS_MAX; i++) + { + CLzma2DecMtThread *t = &p->coders[i]; + if (t->dec_created) +@@ -226,19 +227,19 @@ void Lzma2DecMt_Destroy(CLzma2DecMtHandle pp) + + #endif + +- ISzAlloc_Free(p->alignOffsetAlloc.baseAlloc, pp); ++ ISzAlloc_Free(p->alignOffsetAlloc.baseAlloc, p); + } + + + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + + static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCallbackInfo *cc) + { + CLzma2DecMt *me = (CLzma2DecMt *)obj; + CLzma2DecMtThread *t = &me->coders[coderIndex]; + +- PRF_STR_INT_2("Parse", coderIndex, cc->srcSize); ++ PRF_STR_INT_2("Parse", coderIndex, cc->srcSize) + + cc->state = MTDEC_PARSE_CONTINUE; + +@@ -246,7 +247,7 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa + { + if (!t->dec_created) + { +- Lzma2Dec_Construct(&t->dec); ++ Lzma2Dec_CONSTRUCT(&t->dec) + t->dec_created = True7z; + AlignOffsetAlloc_CreateVTable(&t->alloc); + { +@@ -297,7 +298,7 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa + // that must be finished at position <= outBlockMax. + + { +- const SizeT srcOrig = cc->srcSize; ++ const size_t srcOrig = cc->srcSize; + SizeT srcSize_Point = 0; + SizeT dicPos_Point = 0; + +@@ -306,10 +307,10 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa + + for (;;) + { +- SizeT srcCur = srcOrig - cc->srcSize; ++ SizeT srcCur = (SizeT)(srcOrig - cc->srcSize); + + status = Lzma2Dec_Parse(&t->dec, +- limit - t->dec.decoder.dicPos, ++ (SizeT)limit - t->dec.decoder.dicPos, + cc->src + cc->srcSize, &srcCur, + checkFinishBlock); + +@@ -333,7 +334,7 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa + if (t->dec.decoder.dicPos >= (1 << 14)) + break; + dicPos_Point = t->dec.decoder.dicPos; +- srcSize_Point = cc->srcSize; ++ srcSize_Point = (SizeT)cc->srcSize; + continue; + } + +@@ -391,7 +392,7 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa + if (unpackRem != 0) + { + /* we also reserve space for max possible number of output bytes of current LZMA chunk */ +- SizeT rem = limit - dicPos; ++ size_t rem = limit - dicPos; + if (rem > unpackRem) + rem = unpackRem; + dicPos += rem; +@@ -444,7 +445,7 @@ static SRes Lzma2DecMt_MtCallback_PreCode(void *pp, unsigned coderIndex) + } + + t->dec.decoder.dic = dest; +- t->dec.decoder.dicBufSize = t->outPreSize; ++ t->dec.decoder.dicBufSize = (SizeT)t->outPreSize; + + t->needInit = True7z; + +@@ -462,7 +463,7 @@ static SRes Lzma2DecMt_MtCallback_Code(void *pp, unsigned coderIndex, + + UNUSED_VAR(srcFinished) + +- PRF_STR_INT_2("Code", coderIndex, srcSize); ++ PRF_STR_INT_2("Code", coderIndex, srcSize) + + *inCodePos = t->inCodeSize; + *outCodePos = 0; +@@ -476,13 +477,13 @@ static SRes Lzma2DecMt_MtCallback_Code(void *pp, unsigned coderIndex, + + { + ELzmaStatus status; +- size_t srcProcessed = srcSize; ++ SizeT srcProcessed = (SizeT)srcSize; + BoolInt blockWasFinished = + ((int)t->parseStatus == LZMA_STATUS_FINISHED_WITH_MARK + || t->parseStatus == LZMA2_PARSE_STATUS_NEW_BLOCK); + + SRes res = Lzma2Dec_DecodeToDic(&t->dec, +- t->outPreSize, ++ (SizeT)t->outPreSize, + src, &srcProcessed, + blockWasFinished ? LZMA_FINISH_END : LZMA_FINISH_ANY, + &status); +@@ -540,7 +541,7 @@ static SRes Lzma2DecMt_MtCallback_Write(void *pp, unsigned coderIndex, + UNUSED_VAR(srcSize) + UNUSED_VAR(isCross) + +- PRF_STR_INT_2("Write", coderIndex, srcSize); ++ PRF_STR_INT_2("Write", coderIndex, srcSize) + + *needContinue = False7z; + *canRecode = True7z; +@@ -588,7 +589,7 @@ static SRes Lzma2DecMt_MtCallback_Write(void *pp, unsigned coderIndex, + *needContinue = needContinue2; + return SZ_OK; + } +- RINOK(MtProgress_ProgressAdd(&me->mtc.mtProgress, 0, 0)); ++ RINOK(MtProgress_ProgressAdd(&me->mtc.mtProgress, 0, 0)) + } + } + +@@ -611,11 +612,11 @@ static SRes Lzma2Dec_Prepare_ST(CLzma2DecMt *p) + { + if (!p->dec_created) + { +- Lzma2Dec_Construct(&p->dec); ++ Lzma2Dec_CONSTRUCT(&p->dec) + p->dec_created = True7z; + } + +- RINOK(Lzma2Dec_Allocate(&p->dec, p->prop, &p->alignOffsetAlloc.vt)); ++ RINOK(Lzma2Dec_Allocate(&p->dec, p->prop, &p->alignOffsetAlloc.vt)) + + if (!p->inBuf || p->inBufSize != p->props.inBufSize_ST) + { +@@ -634,7 +635,7 @@ static SRes Lzma2Dec_Prepare_ST(CLzma2DecMt *p) + + + static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + , BoolInt tMode + #endif + ) +@@ -646,7 +647,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p + + CLzma2Dec *dec; + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + if (tMode) + { + Lzma2DecMt_FreeOutBufs(p); +@@ -654,7 +655,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p + } + #endif + +- RINOK(Lzma2Dec_Prepare_ST(p)); ++ RINOK(Lzma2Dec_Prepare_ST(p)) + + dec = &p->dec; + +@@ -681,7 +682,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p + + if (inPos == inLim) + { +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + if (tMode) + { + inData = MtDec_Read(&p->mtc, &inLim); +@@ -710,7 +711,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p + { + SizeT next = dec->decoder.dicBufSize; + if (next - wrPos > p->props.outStep_ST) +- next = wrPos + p->props.outStep_ST; ++ next = wrPos + (SizeT)p->props.outStep_ST; + size = next - dicPos; + } + +@@ -726,7 +727,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p + } + } + +- inProcessed = inLim - inPos; ++ inProcessed = (SizeT)(inLim - inPos); + + res = Lzma2Dec_DecodeToDic(dec, dicPos + size, inData + inPos, &inProcessed, finishMode, &status); + +@@ -755,7 +756,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p + dec->decoder.dicPos = 0; + wrPos = dec->decoder.dicPos; + +- RINOK(res2); ++ RINOK(res2) + + if (needStop) + { +@@ -788,7 +789,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p + UInt64 outDelta = p->outProcessed - outPrev; + if (inDelta >= (1 << 22) || outDelta >= (1 << 22)) + { +- RINOK(ICompressProgress_Progress(p->progress, p->inProcessed, p->outProcessed)); ++ RINOK(ICompressProgress_Progress(p->progress, p->inProcessed, p->outProcessed)) + inPrev = p->inProcessed; + outPrev = p->outProcessed; + } +@@ -798,20 +799,20 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p + + + +-SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, ++SRes Lzma2DecMt_Decode(CLzma2DecMtHandle p, + Byte prop, + const CLzma2DecMtProps *props, +- ISeqOutStream *outStream, const UInt64 *outDataSize, int finishMode, ++ ISeqOutStreamPtr outStream, const UInt64 *outDataSize, int finishMode, + // Byte *outBuf, size_t *outBufSize, +- ISeqInStream *inStream, ++ ISeqInStreamPtr inStream, + // const Byte *inData, size_t inDataSize, + UInt64 *inProcessed, + // UInt64 *outProcessed, + int *isMT, +- ICompressProgress *progress) ++ ICompressProgressPtr progress) + { +- CLzma2DecMt *p = (CLzma2DecMt *)pp; +- #ifndef _7ZIP_ST ++ // GET_CLzma2DecMt_p ++ #ifndef Z7_ST + BoolInt tMode; + #endif + +@@ -845,7 +846,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, + *isMT = False7z; + + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + + tMode = False7z; + +@@ -939,7 +940,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, + p->readWasFinished = p->mtc.readWasFinished; + p->inProcessed = p->mtc.inProcessed; + +- PRF_STR("----- decoding ST -----"); ++ PRF_STR("----- decoding ST -----") + } + } + +@@ -950,7 +951,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, + + { + SRes res = Lzma2Dec_Decode_ST(p +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + , tMode + #endif + ); +@@ -967,7 +968,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, + res = p->readRes; + + /* +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + if (res == SZ_OK && tMode && p->mtc.parseRes != SZ_OK) + res = p->mtc.parseRes; + #endif +@@ -980,13 +981,13 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, + + /* ---------- Read from CLzma2DecMtHandle Interface ---------- */ + +-SRes Lzma2DecMt_Init(CLzma2DecMtHandle pp, ++SRes Lzma2DecMt_Init(CLzma2DecMtHandle p, + Byte prop, + const CLzma2DecMtProps *props, + const UInt64 *outDataSize, int finishMode, +- ISeqInStream *inStream) ++ ISeqInStreamPtr inStream) + { +- CLzma2DecMt *p = (CLzma2DecMt *)pp; ++ // GET_CLzma2DecMt_p + + if (prop > 40) + return SZ_ERROR_UNSUPPORTED; +@@ -1015,11 +1016,11 @@ SRes Lzma2DecMt_Init(CLzma2DecMtHandle pp, + } + + +-SRes Lzma2DecMt_Read(CLzma2DecMtHandle pp, ++SRes Lzma2DecMt_Read(CLzma2DecMtHandle p, + Byte *data, size_t *outSize, + UInt64 *inStreamProcessed) + { +- CLzma2DecMt *p = (CLzma2DecMt *)pp; ++ // GET_CLzma2DecMt_p + ELzmaFinishMode finishMode; + SRes readRes; + size_t size = *outSize; +@@ -1055,8 +1056,8 @@ SRes Lzma2DecMt_Read(CLzma2DecMtHandle pp, + readRes = ISeqInStream_Read(p->inStream, p->inBuf, &p->inLim); + } + +- inCur = p->inLim - p->inPos; +- outCur = size; ++ inCur = (SizeT)(p->inLim - p->inPos); ++ outCur = (SizeT)size; + + res = Lzma2Dec_DecodeToBuf(&p->dec, data, &outCur, + p->inBuf + p->inPos, &inCur, finishMode, &status); +@@ -1088,3 +1089,7 @@ SRes Lzma2DecMt_Read(CLzma2DecMtHandle pp, + return readRes; + } + } ++ ++#undef PRF ++#undef PRF_STR ++#undef PRF_STR_INT_2 +diff --git a/src/lzma/Lzma2DecMt.h b/src/lzma/Lzma2DecMt.h +index 7791c310b..93a5cd59e 100644 +--- a/src/lzma/Lzma2DecMt.h ++++ b/src/lzma/Lzma2DecMt.h +@@ -1,8 +1,8 @@ + /* Lzma2DecMt.h -- LZMA2 Decoder Multi-thread +-2018-02-17 : Igor Pavlov : Public domain */ ++2023-04-13 : Igor Pavlov : Public domain */ + +-#ifndef __LZMA2_DEC_MT_H +-#define __LZMA2_DEC_MT_H ++#ifndef ZIP7_INC_LZMA2_DEC_MT_H ++#define ZIP7_INC_LZMA2_DEC_MT_H + + #include "7zTypes.h" + +@@ -13,7 +13,7 @@ typedef struct + size_t inBufSize_ST; + size_t outStep_ST; + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + unsigned numThreads; + size_t inBufSize_MT; + size_t outBlockMax; +@@ -38,7 +38,9 @@ SRes: + SZ_ERROR_THREAD - error in multithreading functions (only for Mt version) + */ + +-typedef void * CLzma2DecMtHandle; ++typedef struct CLzma2DecMt CLzma2DecMt; ++typedef CLzma2DecMt * CLzma2DecMtHandle; ++// Z7_DECLARE_HANDLE(CLzma2DecMtHandle) + + CLzma2DecMtHandle Lzma2DecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid); + void Lzma2DecMt_Destroy(CLzma2DecMtHandle p); +@@ -46,11 +48,11 @@ void Lzma2DecMt_Destroy(CLzma2DecMtHandle p); + SRes Lzma2DecMt_Decode(CLzma2DecMtHandle p, + Byte prop, + const CLzma2DecMtProps *props, +- ISeqOutStream *outStream, ++ ISeqOutStreamPtr outStream, + const UInt64 *outDataSize, // NULL means undefined + int finishMode, // 0 - partial unpacking is allowed, 1 - if lzma2 stream must be finished + // Byte *outBuf, size_t *outBufSize, +- ISeqInStream *inStream, ++ ISeqInStreamPtr inStream, + // const Byte *inData, size_t inDataSize, + + // out variables: +@@ -58,7 +60,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle p, + int *isMT, /* out: (*isMT == 0), if single thread decoding was used */ + + // UInt64 *outProcessed, +- ICompressProgress *progress); ++ ICompressProgressPtr progress); + + + /* ---------- Read from CLzma2DecMtHandle Interface ---------- */ +@@ -67,7 +69,7 @@ SRes Lzma2DecMt_Init(CLzma2DecMtHandle pp, + Byte prop, + const CLzma2DecMtProps *props, + const UInt64 *outDataSize, int finishMode, +- ISeqInStream *inStream); ++ ISeqInStreamPtr inStream); + + SRes Lzma2DecMt_Read(CLzma2DecMtHandle pp, + Byte *data, size_t *outSize, +diff --git a/src/lzma/Lzma2Enc.c b/src/lzma/Lzma2Enc.c +index 4799b65ad..f31c3ddad 100644 +--- a/src/lzma/Lzma2Enc.c ++++ b/src/lzma/Lzma2Enc.c +@@ -1,18 +1,18 @@ + /* Lzma2Enc.c -- LZMA2 Encoder +-2021-02-09 : Igor Pavlov : Public domain */ ++2023-04-13 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + + #include + +-/* #define _7ZIP_ST */ ++/* #define Z7_ST */ + + #include "Lzma2Enc.h" + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + #include "MtCoder.h" + #else +-#define MTCODER__THREADS_MAX 1 ++#define MTCODER_THREADS_MAX 1 + #endif + + #define LZMA2_CONTROL_LZMA (1 << 7) +@@ -40,7 +40,7 @@ + typedef struct + { + ISeqInStream vt; +- ISeqInStream *realStream; ++ ISeqInStreamPtr realStream; + UInt64 limit; + UInt64 processed; + int finished; +@@ -53,15 +53,15 @@ static void LimitedSeqInStream_Init(CLimitedSeqInStream *p) + p->finished = 0; + } + +-static SRes LimitedSeqInStream_Read(const ISeqInStream *pp, void *data, size_t *size) ++static SRes LimitedSeqInStream_Read(ISeqInStreamPtr pp, void *data, size_t *size) + { +- CLimitedSeqInStream *p = CONTAINER_FROM_VTBL(pp, CLimitedSeqInStream, vt); ++ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CLimitedSeqInStream) + size_t size2 = *size; + SRes res = SZ_OK; + + if (p->limit != (UInt64)(Int64)-1) + { +- UInt64 rem = p->limit - p->processed; ++ const UInt64 rem = p->limit - p->processed; + if (size2 > rem) + size2 = (size_t)rem; + } +@@ -95,8 +95,8 @@ static SRes Lzma2EncInt_InitStream(CLzma2EncInt *p, const CLzma2EncProps *props) + { + SizeT propsSize = LZMA_PROPS_SIZE; + Byte propsEncoded[LZMA_PROPS_SIZE]; +- RINOK(LzmaEnc_SetProps(p->enc, &props->lzmaProps)); +- RINOK(LzmaEnc_WriteProperties(p->enc, propsEncoded, &propsSize)); ++ RINOK(LzmaEnc_SetProps(p->enc, &props->lzmaProps)) ++ RINOK(LzmaEnc_WriteProperties(p->enc, propsEncoded, &propsSize)) + p->propsByte = propsEncoded[0]; + p->propsAreSet = True7z; + } +@@ -111,23 +111,23 @@ static void Lzma2EncInt_InitBlock(CLzma2EncInt *p) + } + + +-SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp, ISeqInStream *inStream, UInt32 keepWindowSize, ++SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle p, ISeqInStreamPtr inStream, UInt32 keepWindowSize, + ISzAllocPtr alloc, ISzAllocPtr allocBig); +-SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen, ++SRes LzmaEnc_MemPrepare(CLzmaEncHandle p, const Byte *src, SizeT srcLen, + UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig); +-SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit, ++SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle p, BoolInt reInit, + Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize); +-const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp); +-void LzmaEnc_Finish(CLzmaEncHandle pp); +-void LzmaEnc_SaveState(CLzmaEncHandle pp); +-void LzmaEnc_RestoreState(CLzmaEncHandle pp); ++const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle p); ++void LzmaEnc_Finish(CLzmaEncHandle p); ++void LzmaEnc_SaveState(CLzmaEncHandle p); ++void LzmaEnc_RestoreState(CLzmaEncHandle p); + + /* +-UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp); ++UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle p); + */ + + static SRes Lzma2EncInt_EncodeSubblock(CLzma2EncInt *p, Byte *outBuf, +- size_t *packSizeRes, ISeqOutStream *outStream) ++ size_t *packSizeRes, ISeqOutStreamPtr outStream) + { + size_t packSizeLimit = *packSizeRes; + size_t packSize = packSizeLimit; +@@ -167,7 +167,7 @@ static SRes Lzma2EncInt_EncodeSubblock(CLzma2EncInt *p, Byte *outBuf, + + while (unpackSize > 0) + { +- UInt32 u = (unpackSize < LZMA2_COPY_CHUNK_SIZE) ? unpackSize : LZMA2_COPY_CHUNK_SIZE; ++ const UInt32 u = (unpackSize < LZMA2_COPY_CHUNK_SIZE) ? unpackSize : LZMA2_COPY_CHUNK_SIZE; + if (packSizeLimit - destPos < u + 3) + return SZ_ERROR_OUTPUT_EOF; + outBuf[destPos++] = (Byte)(p->srcPos == 0 ? LZMA2_CONTROL_COPY_RESET_DIC : LZMA2_CONTROL_COPY_NO_RESET); +@@ -196,9 +196,9 @@ static SRes Lzma2EncInt_EncodeSubblock(CLzma2EncInt *p, Byte *outBuf, + + { + size_t destPos = 0; +- UInt32 u = unpackSize - 1; +- UInt32 pm = (UInt32)(packSize - 1); +- unsigned mode = (p->srcPos == 0) ? 3 : (p->needInitState ? (p->needInitProp ? 2 : 1) : 0); ++ const UInt32 u = unpackSize - 1; ++ const UInt32 pm = (UInt32)(packSize - 1); ++ const unsigned mode = (p->srcPos == 0) ? 3 : (p->needInitState ? (p->needInitProp ? 2 : 1) : 0); + + PRF(printf(" ")); + +@@ -231,7 +231,7 @@ static SRes Lzma2EncInt_EncodeSubblock(CLzma2EncInt *p, Byte *outBuf, + void Lzma2EncProps_Init(CLzma2EncProps *p) + { + LzmaEncProps_Init(&p->lzmaProps); +- p->blockSize = LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO; ++ p->blockSize = LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO; + p->numBlockThreads_Reduced = -1; + p->numBlockThreads_Max = -1; + p->numTotalThreads = -1; +@@ -251,8 +251,8 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p) + t2 = p->numBlockThreads_Max; + t3 = p->numTotalThreads; + +- if (t2 > MTCODER__THREADS_MAX) +- t2 = MTCODER__THREADS_MAX; ++ if (t2 > MTCODER_THREADS_MAX) ++ t2 = MTCODER_THREADS_MAX; + + if (t3 <= 0) + { +@@ -268,8 +268,8 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p) + t1 = 1; + t2 = t3; + } +- if (t2 > MTCODER__THREADS_MAX) +- t2 = MTCODER__THREADS_MAX; ++ if (t2 > MTCODER_THREADS_MAX) ++ t2 = MTCODER_THREADS_MAX; + } + else if (t1 <= 0) + { +@@ -286,8 +286,8 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p) + + fileSize = p->lzmaProps.reduceSize; + +- if ( p->blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID +- && p->blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO ++ if ( p->blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID ++ && p->blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO + && (p->blockSize < fileSize || fileSize == (UInt64)(Int64)-1)) + p->lzmaProps.reduceSize = p->blockSize; + +@@ -297,19 +297,19 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p) + + t1 = p->lzmaProps.numThreads; + +- if (p->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID) ++ if (p->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID) + { + t2r = t2 = 1; + t3 = t1; + } +- else if (p->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO && t2 <= 1) ++ else if (p->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO && t2 <= 1) + { + /* if there is no block multi-threading, we use SOLID block */ +- p->blockSize = LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID; ++ p->blockSize = LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID; + } + else + { +- if (p->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO) ++ if (p->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO) + { + const UInt32 kMinSize = (UInt32)1 << 20; + const UInt32 kMaxSize = (UInt32)1 << 28; +@@ -344,7 +344,7 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p) + } + + +-static SRes Progress(ICompressProgress *p, UInt64 inSize, UInt64 outSize) ++static SRes Progress(ICompressProgressPtr p, UInt64 inSize, UInt64 outSize) + { + return (p && ICompressProgress_Progress(p, inSize, outSize) != SZ_OK) ? SZ_ERROR_PROGRESS : SZ_OK; + } +@@ -352,7 +352,7 @@ static SRes Progress(ICompressProgress *p, UInt64 inSize, UInt64 outSize) + + /* ---------- Lzma2 ---------- */ + +-typedef struct ++struct CLzma2Enc + { + Byte propEncoded; + CLzma2EncProps props; +@@ -363,23 +363,22 @@ typedef struct + ISzAllocPtr alloc; + ISzAllocPtr allocBig; + +- CLzma2EncInt coders[MTCODER__THREADS_MAX]; ++ CLzma2EncInt coders[MTCODER_THREADS_MAX]; + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + +- ISeqOutStream *outStream; ++ ISeqOutStreamPtr outStream; + Byte *outBuf; + size_t outBuf_Rem; /* remainder in outBuf */ + + size_t outBufSize; /* size of allocated outBufs[i] */ +- size_t outBufsDataSizes[MTCODER__BLOCKS_MAX]; ++ size_t outBufsDataSizes[MTCODER_BLOCKS_MAX]; + BoolInt mtCoder_WasConstructed; + CMtCoder mtCoder; +- Byte *outBufs[MTCODER__BLOCKS_MAX]; ++ Byte *outBufs[MTCODER_BLOCKS_MAX]; + + #endif +- +-} CLzma2Enc; ++}; + + + +@@ -396,30 +395,30 @@ CLzma2EncHandle Lzma2Enc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig) + p->allocBig = allocBig; + { + unsigned i; +- for (i = 0; i < MTCODER__THREADS_MAX; i++) ++ for (i = 0; i < MTCODER_THREADS_MAX; i++) + p->coders[i].enc = NULL; + } + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + p->mtCoder_WasConstructed = False7z; + { + unsigned i; +- for (i = 0; i < MTCODER__BLOCKS_MAX; i++) ++ for (i = 0; i < MTCODER_BLOCKS_MAX; i++) + p->outBufs[i] = NULL; + p->outBufSize = 0; + } + #endif + +- return p; ++ return (CLzma2EncHandle)p; + } + + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + + static void Lzma2Enc_FreeOutBufs(CLzma2Enc *p) + { + unsigned i; +- for (i = 0; i < MTCODER__BLOCKS_MAX; i++) ++ for (i = 0; i < MTCODER_BLOCKS_MAX; i++) + if (p->outBufs[i]) + { + ISzAlloc_Free(p->alloc, p->outBufs[i]); +@@ -430,12 +429,13 @@ static void Lzma2Enc_FreeOutBufs(CLzma2Enc *p) + + #endif + ++// #define GET_CLzma2Enc_p CLzma2Enc *p = (CLzma2Enc *)(void *)p; + +-void Lzma2Enc_Destroy(CLzma2EncHandle pp) ++void Lzma2Enc_Destroy(CLzma2EncHandle p) + { +- CLzma2Enc *p = (CLzma2Enc *)pp; ++ // GET_CLzma2Enc_p + unsigned i; +- for (i = 0; i < MTCODER__THREADS_MAX; i++) ++ for (i = 0; i < MTCODER_THREADS_MAX; i++) + { + CLzma2EncInt *t = &p->coders[i]; + if (t->enc) +@@ -446,7 +446,7 @@ void Lzma2Enc_Destroy(CLzma2EncHandle pp) + } + + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + if (p->mtCoder_WasConstructed) + { + MtCoder_Destruct(&p->mtCoder); +@@ -458,13 +458,13 @@ void Lzma2Enc_Destroy(CLzma2EncHandle pp) + ISzAlloc_Free(p->alloc, p->tempBufLzma); + p->tempBufLzma = NULL; + +- ISzAlloc_Free(p->alloc, pp); ++ ISzAlloc_Free(p->alloc, p); + } + + +-SRes Lzma2Enc_SetProps(CLzma2EncHandle pp, const CLzma2EncProps *props) ++SRes Lzma2Enc_SetProps(CLzma2EncHandle p, const CLzma2EncProps *props) + { +- CLzma2Enc *p = (CLzma2Enc *)pp; ++ // GET_CLzma2Enc_p + CLzmaEncProps lzmaProps = props->lzmaProps; + LzmaEncProps_Normalize(&lzmaProps); + if (lzmaProps.lc + lzmaProps.lp > LZMA2_LCLP_MAX) +@@ -475,16 +475,16 @@ SRes Lzma2Enc_SetProps(CLzma2EncHandle pp, const CLzma2EncProps *props) + } + + +-void Lzma2Enc_SetDataSize(CLzmaEncHandle pp, UInt64 expectedDataSiize) ++void Lzma2Enc_SetDataSize(CLzma2EncHandle p, UInt64 expectedDataSiize) + { +- CLzma2Enc *p = (CLzma2Enc *)pp; ++ // GET_CLzma2Enc_p + p->expectedDataSize = expectedDataSiize; + } + + +-Byte Lzma2Enc_WriteProperties(CLzma2EncHandle pp) ++Byte Lzma2Enc_WriteProperties(CLzma2EncHandle p) + { +- CLzma2Enc *p = (CLzma2Enc *)pp; ++ // GET_CLzma2Enc_p + unsigned i; + UInt32 dicSize = LzmaEncProps_GetDictSize(&p->props.lzmaProps); + for (i = 0; i < 40; i++) +@@ -497,12 +497,12 @@ Byte Lzma2Enc_WriteProperties(CLzma2EncHandle pp) + static SRes Lzma2Enc_EncodeMt1( + CLzma2Enc *me, + CLzma2EncInt *p, +- ISeqOutStream *outStream, ++ ISeqOutStreamPtr outStream, + Byte *outBuf, size_t *outBufSize, +- ISeqInStream *inStream, ++ ISeqInStreamPtr inStream, + const Byte *inData, size_t inDataSize, + int finished, +- ICompressProgress *progress) ++ ICompressProgressPtr progress) + { + UInt64 unpackTotal = 0; + UInt64 packTotal = 0; +@@ -540,12 +540,12 @@ static SRes Lzma2Enc_EncodeMt1( + } + } + +- RINOK(Lzma2EncInt_InitStream(p, &me->props)); ++ RINOK(Lzma2EncInt_InitStream(p, &me->props)) + + for (;;) + { + SRes res = SZ_OK; +- size_t inSizeCur = 0; ++ SizeT inSizeCur = 0; + + Lzma2EncInt_InitBlock(p); + +@@ -559,7 +559,7 @@ static SRes Lzma2Enc_EncodeMt1( + if (me->expectedDataSize != (UInt64)(Int64)-1 + && me->expectedDataSize >= unpackTotal) + expected = me->expectedDataSize - unpackTotal; +- if (me->props.blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID ++ if (me->props.blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID + && expected > me->props.blockSize) + expected = (size_t)me->props.blockSize; + +@@ -569,14 +569,14 @@ static SRes Lzma2Enc_EncodeMt1( + &limitedInStream.vt, + LZMA2_KEEP_WINDOW_SIZE, + me->alloc, +- me->allocBig)); ++ me->allocBig)) + } + else + { +- inSizeCur = inDataSize - (size_t)unpackTotal; +- if (me->props.blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID ++ inSizeCur = (SizeT)(inDataSize - (size_t)unpackTotal); ++ if (me->props.blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID + && inSizeCur > me->props.blockSize) +- inSizeCur = (size_t)me->props.blockSize; ++ inSizeCur = (SizeT)(size_t)me->props.blockSize; + + // LzmaEnc_SetDataSize(p->enc, inSizeCur); + +@@ -584,7 +584,7 @@ static SRes Lzma2Enc_EncodeMt1( + inData + (size_t)unpackTotal, inSizeCur, + LZMA2_KEEP_WINDOW_SIZE, + me->alloc, +- me->allocBig)); ++ me->allocBig)) + } + + for (;;) +@@ -621,7 +621,7 @@ static SRes Lzma2Enc_EncodeMt1( + + unpackTotal += p->srcPos; + +- RINOK(res); ++ RINOK(res) + + if (p->srcPos != (inStream ? limitedInStream.processed : inSizeCur)) + return SZ_ERROR_FAIL; +@@ -652,12 +652,12 @@ static SRes Lzma2Enc_EncodeMt1( + + + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + +-static SRes Lzma2Enc_MtCallback_Code(void *pp, unsigned coderIndex, unsigned outBufIndex, ++static SRes Lzma2Enc_MtCallback_Code(void *p, unsigned coderIndex, unsigned outBufIndex, + const Byte *src, size_t srcSize, int finished) + { +- CLzma2Enc *me = (CLzma2Enc *)pp; ++ CLzma2Enc *me = (CLzma2Enc *)p; + size_t destSize = me->outBufSize; + SRes res; + CMtProgressThunk progressThunk; +@@ -692,9 +692,9 @@ static SRes Lzma2Enc_MtCallback_Code(void *pp, unsigned coderIndex, unsigned out + } + + +-static SRes Lzma2Enc_MtCallback_Write(void *pp, unsigned outBufIndex) ++static SRes Lzma2Enc_MtCallback_Write(void *p, unsigned outBufIndex) + { +- CLzma2Enc *me = (CLzma2Enc *)pp; ++ CLzma2Enc *me = (CLzma2Enc *)p; + size_t size = me->outBufsDataSizes[outBufIndex]; + const Byte *data = me->outBufs[outBufIndex]; + +@@ -713,14 +713,14 @@ static SRes Lzma2Enc_MtCallback_Write(void *pp, unsigned outBufIndex) + + + +-SRes Lzma2Enc_Encode2(CLzma2EncHandle pp, +- ISeqOutStream *outStream, ++SRes Lzma2Enc_Encode2(CLzma2EncHandle p, ++ ISeqOutStreamPtr outStream, + Byte *outBuf, size_t *outBufSize, +- ISeqInStream *inStream, ++ ISeqInStreamPtr inStream, + const Byte *inData, size_t inDataSize, +- ICompressProgress *progress) ++ ICompressProgressPtr progress) + { +- CLzma2Enc *p = (CLzma2Enc *)pp; ++ // GET_CLzma2Enc_p + + if (inStream && inData) + return SZ_ERROR_PARAM; +@@ -730,11 +730,11 @@ SRes Lzma2Enc_Encode2(CLzma2EncHandle pp, + + { + unsigned i; +- for (i = 0; i < MTCODER__THREADS_MAX; i++) ++ for (i = 0; i < MTCODER_THREADS_MAX; i++) + p->coders[i].propsAreSet = False7z; + } + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + + if (p->props.numBlockThreads_Reduced > 1) + { +@@ -772,7 +772,7 @@ SRes Lzma2Enc_Encode2(CLzma2EncHandle pp, + return SZ_ERROR_PARAM; /* SZ_ERROR_MEM */ + + { +- size_t destBlockSize = p->mtCoder.blockSize + (p->mtCoder.blockSize >> 10) + 16; ++ const size_t destBlockSize = p->mtCoder.blockSize + (p->mtCoder.blockSize >> 10) + 16; + if (destBlockSize < p->mtCoder.blockSize) + return SZ_ERROR_PARAM; + if (p->outBufSize != destBlockSize) +@@ -784,7 +784,7 @@ SRes Lzma2Enc_Encode2(CLzma2EncHandle pp, + p->mtCoder.expectedDataSize = p->expectedDataSize; + + { +- SRes res = MtCoder_Code(&p->mtCoder); ++ const SRes res = MtCoder_Code(&p->mtCoder); + if (!outStream) + *outBufSize = (size_t)(p->outBuf - outBuf); + return res; +@@ -801,3 +801,5 @@ SRes Lzma2Enc_Encode2(CLzma2EncHandle pp, + True7z, /* finished */ + progress); + } ++ ++#undef PRF +diff --git a/src/lzma/Lzma2Enc.h b/src/lzma/Lzma2Enc.h +index 6a6110ff7..cb25275c6 100644 +--- a/src/lzma/Lzma2Enc.h ++++ b/src/lzma/Lzma2Enc.h +@@ -1,15 +1,15 @@ + /* Lzma2Enc.h -- LZMA2 Encoder +-2017-07-27 : Igor Pavlov : Public domain */ ++2023-04-13 : Igor Pavlov : Public domain */ + +-#ifndef __LZMA2_ENC_H +-#define __LZMA2_ENC_H ++#ifndef ZIP7_INC_LZMA2_ENC_H ++#define ZIP7_INC_LZMA2_ENC_H + + #include "LzmaEnc.h" + + EXTERN_C_BEGIN + +-#define LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO 0 +-#define LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID ((UInt64)(Int64)-1) ++#define LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO 0 ++#define LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID ((UInt64)(Int64)-1) + + typedef struct + { +@@ -36,7 +36,9 @@ SRes: + SZ_ERROR_THREAD - error in multithreading functions (only for Mt version) + */ + +-typedef void * CLzma2EncHandle; ++typedef struct CLzma2Enc CLzma2Enc; ++typedef CLzma2Enc * CLzma2EncHandle; ++// Z7_DECLARE_HANDLE(CLzma2EncHandle) + + CLzma2EncHandle Lzma2Enc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig); + void Lzma2Enc_Destroy(CLzma2EncHandle p); +@@ -44,11 +46,11 @@ SRes Lzma2Enc_SetProps(CLzma2EncHandle p, const CLzma2EncProps *props); + void Lzma2Enc_SetDataSize(CLzma2EncHandle p, UInt64 expectedDataSiize); + Byte Lzma2Enc_WriteProperties(CLzma2EncHandle p); + SRes Lzma2Enc_Encode2(CLzma2EncHandle p, +- ISeqOutStream *outStream, ++ ISeqOutStreamPtr outStream, + Byte *outBuf, size_t *outBufSize, +- ISeqInStream *inStream, ++ ISeqInStreamPtr inStream, + const Byte *inData, size_t inDataSize, +- ICompressProgress *progress); ++ ICompressProgressPtr progress); + + EXTERN_C_END + +diff --git a/src/lzma/Lzma86.h b/src/lzma/Lzma86.h +index bebed5cb7..e7707e2c4 100644 +--- a/src/lzma/Lzma86.h ++++ b/src/lzma/Lzma86.h +@@ -1,8 +1,8 @@ + /* Lzma86.h -- LZMA + x86 (BCJ) Filter +-2013-01-18 : Igor Pavlov : Public domain */ ++2023-03-03 : Igor Pavlov : Public domain */ + +-#ifndef __LZMA86_H +-#define __LZMA86_H ++#ifndef ZIP7_INC_LZMA86_H ++#define ZIP7_INC_LZMA86_H + + #include "7zTypes.h" + +diff --git a/src/lzma/Lzma86Dec.c b/src/lzma/Lzma86Dec.c +index 21031745c..f094d4c35 100644 +--- a/src/lzma/Lzma86Dec.c ++++ b/src/lzma/Lzma86Dec.c +@@ -1,5 +1,5 @@ + /* Lzma86Dec.c -- LZMA + x86 (BCJ) Filter Decoder +-2016-05-16 : Igor Pavlov : Public domain */ ++2023-03-03 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -46,9 +46,8 @@ SRes Lzma86_Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen) + return res; + if (useFilter == 1) + { +- UInt32 x86State; +- x86_Convert_Init(x86State); +- x86_Convert(dest, *destLen, 0, &x86State, 0); ++ UInt32 x86State = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL; ++ z7_BranchConvSt_X86_Dec(dest, *destLen, 0, &x86State); + } + return SZ_OK; + } +diff --git a/src/lzma/Lzma86Enc.c b/src/lzma/Lzma86Enc.c +index 2aed6758f..e87e2c7ce 100644 +--- a/src/lzma/Lzma86Enc.c ++++ b/src/lzma/Lzma86Enc.c +@@ -1,5 +1,5 @@ + /* Lzma86Enc.c -- LZMA + x86 (BCJ) Filter Encoder +-2018-07-04 : Igor Pavlov : Public domain */ ++2023-03-03 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -46,9 +46,8 @@ int Lzma86_Encode(Byte *dest, size_t *destLen, const Byte *src, size_t srcLen, + memcpy(filteredStream, src, srcLen); + } + { +- UInt32 x86State; +- x86_Convert_Init(x86State); +- x86_Convert(filteredStream, srcLen, 0, &x86State, 1); ++ UInt32 x86State = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL; ++ z7_BranchConvSt_X86_Enc(filteredStream, srcLen, 0, &x86State); + } + } + +diff --git a/src/lzma/LzmaDec.c b/src/lzma/LzmaDec.c +index 536fc6ed3..535c60c08 100644 +--- a/src/lzma/LzmaDec.c ++++ b/src/lzma/LzmaDec.c +@@ -1,5 +1,5 @@ + /* LzmaDec.c -- LZMA Decoder +-2021-04-01 : Igor Pavlov : Public domain */ ++2023-04-07 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -8,15 +8,15 @@ + /* #include "CpuArch.h" */ + #include "LzmaDec.h" + +-#define kNumTopBits 24 +-#define kTopValue ((UInt32)1 << kNumTopBits) ++// #define kNumTopBits 24 ++#define kTopValue ((UInt32)1 << 24) + + #define kNumBitModelTotalBits 11 + #define kBitModelTotal (1 << kNumBitModelTotalBits) + + #define RC_INIT_SIZE 5 + +-#ifndef _LZMA_DEC_OPT ++#ifndef Z7_LZMA_DEC_OPT + + #define kNumMoveBits 5 + #define NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | (*buf++); } +@@ -25,14 +25,14 @@ + #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; } ++ { UPDATE_0(p) i = (i + i); A0; } else \ ++ { UPDATE_1(p) i = (i + i) + 1; A1; } + + #define TREE_GET_BIT(probs, i) { GET_BIT2(probs + i, i, ;, ;); } + + #define REV_BIT(p, i, A0, A1) IF_BIT_0(p + i) \ +- { UPDATE_0(p + i); A0; } else \ +- { UPDATE_1(p + i); A1; } ++ { UPDATE_0(p + i) A0; } else \ ++ { UPDATE_1(p + i) A1; } + #define REV_BIT_VAR( p, i, m) REV_BIT(p, i, i += m; m += m, m += m; i += m; ) + #define REV_BIT_CONST(p, i, m) REV_BIT(p, i, i += m; , i += m * 2; ) + #define REV_BIT_LAST( p, i, m) REV_BIT(p, i, i -= m , ; ) +@@ -40,19 +40,19 @@ + #define TREE_DECODE(probs, limit, i) \ + { i = 1; do { TREE_GET_BIT(probs, i); } while (i < limit); i -= limit; } + +-/* #define _LZMA_SIZE_OPT */ ++/* #define Z7_LZMA_SIZE_OPT */ + +-#ifdef _LZMA_SIZE_OPT ++#ifdef Z7_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); \ ++ 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 + +@@ -64,25 +64,25 @@ + probLit = prob + (offs + bit + symbol); \ + GET_BIT2(probLit, symbol, offs ^= bit; , ;) + +-#endif // _LZMA_DEC_OPT ++#endif // Z7_LZMA_DEC_OPT + + + #define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_INPUT_EOF; range <<= 8; code = (code << 8) | (*buf++); } + +-#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK; bound = (range >> kNumBitModelTotalBits) * (UInt32)ttt; if (code < bound) ++#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK bound = (range >> kNumBitModelTotalBits) * (UInt32)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; } ++ { 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 REV_BIT_CHECK(p, i, m) IF_BIT_0_CHECK(p + i) \ +- { UPDATE_0_CHECK; i += m; m += m; } else \ +- { UPDATE_1_CHECK; m += m; i += m; } ++ { UPDATE_0_CHECK i += m; m += m; } else \ ++ { UPDATE_1_CHECK m += m; i += m; } + + + #define kNumPosBitsMax 4 +@@ -224,14 +224,14 @@ Out: + */ + + +-#ifdef _LZMA_DEC_OPT ++#ifdef Z7_LZMA_DEC_OPT + +-int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit); ++int Z7_FASTCALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit); + + #else + + static +-int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit) ++int Z7_FASTCALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit) + { + CLzmaProb *probs = GET_PROBS; + unsigned state = (unsigned)p->state; +@@ -263,7 +263,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit + IF_BIT_0(prob) + { + unsigned symbol; +- UPDATE_0(prob); ++ UPDATE_0(prob) + prob = probs + Literal; + if (processedPos != 0 || checkDicSize != 0) + prob += (UInt32)3 * ((((processedPos << 8) + dic[(dicPos == 0 ? dicBufSize : dicPos) - 1]) & lpMask) << lc); +@@ -273,7 +273,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit + { + state -= (state < 4) ? state : 3; + symbol = 1; +- #ifdef _LZMA_SIZE_OPT ++ #ifdef Z7_LZMA_SIZE_OPT + do { NORMAL_LITER_DEC } while (symbol < 0x100); + #else + NORMAL_LITER_DEC +@@ -292,7 +292,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit + unsigned offs = 0x100; + state -= (state < 10) ? 3 : 6; + symbol = 1; +- #ifdef _LZMA_SIZE_OPT ++ #ifdef Z7_LZMA_SIZE_OPT + do + { + unsigned bit; +@@ -321,25 +321,25 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit + } + + { +- UPDATE_1(prob); ++ UPDATE_1(prob) + prob = probs + IsRep + state; + IF_BIT_0(prob) + { +- UPDATE_0(prob); ++ UPDATE_0(prob) + state += kNumStates; + prob = probs + LenCoder; + } + else + { +- UPDATE_1(prob); ++ UPDATE_1(prob) + prob = probs + IsRepG0 + state; + IF_BIT_0(prob) + { +- UPDATE_0(prob); ++ UPDATE_0(prob) + prob = probs + IsRep0Long + COMBINED_PS_STATE; + IF_BIT_0(prob) + { +- UPDATE_0(prob); ++ UPDATE_0(prob) + + // that case was checked before with kBadRepCode + // if (checkDicSize == 0 && processedPos == 0) { len = kMatchSpecLen_Error_Data + 1; break; } +@@ -353,30 +353,30 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit + state = state < kNumLitStates ? 9 : 11; + continue; + } +- UPDATE_1(prob); ++ UPDATE_1(prob) + } + else + { + UInt32 distance; +- UPDATE_1(prob); ++ UPDATE_1(prob) + prob = probs + IsRepG1 + state; + IF_BIT_0(prob) + { +- UPDATE_0(prob); ++ UPDATE_0(prob) + distance = rep1; + } + else + { +- UPDATE_1(prob); ++ UPDATE_1(prob) + prob = probs + IsRepG2 + state; + IF_BIT_0(prob) + { +- UPDATE_0(prob); ++ UPDATE_0(prob) + distance = rep2; + } + else + { +- UPDATE_1(prob); ++ UPDATE_1(prob) + distance = rep3; + rep3 = rep2; + } +@@ -389,37 +389,37 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit + prob = probs + RepLenCoder; + } + +- #ifdef _LZMA_SIZE_OPT ++ #ifdef Z7_LZMA_SIZE_OPT + { + unsigned lim, offset; + CLzmaProb *probLen = prob + LenChoice; + IF_BIT_0(probLen) + { +- UPDATE_0(probLen); ++ UPDATE_0(probLen) + probLen = prob + LenLow + GET_LEN_STATE; + offset = 0; + lim = (1 << kLenNumLowBits); + } + else + { +- UPDATE_1(probLen); ++ UPDATE_1(probLen) + probLen = prob + LenChoice2; + IF_BIT_0(probLen) + { +- UPDATE_0(probLen); ++ UPDATE_0(probLen) + probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); + offset = kLenNumLowSymbols; + lim = (1 << kLenNumLowBits); + } + else + { +- UPDATE_1(probLen); ++ UPDATE_1(probLen) + probLen = prob + LenHigh; + offset = kLenNumLowSymbols * 2; + lim = (1 << kLenNumHighBits); + } + } +- TREE_DECODE(probLen, lim, len); ++ TREE_DECODE(probLen, lim, len) + len += offset; + } + #else +@@ -427,32 +427,32 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit + CLzmaProb *probLen = prob + LenChoice; + IF_BIT_0(probLen) + { +- UPDATE_0(probLen); ++ UPDATE_0(probLen) + probLen = prob + LenLow + GET_LEN_STATE; + len = 1; +- TREE_GET_BIT(probLen, len); +- TREE_GET_BIT(probLen, len); +- TREE_GET_BIT(probLen, len); ++ TREE_GET_BIT(probLen, len) ++ TREE_GET_BIT(probLen, len) ++ TREE_GET_BIT(probLen, len) + len -= 8; + } + else + { +- UPDATE_1(probLen); ++ UPDATE_1(probLen) + probLen = prob + LenChoice2; + IF_BIT_0(probLen) + { +- UPDATE_0(probLen); ++ UPDATE_0(probLen) + probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); + len = 1; +- TREE_GET_BIT(probLen, len); +- TREE_GET_BIT(probLen, len); +- TREE_GET_BIT(probLen, len); ++ TREE_GET_BIT(probLen, len) ++ TREE_GET_BIT(probLen, len) ++ TREE_GET_BIT(probLen, len) + } + else + { +- UPDATE_1(probLen); ++ UPDATE_1(probLen) + probLen = prob + LenHigh; +- TREE_DECODE(probLen, (1 << kLenNumHighBits), len); ++ TREE_DECODE(probLen, (1 << kLenNumHighBits), len) + len += kLenNumLowSymbols * 2; + } + } +@@ -464,7 +464,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit + UInt32 distance; + prob = probs + PosSlot + + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits); +- TREE_6_DECODE(prob, distance); ++ TREE_6_DECODE(prob, distance) + if (distance >= kStartPosModelIndex) + { + unsigned posSlot = (unsigned)distance; +@@ -479,7 +479,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit + distance++; + do + { +- REV_BIT_VAR(prob, distance, m); ++ REV_BIT_VAR(prob, distance, m) + } + while (--numDirectBits); + distance -= m; +@@ -514,10 +514,10 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit + distance <<= kNumAlignBits; + { + unsigned i = 1; +- REV_BIT_CONST(prob, i, 1); +- REV_BIT_CONST(prob, i, 2); +- REV_BIT_CONST(prob, i, 4); +- REV_BIT_LAST (prob, i, 8); ++ REV_BIT_CONST(prob, i, 1) ++ REV_BIT_CONST(prob, i, 2) ++ REV_BIT_CONST(prob, i, 4) ++ REV_BIT_LAST (prob, i, 8) + distance |= i; + } + if (distance == (UInt32)0xFFFFFFFF) +@@ -592,7 +592,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit + } + while (dicPos < limit && buf < bufLimit); + +- NORMALIZE; ++ NORMALIZE + + p->buf = buf; + p->range = range; +@@ -613,7 +613,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit + + + +-static void MY_FAST_CALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit) ++static void Z7_FASTCALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit) + { + unsigned len = (unsigned)p->remainLen; + if (len == 0 /* || len >= kMatchSpecLenStart */) +@@ -683,7 +683,7 @@ and we support the following state of (p->checkDicSize): + (p->checkDicSize == p->prop.dicSize) + */ + +-static int MY_FAST_CALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit) ++static int Z7_FASTCALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit) + { + if (p->checkDicSize == 0) + { +@@ -767,54 +767,54 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt + else + { + unsigned len; +- UPDATE_1_CHECK; ++ UPDATE_1_CHECK + + prob = probs + IsRep + state; + IF_BIT_0_CHECK(prob) + { +- UPDATE_0_CHECK; ++ UPDATE_0_CHECK + state = 0; + prob = probs + LenCoder; + res = DUMMY_MATCH; + } + else + { +- UPDATE_1_CHECK; ++ UPDATE_1_CHECK + res = DUMMY_REP; + prob = probs + IsRepG0 + state; + IF_BIT_0_CHECK(prob) + { +- UPDATE_0_CHECK; ++ UPDATE_0_CHECK + prob = probs + IsRep0Long + COMBINED_PS_STATE; + IF_BIT_0_CHECK(prob) + { +- UPDATE_0_CHECK; ++ UPDATE_0_CHECK + break; + } + else + { +- UPDATE_1_CHECK; ++ UPDATE_1_CHECK + } + } + else + { +- UPDATE_1_CHECK; ++ UPDATE_1_CHECK + prob = probs + IsRepG1 + state; + IF_BIT_0_CHECK(prob) + { +- UPDATE_0_CHECK; ++ UPDATE_0_CHECK + } + else + { +- UPDATE_1_CHECK; ++ UPDATE_1_CHECK + prob = probs + IsRepG2 + state; + IF_BIT_0_CHECK(prob) + { +- UPDATE_0_CHECK; ++ UPDATE_0_CHECK + } + else + { +- UPDATE_1_CHECK; ++ UPDATE_1_CHECK + } + } + } +@@ -826,31 +826,31 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt + const CLzmaProb *probLen = prob + LenChoice; + IF_BIT_0_CHECK(probLen) + { +- UPDATE_0_CHECK; ++ UPDATE_0_CHECK + probLen = prob + LenLow + GET_LEN_STATE; + offset = 0; + limit = 1 << kLenNumLowBits; + } + else + { +- UPDATE_1_CHECK; ++ UPDATE_1_CHECK + probLen = prob + LenChoice2; + IF_BIT_0_CHECK(probLen) + { +- UPDATE_0_CHECK; ++ UPDATE_0_CHECK + probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); + offset = kLenNumLowSymbols; + limit = 1 << kLenNumLowBits; + } + else + { +- UPDATE_1_CHECK; ++ UPDATE_1_CHECK + probLen = prob + LenHigh; + offset = kLenNumLowSymbols * 2; + limit = 1 << kLenNumHighBits; + } + } +- TREE_DECODE_CHECK(probLen, limit, len); ++ TREE_DECODE_CHECK(probLen, limit, len) + len += offset; + } + +@@ -860,7 +860,7 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt + prob = probs + PosSlot + + ((len < kNumLenToPosStates - 1 ? len : kNumLenToPosStates - 1) << + kNumPosSlotBits); +- TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot); ++ TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot) + if (posSlot >= kStartPosModelIndex) + { + unsigned numDirectBits = ((posSlot >> 1) - 1); +@@ -888,7 +888,7 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt + unsigned m = 1; + do + { +- REV_BIT_CHECK(prob, i, m); ++ REV_BIT_CHECK(prob, i, m) + } + while (--numDirectBits); + } +@@ -897,7 +897,7 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt + } + break; + } +- NORMALIZE_CHECK; ++ NORMALIZE_CHECK + + *bufOut = buf; + return res; +@@ -943,7 +943,7 @@ When the decoder lookahead, and the lookahead symbol is not end_marker, we have + */ + + +-#define RETURN__NOT_FINISHED__FOR_FINISH \ ++#define RETURN_NOT_FINISHED_FOR_FINISH \ + *status = LZMA_STATUS_NOT_FINISHED; \ + return SZ_ERROR_DATA; // for strict mode + // return SZ_OK; // for relaxed mode +@@ -1029,7 +1029,7 @@ SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *sr + } + if (p->remainLen != 0) + { +- RETURN__NOT_FINISHED__FOR_FINISH; ++ RETURN_NOT_FINISHED_FOR_FINISH + } + checkEndMarkNow = 1; + } +@@ -1072,7 +1072,7 @@ SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *sr + for (i = 0; i < (unsigned)dummyProcessed; i++) + p->tempBuf[i] = src[i]; + // p->remainLen = kMatchSpecLen_Error_Data; +- RETURN__NOT_FINISHED__FOR_FINISH; ++ RETURN_NOT_FINISHED_FOR_FINISH + } + + bufLimit = src; +@@ -1150,7 +1150,7 @@ SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *sr + (*srcLen) += (unsigned)dummyProcessed - p->tempBufSize; + p->tempBufSize = (unsigned)dummyProcessed; + // p->remainLen = kMatchSpecLen_Error_Data; +- RETURN__NOT_FINISHED__FOR_FINISH; ++ RETURN_NOT_FINISHED_FOR_FINISH + } + } + +@@ -1299,8 +1299,8 @@ static SRes LzmaDec_AllocateProbs2(CLzmaDec *p, const CLzmaProps *propNew, ISzAl + SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc) + { + CLzmaProps propNew; +- RINOK(LzmaProps_Decode(&propNew, props, propsSize)); +- RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)); ++ RINOK(LzmaProps_Decode(&propNew, props, propsSize)) ++ RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)) + p->prop = propNew; + return SZ_OK; + } +@@ -1309,14 +1309,14 @@ SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAll + { + CLzmaProps propNew; + SizeT dicBufSize; +- RINOK(LzmaProps_Decode(&propNew, props, propsSize)); +- RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)); ++ RINOK(LzmaProps_Decode(&propNew, props, propsSize)) ++ RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)) + + { + UInt32 dictSize = propNew.dicSize; + SizeT mask = ((UInt32)1 << 12) - 1; + if (dictSize >= ((UInt32)1 << 30)) mask = ((UInt32)1 << 22) - 1; +- else if (dictSize >= ((UInt32)1 << 22)) mask = ((UInt32)1 << 20) - 1;; ++ else if (dictSize >= ((UInt32)1 << 22)) mask = ((UInt32)1 << 20) - 1; + dicBufSize = ((SizeT)dictSize + mask) & ~mask; + if (dicBufSize < dictSize) + dicBufSize = dictSize; +@@ -1348,8 +1348,8 @@ SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, + *status = LZMA_STATUS_NOT_SPECIFIED; + if (inSize < RC_INIT_SIZE) + return SZ_ERROR_INPUT_EOF; +- LzmaDec_Construct(&p); +- RINOK(LzmaDec_AllocateProbs(&p, propData, propSize, alloc)); ++ LzmaDec_CONSTRUCT(&p) ++ RINOK(LzmaDec_AllocateProbs(&p, propData, propSize, alloc)) + p.dic = dest; + p.dicBufSize = outSize; + LzmaDec_Init(&p); +diff --git a/src/lzma/LzmaDec.h b/src/lzma/LzmaDec.h +index 6f1296250..b0ce28fa0 100644 +--- a/src/lzma/LzmaDec.h ++++ b/src/lzma/LzmaDec.h +@@ -1,19 +1,19 @@ + /* LzmaDec.h -- LZMA Decoder +-2020-03-19 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + +-#ifndef __LZMA_DEC_H +-#define __LZMA_DEC_H ++#ifndef ZIP7_INC_LZMA_DEC_H ++#define ZIP7_INC_LZMA_DEC_H + + #include "7zTypes.h" + + EXTERN_C_BEGIN + +-/* #define _LZMA_PROB32 */ +-/* _LZMA_PROB32 can increase the speed on some CPUs, ++/* #define Z7_LZMA_PROB32 */ ++/* Z7_LZMA_PROB32 can increase the speed on some CPUs, + but memory usage for CLzmaDec::probs will be doubled in that case */ + + typedef +-#ifdef _LZMA_PROB32 ++#ifdef Z7_LZMA_PROB32 + UInt32 + #else + UInt16 +@@ -25,7 +25,7 @@ typedef + + #define LZMA_PROPS_SIZE 5 + +-typedef struct _CLzmaProps ++typedef struct + { + Byte lc; + Byte lp; +@@ -73,7 +73,8 @@ typedef struct + Byte tempBuf[LZMA_REQUIRED_INPUT_MAX]; + } CLzmaDec; + +-#define LzmaDec_Construct(p) { (p)->dic = NULL; (p)->probs = NULL; } ++#define LzmaDec_CONSTRUCT(p) { (p)->dic = NULL; (p)->probs = NULL; } ++#define LzmaDec_Construct(p) LzmaDec_CONSTRUCT(p) + + void LzmaDec_Init(CLzmaDec *p); + +diff --git a/src/lzma/LzmaEnc.c b/src/lzma/LzmaEnc.c +index 2fa3456b7..664397349 100644 +--- a/src/lzma/LzmaEnc.c ++++ b/src/lzma/LzmaEnc.c +@@ -1,5 +1,5 @@ + /* LzmaEnc.c -- LZMA Encoder +-2021-11-18: Igor Pavlov : Public domain */ ++2023-04-13: Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -16,22 +16,22 @@ + #include "LzmaEnc.h" + + #include "LzFind.h" +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + #include "LzFindMt.h" + #endif + + /* the following LzmaEnc_* declarations is internal LZMA interface for LZMA2 encoder */ + +-SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp, ISeqInStream *inStream, UInt32 keepWindowSize, ++SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle p, ISeqInStreamPtr inStream, UInt32 keepWindowSize, + ISzAllocPtr alloc, ISzAllocPtr allocBig); +-SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen, ++SRes LzmaEnc_MemPrepare(CLzmaEncHandle p, const Byte *src, SizeT srcLen, + UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig); +-SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit, ++SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle p, BoolInt reInit, + Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize); +-const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp); +-void LzmaEnc_Finish(CLzmaEncHandle pp); +-void LzmaEnc_SaveState(CLzmaEncHandle pp); +-void LzmaEnc_RestoreState(CLzmaEncHandle pp); ++const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle p); ++void LzmaEnc_Finish(CLzmaEncHandle p); ++void LzmaEnc_SaveState(CLzmaEncHandle p); ++void LzmaEnc_RestoreState(CLzmaEncHandle p); + + #ifdef SHOW_STAT + static unsigned g_STAT_OFFSET = 0; +@@ -40,8 +40,8 @@ static unsigned g_STAT_OFFSET = 0; + /* for good normalization speed we still reserve 256 MB before 4 GB range */ + #define kLzmaMaxHistorySize ((UInt32)15 << 28) + +-#define kNumTopBits 24 +-#define kTopValue ((UInt32)1 << kNumTopBits) ++// #define kNumTopBits 24 ++#define kTopValue ((UInt32)1 << 24) + + #define kNumBitModelTotalBits 11 + #define kBitModelTotal (1 << kNumBitModelTotalBits) +@@ -60,6 +60,7 @@ void LzmaEncProps_Init(CLzmaEncProps *p) + p->dictSize = p->mc = 0; + p->reduceSize = (UInt64)(Int64)-1; + p->lc = p->lp = p->pb = p->algo = p->fb = p->btMode = p->numHashBytes = p->numThreads = -1; ++ p->numHashOutBits = 0; + p->writeEndMark = 0; + p->affinity = 0; + } +@@ -99,7 +100,7 @@ void LzmaEncProps_Normalize(CLzmaEncProps *p) + + if (p->numThreads < 0) + p->numThreads = +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + ((p->btMode && p->algo) ? 2 : 1); + #else + 1; +@@ -293,7 +294,7 @@ typedef struct + #define kNumFullDistances (1 << (kEndPosModelIndex >> 1)) + + typedef +-#ifdef _LZMA_PROB32 ++#ifdef Z7_LZMA_PROB32 + UInt32 + #else + UInt16 +@@ -350,7 +351,7 @@ typedef struct + Byte *buf; + Byte *bufLim; + Byte *bufBase; +- ISeqOutStream *outStream; ++ ISeqOutStreamPtr outStream; + UInt64 processed; + SRes res; + } CRangeEnc; +@@ -383,7 +384,7 @@ typedef struct + typedef UInt32 CProbPrice; + + +-typedef struct ++struct CLzmaEnc + { + void *matchFinderObj; + IMatchFinder2 matchFinder; +@@ -426,7 +427,7 @@ typedef struct + UInt32 dictSize; + SRes result; + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + BoolInt mtMode; + // begin of CMatchFinderMt is used in LZ thread + CMatchFinderMt matchFinderMt; +@@ -439,7 +440,7 @@ typedef struct + + // we suppose that we have 8-bytes alignment after CMatchFinder + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + Byte pad[128]; + #endif + +@@ -479,77 +480,59 @@ typedef struct + CSaveState saveState; + + // BoolInt mf_Failure; +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + Byte pad2[128]; + #endif +-} CLzmaEnc; ++}; + + + #define MFB (p->matchFinderBase) + /* +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + #define MFB (p->matchFinderMt.MatchFinder) + #endif + */ + +-#define COPY_ARR(dest, src, arr) memcpy(dest->arr, src->arr, sizeof(src->arr)); +- +-void LzmaEnc_SaveState(CLzmaEncHandle pp) +-{ +- CLzmaEnc *p = (CLzmaEnc *)pp; +- CSaveState *dest = &p->saveState; +- +- dest->state = p->state; +- +- dest->lenProbs = p->lenProbs; +- dest->repLenProbs = p->repLenProbs; +- +- COPY_ARR(dest, p, reps); +- +- COPY_ARR(dest, p, posAlignEncoder); +- COPY_ARR(dest, p, isRep); +- COPY_ARR(dest, p, isRepG0); +- COPY_ARR(dest, p, isRepG1); +- COPY_ARR(dest, p, isRepG2); +- COPY_ARR(dest, p, isMatch); +- COPY_ARR(dest, p, isRep0Long); +- COPY_ARR(dest, p, posSlotEncoder); +- COPY_ARR(dest, p, posEncoders); +- +- memcpy(dest->litProbs, p->litProbs, ((UInt32)0x300 << p->lclp) * sizeof(CLzmaProb)); ++// #define GET_CLzmaEnc_p CLzmaEnc *p = (CLzmaEnc*)(void *)p; ++// #define GET_const_CLzmaEnc_p const CLzmaEnc *p = (const CLzmaEnc*)(const void *)p; ++ ++#define COPY_ARR(dest, src, arr) memcpy((dest)->arr, (src)->arr, sizeof((src)->arr)); ++ ++#define COPY_LZMA_ENC_STATE(d, s, p) \ ++ (d)->state = (s)->state; \ ++ COPY_ARR(d, s, reps) \ ++ COPY_ARR(d, s, posAlignEncoder) \ ++ COPY_ARR(d, s, isRep) \ ++ COPY_ARR(d, s, isRepG0) \ ++ COPY_ARR(d, s, isRepG1) \ ++ COPY_ARR(d, s, isRepG2) \ ++ COPY_ARR(d, s, isMatch) \ ++ COPY_ARR(d, s, isRep0Long) \ ++ COPY_ARR(d, s, posSlotEncoder) \ ++ COPY_ARR(d, s, posEncoders) \ ++ (d)->lenProbs = (s)->lenProbs; \ ++ (d)->repLenProbs = (s)->repLenProbs; \ ++ memcpy((d)->litProbs, (s)->litProbs, ((UInt32)0x300 << (p)->lclp) * sizeof(CLzmaProb)); ++ ++void LzmaEnc_SaveState(CLzmaEncHandle p) ++{ ++ // GET_CLzmaEnc_p ++ CSaveState *v = &p->saveState; ++ COPY_LZMA_ENC_STATE(v, p, p) + } + +- +-void LzmaEnc_RestoreState(CLzmaEncHandle pp) ++void LzmaEnc_RestoreState(CLzmaEncHandle p) + { +- CLzmaEnc *dest = (CLzmaEnc *)pp; +- const CSaveState *p = &dest->saveState; +- +- dest->state = p->state; +- +- dest->lenProbs = p->lenProbs; +- dest->repLenProbs = p->repLenProbs; +- +- COPY_ARR(dest, p, reps); +- +- COPY_ARR(dest, p, posAlignEncoder); +- COPY_ARR(dest, p, isRep); +- COPY_ARR(dest, p, isRepG0); +- COPY_ARR(dest, p, isRepG1); +- COPY_ARR(dest, p, isRepG2); +- COPY_ARR(dest, p, isMatch); +- COPY_ARR(dest, p, isRep0Long); +- COPY_ARR(dest, p, posSlotEncoder); +- COPY_ARR(dest, p, posEncoders); +- +- memcpy(dest->litProbs, p->litProbs, ((UInt32)0x300 << dest->lclp) * sizeof(CLzmaProb)); ++ // GET_CLzmaEnc_p ++ const CSaveState *v = &p->saveState; ++ COPY_LZMA_ENC_STATE(p, v, p) + } + + +- +-SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) ++Z7_NO_INLINE ++SRes LzmaEnc_SetProps(CLzmaEncHandle p, const CLzmaEncProps *props2) + { +- CLzmaEnc *p = (CLzmaEnc *)pp; ++ // GET_CLzmaEnc_p + CLzmaEncProps props = *props2; + LzmaEncProps_Normalize(&props); + +@@ -585,6 +568,7 @@ SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) + p->fastMode = (props.algo == 0); + // p->_maxMode = True7z; + MFB.btMode = (Byte)(props.btMode ? 1 : 0); ++ // MFB.btMode = (Byte)(props.btMode); + { + unsigned numHashBytes = 4; + if (props.btMode) +@@ -595,13 +579,15 @@ SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) + if (props.numHashBytes >= 5) numHashBytes = 5; + + MFB.numHashBytes = numHashBytes; ++ // MFB.numHashBytes_Min = 2; ++ MFB.numHashOutBits = (Byte)props.numHashOutBits; + } + + MFB.cutValue = props.mc; + + p->writeEndMark = (BoolInt)props.writeEndMark; + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + /* + if (newMultiThread != _multiThread) + { +@@ -618,9 +604,9 @@ SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) + } + + +-void LzmaEnc_SetDataSize(CLzmaEncHandle pp, UInt64 expectedDataSiize) ++void LzmaEnc_SetDataSize(CLzmaEncHandle p, UInt64 expectedDataSiize) + { +- CLzmaEnc *p = (CLzmaEnc *)pp; ++ // GET_CLzmaEnc_p + MFB.expectedDataSize = expectedDataSiize; + } + +@@ -684,7 +670,7 @@ static void RangeEnc_Init(CRangeEnc *p) + p->res = SZ_OK; + } + +-MY_NO_INLINE static void RangeEnc_FlushStream(CRangeEnc *p) ++Z7_NO_INLINE static void RangeEnc_FlushStream(CRangeEnc *p) + { + const size_t num = (size_t)(p->buf - p->bufBase); + if (p->res == SZ_OK) +@@ -696,7 +682,7 @@ MY_NO_INLINE static void RangeEnc_FlushStream(CRangeEnc *p) + p->buf = p->bufBase; + } + +-MY_NO_INLINE static void MY_FAST_CALL RangeEnc_ShiftLow(CRangeEnc *p) ++Z7_NO_INLINE static void Z7_FASTCALL RangeEnc_ShiftLow(CRangeEnc *p) + { + UInt32 low = (UInt32)p->low; + unsigned high = (unsigned)(p->low >> 32); +@@ -741,9 +727,9 @@ static void RangeEnc_FlushData(CRangeEnc *p) + ttt = *(prob); \ + newBound = (range >> kNumBitModelTotalBits) * ttt; + +-// #define _LZMA_ENC_USE_BRANCH ++// #define Z7_LZMA_ENC_USE_BRANCH + +-#ifdef _LZMA_ENC_USE_BRANCH ++#ifdef Z7_LZMA_ENC_USE_BRANCH + + #define RC_BIT(p, prob, bit) { \ + RC_BIT_PRE(p, prob) \ +@@ -811,7 +797,7 @@ static void LitEnc_Encode(CRangeEnc *p, CLzmaProb *probs, UInt32 sym) + CLzmaProb *prob = probs + (sym >> 8); + UInt32 bit = (sym >> 7) & 1; + sym <<= 1; +- RC_BIT(p, prob, bit); ++ RC_BIT(p, prob, bit) + } + while (sym < 0x10000); + p->range = range; +@@ -833,7 +819,7 @@ static void LitEnc_EncodeMatched(CRangeEnc *p, CLzmaProb *probs, UInt32 sym, UIn + bit = (sym >> 7) & 1; + sym <<= 1; + offs &= ~(matchByte ^ sym); +- RC_BIT(p, prob, bit); ++ RC_BIT(p, prob, bit) + } + while (sym < 0x10000); + p->range = range; +@@ -867,10 +853,10 @@ static void LzmaEnc_InitPriceTables(CProbPrice *ProbPrices) + + + #define GET_PRICE(prob, bit) \ +- p->ProbPrices[((prob) ^ (unsigned)(((-(int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits]; ++ p->ProbPrices[((prob) ^ (unsigned)(((-(int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits] + + #define GET_PRICEa(prob, bit) \ +- ProbPrices[((prob) ^ (unsigned)((-((int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits]; ++ ProbPrices[((prob) ^ (unsigned)((-((int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits] + + #define GET_PRICE_0(prob) p->ProbPrices[(prob) >> kNumMoveReducingBits] + #define GET_PRICE_1(prob) p->ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits] +@@ -921,7 +907,7 @@ static void RcTree_ReverseEncode(CRangeEnc *rc, CLzmaProb *probs, unsigned numBi + unsigned bit = sym & 1; + // RangeEnc_EncodeBit(rc, probs + m, bit); + sym >>= 1; +- RC_BIT(rc, probs + m, bit); ++ RC_BIT(rc, probs + m, bit) + m = (m << 1) | bit; + } + while (--numBits); +@@ -944,15 +930,15 @@ static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, unsigned sym, unsigned posS + UInt32 range, ttt, newBound; + CLzmaProb *probs = p->low; + range = rc->range; +- RC_BIT_PRE(rc, probs); ++ RC_BIT_PRE(rc, probs) + if (sym >= kLenNumLowSymbols) + { +- RC_BIT_1(rc, probs); ++ RC_BIT_1(rc, probs) + probs += kLenNumLowSymbols; +- RC_BIT_PRE(rc, probs); ++ RC_BIT_PRE(rc, probs) + if (sym >= kLenNumLowSymbols * 2) + { +- RC_BIT_1(rc, probs); ++ RC_BIT_1(rc, probs) + rc->range = range; + // RcTree_Encode(rc, p->high, kLenNumHighBits, sym - kLenNumLowSymbols * 2); + LitEnc_Encode(rc, p->high, sym - kLenNumLowSymbols * 2); +@@ -965,11 +951,11 @@ static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, unsigned sym, unsigned posS + { + unsigned m; + unsigned bit; +- RC_BIT_0(rc, probs); ++ RC_BIT_0(rc, probs) + probs += (posState << (1 + kLenNumLowBits)); +- bit = (sym >> 2) ; RC_BIT(rc, probs + 1, bit); m = (1 << 1) + bit; +- bit = (sym >> 1) & 1; RC_BIT(rc, probs + m, bit); m = (m << 1) + bit; +- bit = sym & 1; RC_BIT(rc, probs + m, bit); ++ bit = (sym >> 2) ; RC_BIT(rc, probs + 1, bit) m = (1 << 1) + bit; ++ bit = (sym >> 1) & 1; RC_BIT(rc, probs + m, bit) m = (m << 1) + bit; ++ bit = sym & 1; RC_BIT(rc, probs + m, bit) + rc->range = range; + } + } +@@ -990,7 +976,7 @@ static void SetPrices_3(const CLzmaProb *probs, UInt32 startPrice, UInt32 *price + } + + +-MY_NO_INLINE static void MY_FAST_CALL LenPriceEnc_UpdateTables( ++Z7_NO_INLINE static void Z7_FASTCALL LenPriceEnc_UpdateTables( + CLenPriceEnc *p, + unsigned numPosStates, + const CLenEnc *enc, +@@ -1152,7 +1138,7 @@ static unsigned ReadMatchDistances(CLzmaEnc *p, unsigned *numPairsRes) + + GET_PRICE_1(p->isRep[state]) \ + + GET_PRICE_0(p->isRepG0[state]) + +-MY_FORCE_INLINE ++Z7_FORCE_INLINE + static UInt32 GetPrice_PureRep(const CLzmaEnc *p, unsigned repIndex, size_t state, size_t posState) + { + UInt32 price; +@@ -1331,7 +1317,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) + LitEnc_GetPrice(probs, curByte, p->ProbPrices)); + } + +- MakeAs_Lit(&p->opt[1]); ++ MakeAs_Lit(&p->opt[1]) + + matchPrice = GET_PRICE_1(p->isMatch[p->state][posState]); + repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[p->state]); +@@ -1343,7 +1329,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) + if (shortRepPrice < p->opt[1].price) + { + p->opt[1].price = shortRepPrice; +- MakeAs_ShortRep(&p->opt[1]); ++ MakeAs_ShortRep(&p->opt[1]) + } + if (last < 2) + { +@@ -1410,7 +1396,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) + else + { + unsigned slot; +- GetPosSlot2(dist, slot); ++ GetPosSlot2(dist, slot) + price += p->alignPrices[dist & kAlignMask]; + price += p->posSlotPrices[lenToPosState][slot]; + } +@@ -1486,7 +1472,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) + unsigned delta = best - cur; + if (delta != 0) + { +- MOVE_POS(p, delta); ++ MOVE_POS(p, delta) + } + } + cur = best; +@@ -1633,7 +1619,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) + { + nextOpt->price = litPrice; + nextOpt->len = 1; +- MakeAs_Lit(nextOpt); ++ MakeAs_Lit(nextOpt) + nextIsLit = True7z; + } + } +@@ -1667,7 +1653,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) + { + nextOpt->price = shortRepPrice; + nextOpt->len = 1; +- MakeAs_ShortRep(nextOpt); ++ MakeAs_ShortRep(nextOpt) + nextIsLit = False7z; + } + } +@@ -1871,7 +1857,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) + dist = MATCHES[(size_t)offs + 1]; + + // if (dist >= kNumFullDistances) +- GetPosSlot2(dist, posSlot); ++ GetPosSlot2(dist, posSlot) + + for (len = /*2*/ startLen; ; len++) + { +@@ -1962,7 +1948,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) + break; + dist = MATCHES[(size_t)offs + 1]; + // if (dist >= kNumFullDistances) +- GetPosSlot2(dist, posSlot); ++ GetPosSlot2(dist, posSlot) + } + } + } +@@ -2138,7 +2124,7 @@ static void WriteEndMarker(CLzmaEnc *p, unsigned posState) + { + UInt32 ttt, newBound; + RC_BIT_PRE(p, probs + m) +- RC_BIT_1(&p->rc, probs + m); ++ RC_BIT_1(&p->rc, probs + m) + m = (m << 1) + 1; + } + while (m < (1 << kNumPosSlotBits)); +@@ -2163,7 +2149,7 @@ static void WriteEndMarker(CLzmaEnc *p, unsigned posState) + { + UInt32 ttt, newBound; + RC_BIT_PRE(p, probs + m) +- RC_BIT_1(&p->rc, probs + m); ++ RC_BIT_1(&p->rc, probs + m) + m = (m << 1) + 1; + } + while (m < kAlignTableSize); +@@ -2179,7 +2165,7 @@ static SRes CheckErrors(CLzmaEnc *p) + if (p->rc.res != SZ_OK) + p->result = SZ_ERROR_WRITE; + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + if ( + // p->mf_Failure || + (p->mtMode && +@@ -2187,7 +2173,7 @@ static SRes CheckErrors(CLzmaEnc *p) + p->matchFinderMt.failure_LZ_BT)) + ) + { +- p->result = MY_HRES_ERROR__INTERNAL_ERROR; ++ p->result = MY_HRES_ERROR_INTERNAL_ERROR; + // printf("\nCheckErrors p->matchFinderMt.failureLZ\n"); + } + #endif +@@ -2201,7 +2187,7 @@ static SRes CheckErrors(CLzmaEnc *p) + } + + +-MY_NO_INLINE static SRes Flush(CLzmaEnc *p, UInt32 nowPos) ++Z7_NO_INLINE static SRes Flush(CLzmaEnc *p, UInt32 nowPos) + { + /* ReleaseMFStream(); */ + p->finished = True7z; +@@ -2213,7 +2199,7 @@ MY_NO_INLINE static SRes Flush(CLzmaEnc *p, UInt32 nowPos) + } + + +-MY_NO_INLINE static void FillAlignPrices(CLzmaEnc *p) ++Z7_NO_INLINE static void FillAlignPrices(CLzmaEnc *p) + { + unsigned i; + const CProbPrice *ProbPrices = p->ProbPrices; +@@ -2237,7 +2223,7 @@ MY_NO_INLINE static void FillAlignPrices(CLzmaEnc *p) + } + + +-MY_NO_INLINE static void FillDistancesPrices(CLzmaEnc *p) ++Z7_NO_INLINE static void FillDistancesPrices(CLzmaEnc *p) + { + // int y; for (y = 0; y < 100; y++) { + +@@ -2337,7 +2323,7 @@ static void LzmaEnc_Construct(CLzmaEnc *p) + RangeEnc_Construct(&p->rc); + MatchFinder_Construct(&MFB); + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + p->matchFinderMt.MatchFinder = &MFB; + MatchFinderMt_Construct(&p->matchFinderMt); + #endif +@@ -2345,7 +2331,7 @@ static void LzmaEnc_Construct(CLzmaEnc *p) + { + CLzmaEncProps props; + LzmaEncProps_Init(&props); +- LzmaEnc_SetProps(p, &props); ++ LzmaEnc_SetProps((CLzmaEncHandle)(void *)p, &props); + } + + #ifndef LZMA_LOG_BSR +@@ -2376,7 +2362,7 @@ static void LzmaEnc_FreeLits(CLzmaEnc *p, ISzAllocPtr alloc) + + static void LzmaEnc_Destruct(CLzmaEnc *p, ISzAllocPtr alloc, ISzAllocPtr allocBig) + { +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + MatchFinderMt_Destruct(&p->matchFinderMt, allocBig); + #endif + +@@ -2387,21 +2373,22 @@ static void LzmaEnc_Destruct(CLzmaEnc *p, ISzAllocPtr alloc, ISzAllocPtr allocBi + + void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAllocPtr alloc, ISzAllocPtr allocBig) + { +- LzmaEnc_Destruct((CLzmaEnc *)p, alloc, allocBig); ++ // GET_CLzmaEnc_p ++ LzmaEnc_Destruct(p, alloc, allocBig); + ISzAlloc_Free(alloc, p); + } + + +-MY_NO_INLINE ++Z7_NO_INLINE + static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpackSize) + { + UInt32 nowPos32, startPos32; + if (p->needInit) + { +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + if (p->mtMode) + { +- RINOK(MatchFinderMt_InitMt(&p->matchFinderMt)); ++ RINOK(MatchFinderMt_InitMt(&p->matchFinderMt)) + } + #endif + p->matchFinder.Init(p->matchFinderObj); +@@ -2410,7 +2397,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa + + if (p->finished) + return p->result; +- RINOK(CheckErrors(p)); ++ RINOK(CheckErrors(p)) + + nowPos32 = (UInt32)p->nowPos64; + startPos32 = nowPos32; +@@ -2473,7 +2460,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa + const Byte *data; + unsigned state; + +- RC_BIT_0(&p->rc, probs); ++ RC_BIT_0(&p->rc, probs) + p->rc.range = range; + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset; + probs = LIT_PROBS(nowPos32, *(data - 1)); +@@ -2487,53 +2474,53 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa + } + else + { +- RC_BIT_1(&p->rc, probs); ++ RC_BIT_1(&p->rc, probs) + probs = &p->isRep[p->state]; + RC_BIT_PRE(&p->rc, probs) + + if (dist < LZMA_NUM_REPS) + { +- RC_BIT_1(&p->rc, probs); ++ RC_BIT_1(&p->rc, probs) + probs = &p->isRepG0[p->state]; + RC_BIT_PRE(&p->rc, probs) + if (dist == 0) + { +- RC_BIT_0(&p->rc, probs); ++ RC_BIT_0(&p->rc, probs) + probs = &p->isRep0Long[p->state][posState]; + RC_BIT_PRE(&p->rc, probs) + if (len != 1) + { +- RC_BIT_1_BASE(&p->rc, probs); ++ RC_BIT_1_BASE(&p->rc, probs) + } + else + { +- RC_BIT_0_BASE(&p->rc, probs); ++ RC_BIT_0_BASE(&p->rc, probs) + p->state = kShortRepNextStates[p->state]; + } + } + else + { +- RC_BIT_1(&p->rc, probs); ++ RC_BIT_1(&p->rc, probs) + probs = &p->isRepG1[p->state]; + RC_BIT_PRE(&p->rc, probs) + if (dist == 1) + { +- RC_BIT_0_BASE(&p->rc, probs); ++ RC_BIT_0_BASE(&p->rc, probs) + dist = p->reps[1]; + } + else + { +- RC_BIT_1(&p->rc, probs); ++ RC_BIT_1(&p->rc, probs) + probs = &p->isRepG2[p->state]; + RC_BIT_PRE(&p->rc, probs) + if (dist == 2) + { +- RC_BIT_0_BASE(&p->rc, probs); ++ RC_BIT_0_BASE(&p->rc, probs) + dist = p->reps[2]; + } + else + { +- RC_BIT_1_BASE(&p->rc, probs); ++ RC_BIT_1_BASE(&p->rc, probs) + dist = p->reps[3]; + p->reps[3] = p->reps[2]; + } +@@ -2557,7 +2544,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa + else + { + unsigned posSlot; +- RC_BIT_0(&p->rc, probs); ++ RC_BIT_0(&p->rc, probs) + p->rc.range = range; + p->state = kMatchNextStates[p->state]; + +@@ -2571,7 +2558,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa + p->reps[0] = dist + 1; + + p->matchPriceCount++; +- GetPosSlot(dist, posSlot); ++ GetPosSlot(dist, posSlot) + // RcTree_Encode_PosSlot(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], posSlot); + { + UInt32 sym = (UInt32)posSlot + (1 << kNumPosSlotBits); +@@ -2582,7 +2569,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa + CLzmaProb *prob = probs + (sym >> kNumPosSlotBits); + UInt32 bit = (sym >> (kNumPosSlotBits - 1)) & 1; + sym <<= 1; +- RC_BIT(&p->rc, prob, bit); ++ RC_BIT(&p->rc, prob, bit) + } + while (sym < (1 << kNumPosSlotBits * 2)); + p->rc.range = range; +@@ -2626,10 +2613,10 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa + { + unsigned m = 1; + unsigned bit; +- bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit; +- bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit; +- bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit; +- bit = dist & 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); ++ bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit) m = (m << 1) + bit; ++ bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit) m = (m << 1) + bit; ++ bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit) m = (m << 1) + bit; ++ bit = dist & 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit) + p->rc.range = range; + // p->alignPriceCount++; + } +@@ -2704,7 +2691,7 @@ static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr alloc, + if (!RangeEnc_Alloc(&p->rc, alloc)) + return SZ_ERROR_MEM; + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + p->mtMode = (p->multiThread && !p->fastMode && (MFB.btMode != 0)); + #endif + +@@ -2748,15 +2735,14 @@ static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr alloc, + (numFastBytes + LZMA_MATCH_LEN_MAX + 1) + */ + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + if (p->mtMode) + { + RINOK(MatchFinderMt_Create(&p->matchFinderMt, dictSize, beforeSize, + p->numFastBytes, LZMA_MATCH_LEN_MAX + 1 /* 18.04 */ +- , allocBig)); ++ , allocBig)) + p->matchFinderObj = &p->matchFinderMt; +- MFB.bigHash = (Byte)( +- (p->dictSize > kBigHashDicLimit && MFB.hashMask >= 0xFFFFFF) ? 1 : 0); ++ MFB.bigHash = (Byte)(MFB.hashMask >= 0xFFFFFF ? 1 : 0); + MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder); + } + else +@@ -2872,59 +2858,53 @@ static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr + + p->finished = False7z; + p->result = SZ_OK; +- RINOK(LzmaEnc_Alloc(p, keepWindowSize, alloc, allocBig)); ++ p->nowPos64 = 0; ++ p->needInit = 1; ++ 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, ISeqOutStream *outStream, ISeqInStream *inStream, ++static SRes LzmaEnc_Prepare(CLzmaEncHandle p, ++ ISeqOutStreamPtr outStream, ++ ISeqInStreamPtr inStream, + ISzAllocPtr alloc, ISzAllocPtr allocBig) + { +- CLzmaEnc *p = (CLzmaEnc *)pp; +- MFB.stream = inStream; +- p->needInit = 1; ++ // GET_CLzmaEnc_p ++ MatchFinder_SET_STREAM(&MFB, inStream) + p->rc.outStream = outStream; + return LzmaEnc_AllocAndInit(p, 0, alloc, allocBig); + } + +-SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp, +- ISeqInStream *inStream, UInt32 keepWindowSize, ++SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle p, ++ ISeqInStreamPtr inStream, UInt32 keepWindowSize, + ISzAllocPtr alloc, ISzAllocPtr allocBig) + { +- CLzmaEnc *p = (CLzmaEnc *)pp; +- MFB.stream = inStream; +- p->needInit = 1; ++ // GET_CLzmaEnc_p ++ MatchFinder_SET_STREAM(&MFB, inStream) + return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig); + } + +-static void LzmaEnc_SetInputBuf(CLzmaEnc *p, const Byte *src, SizeT srcLen) +-{ +- MFB.directInput = 1; +- MFB.bufferBase = (Byte *)src; +- MFB.directInputRem = srcLen; +-} +- +-SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen, +- UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig) ++SRes LzmaEnc_MemPrepare(CLzmaEncHandle p, ++ const Byte *src, SizeT srcLen, ++ UInt32 keepWindowSize, ++ ISzAllocPtr alloc, ISzAllocPtr allocBig) + { +- CLzmaEnc *p = (CLzmaEnc *)pp; +- LzmaEnc_SetInputBuf(p, src, srcLen); +- p->needInit = 1; +- +- LzmaEnc_SetDataSize(pp, srcLen); ++ // GET_CLzmaEnc_p ++ MatchFinder_SET_DIRECT_INPUT_BUF(&MFB, src, srcLen) ++ LzmaEnc_SetDataSize(p, srcLen); + return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig); + } + +-void LzmaEnc_Finish(CLzmaEncHandle pp) ++void LzmaEnc_Finish(CLzmaEncHandle p) + { +- #ifndef _7ZIP_ST +- CLzmaEnc *p = (CLzmaEnc *)pp; ++ #ifndef Z7_ST ++ // GET_CLzmaEnc_p + if (p->mtMode) + MatchFinderMt_ReleaseStream(&p->matchFinderMt); + #else +- UNUSED_VAR(pp); ++ UNUSED_VAR(p) + #endif + } + +@@ -2933,13 +2913,13 @@ typedef struct + { + ISeqOutStream vt; + Byte *data; +- SizeT rem; ++ size_t rem; + BoolInt overflow; + } CLzmaEnc_SeqOutStreamBuf; + +-static size_t SeqOutStreamBuf_Write(const ISeqOutStream *pp, const void *data, size_t size) ++static size_t SeqOutStreamBuf_Write(ISeqOutStreamPtr pp, const void *data, size_t size) + { +- CLzmaEnc_SeqOutStreamBuf *p = CONTAINER_FROM_VTBL(pp, CLzmaEnc_SeqOutStreamBuf, vt); ++ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CLzmaEnc_SeqOutStreamBuf) + if (p->rem < size) + { + size = p->rem; +@@ -2956,24 +2936,25 @@ static size_t SeqOutStreamBuf_Write(const ISeqOutStream *pp, const void *data, s + + + /* +-UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp) ++UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle p) + { +- const CLzmaEnc *p = (CLzmaEnc *)pp; ++ GET_const_CLzmaEnc_p + return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj); + } + */ + +-const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp) ++const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle p) + { +- const CLzmaEnc *p = (CLzmaEnc *)pp; ++ // GET_const_CLzmaEnc_p + return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset; + } + + +-SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit, ++// (desiredPackSize == 0) is not allowed ++SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle p, BoolInt reInit, + Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize) + { +- CLzmaEnc *p = (CLzmaEnc *)pp; ++ // GET_CLzmaEnc_p + UInt64 nowPos64; + SRes res; + CLzmaEnc_SeqOutStreamBuf outStream; +@@ -2990,14 +2971,10 @@ SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit, + if (reInit) + LzmaEnc_Init(p); + LzmaEnc_InitPrices(p); +- +- nowPos64 = p->nowPos64; + RangeEnc_Init(&p->rc); + p->rc.outStream = &outStream.vt; +- +- if (desiredPackSize == 0) +- return SZ_ERROR_OUTPUT_EOF; +- ++ nowPos64 = p->nowPos64; ++ + res = LzmaEnc_CodeOneBlock(p, desiredPackSize, *unpackSize); + + *unpackSize = (UInt32)(p->nowPos64 - nowPos64); +@@ -3009,12 +2986,12 @@ SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit, + } + + +-MY_NO_INLINE +-static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress) ++Z7_NO_INLINE ++static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgressPtr progress) + { + SRes res = SZ_OK; + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + Byte allocaDummy[0x300]; + allocaDummy[0] = 0; + allocaDummy[1] = allocaDummy[0]; +@@ -3036,7 +3013,7 @@ static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress) + } + } + +- LzmaEnc_Finish(p); ++ LzmaEnc_Finish((CLzmaEncHandle)(void *)p); + + /* + if (res == SZ_OK && !Inline_MatchFinder_IsFinishedOK(&MFB)) +@@ -3048,21 +3025,22 @@ static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress) + } + + +-SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress, ++SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, ICompressProgressPtr progress, + ISzAllocPtr alloc, ISzAllocPtr allocBig) + { +- RINOK(LzmaEnc_Prepare(pp, outStream, inStream, alloc, allocBig)); +- return LzmaEnc_Encode2((CLzmaEnc *)pp, progress); ++ // GET_CLzmaEnc_p ++ RINOK(LzmaEnc_Prepare(p, outStream, inStream, alloc, allocBig)) ++ return LzmaEnc_Encode2(p, progress); + } + + +-SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size) ++SRes LzmaEnc_WriteProperties(CLzmaEncHandle p, Byte *props, SizeT *size) + { + if (*size < LZMA_PROPS_SIZE) + return SZ_ERROR_PARAM; + *size = LZMA_PROPS_SIZE; + { +- const CLzmaEnc *p = (const CLzmaEnc *)pp; ++ // GET_CLzmaEnc_p + const UInt32 dictSize = p->dictSize; + UInt32 v; + props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc); +@@ -3086,23 +3064,24 @@ SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size) + while (v < dictSize); + } + +- SetUi32(props + 1, v); ++ SetUi32(props + 1, v) + return SZ_OK; + } + } + + +-unsigned LzmaEnc_IsWriteEndMark(CLzmaEncHandle pp) ++unsigned LzmaEnc_IsWriteEndMark(CLzmaEncHandle p) + { +- return (unsigned)((CLzmaEnc *)pp)->writeEndMark; ++ // GET_CLzmaEnc_p ++ return (unsigned)p->writeEndMark; + } + + +-SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, +- int writeEndMark, ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig) ++SRes LzmaEnc_MemEncode(CLzmaEncHandle p, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, ++ int writeEndMark, ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig) + { + SRes res; +- CLzmaEnc *p = (CLzmaEnc *)pp; ++ // GET_CLzmaEnc_p + + CLzmaEnc_SeqOutStreamBuf outStream; + +@@ -3114,7 +3093,7 @@ SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte + p->writeEndMark = writeEndMark; + p->rc.outStream = &outStream.vt; + +- res = LzmaEnc_MemPrepare(pp, src, srcLen, 0, alloc, allocBig); ++ res = LzmaEnc_MemPrepare(p, src, srcLen, 0, alloc, allocBig); + + if (res == SZ_OK) + { +@@ -3123,7 +3102,7 @@ SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte + res = SZ_ERROR_FAIL; + } + +- *destLen -= outStream.rem; ++ *destLen -= (SizeT)outStream.rem; + if (outStream.overflow) + return SZ_ERROR_OUTPUT_EOF; + return res; +@@ -3132,9 +3111,9 @@ SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte + + SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, + const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark, +- ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig) ++ ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig) + { +- CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc); ++ CLzmaEncHandle p = LzmaEnc_Create(alloc); + SRes res; + if (!p) + return SZ_ERROR_MEM; +@@ -3154,10 +3133,10 @@ SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, + + + /* +-#ifndef _7ZIP_ST +-void LzmaEnc_GetLzThreads(CLzmaEncHandle pp, HANDLE lz_threads[2]) ++#ifndef Z7_ST ++void LzmaEnc_GetLzThreads(CLzmaEncHandle p, HANDLE lz_threads[2]) + { +- const CLzmaEnc *p = (CLzmaEnc *)pp; ++ GET_const_CLzmaEnc_p + lz_threads[0] = p->matchFinderMt.hashSync.thread; + lz_threads[1] = p->matchFinderMt.btSync.thread; + } +diff --git a/src/lzma/LzmaEnc.h b/src/lzma/LzmaEnc.h +index bc2ed5042..9f8039a10 100644 +--- a/src/lzma/LzmaEnc.h ++++ b/src/lzma/LzmaEnc.h +@@ -1,8 +1,8 @@ + /* LzmaEnc.h -- LZMA Encoder +-2019-10-30 : Igor Pavlov : Public domain */ ++2023-04-13 : Igor Pavlov : Public domain */ + +-#ifndef __LZMA_ENC_H +-#define __LZMA_ENC_H ++#ifndef ZIP7_INC_LZMA_ENC_H ++#define ZIP7_INC_LZMA_ENC_H + + #include "7zTypes.h" + +@@ -10,7 +10,7 @@ EXTERN_C_BEGIN + + #define LZMA_PROPS_SIZE 5 + +-typedef struct _CLzmaEncProps ++typedef struct + { + int level; /* 0 <= level <= 9 */ + UInt32 dictSize; /* (1 << 12) <= dictSize <= (1 << 27) for 32-bit version +@@ -23,10 +23,13 @@ typedef struct _CLzmaEncProps + 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 */ ++ unsigned numHashOutBits; /* default = ? */ + 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 */ + ++ // int _pad; ++ + UInt64 reduceSize; /* estimated size of data that will be compressed. default = (UInt64)(Int64)-1. + Encoder uses this value to reduce dictionary size */ + +@@ -51,7 +54,9 @@ SRes: + SZ_ERROR_THREAD - error in multithreading functions (only for Mt version) + */ + +-typedef void * CLzmaEncHandle; ++typedef struct CLzmaEnc CLzmaEnc; ++typedef CLzmaEnc * CLzmaEncHandle; ++// Z7_DECLARE_HANDLE(CLzmaEncHandle) + + CLzmaEncHandle LzmaEnc_Create(ISzAllocPtr alloc); + void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAllocPtr alloc, ISzAllocPtr allocBig); +@@ -61,17 +66,17 @@ void LzmaEnc_SetDataSize(CLzmaEncHandle p, UInt64 expectedDataSiize); + SRes LzmaEnc_WriteProperties(CLzmaEncHandle p, Byte *properties, SizeT *size); + unsigned LzmaEnc_IsWriteEndMark(CLzmaEncHandle p); + +-SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStream *outStream, ISeqInStream *inStream, +- ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); ++SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, ++ ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); + SRes LzmaEnc_MemEncode(CLzmaEncHandle p, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, +- int writeEndMark, ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); ++ int writeEndMark, ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); + + + /* ---------- One Call Interface ---------- */ + + SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, + const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark, +- ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); ++ ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); + + EXTERN_C_END + +diff --git a/src/lzma/LzmaLib.c b/src/lzma/LzmaLib.c +index 706e9e58c..785e88487 100644 +--- a/src/lzma/LzmaLib.c ++++ b/src/lzma/LzmaLib.c +@@ -1,12 +1,14 @@ + /* LzmaLib.c -- LZMA library wrapper +-2015-06-13 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ ++ ++#include "Precomp.h" + + #include "Alloc.h" + #include "LzmaDec.h" + #include "LzmaEnc.h" + #include "LzmaLib.h" + +-MY_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, ++Z7_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, + unsigned char *outProps, size_t *outPropsSize, + int level, /* 0 <= level <= 9, default = 5 */ + unsigned dictSize, /* use (1 << N) or (3 << N). 4 KB < dictSize <= 128 MB */ +@@ -32,7 +34,7 @@ MY_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char + } + + +-MY_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t *srcLen, ++Z7_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t *srcLen, + const unsigned char *props, size_t propsSize) + { + ELzmaStatus status; +diff --git a/src/lzma/LzmaLib.h b/src/lzma/LzmaLib.h +index c343a8596..d7c0724de 100644 +--- a/src/lzma/LzmaLib.h ++++ b/src/lzma/LzmaLib.h +@@ -1,14 +1,14 @@ + /* LzmaLib.h -- LZMA library interface +-2021-04-03 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + +-#ifndef __LZMA_LIB_H +-#define __LZMA_LIB_H ++#ifndef ZIP7_INC_LZMA_LIB_H ++#define ZIP7_INC_LZMA_LIB_H + + #include "7zTypes.h" + + EXTERN_C_BEGIN + +-#define MY_STDAPI int MY_STD_CALL ++#define Z7_STDAPI int Z7_STDCALL + + #define LZMA_PROPS_SIZE 5 + +@@ -100,7 +100,7 @@ Returns: + SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version) + */ + +-MY_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, ++Z7_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, + unsigned char *outProps, size_t *outPropsSize, /* *outPropsSize must be = 5 */ + int level, /* 0 <= level <= 9, default = 5 */ + unsigned dictSize, /* default = (1 << 24) */ +@@ -130,7 +130,7 @@ Returns: + SZ_ERROR_INPUT_EOF - it needs more bytes in input buffer (src) + */ + +-MY_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, SizeT *srcLen, ++Z7_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, SizeT *srcLen, + const unsigned char *props, size_t propsSize); + + EXTERN_C_END +diff --git a/src/lzma/MtCoder.c b/src/lzma/MtCoder.c +index b05fdcace..3fd718e44 100644 +--- a/src/lzma/MtCoder.c ++++ b/src/lzma/MtCoder.c +@@ -1,28 +1,28 @@ + /* MtCoder.c -- Multi-thread Coder +-2021-12-21 : Igor Pavlov : Public domain */ ++2023-04-13 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + + #include "MtCoder.h" + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + +-static SRes MtProgressThunk_Progress(const ICompressProgress *pp, UInt64 inSize, UInt64 outSize) ++static SRes MtProgressThunk_Progress(ICompressProgressPtr pp, UInt64 inSize, UInt64 outSize) + { +- CMtProgressThunk *thunk = CONTAINER_FROM_VTBL(pp, CMtProgressThunk, vt); ++ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CMtProgressThunk) + UInt64 inSize2 = 0; + UInt64 outSize2 = 0; + if (inSize != (UInt64)(Int64)-1) + { +- inSize2 = inSize - thunk->inSize; +- thunk->inSize = inSize; ++ inSize2 = inSize - p->inSize; ++ p->inSize = inSize; + } + if (outSize != (UInt64)(Int64)-1) + { +- outSize2 = outSize - thunk->outSize; +- thunk->outSize = outSize; ++ outSize2 = outSize - p->outSize; ++ p->outSize = outSize; + } +- return MtProgress_ProgressAdd(thunk->mtProgress, inSize2, outSize2); ++ return MtProgress_ProgressAdd(p->mtProgress, inSize2, outSize2); + } + + +@@ -36,20 +36,12 @@ void MtProgressThunk_CreateVTable(CMtProgressThunk *p) + #define RINOK_THREAD(x) { if ((x) != 0) return SZ_ERROR_THREAD; } + + +-static WRes ArEvent_OptCreate_And_Reset(CEvent *p) +-{ +- if (Event_IsCreated(p)) +- return Event_Reset(p); +- return AutoResetEvent_CreateNotSignaled(p); +-} +- +- + static THREAD_FUNC_DECL ThreadFunc(void *pp); + + + static SRes MtCoderThread_CreateAndStart(CMtCoderThread *t) + { +- WRes wres = ArEvent_OptCreate_And_Reset(&t->startEvent); ++ WRes wres = AutoResetEvent_OptCreate_And_Reset(&t->startEvent); + if (wres == 0) + { + t->stop = False7z; +@@ -84,24 +76,6 @@ static void MtCoderThread_Destruct(CMtCoderThread *t) + + + +-static SRes FullRead(ISeqInStream *stream, Byte *data, size_t *processedSize) +-{ +- size_t size = *processedSize; +- *processedSize = 0; +- while (size != 0) +- { +- size_t cur = size; +- SRes res = ISeqInStream_Read(stream, data, &cur); +- *processedSize += cur; +- data += cur; +- size -= cur; +- RINOK(res); +- if (cur == 0) +- return SZ_OK; +- } +- return SZ_OK; +-} +- + + /* + ThreadFunc2() returns: +@@ -152,7 +126,7 @@ static SRes ThreadFunc2(CMtCoderThread *t) + } + if (res == SZ_OK) + { +- res = FullRead(mtc->inStream, t->inBuf, &size); ++ res = SeqInStream_ReadMax(mtc->inStream, t->inBuf, &size); + readProcessed = mtc->readProcessed + size; + mtc->readProcessed = readProcessed; + } +@@ -253,7 +227,7 @@ static SRes ThreadFunc2(CMtCoderThread *t) + block->finished = finished; + } + +- #ifdef MTCODER__USE_WRITE_THREAD ++ #ifdef MTCODER_USE_WRITE_THREAD + RINOK_THREAD(Event_Set(&mtc->writeEvents[bi])) + #else + { +@@ -352,7 +326,7 @@ static THREAD_FUNC_DECL ThreadFunc(void *pp) + MtProgress_SetError(&mtc->mtProgress, res); + } + +- #ifndef MTCODER__USE_WRITE_THREAD ++ #ifndef MTCODER_USE_WRITE_THREAD + { + unsigned numFinished = (unsigned)InterlockedIncrement(&mtc->numFinishedThreads); + if (numFinished == mtc->numStartedThreads) +@@ -389,7 +363,7 @@ void MtCoder_Construct(CMtCoder *p) + Event_Construct(&p->readEvent); + Semaphore_Construct(&p->blocksSemaphore); + +- for (i = 0; i < MTCODER__THREADS_MAX; i++) ++ for (i = 0; i < MTCODER_THREADS_MAX; i++) + { + CMtCoderThread *t = &p->threads[i]; + t->mtCoder = p; +@@ -397,11 +371,11 @@ void MtCoder_Construct(CMtCoder *p) + t->inBuf = NULL; + t->stop = False7z; + Event_Construct(&t->startEvent); +- Thread_Construct(&t->thread); ++ Thread_CONSTRUCT(&t->thread) + } + +- #ifdef MTCODER__USE_WRITE_THREAD +- for (i = 0; i < MTCODER__BLOCKS_MAX; i++) ++ #ifdef MTCODER_USE_WRITE_THREAD ++ for (i = 0; i < MTCODER_BLOCKS_MAX; i++) + Event_Construct(&p->writeEvents[i]); + #else + Event_Construct(&p->finishedEvent); +@@ -424,14 +398,14 @@ static void MtCoder_Free(CMtCoder *p) + Event_Set(&p->readEvent); + */ + +- for (i = 0; i < MTCODER__THREADS_MAX; i++) ++ for (i = 0; i < MTCODER_THREADS_MAX; i++) + MtCoderThread_Destruct(&p->threads[i]); + + Event_Close(&p->readEvent); + Semaphore_Close(&p->blocksSemaphore); + +- #ifdef MTCODER__USE_WRITE_THREAD +- for (i = 0; i < MTCODER__BLOCKS_MAX; i++) ++ #ifdef MTCODER_USE_WRITE_THREAD ++ for (i = 0; i < MTCODER_BLOCKS_MAX; i++) + Event_Close(&p->writeEvents[i]); + #else + Event_Close(&p->finishedEvent); +@@ -455,20 +429,20 @@ SRes MtCoder_Code(CMtCoder *p) + unsigned i; + SRes res = SZ_OK; + +- if (numThreads > MTCODER__THREADS_MAX) +- numThreads = MTCODER__THREADS_MAX; +- numBlocksMax = MTCODER__GET_NUM_BLOCKS_FROM_THREADS(numThreads); ++ if (numThreads > MTCODER_THREADS_MAX) ++ numThreads = MTCODER_THREADS_MAX; ++ numBlocksMax = MTCODER_GET_NUM_BLOCKS_FROM_THREADS(numThreads); + + if (p->blockSize < ((UInt32)1 << 26)) numBlocksMax++; + if (p->blockSize < ((UInt32)1 << 24)) numBlocksMax++; + if (p->blockSize < ((UInt32)1 << 22)) numBlocksMax++; + +- if (numBlocksMax > MTCODER__BLOCKS_MAX) +- numBlocksMax = MTCODER__BLOCKS_MAX; ++ if (numBlocksMax > MTCODER_BLOCKS_MAX) ++ numBlocksMax = MTCODER_BLOCKS_MAX; + + if (p->blockSize != p->allocatedBufsSize) + { +- for (i = 0; i < MTCODER__THREADS_MAX; i++) ++ for (i = 0; i < MTCODER_THREADS_MAX; i++) + { + CMtCoderThread *t = &p->threads[i]; + if (t->inBuf) +@@ -484,23 +458,23 @@ SRes MtCoder_Code(CMtCoder *p) + + MtProgress_Init(&p->mtProgress, p->progress); + +- #ifdef MTCODER__USE_WRITE_THREAD ++ #ifdef MTCODER_USE_WRITE_THREAD + for (i = 0; i < numBlocksMax; i++) + { +- RINOK_THREAD(ArEvent_OptCreate_And_Reset(&p->writeEvents[i])); ++ RINOK_THREAD(AutoResetEvent_OptCreate_And_Reset(&p->writeEvents[i])) + } + #else +- RINOK_THREAD(ArEvent_OptCreate_And_Reset(&p->finishedEvent)); ++ RINOK_THREAD(AutoResetEvent_OptCreate_And_Reset(&p->finishedEvent)) + #endif + + { +- RINOK_THREAD(ArEvent_OptCreate_And_Reset(&p->readEvent)); +- RINOK_THREAD(Semaphore_OptCreateInit(&p->blocksSemaphore, numBlocksMax, numBlocksMax)); ++ RINOK_THREAD(AutoResetEvent_OptCreate_And_Reset(&p->readEvent)) ++ RINOK_THREAD(Semaphore_OptCreateInit(&p->blocksSemaphore, numBlocksMax, numBlocksMax)) + } + +- for (i = 0; i < MTCODER__BLOCKS_MAX - 1; i++) ++ for (i = 0; i < MTCODER_BLOCKS_MAX - 1; i++) + p->freeBlockList[i] = i + 1; +- p->freeBlockList[MTCODER__BLOCKS_MAX - 1] = (unsigned)(int)-1; ++ p->freeBlockList[MTCODER_BLOCKS_MAX - 1] = (unsigned)(int)-1; + p->freeBlockHead = 0; + + p->readProcessed = 0; +@@ -508,10 +482,10 @@ SRes MtCoder_Code(CMtCoder *p) + p->numBlocksMax = numBlocksMax; + p->stopReading = False7z; + +- #ifndef MTCODER__USE_WRITE_THREAD ++ #ifndef MTCODER_USE_WRITE_THREAD + p->writeIndex = 0; + p->writeRes = SZ_OK; +- for (i = 0; i < MTCODER__BLOCKS_MAX; i++) ++ for (i = 0; i < MTCODER_BLOCKS_MAX; i++) + p->ReadyBlocks[i] = False7z; + p->numFinishedThreads = 0; + #endif +@@ -522,12 +496,12 @@ SRes MtCoder_Code(CMtCoder *p) + // for (i = 0; i < numThreads; i++) + { + CMtCoderThread *nextThread = &p->threads[p->numStartedThreads++]; +- RINOK(MtCoderThread_CreateAndStart(nextThread)); ++ RINOK(MtCoderThread_CreateAndStart(nextThread)) + } + + RINOK_THREAD(Event_Set(&p->readEvent)) + +- #ifdef MTCODER__USE_WRITE_THREAD ++ #ifdef MTCODER_USE_WRITE_THREAD + { + unsigned bi = 0; + +@@ -582,7 +556,7 @@ SRes MtCoder_Code(CMtCoder *p) + if (res == SZ_OK) + res = p->mtProgress.res; + +- #ifndef MTCODER__USE_WRITE_THREAD ++ #ifndef MTCODER_USE_WRITE_THREAD + if (res == SZ_OK) + res = p->writeRes; + #endif +@@ -593,3 +567,5 @@ SRes MtCoder_Code(CMtCoder *p) + } + + #endif ++ ++#undef RINOK_THREAD +diff --git a/src/lzma/MtCoder.h b/src/lzma/MtCoder.h +index 5a5f4d11b..1231d3c2a 100644 +--- a/src/lzma/MtCoder.h ++++ b/src/lzma/MtCoder.h +@@ -1,30 +1,30 @@ + /* MtCoder.h -- Multi-thread Coder +-2018-07-04 : Igor Pavlov : Public domain */ ++2023-04-13 : Igor Pavlov : Public domain */ + +-#ifndef __MT_CODER_H +-#define __MT_CODER_H ++#ifndef ZIP7_INC_MT_CODER_H ++#define ZIP7_INC_MT_CODER_H + + #include "MtDec.h" + + EXTERN_C_BEGIN + + /* +- if ( defined MTCODER__USE_WRITE_THREAD) : main thread writes all data blocks to output stream +- if (not defined MTCODER__USE_WRITE_THREAD) : any coder thread can write data blocks to output stream ++ if ( defined MTCODER_USE_WRITE_THREAD) : main thread writes all data blocks to output stream ++ if (not defined MTCODER_USE_WRITE_THREAD) : any coder thread can write data blocks to output stream + */ +-/* #define MTCODER__USE_WRITE_THREAD */ ++/* #define MTCODER_USE_WRITE_THREAD */ + +-#ifndef _7ZIP_ST +- #define MTCODER__GET_NUM_BLOCKS_FROM_THREADS(numThreads) ((numThreads) + (numThreads) / 8 + 1) +- #define MTCODER__THREADS_MAX 64 +- #define MTCODER__BLOCKS_MAX (MTCODER__GET_NUM_BLOCKS_FROM_THREADS(MTCODER__THREADS_MAX) + 3) ++#ifndef Z7_ST ++ #define MTCODER_GET_NUM_BLOCKS_FROM_THREADS(numThreads) ((numThreads) + (numThreads) / 8 + 1) ++ #define MTCODER_THREADS_MAX 64 ++ #define MTCODER_BLOCKS_MAX (MTCODER_GET_NUM_BLOCKS_FROM_THREADS(MTCODER_THREADS_MAX) + 3) + #else +- #define MTCODER__THREADS_MAX 1 +- #define MTCODER__BLOCKS_MAX 1 ++ #define MTCODER_THREADS_MAX 1 ++ #define MTCODER_BLOCKS_MAX 1 + #endif + + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + + + typedef struct +@@ -37,15 +37,15 @@ typedef struct + + void MtProgressThunk_CreateVTable(CMtProgressThunk *p); + +-#define MtProgressThunk_Init(p) { (p)->inSize = 0; (p)->outSize = 0; } ++#define MtProgressThunk_INIT(p) { (p)->inSize = 0; (p)->outSize = 0; } + + +-struct _CMtCoder; ++struct CMtCoder_; + + + typedef struct + { +- struct _CMtCoder *mtCoder; ++ struct CMtCoder_ *mtCoder; + unsigned index; + int stop; + Byte *inBuf; +@@ -71,7 +71,7 @@ typedef struct + } CMtCoderBlock; + + +-typedef struct _CMtCoder ++typedef struct CMtCoder_ + { + /* input variables */ + +@@ -79,11 +79,11 @@ typedef struct _CMtCoder + unsigned numThreadsMax; + UInt64 expectedDataSize; + +- ISeqInStream *inStream; ++ ISeqInStreamPtr inStream; + const Byte *inData; + size_t inDataSize; + +- ICompressProgress *progress; ++ ICompressProgressPtr progress; + ISzAllocPtr allocBig; + + IMtCoderCallback2 *mtCallback; +@@ -100,13 +100,13 @@ typedef struct _CMtCoder + BoolInt stopReading; + SRes readRes; + +- #ifdef MTCODER__USE_WRITE_THREAD +- CAutoResetEvent writeEvents[MTCODER__BLOCKS_MAX]; ++ #ifdef MTCODER_USE_WRITE_THREAD ++ CAutoResetEvent writeEvents[MTCODER_BLOCKS_MAX]; + #else + CAutoResetEvent finishedEvent; + SRes writeRes; + unsigned writeIndex; +- Byte ReadyBlocks[MTCODER__BLOCKS_MAX]; ++ Byte ReadyBlocks[MTCODER_BLOCKS_MAX]; + LONG numFinishedThreads; + #endif + +@@ -120,11 +120,11 @@ typedef struct _CMtCoder + CCriticalSection cs; + + unsigned freeBlockHead; +- unsigned freeBlockList[MTCODER__BLOCKS_MAX]; ++ unsigned freeBlockList[MTCODER_BLOCKS_MAX]; + + CMtProgress mtProgress; +- CMtCoderBlock blocks[MTCODER__BLOCKS_MAX]; +- CMtCoderThread threads[MTCODER__THREADS_MAX]; ++ CMtCoderBlock blocks[MTCODER_BLOCKS_MAX]; ++ CMtCoderThread threads[MTCODER_THREADS_MAX]; + } CMtCoder; + + +diff --git a/src/lzma/MtDec.c b/src/lzma/MtDec.c +index b75e892fe..80c186950 100644 +--- a/src/lzma/MtDec.c ++++ b/src/lzma/MtDec.c +@@ -1,5 +1,5 @@ + /* MtDec.c -- Multi-thread Decoder +-2021-12-21 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -14,7 +14,7 @@ + + #include "MtDec.h" + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + + #ifdef SHOW_DEBUG_INFO + #define PRF(x) x +@@ -24,7 +24,7 @@ + + #define PRF_STR_INT(s, d) PRF(printf("\n" s " %d\n", (unsigned)d)) + +-void MtProgress_Init(CMtProgress *p, ICompressProgress *progress) ++void MtProgress_Init(CMtProgress *p, ICompressProgressPtr progress) + { + p->progress = progress; + p->res = SZ_OK; +@@ -81,36 +81,28 @@ void MtProgress_SetError(CMtProgress *p, SRes res) + #define RINOK_THREAD(x) RINOK_WRes(x) + + +-static WRes ArEvent_OptCreate_And_Reset(CEvent *p) ++struct CMtDecBufLink_ + { +- if (Event_IsCreated(p)) +- return Event_Reset(p); +- return AutoResetEvent_CreateNotSignaled(p); +-} +- +- +-struct __CMtDecBufLink +-{ +- struct __CMtDecBufLink *next; ++ struct CMtDecBufLink_ *next; + void *pad[3]; + }; + +-typedef struct __CMtDecBufLink CMtDecBufLink; ++typedef struct CMtDecBufLink_ CMtDecBufLink; + + #define MTDEC__LINK_DATA_OFFSET sizeof(CMtDecBufLink) + #define MTDEC__DATA_PTR_FROM_LINK(link) ((Byte *)(link) + MTDEC__LINK_DATA_OFFSET) + + + +-static THREAD_FUNC_DECL ThreadFunc(void *pp); ++static THREAD_FUNC_DECL MtDec_ThreadFunc(void *pp); + + + static WRes MtDecThread_CreateEvents(CMtDecThread *t) + { +- WRes wres = ArEvent_OptCreate_And_Reset(&t->canWrite); ++ WRes wres = AutoResetEvent_OptCreate_And_Reset(&t->canWrite); + if (wres == 0) + { +- wres = ArEvent_OptCreate_And_Reset(&t->canRead); ++ wres = AutoResetEvent_OptCreate_And_Reset(&t->canRead); + if (wres == 0) + return SZ_OK; + } +@@ -126,7 +118,7 @@ static SRes MtDecThread_CreateAndStart(CMtDecThread *t) + { + if (Thread_WasCreated(&t->thread)) + return SZ_OK; +- wres = Thread_Create(&t->thread, ThreadFunc, t); ++ wres = Thread_Create(&t->thread, MtDec_ThreadFunc, t); + if (wres == 0) + return SZ_OK; + } +@@ -167,7 +159,7 @@ static void MtDecThread_CloseThread(CMtDecThread *t) + static void MtDec_CloseThreads(CMtDec *p) + { + unsigned i; +- for (i = 0; i < MTDEC__THREADS_MAX; i++) ++ for (i = 0; i < MTDEC_THREADS_MAX; i++) + MtDecThread_CloseThread(&p->threads[i]); + } + +@@ -179,25 +171,6 @@ static void MtDecThread_Destruct(CMtDecThread *t) + + + +-static SRes FullRead(ISeqInStream *stream, Byte *data, size_t *processedSize) +-{ +- size_t size = *processedSize; +- *processedSize = 0; +- while (size != 0) +- { +- size_t cur = size; +- SRes res = ISeqInStream_Read(stream, data, &cur); +- *processedSize += cur; +- data += cur; +- size -= cur; +- RINOK(res); +- if (cur == 0) +- return SZ_OK; +- } +- return SZ_OK; +-} +- +- + static SRes MtDec_GetError_Spec(CMtDec *p, UInt64 interruptIndex, BoolInt *wasInterrupted) + { + SRes res; +@@ -253,7 +226,7 @@ Byte *MtDec_GetCrossBuff(CMtDec *p) + + + /* +- ThreadFunc2() returns: ++ MtDec_ThreadFunc2() returns: + 0 - in all normal cases (even for stream error or memory allocation error) + (!= 0) - WRes error return by system threading function + */ +@@ -261,11 +234,11 @@ Byte *MtDec_GetCrossBuff(CMtDec *p) + // #define MTDEC_ProgessStep (1 << 22) + #define MTDEC_ProgessStep (1 << 0) + +-static WRes ThreadFunc2(CMtDecThread *t) ++static WRes MtDec_ThreadFunc2(CMtDecThread *t) + { + CMtDec *p = t->mtDec; + +- PRF_STR_INT("ThreadFunc2", t->index); ++ PRF_STR_INT("MtDec_ThreadFunc2", t->index) + + // SetThreadAffinityMask(GetCurrentThread(), 1 << t->index); + +@@ -295,13 +268,13 @@ static WRes ThreadFunc2(CMtDecThread *t) + // CMtDecCallbackInfo parse; + CMtDecThread *nextThread; + +- PRF_STR_INT("=============== Event_Wait(&t->canRead)", t->index); ++ PRF_STR_INT("=============== Event_Wait(&t->canRead)", t->index) + +- RINOK_THREAD(Event_Wait(&t->canRead)); ++ RINOK_THREAD(Event_Wait(&t->canRead)) + if (p->exitThread) + return 0; + +- PRF_STR_INT("after Event_Wait(&t->canRead)", t->index); ++ PRF_STR_INT("after Event_Wait(&t->canRead)", t->index) + + // if (t->index == 3) return 19; // for test + +@@ -373,7 +346,7 @@ static WRes ThreadFunc2(CMtDecThread *t) + { + size = p->inBufSize; + +- res = FullRead(p->inStream, data, &size); ++ res = SeqInStream_ReadMax(p->inStream, data, &size); + + // size = 10; // test + +@@ -615,7 +588,7 @@ static WRes ThreadFunc2(CMtDecThread *t) + // if ( !finish ) we must call Event_Set(&nextThread->canWrite) in any case + // if ( finish ) we switch to single-thread mode and there are 2 ways at the end of current iteration (current block): + // - if (needContinue) after Write(&needContinue), we restore decoding with new iteration +- // - otherwise we stop decoding and exit from ThreadFunc2() ++ // - otherwise we stop decoding and exit from MtDec_ThreadFunc2() + + // Don't change (finish) variable in the further code + +@@ -688,7 +661,7 @@ static WRes ThreadFunc2(CMtDecThread *t) + + // ---------- WRITE ---------- + +- RINOK_THREAD(Event_Wait(&t->canWrite)); ++ RINOK_THREAD(Event_Wait(&t->canWrite)) + + { + BoolInt isErrorMode = False7z; +@@ -801,14 +774,14 @@ static WRes ThreadFunc2(CMtDecThread *t) + + if (!finish) + { +- RINOK_THREAD(Event_Set(&nextThread->canWrite)); ++ RINOK_THREAD(Event_Set(&nextThread->canWrite)) + } + else + { + if (needContinue) + { + // we restore decoding with new iteration +- RINOK_THREAD(Event_Set(&p->threads[0].canWrite)); ++ RINOK_THREAD(Event_Set(&p->threads[0].canWrite)) + } + else + { +@@ -817,7 +790,7 @@ static WRes ThreadFunc2(CMtDecThread *t) + return SZ_OK; + p->exitThread = True7z; + } +- RINOK_THREAD(Event_Set(&p->threads[0].canRead)); ++ RINOK_THREAD(Event_Set(&p->threads[0].canRead)) + } + } + } +@@ -836,7 +809,7 @@ static WRes ThreadFunc2(CMtDecThread *t) + #endif + + +-static THREAD_FUNC_DECL ThreadFunc1(void *pp) ++static THREAD_FUNC_DECL MtDec_ThreadFunc1(void *pp) + { + WRes res; + +@@ -845,7 +818,7 @@ static THREAD_FUNC_DECL ThreadFunc1(void *pp) + + // fprintf(stdout, "\n%d = %p\n", t->index, &t); + +- res = ThreadFunc2(t); ++ res = MtDec_ThreadFunc2(t); + p = t->mtDec; + if (res == 0) + return (THREAD_FUNC_RET_TYPE)(UINT_PTR)p->exitThreadWRes; +@@ -862,14 +835,14 @@ static THREAD_FUNC_DECL ThreadFunc1(void *pp) + return (THREAD_FUNC_RET_TYPE)(UINT_PTR)res; + } + +-static MY_NO_INLINE THREAD_FUNC_DECL ThreadFunc(void *pp) ++static Z7_NO_INLINE THREAD_FUNC_DECL MtDec_ThreadFunc(void *pp) + { + #ifdef USE_ALLOCA + CMtDecThread *t = (CMtDecThread *)pp; + // fprintf(stderr, "\n%d = %p - before", t->index, &t); + t->allocaPtr = alloca(t->index * 128); + #endif +- return ThreadFunc1(pp); ++ return MtDec_ThreadFunc1(pp); + } + + +@@ -883,7 +856,7 @@ int MtDec_PrepareRead(CMtDec *p) + + { + unsigned i; +- for (i = 0; i < MTDEC__THREADS_MAX; i++) ++ for (i = 0; i < MTDEC_THREADS_MAX; i++) + if (i > p->numStartedThreads + || p->numFilledThreads <= + (i >= p->filledThreadStart ? +@@ -987,7 +960,7 @@ void MtDec_Construct(CMtDec *p) + + p->allocatedBufsSize = 0; + +- for (i = 0; i < MTDEC__THREADS_MAX; i++) ++ for (i = 0; i < MTDEC_THREADS_MAX; i++) + { + CMtDecThread *t = &p->threads[i]; + t->mtDec = p; +@@ -995,7 +968,7 @@ void MtDec_Construct(CMtDec *p) + t->inBuf = NULL; + Event_Construct(&t->canRead); + Event_Construct(&t->canWrite); +- Thread_Construct(&t->thread); ++ Thread_CONSTRUCT(&t->thread) + } + + // Event_Construct(&p->finishedEvent); +@@ -1010,7 +983,7 @@ static void MtDec_Free(CMtDec *p) + + p->exitThread = True7z; + +- for (i = 0; i < MTDEC__THREADS_MAX; i++) ++ for (i = 0; i < MTDEC_THREADS_MAX; i++) + MtDecThread_Destruct(&p->threads[i]); + + // Event_Close(&p->finishedEvent); +@@ -1061,15 +1034,15 @@ SRes MtDec_Code(CMtDec *p) + + { + unsigned numThreads = p->numThreadsMax; +- if (numThreads > MTDEC__THREADS_MAX) +- numThreads = MTDEC__THREADS_MAX; ++ if (numThreads > MTDEC_THREADS_MAX) ++ numThreads = MTDEC_THREADS_MAX; + p->numStartedThreads_Limit = numThreads; + p->numStartedThreads = 0; + } + + if (p->inBufSize != p->allocatedBufsSize) + { +- for (i = 0; i < MTDEC__THREADS_MAX; i++) ++ for (i = 0; i < MTDEC_THREADS_MAX; i++) + { + CMtDecThread *t = &p->threads[i]; + if (t->inBuf) +@@ -1086,7 +1059,7 @@ SRes MtDec_Code(CMtDec *p) + + MtProgress_Init(&p->mtProgress, p->progress); + +- // RINOK_THREAD(ArEvent_OptCreate_And_Reset(&p->finishedEvent)); ++ // RINOK_THREAD(AutoResetEvent_OptCreate_And_Reset(&p->finishedEvent)) + p->exitThread = False7z; + p->exitThreadWRes = 0; + +@@ -1098,7 +1071,7 @@ SRes MtDec_Code(CMtDec *p) + wres = MtDecThread_CreateEvents(nextThread); + if (wres == 0) { wres = Event_Set(&nextThread->canWrite); + if (wres == 0) { wres = Event_Set(&nextThread->canRead); +- if (wres == 0) { THREAD_FUNC_RET_TYPE res = ThreadFunc(nextThread); ++ if (wres == 0) { THREAD_FUNC_RET_TYPE res = MtDec_ThreadFunc(nextThread); + wres = (WRes)(UINT_PTR)res; + if (wres != 0) + { +@@ -1137,3 +1110,5 @@ SRes MtDec_Code(CMtDec *p) + } + + #endif ++ ++#undef PRF +diff --git a/src/lzma/MtDec.h b/src/lzma/MtDec.h +index c2da46ae2..c28e8d9ac 100644 +--- a/src/lzma/MtDec.h ++++ b/src/lzma/MtDec.h +@@ -1,46 +1,46 @@ + /* MtDec.h -- Multi-thread Decoder +-2020-03-05 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + +-#ifndef __MT_DEC_H +-#define __MT_DEC_H ++#ifndef ZIP7_INC_MT_DEC_H ++#define ZIP7_INC_MT_DEC_H + + #include "7zTypes.h" + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + #include "Threads.h" + #endif + + EXTERN_C_BEGIN + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + +-#ifndef _7ZIP_ST +- #define MTDEC__THREADS_MAX 32 ++#ifndef Z7_ST ++ #define MTDEC_THREADS_MAX 32 + #else +- #define MTDEC__THREADS_MAX 1 ++ #define MTDEC_THREADS_MAX 1 + #endif + + + typedef struct + { +- ICompressProgress *progress; ++ ICompressProgressPtr progress; + SRes res; + UInt64 totalInSize; + UInt64 totalOutSize; + CCriticalSection cs; + } CMtProgress; + +-void MtProgress_Init(CMtProgress *p, ICompressProgress *progress); ++void MtProgress_Init(CMtProgress *p, ICompressProgressPtr progress); + SRes MtProgress_Progress_ST(CMtProgress *p); + SRes MtProgress_ProgressAdd(CMtProgress *p, UInt64 inSize, UInt64 outSize); + SRes MtProgress_GetError(CMtProgress *p); + void MtProgress_SetError(CMtProgress *p, SRes res); + +-struct _CMtDec; ++struct CMtDec; + + typedef struct + { +- struct _CMtDec *mtDec; ++ struct CMtDec_ *mtDec; + unsigned index; + void *inBuf; + +@@ -117,7 +117,7 @@ typedef struct + + + +-typedef struct _CMtDec ++typedef struct CMtDec_ + { + /* input variables */ + +@@ -126,11 +126,11 @@ typedef struct _CMtDec + // size_t inBlockMax; + unsigned numThreadsMax_2; + +- ISeqInStream *inStream; ++ ISeqInStreamPtr inStream; + // const Byte *inData; + // size_t inDataSize; + +- ICompressProgress *progress; ++ ICompressProgressPtr progress; + ISzAllocPtr alloc; + + IMtDecCallback2 *mtCallback; +@@ -171,11 +171,11 @@ typedef struct _CMtDec + unsigned filledThreadStart; + unsigned numFilledThreads; + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + BoolInt needInterrupt; + UInt64 interruptIndex; + CMtProgress mtProgress; +- CMtDecThread threads[MTDEC__THREADS_MAX]; ++ CMtDecThread threads[MTDEC_THREADS_MAX]; + #endif + } CMtDec; + +diff --git a/src/lzma/Ppmd.h b/src/lzma/Ppmd.h +index b19879208..66b26266f 100644 +--- a/src/lzma/Ppmd.h ++++ b/src/lzma/Ppmd.h +@@ -1,9 +1,9 @@ + /* Ppmd.h -- PPMD codec common code +-2021-04-13 : Igor Pavlov : Public domain ++2023-03-05 : Igor Pavlov : Public domain + This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */ + +-#ifndef __PPMD_H +-#define __PPMD_H ++#ifndef ZIP7_INC_PPMD_H ++#define ZIP7_INC_PPMD_H + + #include "CpuArch.h" + +@@ -48,8 +48,10 @@ typedef struct + Byte Count; /* Count to next change of Shift */ + } CPpmd_See; + +-#define Ppmd_See_Update(p) if ((p)->Shift < PPMD_PERIOD_BITS && --(p)->Count == 0) \ +- { (p)->Summ = (UInt16)((p)->Summ << 1); (p)->Count = (Byte)(3 << (p)->Shift++); } ++#define Ppmd_See_UPDATE(p) \ ++ { if ((p)->Shift < PPMD_PERIOD_BITS && --(p)->Count == 0) \ ++ { (p)->Summ = (UInt16)((p)->Summ << 1); \ ++ (p)->Count = (Byte)(3 << (p)->Shift++); }} + + + typedef struct +diff --git a/src/lzma/Ppmd7.c b/src/lzma/Ppmd7.c +index e5c6114af..5d32607fc 100644 +--- a/src/lzma/Ppmd7.c ++++ b/src/lzma/Ppmd7.c +@@ -1,5 +1,5 @@ + /* Ppmd7.c -- PPMdH codec +-2021-04-13 : Igor Pavlov : Public domain ++2023-04-02 : Igor Pavlov : Public domain + This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */ + + #include "Precomp.h" +@@ -14,7 +14,7 @@ This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */ + MY_ALIGN(16) + static const Byte PPMD7_kExpEscape[16] = { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 }; + MY_ALIGN(16) +-static const UInt16 kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051}; ++static const UInt16 PPMD7_kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051}; + + #define MAX_FREQ 124 + #define UNIT_SIZE 12 +@@ -33,7 +33,7 @@ static const UInt16 kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x + #define ONE_STATE(ctx) Ppmd7Context_OneState(ctx) + #define SUFFIX(ctx) CTX((ctx)->Suffix) + +-typedef CPpmd7_Context * CTX_PTR; ++typedef CPpmd7_Context * PPMD7_CTX_PTR; + + struct CPpmd7_Node_; + +@@ -107,14 +107,14 @@ BoolInt Ppmd7_Alloc(CPpmd7 *p, UInt32 size, ISzAllocPtr alloc) + // ---------- Internal Memory Allocator ---------- + + /* We can use CPpmd7_Node in list of free units (as in Ppmd8) +- But we still need one additional list walk pass in GlueFreeBlocks(). +- So we use simple CPpmd_Void_Ref instead of CPpmd7_Node in InsertNode() / RemoveNode() ++ But we still need one additional list walk pass in Ppmd7_GlueFreeBlocks(). ++ So we use simple CPpmd_Void_Ref instead of CPpmd7_Node in Ppmd7_InsertNode() / Ppmd7_RemoveNode() + */ + + #define EMPTY_NODE 0 + + +-static void InsertNode(CPpmd7 *p, void *node, unsigned indx) ++static void Ppmd7_InsertNode(CPpmd7 *p, void *node, unsigned indx) + { + *((CPpmd_Void_Ref *)node) = p->FreeList[indx]; + // ((CPpmd7_Node *)node)->Next = (CPpmd7_Node_Ref)p->FreeList[indx]; +@@ -124,7 +124,7 @@ static void InsertNode(CPpmd7 *p, void *node, unsigned indx) + } + + +-static void *RemoveNode(CPpmd7 *p, unsigned indx) ++static void *Ppmd7_RemoveNode(CPpmd7 *p, unsigned indx) + { + CPpmd_Void_Ref *node = (CPpmd_Void_Ref *)Ppmd7_GetPtr(p, p->FreeList[indx]); + p->FreeList[indx] = *node; +@@ -134,32 +134,32 @@ static void *RemoveNode(CPpmd7 *p, unsigned indx) + } + + +-static void SplitBlock(CPpmd7 *p, void *ptr, unsigned oldIndx, unsigned newIndx) ++static void Ppmd7_SplitBlock(CPpmd7 *p, void *ptr, unsigned oldIndx, unsigned newIndx) + { + unsigned i, nu = I2U(oldIndx) - I2U(newIndx); + ptr = (Byte *)ptr + U2B(I2U(newIndx)); + if (I2U(i = U2I(nu)) != nu) + { + unsigned k = I2U(--i); +- InsertNode(p, ((Byte *)ptr) + U2B(k), nu - k - 1); ++ Ppmd7_InsertNode(p, ((Byte *)ptr) + U2B(k), nu - k - 1); + } +- InsertNode(p, ptr, i); ++ Ppmd7_InsertNode(p, ptr, i); + } + + + /* we use CPpmd7_Node_Union union to solve XLC -O2 strict pointer aliasing problem */ + +-typedef union _CPpmd7_Node_Union ++typedef union + { + CPpmd7_Node Node; + CPpmd7_Node_Ref NextRef; + } CPpmd7_Node_Union; + +-/* Original PPmdH (Ppmd7) code uses doubly linked list in GlueFreeBlocks() ++/* Original PPmdH (Ppmd7) code uses doubly linked list in Ppmd7_GlueFreeBlocks() + we use single linked list similar to Ppmd8 code */ + + +-static void GlueFreeBlocks(CPpmd7 *p) ++static void Ppmd7_GlueFreeBlocks(CPpmd7 *p) + { + /* + we use first UInt16 field of 12-bytes UNITs as record type stamp +@@ -239,27 +239,27 @@ static void GlueFreeBlocks(CPpmd7 *p) + if (nu == 0) + continue; + for (; nu > 128; nu -= 128, node += 128) +- InsertNode(p, node, PPMD_NUM_INDEXES - 1); ++ Ppmd7_InsertNode(p, node, PPMD_NUM_INDEXES - 1); + if (I2U(i = U2I(nu)) != nu) + { + unsigned k = I2U(--i); +- InsertNode(p, node + k, (unsigned)nu - k - 1); ++ Ppmd7_InsertNode(p, node + k, (unsigned)nu - k - 1); + } +- InsertNode(p, node, i); ++ Ppmd7_InsertNode(p, node, i); + } + } + + +-MY_NO_INLINE +-static void *AllocUnitsRare(CPpmd7 *p, unsigned indx) ++Z7_NO_INLINE ++static void *Ppmd7_AllocUnitsRare(CPpmd7 *p, unsigned indx) + { + unsigned i; + + if (p->GlueCount == 0) + { +- GlueFreeBlocks(p); ++ Ppmd7_GlueFreeBlocks(p); + if (p->FreeList[indx] != 0) +- return RemoveNode(p, indx); ++ return Ppmd7_RemoveNode(p, indx); + } + + i = indx; +@@ -277,17 +277,17 @@ static void *AllocUnitsRare(CPpmd7 *p, unsigned indx) + while (p->FreeList[i] == 0); + + { +- void *block = RemoveNode(p, i); +- SplitBlock(p, block, i, indx); ++ void *block = Ppmd7_RemoveNode(p, i); ++ Ppmd7_SplitBlock(p, block, i, indx); + return block; + } + } + + +-static void *AllocUnits(CPpmd7 *p, unsigned indx) ++static void *Ppmd7_AllocUnits(CPpmd7 *p, unsigned indx) + { + if (p->FreeList[indx] != 0) +- return RemoveNode(p, indx); ++ return Ppmd7_RemoveNode(p, indx); + { + UInt32 numBytes = U2B(I2U(indx)); + Byte *lo = p->LoUnit; +@@ -297,11 +297,11 @@ static void *AllocUnits(CPpmd7 *p, unsigned indx) + return lo; + } + } +- return AllocUnitsRare(p, indx); ++ return Ppmd7_AllocUnitsRare(p, indx); + } + + +-#define MyMem12Cpy(dest, src, num) \ ++#define MEM_12_CPY(dest, src, num) \ + { UInt32 *d = (UInt32 *)dest; const UInt32 *z = (const UInt32 *)src; UInt32 n = num; \ + do { d[0] = z[0]; d[1] = z[1]; d[2] = z[2]; z += 3; d += 3; } while (--n); } + +@@ -315,12 +315,12 @@ static void *ShrinkUnits(CPpmd7 *p, void *oldPtr, unsigned oldNU, unsigned newNU + return oldPtr; + if (p->FreeList[i1] != 0) + { +- void *ptr = RemoveNode(p, i1); +- MyMem12Cpy(ptr, oldPtr, newNU); +- InsertNode(p, oldPtr, i0); ++ void *ptr = Ppmd7_RemoveNode(p, i1); ++ MEM_12_CPY(ptr, oldPtr, newNU) ++ Ppmd7_InsertNode(p, oldPtr, i0); + return ptr; + } +- SplitBlock(p, oldPtr, i0, i1); ++ Ppmd7_SplitBlock(p, oldPtr, i0, i1); + return oldPtr; + } + */ +@@ -329,14 +329,14 @@ static void *ShrinkUnits(CPpmd7 *p, void *oldPtr, unsigned oldNU, unsigned newNU + #define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) + static void SetSuccessor(CPpmd_State *p, CPpmd_Void_Ref v) + { +- Ppmd_SET_SUCCESSOR(p, v); ++ Ppmd_SET_SUCCESSOR(p, v) + } + + + +-MY_NO_INLINE ++Z7_NO_INLINE + static +-void RestartModel(CPpmd7 *p) ++void Ppmd7_RestartModel(CPpmd7 *p) + { + unsigned i, k; + +@@ -352,8 +352,8 @@ void RestartModel(CPpmd7 *p) + p->PrevSuccess = 0; + + { +- CPpmd7_Context *mc = (CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */ +- CPpmd_State *s = (CPpmd_State *)p->LoUnit; /* AllocUnits(p, PPMD_NUM_INDEXES - 1); */ ++ CPpmd7_Context *mc = (PPMD7_CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */ ++ CPpmd_State *s = (CPpmd_State *)p->LoUnit; /* Ppmd7_AllocUnits(p, PPMD_NUM_INDEXES - 1); */ + + p->LoUnit += U2B(256 / 2); + p->MaxContext = p->MinContext = mc; +@@ -391,7 +391,7 @@ void RestartModel(CPpmd7 *p) + { + unsigned m; + UInt16 *dest = p->BinSumm[i] + k; +- UInt16 val = (UInt16)(PPMD_BIN_SCALE - kInitBinEsc[k] / (i + 2)); ++ const UInt16 val = (UInt16)(PPMD_BIN_SCALE - PPMD7_kInitBinEsc[k] / (i + 2)); + for (m = 0; m < 64; m += 8) + dest[m] = val; + } +@@ -423,13 +423,13 @@ void Ppmd7_Init(CPpmd7 *p, unsigned maxOrder) + { + p->MaxOrder = maxOrder; + +- RestartModel(p); ++ Ppmd7_RestartModel(p); + } + + + + /* +- CreateSuccessors() ++ Ppmd7_CreateSuccessors() + It's called when (FoundState->Successor) is RAW-Successor, + that is the link to position in Raw text. + So we create Context records and write the links to +@@ -445,10 +445,10 @@ void Ppmd7_Init(CPpmd7 *p, unsigned maxOrder) + also it can return pointer to real context of same order, + */ + +-MY_NO_INLINE +-static CTX_PTR CreateSuccessors(CPpmd7 *p) ++Z7_NO_INLINE ++static PPMD7_CTX_PTR Ppmd7_CreateSuccessors(CPpmd7 *p) + { +- CTX_PTR c = p->MinContext; ++ PPMD7_CTX_PTR c = p->MinContext; + CPpmd_Byte_Ref upBranch = (CPpmd_Byte_Ref)SUCCESSOR(p->FoundState); + Byte newSym, newFreq; + unsigned numPs = 0; +@@ -522,15 +522,15 @@ static CTX_PTR CreateSuccessors(CPpmd7 *p) + + do + { +- CTX_PTR c1; ++ PPMD7_CTX_PTR c1; + /* = AllocContext(p); */ + if (p->HiUnit != p->LoUnit) +- c1 = (CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); ++ c1 = (PPMD7_CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); + else if (p->FreeList[0] != 0) +- c1 = (CTX_PTR)RemoveNode(p, 0); ++ c1 = (PPMD7_CTX_PTR)Ppmd7_RemoveNode(p, 0); + else + { +- c1 = (CTX_PTR)AllocUnitsRare(p, 0); ++ c1 = (PPMD7_CTX_PTR)Ppmd7_AllocUnitsRare(p, 0); + if (!c1) + return NULL; + } +@@ -550,16 +550,16 @@ static CTX_PTR CreateSuccessors(CPpmd7 *p) + + + +-#define SwapStates(s) \ ++#define SWAP_STATES(s) \ + { CPpmd_State tmp = s[0]; s[0] = s[-1]; s[-1] = tmp; } + + + void Ppmd7_UpdateModel(CPpmd7 *p); +-MY_NO_INLINE ++Z7_NO_INLINE + void Ppmd7_UpdateModel(CPpmd7 *p) + { + CPpmd_Void_Ref maxSuccessor, minSuccessor; +- CTX_PTR c, mc; ++ PPMD7_CTX_PTR c, mc; + unsigned s0, ns; + + +@@ -592,7 +592,7 @@ void Ppmd7_UpdateModel(CPpmd7 *p) + + if (s[0].Freq >= s[-1].Freq) + { +- SwapStates(s); ++ SWAP_STATES(s) + s--; + } + } +@@ -610,10 +610,10 @@ void Ppmd7_UpdateModel(CPpmd7 *p) + { + /* MAX ORDER context */ + /* (FoundState->Successor) is RAW-Successor. */ +- p->MaxContext = p->MinContext = CreateSuccessors(p); ++ p->MaxContext = p->MinContext = Ppmd7_CreateSuccessors(p); + if (!p->MinContext) + { +- RestartModel(p); ++ Ppmd7_RestartModel(p); + return; + } + SetSuccessor(p->FoundState, REF(p->MinContext)); +@@ -629,7 +629,7 @@ void Ppmd7_UpdateModel(CPpmd7 *p) + p->Text = text; + if (text >= p->UnitsStart) + { +- RestartModel(p); ++ Ppmd7_RestartModel(p); + return; + } + maxSuccessor = REF(text); +@@ -645,10 +645,10 @@ void Ppmd7_UpdateModel(CPpmd7 *p) + if (minSuccessor <= maxSuccessor) + { + // minSuccessor is RAW-Successor. So we will create real contexts records: +- CTX_PTR cs = CreateSuccessors(p); ++ PPMD7_CTX_PTR cs = Ppmd7_CreateSuccessors(p); + if (!cs) + { +- RestartModel(p); ++ Ppmd7_RestartModel(p); + return; + } + minSuccessor = REF(cs); +@@ -715,16 +715,16 @@ void Ppmd7_UpdateModel(CPpmd7 *p) + unsigned i = U2I(oldNU); + if (i != U2I((size_t)oldNU + 1)) + { +- void *ptr = AllocUnits(p, i + 1); ++ void *ptr = Ppmd7_AllocUnits(p, i + 1); + void *oldPtr; + if (!ptr) + { +- RestartModel(p); ++ Ppmd7_RestartModel(p); + return; + } + oldPtr = STATS(c); +- MyMem12Cpy(ptr, oldPtr, oldNU); +- InsertNode(p, oldPtr, i); ++ MEM_12_CPY(ptr, oldPtr, oldNU) ++ Ppmd7_InsertNode(p, oldPtr, i); + c->Union4.Stats = STATS_REF(ptr); + } + } +@@ -739,10 +739,10 @@ void Ppmd7_UpdateModel(CPpmd7 *p) + else + { + // instead of One-symbol context we create 2-symbol context +- CPpmd_State *s = (CPpmd_State*)AllocUnits(p, 0); ++ CPpmd_State *s = (CPpmd_State*)Ppmd7_AllocUnits(p, 0); + if (!s) + { +- RestartModel(p); ++ Ppmd7_RestartModel(p); + return; + } + { +@@ -795,8 +795,8 @@ void Ppmd7_UpdateModel(CPpmd7 *p) + + + +-MY_NO_INLINE +-static void Rescale(CPpmd7 *p) ++Z7_NO_INLINE ++static void Ppmd7_Rescale(CPpmd7 *p) + { + unsigned i, adder, sumFreq, escFreq; + CPpmd_State *stats = STATS(p->MinContext); +@@ -885,7 +885,7 @@ static void Rescale(CPpmd7 *p) + *s = *stats; + s->Freq = (Byte)freq; // (freq <= 260 / 4) + p->FoundState = s; +- InsertNode(p, stats, U2I(n0)); ++ Ppmd7_InsertNode(p, stats, U2I(n0)); + return; + } + +@@ -899,13 +899,13 @@ static void Rescale(CPpmd7 *p) + { + if (p->FreeList[i1] != 0) + { +- void *ptr = RemoveNode(p, i1); ++ void *ptr = Ppmd7_RemoveNode(p, i1); + p->MinContext->Union4.Stats = STATS_REF(ptr); +- MyMem12Cpy(ptr, (const void *)stats, n1); +- InsertNode(p, stats, i0); ++ MEM_12_CPY(ptr, (const void *)stats, n1) ++ Ppmd7_InsertNode(p, stats, i0); + } + else +- SplitBlock(p, stats, i0, i1); ++ Ppmd7_SplitBlock(p, stats, i0, i1); + } + } + } +@@ -948,9 +948,9 @@ CPpmd_See *Ppmd7_MakeEscFreq(CPpmd7 *p, unsigned numMasked, UInt32 *escFreq) + } + + +-static void NextContext(CPpmd7 *p) ++static void Ppmd7_NextContext(CPpmd7 *p) + { +- CTX_PTR c = CTX(SUCCESSOR(p->FoundState)); ++ PPMD7_CTX_PTR c = CTX(SUCCESSOR(p->FoundState)); + if (p->OrderFall == 0 && (const Byte *)c > p->Text) + p->MaxContext = p->MinContext = c; + else +@@ -967,12 +967,12 @@ void Ppmd7_Update1(CPpmd7 *p) + s->Freq = (Byte)freq; + if (freq > s[-1].Freq) + { +- SwapStates(s); ++ SWAP_STATES(s) + p->FoundState = --s; + if (freq > MAX_FREQ) +- Rescale(p); ++ Ppmd7_Rescale(p); + } +- NextContext(p); ++ Ppmd7_NextContext(p); + } + + +@@ -988,8 +988,8 @@ void Ppmd7_Update1_0(CPpmd7 *p) + freq += 4; + s->Freq = (Byte)freq; + if (freq > MAX_FREQ) +- Rescale(p); +- NextContext(p); ++ Ppmd7_Rescale(p); ++ Ppmd7_NextContext(p); + } + + +@@ -1000,7 +1000,7 @@ void Ppmd7_UpdateBin(CPpmd7 *p) + p->FoundState->Freq = (Byte)(freq + (freq < 128)); + p->PrevSuccess = 1; + p->RunLength++; +- NextContext(p); ++ Ppmd7_NextContext(p); + } + */ + +@@ -1013,7 +1013,7 @@ void Ppmd7_Update2(CPpmd7 *p) + p->MinContext->Union2.SummFreq = (UInt16)(p->MinContext->Union2.SummFreq + 4); + s->Freq = (Byte)freq; + if (freq > MAX_FREQ) +- Rescale(p); ++ Ppmd7_Rescale(p); + Ppmd7_UpdateModel(p); + } + +@@ -1042,8 +1042,8 @@ Last UNIT of array at offset (Size - 12) is root order-0 CPpmd7_Context record. + The code can free UNITs memory blocks that were allocated to store CPpmd_State vectors. + The code doesn't free UNITs allocated for CPpmd7_Context records. + +-The code calls RestartModel(), when there is no free memory for allocation. +-And RestartModel() changes the state to orignal start state, with full free block. ++The code calls Ppmd7_RestartModel(), when there is no free memory for allocation. ++And Ppmd7_RestartModel() changes the state to orignal start state, with full free block. + + + The code allocates UNITs with the following order: +@@ -1051,14 +1051,14 @@ The code allocates UNITs with the following order: + Allocation of 1 UNIT for Context record + - from free space (HiUnit) down to (LoUnit) + - from FreeList[0] +- - AllocUnitsRare() ++ - Ppmd7_AllocUnitsRare() + +-AllocUnits() for CPpmd_State vectors: ++Ppmd7_AllocUnits() for CPpmd_State vectors: + - from FreeList[i] + - from free space (LoUnit) up to (HiUnit) +- - AllocUnitsRare() ++ - Ppmd7_AllocUnitsRare() + +-AllocUnitsRare() ++Ppmd7_AllocUnitsRare() + - if (GlueCount == 0) + { Glue lists, GlueCount = 255, allocate from FreeList[i]] } + - loop for all higher sized FreeList[...] lists +@@ -1093,8 +1093,8 @@ The PPMd code tries to fulfill the condition: + We have (Sum(Stats[].Freq) <= 256 * 124), because of (MAX_FREQ = 124) + So (4 = 128 - 124) is average reserve for Escape_Freq for each symbol. + If (CPpmd_State::Freq) is not aligned for 4, the reserve can be 5, 6 or 7. +-SummFreq and Escape_Freq can be changed in Rescale() and *Update*() functions. +-Rescale() can remove symbols only from max-order contexts. So Escape_Freq can increase after multiple calls of Rescale() for ++SummFreq and Escape_Freq can be changed in Ppmd7_Rescale() and *Update*() functions. ++Ppmd7_Rescale() can remove symbols only from max-order contexts. So Escape_Freq can increase after multiple calls of Ppmd7_Rescale() for + max-order context. + + When the PPMd code still break (Total <= RC::Range) condition in range coder, +@@ -1102,3 +1102,21 @@ we have two ways to resolve that problem: + 1) we can report error, if we want to keep compatibility with original PPMd code that has no fix for such cases. + 2) we can reduce (Total) value to (RC::Range) by reducing (Escape_Freq) part of (Total) value. + */ ++ ++#undef MAX_FREQ ++#undef UNIT_SIZE ++#undef U2B ++#undef U2I ++#undef I2U ++#undef I2U_UInt16 ++#undef REF ++#undef STATS_REF ++#undef CTX ++#undef STATS ++#undef ONE_STATE ++#undef SUFFIX ++#undef NODE ++#undef EMPTY_NODE ++#undef MEM_12_CPY ++#undef SUCCESSOR ++#undef SWAP_STATES +diff --git a/src/lzma/Ppmd7.h b/src/lzma/Ppmd7.h +index d31809aeb..d9eb326d6 100644 +--- a/src/lzma/Ppmd7.h ++++ b/src/lzma/Ppmd7.h +@@ -1,11 +1,11 @@ + /* Ppmd7.h -- Ppmd7 (PPMdH) compression codec +-2021-04-13 : Igor Pavlov : Public domain ++2023-04-02 : Igor Pavlov : Public domain + This code is based on: + PPMd var.H (2001): Dmitry Shkarin : Public domain */ + + +-#ifndef __PPMD7_H +-#define __PPMD7_H ++#ifndef ZIP7_INC_PPMD7_H ++#define ZIP7_INC_PPMD7_H + + #include "Ppmd.h" + +@@ -55,7 +55,7 @@ typedef struct + UInt32 Range; + UInt32 Code; + UInt32 Low; +- IByteIn *Stream; ++ IByteInPtr Stream; + } CPpmd7_RangeDec; + + +@@ -66,7 +66,7 @@ typedef struct + // Byte _dummy_[3]; + UInt64 Low; + UInt64 CacheSize; +- IByteOut *Stream; ++ IByteOutPtr Stream; + } CPpmd7z_RangeEnc; + + +diff --git a/src/lzma/Ppmd7Dec.c b/src/lzma/Ppmd7Dec.c +index f446a315c..7d2e55643 100644 +--- a/src/lzma/Ppmd7Dec.c ++++ b/src/lzma/Ppmd7Dec.c +@@ -1,5 +1,5 @@ + /* Ppmd7Dec.c -- Ppmd7z (PPMdH with 7z Range Coder) Decoder +-2021-04-13 : Igor Pavlov : Public domain ++2023-04-02 : Igor Pavlov : Public domain + This code is based on: + PPMd var.H (2001): Dmitry Shkarin : Public domain */ + +@@ -8,7 +8,7 @@ This code is based on: + + #include "Ppmd7.h" + +-#define kTopValue (1 << 24) ++#define kTopValue ((UInt32)1 << 24) + + + #define READ_BYTE(p) IByteIn_Read((p)->Stream) +@@ -37,9 +37,9 @@ BoolInt Ppmd7z_RangeDec_Init(CPpmd7_RangeDec *p) + + #define R (&p->rc.dec) + +-MY_FORCE_INLINE +-// MY_NO_INLINE +-static void RangeDec_Decode(CPpmd7 *p, UInt32 start, UInt32 size) ++Z7_FORCE_INLINE ++// Z7_NO_INLINE ++static void Ppmd7z_RD_Decode(CPpmd7 *p, UInt32 start, UInt32 size) + { + + +@@ -48,18 +48,18 @@ static void RangeDec_Decode(CPpmd7 *p, UInt32 start, UInt32 size) + RC_NORM_LOCAL(R) + } + +-#define RC_Decode(start, size) RangeDec_Decode(p, start, size); +-#define RC_DecodeFinal(start, size) RC_Decode(start, size) RC_NORM_REMOTE(R) +-#define RC_GetThreshold(total) (R->Code / (R->Range /= (total))) ++#define RC_Decode(start, size) Ppmd7z_RD_Decode(p, start, size); ++#define RC_DecodeFinal(start, size) RC_Decode(start, size) RC_NORM_REMOTE(R) ++#define RC_GetThreshold(total) (R->Code / (R->Range /= (total))) + + + #define CTX(ref) ((CPpmd7_Context *)Ppmd7_GetContext(p, ref)) +-typedef CPpmd7_Context * CTX_PTR; ++// typedef CPpmd7_Context * CTX_PTR; + #define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) + void Ppmd7_UpdateModel(CPpmd7 *p); + + #define MASK(sym) ((unsigned char *)charMask)[sym] +-// MY_FORCE_INLINE ++// Z7_FORCE_INLINE + // static + int Ppmd7z_DecodeSymbol(CPpmd7 *p) + { +@@ -70,7 +70,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) + CPpmd_State *s = Ppmd7_GetStats(p, p->MinContext); + unsigned i; + UInt32 count, hiCnt; +- UInt32 summFreq = p->MinContext->Union2.SummFreq; ++ const UInt32 summFreq = p->MinContext->Union2.SummFreq; + + + +@@ -81,7 +81,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) + if ((Int32)(count -= s->Freq) < 0) + { + Byte sym; +- RC_DecodeFinal(0, s->Freq); ++ RC_DecodeFinal(0, s->Freq) + p->FoundState = s; + sym = s->Symbol; + Ppmd7_Update1_0(p); +@@ -96,7 +96,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) + if ((Int32)(count -= (++s)->Freq) < 0) + { + Byte sym; +- RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq); ++ RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq) + p->FoundState = s; + sym = s->Symbol; + Ppmd7_Update1(p); +@@ -109,10 +109,10 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) + return PPMD7_SYM_ERROR; + + hiCnt -= count; +- RC_Decode(hiCnt, summFreq - hiCnt); ++ RC_Decode(hiCnt, summFreq - hiCnt) + + p->HiBitsFlag = PPMD7_HiBitsFlag_3(p->FoundState->Symbol); +- PPMD_SetAllBitsIn256Bytes(charMask); ++ PPMD_SetAllBitsIn256Bytes(charMask) + // i = p->MinContext->NumStats - 1; + // do { MASK((--s)->Symbol) = 0; } while (--i); + { +@@ -152,7 +152,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) + // Ppmd7_UpdateBin(p); + { + unsigned freq = s->Freq; +- CTX_PTR c = CTX(SUCCESSOR(s)); ++ CPpmd7_Context *c = CTX(SUCCESSOR(s)); + sym = s->Symbol; + p->FoundState = s; + p->PrevSuccess = 1; +@@ -176,7 +176,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) + R->Range -= size0; + RC_NORM_LOCAL(R) + +- PPMD_SetAllBitsIn256Bytes(charMask); ++ PPMD_SetAllBitsIn256Bytes(charMask) + MASK(Ppmd7Context_OneState(p->MinContext)->Symbol) = 0; + p->PrevSuccess = 0; + } +@@ -245,13 +245,13 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) + { + count -= s->Freq & (unsigned)(MASK((s)->Symbol)); s++; if ((Int32)count < 0) break; + // count -= s->Freq & (unsigned)(MASK((s)->Symbol)); s++; if ((Int32)count < 0) break; +- }; ++ } + } + s--; +- RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq); ++ RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq) + + // new (see->Summ) value can overflow over 16-bits in some rare cases +- Ppmd_See_Update(see); ++ Ppmd_See_UPDATE(see) + p->FoundState = s; + sym = s->Symbol; + Ppmd7_Update2(p); +@@ -261,7 +261,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) + if (count >= freqSum) + return PPMD7_SYM_ERROR; + +- RC_Decode(hiCnt, freqSum - hiCnt); ++ RC_Decode(hiCnt, freqSum - hiCnt) + + // We increase (see->Summ) for sum of Freqs of all non_Masked symbols. + // new (see->Summ) value can overflow over 16-bits in some rare cases +@@ -295,3 +295,18 @@ Byte *Ppmd7z_DecodeSymbols(CPpmd7 *p, Byte *buf, const Byte *lim) + return buf; + } + */ ++ ++#undef kTopValue ++#undef READ_BYTE ++#undef RC_NORM_BASE ++#undef RC_NORM_1 ++#undef RC_NORM ++#undef RC_NORM_LOCAL ++#undef RC_NORM_REMOTE ++#undef R ++#undef RC_Decode ++#undef RC_DecodeFinal ++#undef RC_GetThreshold ++#undef CTX ++#undef SUCCESSOR ++#undef MASK +diff --git a/src/lzma/Ppmd7Enc.c b/src/lzma/Ppmd7Enc.c +index 62139c5b6..41106bab4 100644 +--- a/src/lzma/Ppmd7Enc.c ++++ b/src/lzma/Ppmd7Enc.c +@@ -1,5 +1,5 @@ + /* Ppmd7Enc.c -- Ppmd7z (PPMdH with 7z Range Coder) Encoder +-2021-04-13 : Igor Pavlov : Public domain ++2023-04-02 : Igor Pavlov : Public domain + This code is based on: + PPMd var.H (2001): Dmitry Shkarin : Public domain */ + +@@ -8,7 +8,7 @@ This code is based on: + + #include "Ppmd7.h" + +-#define kTopValue (1 << 24) ++#define kTopValue ((UInt32)1 << 24) + + #define R (&p->rc.enc) + +@@ -20,8 +20,8 @@ void Ppmd7z_Init_RangeEnc(CPpmd7 *p) + R->CacheSize = 1; + } + +-MY_NO_INLINE +-static void RangeEnc_ShiftLow(CPpmd7 *p) ++Z7_NO_INLINE ++static void Ppmd7z_RangeEnc_ShiftLow(CPpmd7 *p) + { + if ((UInt32)R->Low < (UInt32)0xFF000000 || (unsigned)(R->Low >> 32) != 0) + { +@@ -38,53 +38,53 @@ static void RangeEnc_ShiftLow(CPpmd7 *p) + R->Low = (UInt32)((UInt32)R->Low << 8); + } + +-#define RC_NORM_BASE(p) if (R->Range < kTopValue) { R->Range <<= 8; RangeEnc_ShiftLow(p); +-#define RC_NORM_1(p) RC_NORM_BASE(p) } +-#define RC_NORM(p) RC_NORM_BASE(p) RC_NORM_BASE(p) }} ++#define RC_NORM_BASE(p) if (R->Range < kTopValue) { R->Range <<= 8; Ppmd7z_RangeEnc_ShiftLow(p); ++#define RC_NORM_1(p) RC_NORM_BASE(p) } ++#define RC_NORM(p) RC_NORM_BASE(p) RC_NORM_BASE(p) }} + + // we must use only one type of Normalization from two: LOCAL or REMOTE + #define RC_NORM_LOCAL(p) // RC_NORM(p) + #define RC_NORM_REMOTE(p) RC_NORM(p) + + /* +-#define RangeEnc_Encode(p, start, _size_) \ ++#define Ppmd7z_RangeEnc_Encode(p, start, _size_) \ + { UInt32 size = _size_; \ + R->Low += start * R->Range; \ + R->Range *= size; \ + RC_NORM_LOCAL(p); } + */ + +-MY_FORCE_INLINE +-// MY_NO_INLINE +-static void RangeEnc_Encode(CPpmd7 *p, UInt32 start, UInt32 size) ++Z7_FORCE_INLINE ++// Z7_NO_INLINE ++static void Ppmd7z_RangeEnc_Encode(CPpmd7 *p, UInt32 start, UInt32 size) + { + R->Low += start * R->Range; + R->Range *= size; +- RC_NORM_LOCAL(p); ++ RC_NORM_LOCAL(p) + } + + void Ppmd7z_Flush_RangeEnc(CPpmd7 *p) + { + unsigned i; + for (i = 0; i < 5; i++) +- RangeEnc_ShiftLow(p); ++ Ppmd7z_RangeEnc_ShiftLow(p); + } + + + +-#define RC_Encode(start, size) RangeEnc_Encode(p, start, size); +-#define RC_EncodeFinal(start, size) RC_Encode(start, size); RC_NORM_REMOTE(p); ++#define RC_Encode(start, size) Ppmd7z_RangeEnc_Encode(p, start, size); ++#define RC_EncodeFinal(start, size) RC_Encode(start, size) RC_NORM_REMOTE(p) + + #define CTX(ref) ((CPpmd7_Context *)Ppmd7_GetContext(p, ref)) + #define SUFFIX(ctx) CTX((ctx)->Suffix) +-typedef CPpmd7_Context * CTX_PTR; ++// typedef CPpmd7_Context * CTX_PTR; + #define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) + + void Ppmd7_UpdateModel(CPpmd7 *p); + + #define MASK(sym) ((unsigned char *)charMask)[sym] + +-MY_FORCE_INLINE ++Z7_FORCE_INLINE + static + void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) + { +@@ -104,7 +104,7 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) + if (s->Symbol == symbol) + { + // R->Range /= p->MinContext->Union2.SummFreq; +- RC_EncodeFinal(0, s->Freq); ++ RC_EncodeFinal(0, s->Freq) + p->FoundState = s; + Ppmd7_Update1_0(p); + return; +@@ -117,7 +117,7 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) + if ((++s)->Symbol == symbol) + { + // R->Range /= p->MinContext->Union2.SummFreq; +- RC_EncodeFinal(sum, s->Freq); ++ RC_EncodeFinal(sum, s->Freq) + p->FoundState = s; + Ppmd7_Update1(p); + return; +@@ -127,10 +127,10 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) + while (--i); + + // R->Range /= p->MinContext->Union2.SummFreq; +- RC_Encode(sum, p->MinContext->Union2.SummFreq - sum); ++ RC_Encode(sum, p->MinContext->Union2.SummFreq - sum) + + p->HiBitsFlag = PPMD7_HiBitsFlag_3(p->FoundState->Symbol); +- PPMD_SetAllBitsIn256Bytes(charMask); ++ PPMD_SetAllBitsIn256Bytes(charMask) + // MASK(s->Symbol) = 0; + // i = p->MinContext->NumStats - 1; + // do { MASK((--s)->Symbol) = 0; } while (--i); +@@ -153,20 +153,20 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) + UInt16 *prob = Ppmd7_GetBinSumm(p); + CPpmd_State *s = Ppmd7Context_OneState(p->MinContext); + UInt32 pr = *prob; +- UInt32 bound = (R->Range >> 14) * pr; ++ const UInt32 bound = (R->Range >> 14) * pr; + pr = PPMD_UPDATE_PROB_1(pr); + if (s->Symbol == symbol) + { + *prob = (UInt16)(pr + (1 << PPMD_INT_BITS)); + // RangeEnc_EncodeBit_0(p, bound); + R->Range = bound; +- RC_NORM_1(p); ++ RC_NORM_1(p) + + // p->FoundState = s; + // Ppmd7_UpdateBin(p); + { +- unsigned freq = s->Freq; +- CTX_PTR c = CTX(SUCCESSOR(s)); ++ const unsigned freq = s->Freq; ++ CPpmd7_Context *c = CTX(SUCCESSOR(s)); + p->FoundState = s; + p->PrevSuccess = 1; + p->RunLength++; +@@ -187,7 +187,7 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) + R->Range -= bound; + RC_NORM_LOCAL(p) + +- PPMD_SetAllBitsIn256Bytes(charMask); ++ PPMD_SetAllBitsIn256Bytes(charMask) + MASK(s->Symbol) = 0; + p->PrevSuccess = 0; + } +@@ -248,14 +248,14 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) + + do + { +- unsigned cur = s->Symbol; ++ const unsigned cur = s->Symbol; + if ((int)cur == symbol) + { +- UInt32 low = sum; +- UInt32 freq = s->Freq; ++ const UInt32 low = sum; ++ const UInt32 freq = s->Freq; + unsigned num2; + +- Ppmd_See_Update(see); ++ Ppmd_See_UPDATE(see) + p->FoundState = s; + sum += escFreq; + +@@ -279,7 +279,7 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) + + + R->Range /= sum; +- RC_EncodeFinal(low, freq); ++ RC_EncodeFinal(low, freq) + Ppmd7_Update2(p); + return; + } +@@ -289,21 +289,21 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) + while (--i); + + { +- UInt32 total = sum + escFreq; ++ const UInt32 total = sum + escFreq; + see->Summ = (UInt16)(see->Summ + total); + + R->Range /= total; +- RC_Encode(sum, escFreq); ++ RC_Encode(sum, escFreq) + } + + { +- CPpmd_State *s2 = Ppmd7_GetStats(p, p->MinContext); ++ const CPpmd_State *s2 = Ppmd7_GetStats(p, p->MinContext); + s--; + MASK(s->Symbol) = 0; + do + { +- unsigned sym0 = s2[0].Symbol; +- unsigned sym1 = s2[1].Symbol; ++ const unsigned sym0 = s2[0].Symbol; ++ const unsigned sym1 = s2[1].Symbol; + s2 += 2; + MASK(sym0) = 0; + MASK(sym1) = 0; +@@ -321,3 +321,18 @@ void Ppmd7z_EncodeSymbols(CPpmd7 *p, const Byte *buf, const Byte *lim) + Ppmd7z_EncodeSymbol(p, *buf); + } + } ++ ++#undef kTopValue ++#undef WRITE_BYTE ++#undef RC_NORM_BASE ++#undef RC_NORM_1 ++#undef RC_NORM ++#undef RC_NORM_LOCAL ++#undef RC_NORM_REMOTE ++#undef R ++#undef RC_Encode ++#undef RC_EncodeFinal ++#undef SUFFIX ++#undef CTX ++#undef SUCCESSOR ++#undef MASK +diff --git a/src/lzma/Precomp.h b/src/lzma/Precomp.h +index e8ff8b40e..69afb2ffd 100644 +--- a/src/lzma/Precomp.h ++++ b/src/lzma/Precomp.h +@@ -1,8 +1,8 @@ + /* Precomp.h -- StdAfx +-2013-11-12 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + +-#ifndef __7Z_PRECOMP_H +-#define __7Z_PRECOMP_H ++#ifndef ZIP7_INC_PRECOMP_H ++#define ZIP7_INC_PRECOMP_H + + #include "Compiler.h" + /* #include "7zTypes.h" */ +diff --git a/src/lzma/RotateDefs.h b/src/lzma/RotateDefs.h +index 8f01d1a6c..c16b4f8e6 100644 +--- a/src/lzma/RotateDefs.h ++++ b/src/lzma/RotateDefs.h +@@ -1,14 +1,14 @@ + /* RotateDefs.h -- Rotate functions +-2015-03-25 : Igor Pavlov : Public domain */ ++2023-06-18 : Igor Pavlov : Public domain */ + +-#ifndef __ROTATE_DEFS_H +-#define __ROTATE_DEFS_H ++#ifndef ZIP7_INC_ROTATE_DEFS_H ++#define ZIP7_INC_ROTATE_DEFS_H + + #ifdef _MSC_VER + + #include + +-/* don't use _rotl with MINGW. It can insert slow call to function. */ ++/* don't use _rotl with old MINGW. It can insert slow call to function. */ + + /* #if (_MSC_VER >= 1200) */ + #pragma intrinsic(_rotl) +@@ -18,12 +18,32 @@ + #define rotlFixed(x, n) _rotl((x), (n)) + #define rotrFixed(x, n) _rotr((x), (n)) + ++#if (_MSC_VER >= 1300) ++#define Z7_ROTL64(x, n) _rotl64((x), (n)) ++#define Z7_ROTR64(x, n) _rotr64((x), (n)) ++#else ++#define Z7_ROTL64(x, n) (((x) << (n)) | ((x) >> (64 - (n)))) ++#define Z7_ROTR64(x, n) (((x) >> (n)) | ((x) << (64 - (n)))) ++#endif ++ + #else + + /* new compilers can translate these macros to fast commands. */ + ++#if defined(__clang__) && (__clang_major__ >= 4) \ ++ || defined(__GNUC__) && (__GNUC__ >= 5) ++/* GCC 4.9.0 and clang 3.5 can recognize more correct version: */ ++#define rotlFixed(x, n) (((x) << (n)) | ((x) >> (-(n) & 31))) ++#define rotrFixed(x, n) (((x) >> (n)) | ((x) << (-(n) & 31))) ++#define Z7_ROTL64(x, n) (((x) << (n)) | ((x) >> (-(n) & 63))) ++#define Z7_ROTR64(x, n) (((x) >> (n)) | ((x) << (-(n) & 63))) ++#else ++/* for old GCC / clang: */ + #define rotlFixed(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) + #define rotrFixed(x, n) (((x) >> (n)) | ((x) << (32 - (n)))) ++#define Z7_ROTL64(x, n) (((x) << (n)) | ((x) >> (64 - (n)))) ++#define Z7_ROTR64(x, n) (((x) >> (n)) | ((x) << (64 - (n)))) ++#endif + + #endif + +diff --git a/src/lzma/Sha256.c b/src/lzma/Sha256.c +index 595eeae98..b119ce83f 100644 +--- a/src/lzma/Sha256.c ++++ b/src/lzma/Sha256.c +@@ -1,5 +1,5 @@ + /* Sha256.c -- SHA-256 Hash +-2021-04-01 : Igor Pavlov : Public domain ++2023-04-02 : Igor Pavlov : Public domain + This code is based on public domain code from Wei Dai's Crypto++ library. */ + + #include "Precomp.h" +@@ -17,48 +17,48 @@ This code is based on public domain code from Wei Dai's Crypto++ library. */ + #ifdef MY_CPU_X86_OR_AMD64 + #ifdef _MSC_VER + #if _MSC_VER >= 1200 +- #define _SHA_SUPPORTED ++ #define Z7_COMPILER_SHA256_SUPPORTED + #endif + #elif defined(__clang__) + #if (__clang_major__ >= 8) // fix that check +- #define _SHA_SUPPORTED ++ #define Z7_COMPILER_SHA256_SUPPORTED + #endif + #elif defined(__GNUC__) + #if (__GNUC__ >= 8) // fix that check +- #define _SHA_SUPPORTED ++ #define Z7_COMPILER_SHA256_SUPPORTED + #endif + #elif defined(__INTEL_COMPILER) + #if (__INTEL_COMPILER >= 1800) // fix that check +- #define _SHA_SUPPORTED ++ #define Z7_COMPILER_SHA256_SUPPORTED + #endif + #endif + #elif defined(MY_CPU_ARM_OR_ARM64) + #ifdef _MSC_VER + #if _MSC_VER >= 1910 +- #define _SHA_SUPPORTED ++ #define Z7_COMPILER_SHA256_SUPPORTED + #endif + #elif defined(__clang__) + #if (__clang_major__ >= 8) // fix that check +- #define _SHA_SUPPORTED ++ #define Z7_COMPILER_SHA256_SUPPORTED + #endif + #elif defined(__GNUC__) + #if (__GNUC__ >= 6) // fix that check +- #define _SHA_SUPPORTED ++ #define Z7_COMPILER_SHA256_SUPPORTED + #endif + #endif + #endif + +-void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); ++void Z7_FASTCALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); + +-#ifdef _SHA_SUPPORTED +- void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); ++#ifdef Z7_COMPILER_SHA256_SUPPORTED ++ void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); + +- static SHA256_FUNC_UPDATE_BLOCKS g_FUNC_UPDATE_BLOCKS = Sha256_UpdateBlocks; +- static SHA256_FUNC_UPDATE_BLOCKS g_FUNC_UPDATE_BLOCKS_HW; ++ static SHA256_FUNC_UPDATE_BLOCKS g_SHA256_FUNC_UPDATE_BLOCKS = Sha256_UpdateBlocks; ++ static SHA256_FUNC_UPDATE_BLOCKS g_SHA256_FUNC_UPDATE_BLOCKS_HW; + +- #define UPDATE_BLOCKS(p) p->func_UpdateBlocks ++ #define SHA256_UPDATE_BLOCKS(p) p->func_UpdateBlocks + #else +- #define UPDATE_BLOCKS(p) Sha256_UpdateBlocks ++ #define SHA256_UPDATE_BLOCKS(p) Sha256_UpdateBlocks + #endif + + +@@ -66,16 +66,16 @@ BoolInt Sha256_SetFunction(CSha256 *p, unsigned algo) + { + SHA256_FUNC_UPDATE_BLOCKS func = Sha256_UpdateBlocks; + +- #ifdef _SHA_SUPPORTED ++ #ifdef Z7_COMPILER_SHA256_SUPPORTED + if (algo != SHA256_ALGO_SW) + { + if (algo == SHA256_ALGO_DEFAULT) +- func = g_FUNC_UPDATE_BLOCKS; ++ func = g_SHA256_FUNC_UPDATE_BLOCKS; + else + { + if (algo != SHA256_ALGO_HW) + return False7z; +- func = g_FUNC_UPDATE_BLOCKS_HW; ++ func = g_SHA256_FUNC_UPDATE_BLOCKS_HW; + if (!func) + return False7z; + } +@@ -92,17 +92,18 @@ BoolInt Sha256_SetFunction(CSha256 *p, unsigned algo) + + /* define it for speed optimization */ + +-#ifdef _SFX ++#ifdef Z7_SFX + #define STEP_PRE 1 + #define STEP_MAIN 1 + #else + #define STEP_PRE 2 + #define STEP_MAIN 4 +- // #define _SHA256_UNROLL ++ // #define Z7_SHA256_UNROLL + #endif + ++#undef Z7_SHA256_BIG_W + #if STEP_MAIN != 16 +- #define _SHA256_BIG_W ++ #define Z7_SHA256_BIG_W + #endif + + +@@ -124,8 +125,8 @@ void Sha256_InitState(CSha256 *p) + void Sha256_Init(CSha256 *p) + { + p->func_UpdateBlocks = +- #ifdef _SHA_SUPPORTED +- g_FUNC_UPDATE_BLOCKS; ++ #ifdef Z7_COMPILER_SHA256_SUPPORTED ++ g_SHA256_FUNC_UPDATE_BLOCKS; + #else + NULL; + #endif +@@ -145,7 +146,7 @@ void Sha256_Init(CSha256 *p) + + #define blk2_main(j, i) s1(w(j, (i)-2)) + w(j, (i)-7) + s0(w(j, (i)-15)) + +-#ifdef _SHA256_BIG_W ++#ifdef Z7_SHA256_BIG_W + // we use +i instead of +(i) to change the order to solve CLANG compiler warning for signed/unsigned. + #define w(j, i) W[(size_t)(j) + i] + #define blk2(j, i) (w(j, i) = w(j, (i)-16) + blk2_main(j, i)) +@@ -176,7 +177,7 @@ void Sha256_Init(CSha256 *p) + #define R1_PRE(i) T1( W_PRE, i) + #define R1_MAIN(i) T1( W_MAIN, i) + +-#if (!defined(_SHA256_UNROLL) || STEP_MAIN < 8) && (STEP_MAIN >= 4) ++#if (!defined(Z7_SHA256_UNROLL) || STEP_MAIN < 8) && (STEP_MAIN >= 4) + #define R2_MAIN(i) \ + R1_MAIN(i) \ + R1_MAIN(i + 1) \ +@@ -185,7 +186,7 @@ void Sha256_Init(CSha256 *p) + + + +-#if defined(_SHA256_UNROLL) && STEP_MAIN >= 8 ++#if defined(Z7_SHA256_UNROLL) && STEP_MAIN >= 8 + + #define T4( a,b,c,d,e,f,g,h, wx, i) \ + h += S1(e) + Ch(e,f,g) + K[(i)+(size_t)(j)] + wx(i); \ +@@ -223,7 +224,7 @@ void Sha256_Init(CSha256 *p) + + #endif + +-void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); ++void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); + + // static + extern MY_ALIGN(64) +@@ -252,11 +253,11 @@ const UInt32 SHA256_K_ARRAY[64] = { + #define K SHA256_K_ARRAY + + +-MY_NO_INLINE +-void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks) ++Z7_NO_INLINE ++void Z7_FASTCALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks) + { + UInt32 W +- #ifdef _SHA256_BIG_W ++ #ifdef Z7_SHA256_BIG_W + [64]; + #else + [16]; +@@ -266,7 +267,7 @@ void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t + + UInt32 a,b,c,d,e,f,g,h; + +- #if !defined(_SHA256_UNROLL) || (STEP_MAIN <= 4) || (STEP_PRE <= 4) ++ #if !defined(Z7_SHA256_UNROLL) || (STEP_MAIN <= 4) || (STEP_PRE <= 4) + UInt32 tmp; + #endif + +@@ -297,12 +298,12 @@ void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t + + #else + +- R1_PRE(0); ++ R1_PRE(0) + #if STEP_PRE >= 2 +- R1_PRE(1); ++ R1_PRE(1) + #if STEP_PRE >= 4 +- R1_PRE(2); +- R1_PRE(3); ++ R1_PRE(2) ++ R1_PRE(3) + #endif + #endif + +@@ -311,32 +312,32 @@ void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t + + for (j = 16; j < 64; j += STEP_MAIN) + { +- #if defined(_SHA256_UNROLL) && STEP_MAIN >= 8 ++ #if defined(Z7_SHA256_UNROLL) && STEP_MAIN >= 8 + + #if STEP_MAIN < 8 +- R4_MAIN(0); ++ R4_MAIN(0) + #else +- R8_MAIN(0); ++ R8_MAIN(0) + #if STEP_MAIN == 16 +- R8_MAIN(8); ++ R8_MAIN(8) + #endif + #endif + + #else + +- R1_MAIN(0); ++ R1_MAIN(0) + #if STEP_MAIN >= 2 +- R1_MAIN(1); ++ R1_MAIN(1) + #if STEP_MAIN >= 4 +- R2_MAIN(2); ++ R2_MAIN(2) + #if STEP_MAIN >= 8 +- R2_MAIN(4); +- R2_MAIN(6); ++ R2_MAIN(4) ++ R2_MAIN(6) + #if STEP_MAIN >= 16 +- R2_MAIN(8); +- R2_MAIN(10); +- R2_MAIN(12); +- R2_MAIN(14); ++ R2_MAIN(8) ++ R2_MAIN(10) ++ R2_MAIN(12) ++ R2_MAIN(14) + #endif + #endif + #endif +@@ -367,7 +368,7 @@ void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t + #undef s1 + #undef K + +-#define Sha256_UpdateBlock(p) UPDATE_BLOCKS(p)(p->state, p->buffer, 1) ++#define Sha256_UpdateBlock(p) SHA256_UPDATE_BLOCKS(p)(p->state, p->buffer, 1) + + void Sha256_Update(CSha256 *p, const Byte *data, size_t size) + { +@@ -397,7 +398,7 @@ void Sha256_Update(CSha256 *p, const Byte *data, size_t size) + } + { + size_t numBlocks = size >> 6; +- UPDATE_BLOCKS(p)(p->state, data, numBlocks); ++ SHA256_UPDATE_BLOCKS(p)(p->state, data, numBlocks); + size &= 0x3F; + if (size == 0) + return; +@@ -441,8 +442,8 @@ void Sha256_Final(CSha256 *p, Byte *digest) + + { + UInt64 numBits = (p->count << 3); +- SetBe32(p->buffer + 64 - 8, (UInt32)(numBits >> 32)); +- SetBe32(p->buffer + 64 - 4, (UInt32)(numBits)); ++ SetBe32(p->buffer + 64 - 8, (UInt32)(numBits >> 32)) ++ SetBe32(p->buffer + 64 - 4, (UInt32)(numBits)) + } + + Sha256_UpdateBlock(p); +@@ -451,21 +452,21 @@ void Sha256_Final(CSha256 *p, Byte *digest) + { + UInt32 v0 = p->state[i]; + UInt32 v1 = p->state[(size_t)i + 1]; +- SetBe32(digest , v0); +- SetBe32(digest + 4, v1); ++ SetBe32(digest , v0) ++ SetBe32(digest + 4, v1) + digest += 8; + } + + Sha256_InitState(p); + } + +-#ifdef _SHA_SUPPORTED +-#undef _SHA_SUPPORTED ++#ifdef Z7_COMPILER_SHA256_SUPPORTED ++#undef Z7_COMPILER_SHA256_SUPPORTED + #endif + +-void Sha256Prepare() ++void Sha256Prepare(void) + { +- #ifdef _SHA_SUPPORTED ++ #ifdef Z7_COMPILER_SHA256_SUPPORTED + SHA256_FUNC_UPDATE_BLOCKS f, f_hw; + f = Sha256_UpdateBlocks; + f_hw = NULL; +@@ -483,7 +484,36 @@ void Sha256Prepare() + // printf("\n========== HW SHA256 ======== \n"); + f = f_hw = Sha256_UpdateBlocks_HW; + } +- g_FUNC_UPDATE_BLOCKS = f; +- g_FUNC_UPDATE_BLOCKS_HW = f_hw; ++ g_SHA256_FUNC_UPDATE_BLOCKS = f; ++ g_SHA256_FUNC_UPDATE_BLOCKS_HW = f_hw; + #endif + } ++ ++#undef S0 ++#undef S1 ++#undef s0 ++#undef s1 ++#undef Ch ++#undef Maj ++#undef W_MAIN ++#undef W_PRE ++#undef w ++#undef blk2_main ++#undef blk2 ++#undef T1 ++#undef T4 ++#undef T8 ++#undef R1_PRE ++#undef R1_MAIN ++#undef R2_MAIN ++#undef R4 ++#undef R4_PRE ++#undef R4_MAIN ++#undef R8 ++#undef R8_PRE ++#undef R8_MAIN ++#undef STEP_PRE ++#undef STEP_MAIN ++#undef Z7_SHA256_BIG_W ++#undef Z7_SHA256_UNROLL ++#undef Z7_COMPILER_SHA256_SUPPORTED +diff --git a/src/lzma/Sha256.h b/src/lzma/Sha256.h +index aa38501e5..9e0422320 100644 +--- a/src/lzma/Sha256.h ++++ b/src/lzma/Sha256.h +@@ -1,8 +1,8 @@ + /* Sha256.h -- SHA-256 Hash +-2021-01-01 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + +-#ifndef __7Z_SHA256_H +-#define __7Z_SHA256_H ++#ifndef ZIP7_INC_SHA256_H ++#define ZIP7_INC_SHA256_H + + #include "7zTypes.h" + +@@ -14,7 +14,7 @@ EXTERN_C_BEGIN + #define SHA256_BLOCK_SIZE (SHA256_NUM_BLOCK_WORDS * 4) + #define SHA256_DIGEST_SIZE (SHA256_NUM_DIGEST_WORDS * 4) + +-typedef void (MY_FAST_CALL *SHA256_FUNC_UPDATE_BLOCKS)(UInt32 state[8], const Byte *data, size_t numBlocks); ++typedef void (Z7_FASTCALL *SHA256_FUNC_UPDATE_BLOCKS)(UInt32 state[8], const Byte *data, size_t numBlocks); + + /* + if (the system supports different SHA256 code implementations) +@@ -34,7 +34,7 @@ typedef struct + { + SHA256_FUNC_UPDATE_BLOCKS func_UpdateBlocks; + UInt64 count; +- UInt64 __pad_2[2]; ++ UInt64 _pad_2[2]; + UInt32 state[SHA256_NUM_DIGEST_WORDS]; + + Byte buffer[SHA256_BLOCK_SIZE]; +@@ -62,7 +62,7 @@ void Sha256_Final(CSha256 *p, Byte *digest); + + + +-// void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); ++// void Z7_FASTCALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); + + /* + call Sha256Prepare() once at program start. +diff --git a/src/lzma/Sha256Opt.c b/src/lzma/Sha256Opt.c +index decc1382c..e4465e3e7 100644 +--- a/src/lzma/Sha256Opt.c ++++ b/src/lzma/Sha256Opt.c +@@ -1,7 +1,9 @@ + /* Sha256Opt.c -- SHA-256 optimized code for SHA-256 hardware instructions +-2021-04-01 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" ++#include "Compiler.h" ++#include "CpuArch.h" + + #if defined(_MSC_VER) + #if (_MSC_VER < 1900) && (_MSC_VER >= 1200) +@@ -9,41 +11,26 @@ + #endif + #endif + +-#include "CpuArch.h" +- + #ifdef MY_CPU_X86_OR_AMD64 +- #if defined(__clang__) +- #if (__clang_major__ >= 8) // fix that check ++ #if defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1600) // fix that check + #define USE_HW_SHA +- #ifndef __SHA__ +- #define ATTRIB_SHA __attribute__((__target__("sha,ssse3"))) +- #if defined(_MSC_VER) +- // SSSE3: for clang-cl: +- #include +- #define __SHA__ +- #endif +- #endif +- +- #endif +- #elif defined(__GNUC__) +- #if (__GNUC__ >= 8) // fix that check ++ #elif defined(Z7_LLVM_CLANG_VERSION) && (Z7_LLVM_CLANG_VERSION >= 30800) \ ++ || defined(Z7_APPLE_CLANG_VERSION) && (Z7_APPLE_CLANG_VERSION >= 50100) \ ++ || defined(Z7_GCC_VERSION) && (Z7_GCC_VERSION >= 40900) + #define USE_HW_SHA +- #ifndef __SHA__ ++ #if !defined(_INTEL_COMPILER) ++ // icc defines __GNUC__, but icc doesn't support __attribute__(__target__) ++ #if !defined(__SHA__) || !defined(__SSSE3__) + #define ATTRIB_SHA __attribute__((__target__("sha,ssse3"))) +- // #pragma GCC target("sha,ssse3") + #endif +- #endif +- #elif defined(__INTEL_COMPILER) +- #if (__INTEL_COMPILER >= 1800) // fix that check +- #define USE_HW_SHA +- #endif ++ #endif + #elif defined(_MSC_VER) + #ifdef USE_MY_MM + #define USE_VER_MIN 1300 + #else +- #define USE_VER_MIN 1910 ++ #define USE_VER_MIN 1900 + #endif +- #if _MSC_VER >= USE_VER_MIN ++ #if (_MSC_VER >= USE_VER_MIN) + #define USE_HW_SHA + #endif + #endif +@@ -52,16 +39,19 @@ + #ifdef USE_HW_SHA + + // #pragma message("Sha256 HW") +-// #include + +-#if !defined(_MSC_VER) || (_MSC_VER >= 1900) ++// sse/sse2/ssse3: ++#include ++// sha*: + #include +-#else +-#include + +-#if defined(_MSC_VER) && (_MSC_VER >= 1600) +-// #include +-#endif ++#if defined (__clang__) && defined(_MSC_VER) ++ // #if !defined(__SSSE3__) ++ // #endif ++ #if !defined(__SHA__) ++ #include ++ #endif ++#else + + #ifdef USE_MY_MM + #include "My_mm.h" +@@ -98,9 +88,9 @@ const UInt32 SHA256_K_ARRAY[64]; + #define K SHA256_K_ARRAY + + +-#define ADD_EPI32(dest, src) dest = _mm_add_epi32(dest, src); +-#define SHA256_MSG1(dest, src) dest = _mm_sha256msg1_epu32(dest, src); +-#define SHA25G_MSG2(dest, src) dest = _mm_sha256msg2_epu32(dest, src); ++#define ADD_EPI32(dest, src) dest = _mm_add_epi32(dest, src); ++#define SHA256_MSG1(dest, src) dest = _mm_sha256msg1_epu32(dest, src); ++#define SHA25G_MSG2(dest, src) dest = _mm_sha256msg2_epu32(dest, src); + + + #define LOAD_SHUFFLE(m, k) \ +@@ -112,7 +102,7 @@ const UInt32 SHA256_K_ARRAY[64]; + + #define SM2(g0, g1, g2, g3) \ + tmp = _mm_alignr_epi8(g1, g0, 4); \ +- ADD_EPI32(g2, tmp); \ ++ ADD_EPI32(g2, tmp) \ + SHA25G_MSG2(g2, g1); \ + + // #define LS0(k, g0, g1, g2, g3) LOAD_SHUFFLE(g0, k) +@@ -138,16 +128,16 @@ const UInt32 SHA256_K_ARRAY[64]; + // We use scheme with 3 rounds ahead for SHA256_MSG1 / 2 rounds ahead for SHA256_MSG2 + + #define R4(k, g0, g1, g2, g3, OP0, OP1) \ +- RND2_0(g0, k); \ +- OP0(g0, g1, g2, g3); \ +- RND2_1; \ +- OP1(g0, g1, g2, g3); \ ++ RND2_0(g0, k) \ ++ OP0(g0, g1, g2, g3) \ ++ RND2_1 \ ++ OP1(g0, g1, g2, g3) \ + + #define R16(k, OP0, OP1, OP2, OP3, OP4, OP5, OP6, OP7) \ +- R4 ( (k)*4+0, m0, m1, m2, m3, OP0, OP1 ) \ +- R4 ( (k)*4+1, m1, m2, m3, m0, OP2, OP3 ) \ +- R4 ( (k)*4+2, m2, m3, m0, m1, OP4, OP5 ) \ +- R4 ( (k)*4+3, m3, m0, m1, m2, OP6, OP7 ) \ ++ R4 ( (k)*4+0, m0,m1,m2,m3, OP0, OP1 ) \ ++ R4 ( (k)*4+1, m1,m2,m3,m0, OP2, OP3 ) \ ++ R4 ( (k)*4+2, m2,m3,m0,m1, OP4, OP5 ) \ ++ R4 ( (k)*4+3, m3,m0,m1,m2, OP6, OP7 ) \ + + #define PREPARE_STATE \ + tmp = _mm_shuffle_epi32(state0, 0x1B); /* abcd */ \ +@@ -157,11 +147,11 @@ const UInt32 SHA256_K_ARRAY[64]; + state1 = _mm_unpackhi_epi64(state1, tmp); /* abef */ \ + + +-void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); ++void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); + #ifdef ATTRIB_SHA + ATTRIB_SHA + #endif +-void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) ++void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) + { + const __m128i mask = _mm_set_epi32(0x0c0d0e0f, 0x08090a0b, 0x04050607, 0x00010203); + __m128i tmp; +@@ -192,13 +182,13 @@ void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size + + + +- R16 ( 0, NNN, NNN, SM1, NNN, SM1, SM2, SM1, SM2 ); +- R16 ( 1, SM1, SM2, SM1, SM2, SM1, SM2, SM1, SM2 ); +- R16 ( 2, SM1, SM2, SM1, SM2, SM1, SM2, SM1, SM2 ); +- R16 ( 3, SM1, SM2, NNN, SM2, NNN, NNN, NNN, NNN ); ++ R16 ( 0, NNN, NNN, SM1, NNN, SM1, SM2, SM1, SM2 ) ++ R16 ( 1, SM1, SM2, SM1, SM2, SM1, SM2, SM1, SM2 ) ++ R16 ( 2, SM1, SM2, SM1, SM2, SM1, SM2, SM1, SM2 ) ++ R16 ( 3, SM1, SM2, NNN, SM2, NNN, NNN, NNN, NNN ) + +- ADD_EPI32(state0, state0_save); +- ADD_EPI32(state1, state1_save); ++ ADD_EPI32(state0, state0_save) ++ ADD_EPI32(state1, state1_save) + + data += 64; + } +@@ -298,11 +288,11 @@ const UInt32 SHA256_K_ARRAY[64]; + R4 ( (k)*4+3, m3, m0, m1, m2, OP6, OP7 ) \ + + +-void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); ++void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); + #ifdef ATTRIB_SHA + ATTRIB_SHA + #endif +-void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) ++void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) + { + v128 state0, state1; + +@@ -353,12 +343,12 @@ void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size + // #include + + // #include "Sha256.h" +-void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); ++void Z7_FASTCALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); + + #pragma message("Sha256 HW-SW stub was used") + +-void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); +-void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) ++void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); ++void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) + { + Sha256_UpdateBlocks(state, data, numBlocks); + /* +@@ -371,3 +361,26 @@ void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size + } + + #endif ++ ++ ++ ++#undef K ++#undef RND2 ++#undef RND2_0 ++#undef RND2_1 ++ ++#undef MY_rev32_for_LE ++#undef NNN ++#undef LOAD_128 ++#undef STORE_128 ++#undef LOAD_SHUFFLE ++#undef SM1 ++#undef SM2 ++ ++#undef NNN ++#undef R4 ++#undef R16 ++#undef PREPARE_STATE ++#undef USE_HW_SHA ++#undef ATTRIB_SHA ++#undef USE_VER_MIN +diff --git a/src/lzma/Sort.h b/src/lzma/Sort.h +index 2e2963a23..1817b652f 100644 +--- a/src/lzma/Sort.h ++++ b/src/lzma/Sort.h +@@ -1,8 +1,8 @@ + /* Sort.h -- Sort functions +-2014-04-05 : Igor Pavlov : Public domain */ ++2023-03-05 : Igor Pavlov : Public domain */ + +-#ifndef __7Z_SORT_H +-#define __7Z_SORT_H ++#ifndef ZIP7_INC_SORT_H ++#define ZIP7_INC_SORT_H + + #include "7zTypes.h" + +diff --git a/src/lzma/Threads.c b/src/lzma/Threads.c +index 05bcc55ad..1a9f2bbb1 100644 +--- a/src/lzma/Threads.c ++++ b/src/lzma/Threads.c +@@ -1,5 +1,5 @@ + /* Threads.c -- multithreading library +-2021-12-21 : Igor Pavlov : Public domain */ ++2023-03-04 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -11,9 +11,9 @@ + + #include "Threads.h" + +-static WRes GetError() ++static WRes GetError(void) + { +- DWORD res = GetLastError(); ++ const DWORD res = GetLastError(); + return res ? (WRes)res : 1; + } + +@@ -173,6 +173,9 @@ WRes CriticalSection_Init(CCriticalSection *p) + Windows XP, 2003 : can raise a STATUS_NO_MEMORY exception + Windows Vista+ : no exceptions */ + #ifdef _MSC_VER ++ #ifdef __clang__ ++ #pragma GCC diagnostic ignored "-Wlanguage-extension-token" ++ #endif + __try + #endif + { +@@ -193,18 +196,26 @@ WRes CriticalSection_Init(CCriticalSection *p) + // ---------- POSIX ---------- + + #ifndef __APPLE__ +-#ifndef _7ZIP_AFFINITY_DISABLE ++#ifndef Z7_AFFINITY_DISABLE + // _GNU_SOURCE can be required for pthread_setaffinity_np() / CPU_ZERO / CPU_SET ++// clang < 3.6 : unknown warning group '-Wreserved-id-macro' ++// clang 3.6 - 12.01 : gives warning "macro name is a reserved identifier" ++// clang >= 13 : do not give warning ++#if !defined(_GNU_SOURCE) ++ #if defined(__clang__) && (__clang_major__ >= 4) && (__clang_major__ <= 12) ++ #pragma GCC diagnostic ignored "-Wreserved-id-macro" ++ #endif + #define _GNU_SOURCE +-#endif +-#endif ++#endif // !defined(_GNU_SOURCE) ++#endif // Z7_AFFINITY_DISABLE ++#endif // __APPLE__ + + #include "Threads.h" + + #include + #include + #include +-#ifdef _7ZIP_AFFINITY_SUPPORTED ++#ifdef Z7_AFFINITY_SUPPORTED + // #include + #endif + +@@ -212,15 +223,12 @@ WRes CriticalSection_Init(CCriticalSection *p) + // #include + // #define PRF(p) p + #define PRF(p) +- +-#define Print(s) PRF(printf("\n%s\n", s)) +- +-// #include ++#define Print(s) PRF(printf("\n%s\n", s);) + + WRes Thread_Create_With_CpuSet(CThread *p, THREAD_FUNC_TYPE func, LPVOID param, const CCpuSet *cpuSet) + { + // new thread in Posix probably inherits affinity from parrent thread +- Print("Thread_Create_With_CpuSet"); ++ Print("Thread_Create_With_CpuSet") + + pthread_attr_t attr; + int ret; +@@ -228,7 +236,7 @@ WRes Thread_Create_With_CpuSet(CThread *p, THREAD_FUNC_TYPE func, LPVOID param, + + p->_created = 0; + +- RINOK(pthread_attr_init(&attr)); ++ RINOK(pthread_attr_init(&attr)) + + ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); + +@@ -236,7 +244,7 @@ WRes Thread_Create_With_CpuSet(CThread *p, THREAD_FUNC_TYPE func, LPVOID param, + { + if (cpuSet) + { +- #ifdef _7ZIP_AFFINITY_SUPPORTED ++ #ifdef Z7_AFFINITY_SUPPORTED + + /* + printf("\n affinity :"); +@@ -292,7 +300,7 @@ WRes Thread_Create(CThread *p, THREAD_FUNC_TYPE func, LPVOID param) + + WRes Thread_Create_With_Affinity(CThread *p, THREAD_FUNC_TYPE func, LPVOID param, CAffinityMask affinity) + { +- Print("Thread_Create_WithAffinity"); ++ Print("Thread_Create_WithAffinity") + CCpuSet cs; + unsigned i; + CpuSet_Zero(&cs); +@@ -312,7 +320,7 @@ WRes Thread_Create_With_Affinity(CThread *p, THREAD_FUNC_TYPE func, LPVOID param + + WRes Thread_Close(CThread *p) + { +- // Print("Thread_Close"); ++ // Print("Thread_Close") + int ret; + if (!p->_created) + return 0; +@@ -326,7 +334,7 @@ WRes Thread_Close(CThread *p) + + WRes Thread_Wait_Close(CThread *p) + { +- // Print("Thread_Wait_Close"); ++ // Print("Thread_Wait_Close") + void *thread_return; + int ret; + if (!p->_created) +@@ -343,8 +351,8 @@ WRes Thread_Wait_Close(CThread *p) + + static WRes Event_Create(CEvent *p, int manualReset, int signaled) + { +- RINOK(pthread_mutex_init(&p->_mutex, NULL)); +- RINOK(pthread_cond_init(&p->_cond, NULL)); ++ RINOK(pthread_mutex_init(&p->_mutex, NULL)) ++ RINOK(pthread_cond_init(&p->_cond, NULL)) + p->_manual_reset = manualReset; + p->_state = (signaled ? True7z : False7z); + p->_created = 1; +@@ -363,7 +371,7 @@ WRes AutoResetEvent_CreateNotSignaled(CAutoResetEvent *p) + + WRes Event_Set(CEvent *p) + { +- RINOK(pthread_mutex_lock(&p->_mutex)); ++ RINOK(pthread_mutex_lock(&p->_mutex)) + p->_state = True7z; + int res1 = pthread_cond_broadcast(&p->_cond); + int res2 = pthread_mutex_unlock(&p->_mutex); +@@ -372,14 +380,14 @@ WRes Event_Set(CEvent *p) + + WRes Event_Reset(CEvent *p) + { +- RINOK(pthread_mutex_lock(&p->_mutex)); ++ RINOK(pthread_mutex_lock(&p->_mutex)) + p->_state = False7z; + return pthread_mutex_unlock(&p->_mutex); + } + + WRes Event_Wait(CEvent *p) + { +- RINOK(pthread_mutex_lock(&p->_mutex)); ++ RINOK(pthread_mutex_lock(&p->_mutex)) + while (p->_state == False7z) + { + // ETIMEDOUT +@@ -411,8 +419,8 @@ WRes Semaphore_Create(CSemaphore *p, UInt32 initCount, UInt32 maxCount) + { + if (initCount > maxCount || maxCount < 1) + return EINVAL; +- RINOK(pthread_mutex_init(&p->_mutex, NULL)); +- RINOK(pthread_cond_init(&p->_cond, NULL)); ++ RINOK(pthread_mutex_init(&p->_mutex, NULL)) ++ RINOK(pthread_cond_init(&p->_cond, NULL)) + p->_count = initCount; + p->_maxCount = maxCount; + p->_created = 1; +@@ -448,7 +456,7 @@ WRes Semaphore_ReleaseN(CSemaphore *p, UInt32 releaseCount) + if (releaseCount < 1) + return EINVAL; + +- RINOK(pthread_mutex_lock(&p->_mutex)); ++ RINOK(pthread_mutex_lock(&p->_mutex)) + + newCount = p->_count + releaseCount; + if (newCount > p->_maxCount) +@@ -458,13 +466,13 @@ WRes Semaphore_ReleaseN(CSemaphore *p, UInt32 releaseCount) + p->_count = newCount; + ret = pthread_cond_broadcast(&p->_cond); + } +- RINOK(pthread_mutex_unlock(&p->_mutex)); ++ RINOK(pthread_mutex_unlock(&p->_mutex)) + return ret; + } + + WRes Semaphore_Wait(CSemaphore *p) + { +- RINOK(pthread_mutex_lock(&p->_mutex)); ++ RINOK(pthread_mutex_lock(&p->_mutex)) + while (p->_count < 1) + { + pthread_cond_wait(&p->_cond, &p->_mutex); +@@ -489,7 +497,7 @@ WRes Semaphore_Close(CSemaphore *p) + + WRes CriticalSection_Init(CCriticalSection *p) + { +- // Print("CriticalSection_Init"); ++ // Print("CriticalSection_Init") + if (!p) + return EINTR; + return pthread_mutex_init(&p->_mutex, NULL); +@@ -497,7 +505,7 @@ WRes CriticalSection_Init(CCriticalSection *p) + + void CriticalSection_Enter(CCriticalSection *p) + { +- // Print("CriticalSection_Enter"); ++ // Print("CriticalSection_Enter") + if (p) + { + // int ret = +@@ -507,7 +515,7 @@ void CriticalSection_Enter(CCriticalSection *p) + + void CriticalSection_Leave(CCriticalSection *p) + { +- // Print("CriticalSection_Leave"); ++ // Print("CriticalSection_Leave") + if (p) + { + // int ret = +@@ -517,7 +525,7 @@ void CriticalSection_Leave(CCriticalSection *p) + + void CriticalSection_Delete(CCriticalSection *p) + { +- // Print("CriticalSection_Delete"); ++ // Print("CriticalSection_Delete") + if (p) + { + // int ret = +@@ -527,14 +535,28 @@ void CriticalSection_Delete(CCriticalSection *p) + + LONG InterlockedIncrement(LONG volatile *addend) + { +- // Print("InterlockedIncrement"); ++ // Print("InterlockedIncrement") + #ifdef USE_HACK_UNSAFE_ATOMIC + LONG val = *addend + 1; + *addend = val; + return val; + #else ++ ++ #if defined(__clang__) && (__clang_major__ >= 8) ++ #pragma GCC diagnostic ignored "-Watomic-implicit-seq-cst" ++ #endif + return __sync_add_and_fetch(addend, 1); + #endif + } + + #endif // _WIN32 ++ ++WRes AutoResetEvent_OptCreate_And_Reset(CAutoResetEvent *p) ++{ ++ if (Event_IsCreated(p)) ++ return Event_Reset(p); ++ return AutoResetEvent_CreateNotSignaled(p); ++} ++ ++#undef PRF ++#undef Print +diff --git a/src/lzma/Threads.h b/src/lzma/Threads.h +index 89ecb92be..4028464a3 100644 +--- a/src/lzma/Threads.h ++++ b/src/lzma/Threads.h +@@ -1,18 +1,19 @@ + /* Threads.h -- multithreading library +-2021-12-21 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + +-#ifndef __7Z_THREADS_H +-#define __7Z_THREADS_H ++#ifndef ZIP7_INC_THREADS_H ++#define ZIP7_INC_THREADS_H + + #ifdef _WIN32 +-#include ++#include "7zWindows.h" ++ + #else + + #if defined(__linux__) + #if !defined(__APPLE__) && !defined(_AIX) && !defined(__ANDROID__) +-#ifndef _7ZIP_AFFINITY_DISABLE +-#define _7ZIP_AFFINITY_SUPPORTED +-// #pragma message(" ==== _7ZIP_AFFINITY_SUPPORTED") ++#ifndef Z7_AFFINITY_DISABLE ++#define Z7_AFFINITY_SUPPORTED ++// #pragma message(" ==== Z7_AFFINITY_SUPPORTED") + // #define _GNU_SOURCE + #endif + #endif +@@ -33,7 +34,7 @@ WRes Handle_WaitObject(HANDLE h); + + typedef HANDLE CThread; + +-#define Thread_Construct(p) { *(p) = NULL; } ++#define Thread_CONSTRUCT(p) { *(p) = NULL; } + #define Thread_WasCreated(p) (*(p) != NULL) + #define Thread_Close(p) HandlePtr_Close(p) + // #define Thread_Wait(p) Handle_WaitObject(*(p)) +@@ -52,42 +53,46 @@ typedef + #endif + THREAD_FUNC_RET_TYPE; + ++#define THREAD_FUNC_RET_ZERO 0 ++ + typedef DWORD_PTR CAffinityMask; + typedef DWORD_PTR CCpuSet; + +-#define CpuSet_Zero(p) { *(p) = 0; } +-#define CpuSet_Set(p, cpu) { *(p) |= ((DWORD_PTR)1 << (cpu)); } ++#define CpuSet_Zero(p) *(p) = (0) ++#define CpuSet_Set(p, cpu) *(p) |= ((DWORD_PTR)1 << (cpu)) + + #else // _WIN32 + +-typedef struct _CThread ++typedef struct + { + pthread_t _tid; + int _created; + } CThread; + +-#define Thread_Construct(p) { (p)->_tid = 0; (p)->_created = 0; } +-#define Thread_WasCreated(p) ((p)->_created != 0) ++#define Thread_CONSTRUCT(p) { (p)->_tid = 0; (p)->_created = 0; } ++#define Thread_WasCreated(p) ((p)->_created != 0) + WRes Thread_Close(CThread *p); + // #define Thread_Wait Thread_Wait_Close + + typedef void * THREAD_FUNC_RET_TYPE; ++#define THREAD_FUNC_RET_ZERO NULL ++ + + typedef UInt64 CAffinityMask; + +-#ifdef _7ZIP_AFFINITY_SUPPORTED ++#ifdef Z7_AFFINITY_SUPPORTED + + typedef cpu_set_t CCpuSet; +-#define CpuSet_Zero(p) CPU_ZERO(p) +-#define CpuSet_Set(p, cpu) CPU_SET(cpu, p) +-#define CpuSet_IsSet(p, cpu) CPU_ISSET(cpu, p) ++#define CpuSet_Zero(p) CPU_ZERO(p) ++#define CpuSet_Set(p, cpu) CPU_SET(cpu, p) ++#define CpuSet_IsSet(p, cpu) CPU_ISSET(cpu, p) + + #else + + typedef UInt64 CCpuSet; +-#define CpuSet_Zero(p) { *(p) = 0; } +-#define CpuSet_Set(p, cpu) { *(p) |= ((UInt64)1 << (cpu)); } +-#define CpuSet_IsSet(p, cpu) ((*(p) & ((UInt64)1 << (cpu))) != 0) ++#define CpuSet_Zero(p) *(p) = (0) ++#define CpuSet_Set(p, cpu) *(p) |= ((UInt64)1 << (cpu)) ++#define CpuSet_IsSet(p, cpu) ((*(p) & ((UInt64)1 << (cpu))) != 0) + + #endif + +@@ -95,7 +100,7 @@ typedef UInt64 CCpuSet; + #endif // _WIN32 + + +-#define THREAD_FUNC_CALL_TYPE MY_STD_CALL ++#define THREAD_FUNC_CALL_TYPE Z7_STDCALL + + #if defined(_WIN32) && defined(__GNUC__) + /* GCC compiler for x86 32-bit uses the rule: +@@ -187,6 +192,7 @@ WRes ManualResetEvent_Create(CManualResetEvent *p, int signaled); + WRes ManualResetEvent_CreateNotSignaled(CManualResetEvent *p); + WRes AutoResetEvent_Create(CAutoResetEvent *p, int signaled); + WRes AutoResetEvent_CreateNotSignaled(CAutoResetEvent *p); ++ + WRes Event_Set(CEvent *p); + WRes Event_Reset(CEvent *p); + WRes Event_Wait(CEvent *p); +@@ -227,6 +233,8 @@ LONG InterlockedIncrement(LONG volatile *addend); + + #endif // _WIN32 + ++WRes AutoResetEvent_OptCreate_And_Reset(CAutoResetEvent *p); ++ + EXTERN_C_END + + #endif +diff --git a/src/lzma/Xz.c b/src/lzma/Xz.c +index 7c53b6007..4ad071060 100644 +--- a/src/lzma/Xz.c ++++ b/src/lzma/Xz.c +@@ -1,5 +1,5 @@ + /* Xz.c - Xz +-2021-02-09 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -70,7 +70,7 @@ int XzCheck_Final(CXzCheck *p, Byte *digest) + switch (p->mode) + { + case XZ_CHECK_CRC32: +- SetUi32(digest, CRC_GET_DIGEST(p->crc)); ++ SetUi32(digest, CRC_GET_DIGEST(p->crc)) + break; + case XZ_CHECK_CRC64: + { +diff --git a/src/lzma/Xz.h b/src/lzma/Xz.h +index 849b944bf..d5001f6ca 100644 +--- a/src/lzma/Xz.h ++++ b/src/lzma/Xz.h +@@ -1,21 +1,23 @@ + /* Xz.h - Xz interface +-2021-04-01 : Igor Pavlov : Public domain */ ++2023-04-13 : Igor Pavlov : Public domain */ + +-#ifndef __XZ_H +-#define __XZ_H ++#ifndef ZIP7_INC_XZ_H ++#define ZIP7_INC_XZ_H + + #include "Sha256.h" ++#include "Delta.h" + + EXTERN_C_BEGIN + + #define XZ_ID_Subblock 1 + #define XZ_ID_Delta 3 +-#define XZ_ID_X86 4 +-#define XZ_ID_PPC 5 +-#define XZ_ID_IA64 6 +-#define XZ_ID_ARM 7 +-#define XZ_ID_ARMT 8 ++#define XZ_ID_X86 4 ++#define XZ_ID_PPC 5 ++#define XZ_ID_IA64 6 ++#define XZ_ID_ARM 7 ++#define XZ_ID_ARMT 8 + #define XZ_ID_SPARC 9 ++#define XZ_ID_ARM64 0xa + #define XZ_ID_LZMA2 0x21 + + unsigned Xz_ReadVarInt(const Byte *p, size_t maxSize, UInt64 *value); +@@ -53,7 +55,7 @@ typedef struct + #define XzBlock_HasUnsupportedFlags(p) (((p)->flags & ~(XZ_BF_NUM_FILTERS_MASK | XZ_BF_PACK_SIZE | XZ_BF_UNPACK_SIZE)) != 0) + + SRes XzBlock_Parse(CXzBlock *p, const Byte *header); +-SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStream *inStream, BoolInt *isIndex, UInt32 *headerSizeRes); ++SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStreamPtr inStream, BoolInt *isIndex, UInt32 *headerSizeRes); + + /* ---------- xz stream ---------- */ + +@@ -101,7 +103,7 @@ typedef UInt16 CXzStreamFlags; + unsigned XzFlags_GetCheckSize(CXzStreamFlags f); + + SRes Xz_ParseHeader(CXzStreamFlags *p, const Byte *buf); +-SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStream *inStream); ++SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStreamPtr inStream); + + typedef struct + { +@@ -112,6 +114,7 @@ typedef struct + typedef struct + { + CXzStreamFlags flags; ++ // Byte _pad[6]; + size_t numBlocks; + CXzBlockSizes *blocks; + UInt64 startOffset; +@@ -134,7 +137,7 @@ typedef struct + + void Xzs_Construct(CXzs *p); + void Xzs_Free(CXzs *p, ISzAllocPtr alloc); +-SRes Xzs_ReadBackward(CXzs *p, ILookInStream *inStream, Int64 *startOffset, ICompressProgress *progress, ISzAllocPtr alloc); ++SRes Xzs_ReadBackward(CXzs *p, ILookInStreamPtr inStream, Int64 *startOffset, ICompressProgressPtr progress, ISzAllocPtr alloc); + + UInt64 Xzs_GetNumBlocks(const CXzs *p); + UInt64 Xzs_GetUnpackSize(const CXzs *p); +@@ -160,9 +163,9 @@ typedef enum + } ECoderFinishMode; + + +-typedef struct _IStateCoder ++typedef struct + { +- void *p; ++ void *p; // state object; + void (*Free)(void *p, ISzAllocPtr alloc); + SRes (*SetProps)(void *p, const Byte *props, size_t propSize, ISzAllocPtr alloc); + void (*Init)(void *p); +@@ -174,6 +177,20 @@ typedef struct _IStateCoder + } IStateCoder; + + ++typedef struct ++{ ++ UInt32 methodId; ++ UInt32 delta; ++ UInt32 ip; ++ UInt32 X86_State; ++ Byte delta_State[DELTA_STATE_SIZE]; ++} CXzBcFilterStateBase; ++ ++typedef SizeT (*Xz_Func_BcFilterStateBase_Filter)(CXzBcFilterStateBase *p, Byte *data, SizeT size); ++ ++SRes Xz_StateCoder_Bc_SetFromMethod_Func(IStateCoder *p, UInt64 id, ++ Xz_Func_BcFilterStateBase_Filter func, ISzAllocPtr alloc); ++ + + #define MIXCODER_NUM_FILTERS_MAX 4 + +@@ -422,7 +439,7 @@ typedef struct + size_t outStep_ST; // size of output buffer for Single-Thread decoding + BoolInt ignoreErrors; // if set to 1, the decoder can ignore some errors and it skips broken parts of data. + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + unsigned numThreads; // the number of threads for Multi-Thread decoding. if (umThreads == 1) it will use Single-thread decoding + size_t inBufSize_MT; // size of small input data buffers for Multi-Thread decoding. Big number of such small buffers can be created + size_t memUseMax; // the limit of total memory usage for Multi-Thread decoding. +@@ -432,8 +449,9 @@ typedef struct + + void XzDecMtProps_Init(CXzDecMtProps *p); + +- +-typedef void * CXzDecMtHandle; ++typedef struct CXzDecMt CXzDecMt; ++typedef CXzDecMt * CXzDecMtHandle; ++// Z7_DECLARE_HANDLE(CXzDecMtHandle) + + /* + alloc : XzDecMt uses CAlignOffsetAlloc internally for addresses allocated by (alloc). +@@ -503,14 +521,14 @@ SRes XzDecMt_Decode(CXzDecMtHandle p, + const CXzDecMtProps *props, + const UInt64 *outDataSize, // NULL means undefined + int finishMode, // 0 - partial unpacking is allowed, 1 - xz stream(s) must be finished +- ISeqOutStream *outStream, ++ ISeqOutStreamPtr outStream, + // Byte *outBuf, size_t *outBufSize, +- ISeqInStream *inStream, ++ ISeqInStreamPtr inStream, + // const Byte *inData, size_t inDataSize, + CXzStatInfo *stat, // out: decoding results and statistics + int *isMT, // out: 0 means that ST (Single-Thread) version was used + // 1 means that MT (Multi-Thread) version was used +- ICompressProgress *progress); ++ ICompressProgressPtr progress); + + EXTERN_C_END + +diff --git a/src/lzma/XzCrc64.c b/src/lzma/XzCrc64.c +index b6d02cbeb..c2fad6cda 100644 +--- a/src/lzma/XzCrc64.c ++++ b/src/lzma/XzCrc64.c +@@ -1,5 +1,5 @@ + /* XzCrc64.c -- CRC64 calculation +-2017-05-23 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -12,39 +12,30 @@ + #define CRC64_NUM_TABLES 4 + #else + #define CRC64_NUM_TABLES 5 +- #define CRC_UINT64_SWAP(v) \ +- ((v >> 56) \ +- | ((v >> 40) & ((UInt64)0xFF << 8)) \ +- | ((v >> 24) & ((UInt64)0xFF << 16)) \ +- | ((v >> 8) & ((UInt64)0xFF << 24)) \ +- | ((v << 8) & ((UInt64)0xFF << 32)) \ +- | ((v << 24) & ((UInt64)0xFF << 40)) \ +- | ((v << 40) & ((UInt64)0xFF << 48)) \ +- | ((v << 56))) + +- UInt64 MY_FAST_CALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table); ++ UInt64 Z7_FASTCALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table); + #endif + + #ifndef MY_CPU_BE +- UInt64 MY_FAST_CALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table); ++ UInt64 Z7_FASTCALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table); + #endif + +-typedef UInt64 (MY_FAST_CALL *CRC64_FUNC)(UInt64 v, const void *data, size_t size, const UInt64 *table); ++typedef UInt64 (Z7_FASTCALL *CRC64_FUNC)(UInt64 v, const void *data, size_t size, const UInt64 *table); + + static CRC64_FUNC g_Crc64Update; + UInt64 g_Crc64Table[256 * CRC64_NUM_TABLES]; + +-UInt64 MY_FAST_CALL Crc64Update(UInt64 v, const void *data, size_t size) ++UInt64 Z7_FASTCALL Crc64Update(UInt64 v, const void *data, size_t size) + { + return g_Crc64Update(v, data, size, g_Crc64Table); + } + +-UInt64 MY_FAST_CALL Crc64Calc(const void *data, size_t size) ++UInt64 Z7_FASTCALL Crc64Calc(const void *data, size_t size) + { + return g_Crc64Update(CRC64_INIT_VAL, data, size, g_Crc64Table) ^ CRC64_INIT_VAL; + } + +-void MY_FAST_CALL Crc64GenerateTable() ++void Z7_FASTCALL Crc64GenerateTable(void) + { + UInt32 i; + for (i = 0; i < 256; i++) +@@ -57,7 +48,7 @@ void MY_FAST_CALL Crc64GenerateTable() + } + for (i = 256; i < 256 * CRC64_NUM_TABLES; i++) + { +- UInt64 r = g_Crc64Table[(size_t)i - 256]; ++ const UInt64 r = g_Crc64Table[(size_t)i - 256]; + g_Crc64Table[i] = g_Crc64Table[r & 0xFF] ^ (r >> 8); + } + +@@ -76,11 +67,14 @@ void MY_FAST_CALL Crc64GenerateTable() + { + for (i = 256 * CRC64_NUM_TABLES - 1; i >= 256; i--) + { +- UInt64 x = g_Crc64Table[(size_t)i - 256]; +- g_Crc64Table[i] = CRC_UINT64_SWAP(x); ++ const UInt64 x = g_Crc64Table[(size_t)i - 256]; ++ g_Crc64Table[i] = Z7_BSWAP64(x); + } + g_Crc64Update = XzCrc64UpdateT1_BeT4; + } + } + #endif + } ++ ++#undef kCrc64Poly ++#undef CRC64_NUM_TABLES +diff --git a/src/lzma/XzCrc64.h b/src/lzma/XzCrc64.h +index 08dbc330c..ca46869a6 100644 +--- a/src/lzma/XzCrc64.h ++++ b/src/lzma/XzCrc64.h +@@ -1,8 +1,8 @@ + /* XzCrc64.h -- CRC64 calculation +-2013-01-18 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + +-#ifndef __XZ_CRC64_H +-#define __XZ_CRC64_H ++#ifndef ZIP7_INC_XZ_CRC64_H ++#define ZIP7_INC_XZ_CRC64_H + + #include + +@@ -12,14 +12,14 @@ EXTERN_C_BEGIN + + extern UInt64 g_Crc64Table[]; + +-void MY_FAST_CALL Crc64GenerateTable(void); ++void Z7_FASTCALL Crc64GenerateTable(void); + + #define CRC64_INIT_VAL UINT64_CONST(0xFFFFFFFFFFFFFFFF) + #define CRC64_GET_DIGEST(crc) ((crc) ^ CRC64_INIT_VAL) + #define CRC64_UPDATE_BYTE(crc, b) (g_Crc64Table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) + +-UInt64 MY_FAST_CALL Crc64Update(UInt64 crc, const void *data, size_t size); +-UInt64 MY_FAST_CALL Crc64Calc(const void *data, size_t size); ++UInt64 Z7_FASTCALL Crc64Update(UInt64 crc, const void *data, size_t size); ++UInt64 Z7_FASTCALL Crc64Calc(const void *data, size_t size); + + EXTERN_C_END + +diff --git a/src/lzma/XzCrc64Opt.c b/src/lzma/XzCrc64Opt.c +index 93a9ffff5..d03374c00 100644 +--- a/src/lzma/XzCrc64Opt.c ++++ b/src/lzma/XzCrc64Opt.c +@@ -1,5 +1,5 @@ + /* XzCrc64Opt.c -- CRC64 calculation +-2021-02-09 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -9,15 +9,15 @@ + + #define CRC64_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) + +-UInt64 MY_FAST_CALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table); +-UInt64 MY_FAST_CALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table) ++UInt64 Z7_FASTCALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table); ++UInt64 Z7_FASTCALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table) + { + const Byte *p = (const Byte *)data; + for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++) + v = CRC64_UPDATE_BYTE_2(v, *p); + for (; size >= 4; size -= 4, p += 4) + { +- UInt32 d = (UInt32)v ^ *(const UInt32 *)(const void *)p; ++ const UInt32 d = (UInt32)v ^ *(const UInt32 *)(const void *)p; + v = (v >> 32) + ^ (table + 0x300)[((d ) & 0xFF)] + ^ (table + 0x200)[((d >> 8) & 0xFF)] +@@ -34,29 +34,19 @@ UInt64 MY_FAST_CALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, con + + #ifndef MY_CPU_LE + +-#define CRC_UINT64_SWAP(v) \ +- ((v >> 56) \ +- | ((v >> 40) & ((UInt64)0xFF << 8)) \ +- | ((v >> 24) & ((UInt64)0xFF << 16)) \ +- | ((v >> 8) & ((UInt64)0xFF << 24)) \ +- | ((v << 8) & ((UInt64)0xFF << 32)) \ +- | ((v << 24) & ((UInt64)0xFF << 40)) \ +- | ((v << 40) & ((UInt64)0xFF << 48)) \ +- | ((v << 56))) +- + #define CRC64_UPDATE_BYTE_2_BE(crc, b) (table[(Byte)((crc) >> 56) ^ (b)] ^ ((crc) << 8)) + +-UInt64 MY_FAST_CALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table); +-UInt64 MY_FAST_CALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table) ++UInt64 Z7_FASTCALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table); ++UInt64 Z7_FASTCALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table) + { + const Byte *p = (const Byte *)data; + table += 0x100; +- v = CRC_UINT64_SWAP(v); ++ v = Z7_BSWAP64(v); + for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++) + v = CRC64_UPDATE_BYTE_2_BE(v, *p); + for (; size >= 4; size -= 4, p += 4) + { +- UInt32 d = (UInt32)(v >> 32) ^ *(const UInt32 *)(const void *)p; ++ const UInt32 d = (UInt32)(v >> 32) ^ *(const UInt32 *)(const void *)p; + v = (v << 32) + ^ (table + 0x000)[((d ) & 0xFF)] + ^ (table + 0x100)[((d >> 8) & 0xFF)] +@@ -65,7 +55,7 @@ UInt64 MY_FAST_CALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size + } + for (; size > 0; size--, p++) + v = CRC64_UPDATE_BYTE_2_BE(v, *p); +- return CRC_UINT64_SWAP(v); ++ return Z7_BSWAP64(v); + } + + #endif +diff --git a/src/lzma/XzDec.c b/src/lzma/XzDec.c +index f8c299411..15b1d82b4 100644 +--- a/src/lzma/XzDec.c ++++ b/src/lzma/XzDec.c +@@ -1,5 +1,5 @@ + /* XzDec.c -- Xz Decode +-2021-09-04 : Igor Pavlov : Public domain */ ++2023-04-13 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -67,7 +67,8 @@ unsigned Xz_ReadVarInt(const Byte *p, size_t maxSize, UInt64 *value) + return 0; + } + +-/* ---------- BraState ---------- */ ++ ++/* ---------- XzBcFilterState ---------- */ + + #define BRA_BUF_SIZE (1 << 14) + +@@ -76,27 +77,29 @@ typedef struct + size_t bufPos; + size_t bufConv; + size_t bufTotal; ++ Byte *buf; // must be aligned for 4 bytes ++ Xz_Func_BcFilterStateBase_Filter filter_func; ++ // int encodeMode; ++ CXzBcFilterStateBase base; ++ // Byte buf[BRA_BUF_SIZE]; ++} CXzBcFilterState; + +- int encodeMode; +- +- UInt32 methodId; +- UInt32 delta; +- UInt32 ip; +- UInt32 x86State; +- Byte deltaState[DELTA_STATE_SIZE]; + +- Byte buf[BRA_BUF_SIZE]; +-} CBraState; +- +-static void BraState_Free(void *pp, ISzAllocPtr alloc) ++static void XzBcFilterState_Free(void *pp, ISzAllocPtr alloc) + { +- ISzAlloc_Free(alloc, pp); ++ if (pp) ++ { ++ CXzBcFilterState *p = ((CXzBcFilterState *)pp); ++ ISzAlloc_Free(alloc, p->buf); ++ ISzAlloc_Free(alloc, pp); ++ } + } + +-static SRes BraState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAllocPtr alloc) ++ ++static SRes XzBcFilterState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAllocPtr alloc) + { +- CBraState *p = ((CBraState *)pp); +- UNUSED_VAR(alloc); ++ CXzBcFilterStateBase *p = &((CXzBcFilterState *)pp)->base; ++ UNUSED_VAR(alloc) + p->ip = 0; + if (p->methodId == XZ_ID_Delta) + { +@@ -114,6 +117,7 @@ static SRes BraState_SetProps(void *pp, const Byte *props, size_t propSize, ISzA + case XZ_ID_PPC: + case XZ_ID_ARM: + case XZ_ID_SPARC: ++ case XZ_ID_ARM64: + if ((v & 3) != 0) + return SZ_ERROR_UNSUPPORTED; + break; +@@ -134,73 +138,90 @@ static SRes BraState_SetProps(void *pp, const Byte *props, size_t propSize, ISzA + return SZ_OK; + } + +-static void BraState_Init(void *pp) ++ ++static void XzBcFilterState_Init(void *pp) + { +- CBraState *p = ((CBraState *)pp); ++ CXzBcFilterState *p = ((CXzBcFilterState *)pp); + p->bufPos = p->bufConv = p->bufTotal = 0; +- x86_Convert_Init(p->x86State); +- if (p->methodId == XZ_ID_Delta) +- Delta_Init(p->deltaState); ++ p->base.X86_State = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL; ++ if (p->base.methodId == XZ_ID_Delta) ++ Delta_Init(p->base.delta_State); + } + + +-#define CASE_BRA_CONV(isa) case XZ_ID_ ## isa: size = isa ## _Convert(data, size, p->ip, p->encodeMode); break; +- +-static SizeT BraState_Filter(void *pp, Byte *data, SizeT size) ++static const z7_Func_BranchConv g_Funcs_BranchConv_RISC_Dec[] = ++{ ++ Z7_BRANCH_CONV_DEC(PPC), ++ Z7_BRANCH_CONV_DEC(IA64), ++ Z7_BRANCH_CONV_DEC(ARM), ++ Z7_BRANCH_CONV_DEC(ARMT), ++ Z7_BRANCH_CONV_DEC(SPARC), ++ Z7_BRANCH_CONV_DEC(ARM64) ++}; ++ ++static SizeT XzBcFilterStateBase_Filter_Dec(CXzBcFilterStateBase *p, Byte *data, SizeT size) + { +- CBraState *p = ((CBraState *)pp); + switch (p->methodId) + { + case XZ_ID_Delta: +- if (p->encodeMode) +- Delta_Encode(p->deltaState, p->delta, data, size); +- else +- Delta_Decode(p->deltaState, p->delta, data, size); ++ Delta_Decode(p->delta_State, p->delta, data, size); + break; + case XZ_ID_X86: +- size = x86_Convert(data, size, p->ip, &p->x86State, p->encodeMode); ++ size = (SizeT)(z7_BranchConvSt_X86_Dec(data, size, p->ip, &p->X86_State) - data); ++ break; ++ default: ++ if (p->methodId >= XZ_ID_PPC) ++ { ++ const UInt32 i = p->methodId - XZ_ID_PPC; ++ if (i < Z7_ARRAY_SIZE(g_Funcs_BranchConv_RISC_Dec)) ++ size = (SizeT)(g_Funcs_BranchConv_RISC_Dec[i](data, size, p->ip) - data); ++ } + break; +- CASE_BRA_CONV(PPC) +- CASE_BRA_CONV(IA64) +- CASE_BRA_CONV(ARM) +- CASE_BRA_CONV(ARMT) +- CASE_BRA_CONV(SPARC) + } + p->ip += (UInt32)size; + return size; + } + + +-static SRes BraState_Code2(void *pp, ++static SizeT XzBcFilterState_Filter(void *pp, Byte *data, SizeT size) ++{ ++ CXzBcFilterState *p = ((CXzBcFilterState *)pp); ++ return p->filter_func(&p->base, data, size); ++} ++ ++ ++static SRes XzBcFilterState_Code2(void *pp, + Byte *dest, SizeT *destLen, + const Byte *src, SizeT *srcLen, int srcWasFinished, + ECoderFinishMode finishMode, + // int *wasFinished + ECoderStatus *status) + { +- CBraState *p = ((CBraState *)pp); ++ CXzBcFilterState *p = ((CXzBcFilterState *)pp); + SizeT destRem = *destLen; + SizeT srcRem = *srcLen; +- UNUSED_VAR(finishMode); ++ UNUSED_VAR(finishMode) + + *destLen = 0; + *srcLen = 0; + // *wasFinished = False7z; + *status = CODER_STATUS_NOT_FINISHED; + +- while (destRem > 0) ++ while (destRem != 0) + { +- if (p->bufPos != p->bufConv) + { + size_t size = p->bufConv - p->bufPos; +- if (size > destRem) +- size = destRem; +- memcpy(dest, p->buf + p->bufPos, size); +- p->bufPos += size; +- *destLen += size; +- dest += size; +- destRem -= size; +- continue; ++ if (size) ++ { ++ if (size > destRem) ++ size = destRem; ++ memcpy(dest, p->buf + p->bufPos, size); ++ p->bufPos += size; ++ *destLen += size; ++ dest += size; ++ destRem -= size; ++ continue; ++ } + } + + p->bufTotal -= p->bufPos; +@@ -220,7 +241,7 @@ static SRes BraState_Code2(void *pp, + if (p->bufTotal == 0) + break; + +- p->bufConv = BraState_Filter(pp, p->buf, p->bufTotal); ++ p->bufConv = p->filter_func(&p->base, p->buf, p->bufTotal); + + if (p->bufConv == 0) + { +@@ -240,27 +261,37 @@ static SRes BraState_Code2(void *pp, + } + + +-SRes BraState_SetFromMethod(IStateCoder *p, UInt64 id, int encodeMode, ISzAllocPtr alloc); +-SRes BraState_SetFromMethod(IStateCoder *p, UInt64 id, int encodeMode, ISzAllocPtr alloc) ++#define XZ_IS_SUPPORTED_FILTER_ID(id) \ ++ ((id) >= XZ_ID_Delta && (id) <= XZ_ID_ARM64) ++ ++SRes Xz_StateCoder_Bc_SetFromMethod_Func(IStateCoder *p, UInt64 id, ++ Xz_Func_BcFilterStateBase_Filter func, ISzAllocPtr alloc) + { +- CBraState *decoder; +- if (id < XZ_ID_Delta || id > XZ_ID_SPARC) ++ CXzBcFilterState *decoder; ++ if (!XZ_IS_SUPPORTED_FILTER_ID(id)) + return SZ_ERROR_UNSUPPORTED; +- decoder = (CBraState *)p->p; ++ decoder = (CXzBcFilterState *)p->p; + if (!decoder) + { +- decoder = (CBraState *)ISzAlloc_Alloc(alloc, sizeof(CBraState)); ++ decoder = (CXzBcFilterState *)ISzAlloc_Alloc(alloc, sizeof(CXzBcFilterState)); + if (!decoder) + return SZ_ERROR_MEM; ++ decoder->buf = ISzAlloc_Alloc(alloc, BRA_BUF_SIZE); ++ if (!decoder->buf) ++ { ++ ISzAlloc_Free(alloc, decoder); ++ return SZ_ERROR_MEM; ++ } + p->p = decoder; +- p->Free = BraState_Free; +- p->SetProps = BraState_SetProps; +- p->Init = BraState_Init; +- p->Code2 = BraState_Code2; +- p->Filter = BraState_Filter; ++ p->Free = XzBcFilterState_Free; ++ p->SetProps = XzBcFilterState_SetProps; ++ p->Init = XzBcFilterState_Init; ++ p->Code2 = XzBcFilterState_Code2; ++ p->Filter = XzBcFilterState_Filter; ++ decoder->filter_func = func; + } +- decoder->methodId = (UInt32)id; +- decoder->encodeMode = encodeMode; ++ decoder->base.methodId = (UInt32)id; ++ // decoder->encodeMode = encodeMode; + return SZ_OK; + } + +@@ -279,9 +310,9 @@ static void SbState_Free(void *pp, ISzAllocPtr alloc) + + static SRes SbState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAllocPtr alloc) + { +- UNUSED_VAR(pp); +- UNUSED_VAR(props); +- UNUSED_VAR(alloc); ++ UNUSED_VAR(pp) ++ UNUSED_VAR(props) ++ UNUSED_VAR(alloc) + return (propSize == 0) ? SZ_OK : SZ_ERROR_UNSUPPORTED; + } + +@@ -297,7 +328,7 @@ static SRes SbState_Code2(void *pp, Byte *dest, SizeT *destLen, const Byte *src, + { + CSbDec *p = (CSbDec *)pp; + SRes res; +- UNUSED_VAR(srcWasFinished); ++ UNUSED_VAR(srcWasFinished) + p->dest = dest; + p->destLen = *destLen; + p->src = src; +@@ -389,7 +420,7 @@ static SRes Lzma2State_Code2(void *pp, Byte *dest, SizeT *destLen, const Byte *s + ELzmaStatus status2; + /* ELzmaFinishMode fm = (finishMode == LZMA_FINISH_ANY) ? LZMA_FINISH_ANY : LZMA_FINISH_END; */ + SRes res; +- UNUSED_VAR(srcWasFinished); ++ UNUSED_VAR(srcWasFinished) + if (spec->outBufMode) + { + SizeT dicPos = spec->decoder.decoder.dicPos; +@@ -420,7 +451,7 @@ static SRes Lzma2State_SetFromMethod(IStateCoder *p, Byte *outBuf, size_t outBuf + p->Init = Lzma2State_Init; + p->Code2 = Lzma2State_Code2; + p->Filter = NULL; +- Lzma2Dec_Construct(&spec->decoder); ++ Lzma2Dec_CONSTRUCT(&spec->decoder) + } + spec->outBufMode = False7z; + if (outBuf) +@@ -519,7 +550,8 @@ static SRes MixCoder_SetFromMethod(CMixCoder *p, unsigned coderIndex, UInt64 met + } + if (coderIndex == 0) + return SZ_ERROR_UNSUPPORTED; +- return BraState_SetFromMethod(sc, methodId, 0, p->alloc); ++ return Xz_StateCoder_Bc_SetFromMethod_Func(sc, methodId, ++ XzBcFilterStateBase_Filter_Dec, p->alloc); + } + + +@@ -568,7 +600,7 @@ static SRes MixCoder_Code(CMixCoder *p, + SizeT destLen2, srcLen2; + int wasFinished; + +- PRF_STR("------- MixCoder Single ----------"); ++ PRF_STR("------- MixCoder Single ----------") + + srcLen2 = srcLenOrig; + destLen2 = destLenOrig; +@@ -615,14 +647,14 @@ static SRes MixCoder_Code(CMixCoder *p, + processed = coder->Filter(coder->p, p->outBuf, processed); + if (wasFinished || (destFinish && p->outWritten == destLenOrig)) + processed = p->outWritten; +- PRF_STR_INT("filter", i); ++ PRF_STR_INT("filter", i) + } + *destLen = processed; + } + return res; + } + +- PRF_STR("standard mix"); ++ PRF_STR("standard mix") + + if (p->numCoders != 1) + { +@@ -779,7 +811,7 @@ static BoolInt Xz_CheckFooter(CXzStreamFlags flags, UInt64 indexSize, const Byte + + static BoolInt XzBlock_AreSupportedFilters(const CXzBlock *p) + { +- unsigned numFilters = XzBlock_GetNumFilters(p) - 1; ++ const unsigned numFilters = XzBlock_GetNumFilters(p) - 1; + unsigned i; + { + const CXzFilter *f = &p->filters[numFilters]; +@@ -795,8 +827,7 @@ static BoolInt XzBlock_AreSupportedFilters(const CXzBlock *p) + if (f->propsSize != 1) + return False7z; + } +- else if (f->id < XZ_ID_Delta +- || f->id > XZ_ID_SPARC ++ else if (!XZ_IS_SUPPORTED_FILTER_ID(f->id) + || (f->propsSize != 0 && f->propsSize != 4)) + return False7z; + } +@@ -821,22 +852,24 @@ SRes XzBlock_Parse(CXzBlock *p, const Byte *header) + p->packSize = (UInt64)(Int64)-1; + if (XzBlock_HasPackSize(p)) + { +- READ_VARINT_AND_CHECK(header, pos, headerSize, &p->packSize); ++ READ_VARINT_AND_CHECK(header, pos, headerSize, &p->packSize) + if (p->packSize == 0 || p->packSize + headerSize >= (UInt64)1 << 63) + return SZ_ERROR_ARCHIVE; + } + + p->unpackSize = (UInt64)(Int64)-1; + if (XzBlock_HasUnpackSize(p)) +- READ_VARINT_AND_CHECK(header, pos, headerSize, &p->unpackSize); ++ { ++ READ_VARINT_AND_CHECK(header, pos, headerSize, &p->unpackSize) ++ } + + numFilters = XzBlock_GetNumFilters(p); + for (i = 0; i < numFilters; i++) + { + CXzFilter *filter = p->filters + i; + UInt64 size; +- READ_VARINT_AND_CHECK(header, pos, headerSize, &filter->id); +- READ_VARINT_AND_CHECK(header, pos, headerSize, &size); ++ READ_VARINT_AND_CHECK(header, pos, headerSize, &filter->id) ++ READ_VARINT_AND_CHECK(header, pos, headerSize, &size) + if (size > headerSize - pos || size > XZ_FILTER_PROPS_SIZE_MAX) + return SZ_ERROR_ARCHIVE; + filter->propsSize = (UInt32)size; +@@ -894,20 +927,20 @@ static SRes XzDecMix_Init(CMixCoder *p, const CXzBlock *block, Byte *outBuf, siz + MixCoder_Free(p); + for (i = 0; i < numFilters; i++) + { +- RINOK(MixCoder_SetFromMethod(p, i, block->filters[numFilters - 1 - i].id, outBuf, outBufSize)); ++ RINOK(MixCoder_SetFromMethod(p, i, block->filters[numFilters - 1 - i].id, outBuf, outBufSize)) + } + p->numCoders = numFilters; + } + else + { +- RINOK(MixCoder_ResetFromMethod(p, 0, block->filters[numFilters - 1].id, outBuf, outBufSize)); ++ RINOK(MixCoder_ResetFromMethod(p, 0, block->filters[numFilters - 1].id, outBuf, outBufSize)) + } + + for (i = 0; i < numFilters; i++) + { + const CXzFilter *f = &block->filters[numFilters - 1 - i]; + IStateCoder *sc = &p->coders[i]; +- RINOK(sc->SetProps(sc->p, f->props, f->propsSize, p->alloc)); ++ RINOK(sc->SetProps(sc->p, f->props, f->propsSize, p->alloc)) + } + + MixCoder_Init(p); +@@ -1054,14 +1087,14 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen, + (*destLen) += destLen2; + p->unpackSize += destLen2; + +- RINOK(res); ++ RINOK(res) + + if (*status != CODER_STATUS_FINISHED_WITH_MARK) + { + if (p->block.packSize == p->packSize + && *status == CODER_STATUS_NEEDS_MORE_INPUT) + { +- PRF_STR("CODER_STATUS_NEEDS_MORE_INPUT"); ++ PRF_STR("CODER_STATUS_NEEDS_MORE_INPUT") + *status = CODER_STATUS_NOT_SPECIFIED; + return SZ_ERROR_DATA; + } +@@ -1078,7 +1111,7 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen, + if ((p->block.packSize != (UInt64)(Int64)-1 && p->block.packSize != p->packSize) + || (p->block.unpackSize != (UInt64)(Int64)-1 && p->block.unpackSize != p->unpackSize)) + { +- PRF_STR("ERROR: block.size mismatch"); ++ PRF_STR("ERROR: block.size mismatch") + return SZ_ERROR_DATA; + } + } +@@ -1109,7 +1142,7 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen, + } + else + { +- RINOK(Xz_ParseHeader(&p->streamFlags, p->buf)); ++ RINOK(Xz_ParseHeader(&p->streamFlags, p->buf)) + p->numStartedStreams++; + p->indexSize = 0; + p->numBlocks = 0; +@@ -1155,7 +1188,7 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen, + } + else + { +- RINOK(XzBlock_Parse(&p->block, p->buf)); ++ RINOK(XzBlock_Parse(&p->block, p->buf)) + if (!XzBlock_AreSupportedFilters(&p->block)) + return SZ_ERROR_UNSUPPORTED; + p->numTotalBlocks++; +@@ -1168,7 +1201,7 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen, + p->headerParsedOk = True7z; + return SZ_OK; + } +- RINOK(XzDecMix_Init(&p->decoder, &p->block, p->outBuf, p->outBufSize)); ++ RINOK(XzDecMix_Init(&p->decoder, &p->block, p->outBuf, p->outBufSize)) + } + break; + } +@@ -1389,7 +1422,7 @@ UInt64 XzUnpacker_GetExtraSize(const CXzUnpacker *p) + + + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + #include "MtDec.h" + #endif + +@@ -1400,7 +1433,7 @@ void XzDecMtProps_Init(CXzDecMtProps *p) + p->outStep_ST = 1 << 20; + p->ignoreErrors = False7z; + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + p->numThreads = 1; + p->inBufSize_MT = 1 << 18; + p->memUseMax = sizeof(size_t) << 28; +@@ -1409,7 +1442,7 @@ void XzDecMtProps_Init(CXzDecMtProps *p) + + + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + + /* ---------- CXzDecMtThread ---------- */ + +@@ -1448,7 +1481,7 @@ typedef struct + + /* ---------- CXzDecMt ---------- */ + +-typedef struct ++struct CXzDecMt + { + CAlignOffsetAlloc alignOffsetAlloc; + ISzAllocPtr allocMid; +@@ -1456,9 +1489,9 @@ typedef struct + CXzDecMtProps props; + size_t unpackBlockMaxSize; + +- ISeqInStream *inStream; +- ISeqOutStream *outStream; +- ICompressProgress *progress; ++ ISeqInStreamPtr inStream; ++ ISeqOutStreamPtr outStream; ++ ICompressProgressPtr progress; + + BoolInt finishMode; + BoolInt outSize_Defined; +@@ -1481,7 +1514,7 @@ typedef struct + ECoderStatus status; + SRes codeRes; + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + BoolInt mainDecoderWasCalled; + // int statErrorDefined; + int finishedDecoderIndex; +@@ -1504,10 +1537,9 @@ typedef struct + + BoolInt mtc_WasConstructed; + CMtDec mtc; +- CXzDecMtThread coders[MTDEC__THREADS_MAX]; ++ CXzDecMtThread coders[MTDEC_THREADS_MAX]; + #endif +- +-} CXzDecMt; ++}; + + + +@@ -1535,11 +1567,11 @@ CXzDecMtHandle XzDecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid) + + XzDecMtProps_Init(&p->props); + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + p->mtc_WasConstructed = False7z; + { + unsigned i; +- for (i = 0; i < MTDEC__THREADS_MAX; i++) ++ for (i = 0; i < MTDEC_THREADS_MAX; i++) + { + CXzDecMtThread *coder = &p->coders[i]; + coder->dec_created = False7z; +@@ -1549,16 +1581,16 @@ CXzDecMtHandle XzDecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid) + } + #endif + +- return p; ++ return (CXzDecMtHandle)p; + } + + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + + static void XzDecMt_FreeOutBufs(CXzDecMt *p) + { + unsigned i; +- for (i = 0; i < MTDEC__THREADS_MAX; i++) ++ for (i = 0; i < MTDEC_THREADS_MAX; i++) + { + CXzDecMtThread *coder = &p->coders[i]; + if (coder->outBuf) +@@ -1595,13 +1627,15 @@ static void XzDecMt_FreeSt(CXzDecMt *p) + } + + +-void XzDecMt_Destroy(CXzDecMtHandle pp) ++// #define GET_CXzDecMt_p CXzDecMt *p = pp; ++ ++void XzDecMt_Destroy(CXzDecMtHandle p) + { +- CXzDecMt *p = (CXzDecMt *)pp; ++ // GET_CXzDecMt_p + + XzDecMt_FreeSt(p); + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + + if (p->mtc_WasConstructed) + { +@@ -1610,7 +1644,7 @@ void XzDecMt_Destroy(CXzDecMtHandle pp) + } + { + unsigned i; +- for (i = 0; i < MTDEC__THREADS_MAX; i++) ++ for (i = 0; i < MTDEC_THREADS_MAX; i++) + { + CXzDecMtThread *t = &p->coders[i]; + if (t->dec_created) +@@ -1625,12 +1659,12 @@ void XzDecMt_Destroy(CXzDecMtHandle pp) + + #endif + +- ISzAlloc_Free(p->alignOffsetAlloc.baseAlloc, pp); ++ ISzAlloc_Free(p->alignOffsetAlloc.baseAlloc, p); + } + + + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + + static void XzDecMt_Callback_Parse(void *obj, unsigned coderIndex, CMtDecCallbackInfo *cc) + { +@@ -1696,7 +1730,7 @@ static void XzDecMt_Callback_Parse(void *obj, unsigned coderIndex, CMtDecCallbac + coder->dec.parseMode = True7z; + coder->dec.headerParsedOk = False7z; + +- PRF_STR_INT("Parse", srcSize2); ++ PRF_STR_INT("Parse", srcSize2) + + res = XzUnpacker_Code(&coder->dec, + NULL, &destSize, +@@ -2071,7 +2105,7 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex, + } + data += cur; + size -= cur; +- // PRF_STR_INT("Written size =", size); ++ // PRF_STR_INT("Written size =", size) + if (size == 0) + break; + res = MtProgress_ProgressAdd(&me->mtc.mtProgress, 0, 0); +@@ -2087,7 +2121,7 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex, + return res; + } + +- RINOK(res); ++ RINOK(res) + + if (coder->inPreSize != coder->inCodeSize + || coder->blockPackTotal != coder->inCodeSize) +@@ -2106,13 +2140,13 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex, + // (coder->state == MTDEC_PARSE_END) means that there are no other working threads + // so we can use mtc variables without lock + +- PRF_STR_INT("Write MTDEC_PARSE_END", me->mtc.inProcessed); ++ PRF_STR_INT("Write MTDEC_PARSE_END", me->mtc.inProcessed) + + me->mtc.mtProgress.totalInSize = me->mtc.inProcessed; + { + CXzUnpacker *dec = &me->dec; + +- PRF_STR_INT("PostSingle", srcSize); ++ PRF_STR_INT("PostSingle", srcSize) + + { + size_t srcProcessed = srcSize; +@@ -2186,7 +2220,7 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex, + me->mtc.crossEnd = srcSize; + } + +- PRF_STR_INT("XZ_STATE_STREAM_HEADER crossEnd = ", (unsigned)me->mtc.crossEnd); ++ PRF_STR_INT("XZ_STATE_STREAM_HEADER crossEnd = ", (unsigned)me->mtc.crossEnd) + + return SZ_OK; + } +@@ -2277,7 +2311,7 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex, + UInt64 inDelta = me->mtc.inProcessed - inProgressPrev; + if (inDelta >= (1 << 22)) + { +- RINOK(MtProgress_Progress_ST(&me->mtc.mtProgress)); ++ RINOK(MtProgress_Progress_ST(&me->mtc.mtProgress)) + inProgressPrev = me->mtc.inProcessed; + } + } +@@ -2331,7 +2365,7 @@ void XzStatInfo_Clear(CXzStatInfo *p) + */ + + static SRes XzDecMt_Decode_ST(CXzDecMt *p +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + , BoolInt tMode + #endif + , CXzStatInfo *stat) +@@ -2343,7 +2377,7 @@ static SRes XzDecMt_Decode_ST(CXzDecMt *p + + CXzUnpacker *dec; + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + if (tMode) + { + XzDecMt_FreeOutBufs(p); +@@ -2400,7 +2434,7 @@ static SRes XzDecMt_Decode_ST(CXzDecMt *p + + if (inPos == inLim) + { +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + if (tMode) + { + inData = MtDec_Read(&p->mtc, &inLim); +@@ -2577,19 +2611,19 @@ static void XzStatInfo_SetStat(const CXzUnpacker *dec, + + + +-SRes XzDecMt_Decode(CXzDecMtHandle pp, ++SRes XzDecMt_Decode(CXzDecMtHandle p, + const CXzDecMtProps *props, + const UInt64 *outDataSize, int finishMode, +- ISeqOutStream *outStream, ++ ISeqOutStreamPtr outStream, + // Byte *outBuf, size_t *outBufSize, +- ISeqInStream *inStream, ++ ISeqInStreamPtr inStream, + // const Byte *inData, size_t inDataSize, + CXzStatInfo *stat, + int *isMT, +- ICompressProgress *progress) ++ ICompressProgressPtr progress) + { +- CXzDecMt *p = (CXzDecMt *)pp; +- #ifndef _7ZIP_ST ++ // GET_CXzDecMt_p ++ #ifndef Z7_ST + BoolInt tMode; + #endif + +@@ -2640,7 +2674,7 @@ SRes XzDecMt_Decode(CXzDecMtHandle pp, + */ + + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + + p->isBlockHeaderState_Parse = False7z; + p->isBlockHeaderState_Write = False7z; +@@ -2782,7 +2816,7 @@ SRes XzDecMt_Decode(CXzDecMtHandle pp, + return res; + } + +- PRF_STR("----- decoding ST -----"); ++ PRF_STR("----- decoding ST -----") + } + + #endif +@@ -2792,13 +2826,13 @@ SRes XzDecMt_Decode(CXzDecMtHandle pp, + + { + SRes res = XzDecMt_Decode_ST(p +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + , tMode + #endif + , stat + ); + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + // we must set error code from MT decoding at first + if (p->mainErrorCode != SZ_OK) + stat->DecodeRes = p->mainErrorCode; +@@ -2835,3 +2869,7 @@ SRes XzDecMt_Decode(CXzDecMtHandle pp, + return res; + } + } ++ ++#undef PRF ++#undef PRF_STR ++#undef PRF_STR_INT_2 +diff --git a/src/lzma/XzEnc.c b/src/lzma/XzEnc.c +index 4c77ccaef..a715609d8 100644 +--- a/src/lzma/XzEnc.c ++++ b/src/lzma/XzEnc.c +@@ -1,5 +1,5 @@ + /* XzEnc.c -- Xz Encode +-2021-04-01 : Igor Pavlov : Public domain */ ++2023-04-13 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -18,13 +18,13 @@ + + #include "XzEnc.h" + +-// #define _7ZIP_ST ++// #define Z7_ST + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + #include "MtCoder.h" + #else +-#define MTCODER__THREADS_MAX 1 +-#define MTCODER__BLOCKS_MAX 1 ++#define MTCODER_THREADS_MAX 1 ++#define MTCODER_BLOCKS_MAX 1 + #endif + + #define XZ_GET_PAD_SIZE(dataSize) ((4 - ((unsigned)(dataSize) & 3)) & 3) +@@ -35,25 +35,25 @@ + #define XZ_GET_ESTIMATED_BLOCK_TOTAL_PACK_SIZE(unpackSize) (XZ_BLOCK_HEADER_SIZE_MAX + XZ_GET_MAX_BLOCK_PACK_SIZE(unpackSize)) + + +-#define XzBlock_ClearFlags(p) (p)->flags = 0; +-#define XzBlock_SetNumFilters(p, n) (p)->flags = (Byte)((p)->flags | ((n) - 1)); ++// #define XzBlock_ClearFlags(p) (p)->flags = 0; ++#define XzBlock_ClearFlags_SetNumFilters(p, n) (p)->flags = (Byte)((n) - 1); + #define XzBlock_SetHasPackSize(p) (p)->flags |= XZ_BF_PACK_SIZE; + #define XzBlock_SetHasUnpackSize(p) (p)->flags |= XZ_BF_UNPACK_SIZE; + + +-static SRes WriteBytes(ISeqOutStream *s, const void *buf, size_t size) ++static SRes WriteBytes(ISeqOutStreamPtr s, const void *buf, size_t size) + { + return (ISeqOutStream_Write(s, buf, size) == size) ? SZ_OK : SZ_ERROR_WRITE; + } + +-static SRes WriteBytesUpdateCrc(ISeqOutStream *s, const void *buf, size_t size, UInt32 *crc) ++static SRes WriteBytes_UpdateCrc(ISeqOutStreamPtr s, const void *buf, size_t size, UInt32 *crc) + { + *crc = CrcUpdate(*crc, buf, size); + return WriteBytes(s, buf, size); + } + + +-static SRes Xz_WriteHeader(CXzStreamFlags f, ISeqOutStream *s) ++static SRes Xz_WriteHeader(CXzStreamFlags f, ISeqOutStreamPtr s) + { + UInt32 crc; + Byte header[XZ_STREAM_HEADER_SIZE]; +@@ -61,12 +61,12 @@ static SRes Xz_WriteHeader(CXzStreamFlags f, ISeqOutStream *s) + header[XZ_SIG_SIZE] = (Byte)(f >> 8); + header[XZ_SIG_SIZE + 1] = (Byte)(f & 0xFF); + crc = CrcCalc(header + XZ_SIG_SIZE, XZ_STREAM_FLAGS_SIZE); +- SetUi32(header + XZ_SIG_SIZE + XZ_STREAM_FLAGS_SIZE, crc); ++ SetUi32(header + XZ_SIG_SIZE + XZ_STREAM_FLAGS_SIZE, crc) + return WriteBytes(s, header, XZ_STREAM_HEADER_SIZE); + } + + +-static SRes XzBlock_WriteHeader(const CXzBlock *p, ISeqOutStream *s) ++static SRes XzBlock_WriteHeader(const CXzBlock *p, ISeqOutStreamPtr s) + { + Byte header[XZ_BLOCK_HEADER_SIZE_MAX]; + +@@ -91,7 +91,7 @@ static SRes XzBlock_WriteHeader(const CXzBlock *p, ISeqOutStream *s) + header[pos++] = 0; + + header[0] = (Byte)(pos >> 2); +- SetUi32(header + pos, CrcCalc(header, pos)); ++ SetUi32(header + pos, CrcCalc(header, pos)) + return WriteBytes(s, header, pos + 4); + } + +@@ -182,7 +182,7 @@ static SRes XzEncIndex_AddIndexRecord(CXzEncIndex *p, UInt64 unpackSize, UInt64 + size_t newSize = p->allocated * 2 + 16 * 2; + if (newSize < p->size + pos) + return SZ_ERROR_MEM; +- RINOK(XzEncIndex_ReAlloc(p, newSize, alloc)); ++ RINOK(XzEncIndex_ReAlloc(p, newSize, alloc)) + } + memcpy(p->blocks + p->size, buf, pos); + p->size += pos; +@@ -191,7 +191,7 @@ static SRes XzEncIndex_AddIndexRecord(CXzEncIndex *p, UInt64 unpackSize, UInt64 + } + + +-static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, ISeqOutStream *s) ++static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, ISeqOutStreamPtr s) + { + Byte buf[32]; + UInt64 globalPos; +@@ -200,8 +200,8 @@ static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, I + + globalPos = pos; + buf[0] = 0; +- RINOK(WriteBytesUpdateCrc(s, buf, pos, &crc)); +- RINOK(WriteBytesUpdateCrc(s, p->blocks, p->size, &crc)); ++ RINOK(WriteBytes_UpdateCrc(s, buf, pos, &crc)) ++ RINOK(WriteBytes_UpdateCrc(s, p->blocks, p->size, &crc)) + globalPos += p->size; + + pos = XZ_GET_PAD_SIZE(globalPos); +@@ -211,12 +211,12 @@ static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, I + globalPos += pos; + + crc = CrcUpdate(crc, buf + 4 - pos, pos); +- SetUi32(buf + 4, CRC_GET_DIGEST(crc)); ++ SetUi32(buf + 4, CRC_GET_DIGEST(crc)) + +- SetUi32(buf + 8 + 4, (UInt32)(globalPos >> 2)); ++ SetUi32(buf + 8 + 4, (UInt32)(globalPos >> 2)) + buf[8 + 8] = (Byte)(flags >> 8); + buf[8 + 9] = (Byte)(flags & 0xFF); +- SetUi32(buf + 8, CrcCalc(buf + 8 + 4, 6)); ++ SetUi32(buf + 8, CrcCalc(buf + 8 + 4, 6)) + buf[8 + 10] = XZ_FOOTER_SIG_0; + buf[8 + 11] = XZ_FOOTER_SIG_1; + +@@ -230,7 +230,7 @@ static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, I + typedef struct + { + ISeqInStream vt; +- ISeqInStream *realStream; ++ ISeqInStreamPtr realStream; + const Byte *data; + UInt64 limit; + UInt64 processed; +@@ -251,9 +251,9 @@ static void SeqCheckInStream_GetDigest(CSeqCheckInStream *p, Byte *digest) + XzCheck_Final(&p->check, digest); + } + +-static SRes SeqCheckInStream_Read(const ISeqInStream *pp, void *data, size_t *size) ++static SRes SeqCheckInStream_Read(ISeqInStreamPtr pp, void *data, size_t *size) + { +- CSeqCheckInStream *p = CONTAINER_FROM_VTBL(pp, CSeqCheckInStream, vt); ++ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeqCheckInStream) + size_t size2 = *size; + SRes res = SZ_OK; + +@@ -285,15 +285,15 @@ static SRes SeqCheckInStream_Read(const ISeqInStream *pp, void *data, size_t *si + typedef struct + { + ISeqOutStream vt; +- ISeqOutStream *realStream; ++ ISeqOutStreamPtr realStream; + Byte *outBuf; + size_t outBufLimit; + UInt64 processed; + } CSeqSizeOutStream; + +-static size_t SeqSizeOutStream_Write(const ISeqOutStream *pp, const void *data, size_t size) ++static size_t SeqSizeOutStream_Write(ISeqOutStreamPtr pp, const void *data, size_t size) + { +- CSeqSizeOutStream *p = CONTAINER_FROM_VTBL(pp, CSeqSizeOutStream, vt); ++ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeqSizeOutStream) + if (p->realStream) + size = ISeqOutStream_Write(p->realStream, data, size); + else +@@ -313,8 +313,8 @@ static size_t SeqSizeOutStream_Write(const ISeqOutStream *pp, const void *data, + + typedef struct + { +- ISeqInStream p; +- ISeqInStream *realStream; ++ ISeqInStream vt; ++ ISeqInStreamPtr realStream; + IStateCoder StateCoder; + Byte *buf; + size_t curPos; +@@ -323,7 +323,39 @@ typedef struct + } CSeqInFilter; + + +-SRes BraState_SetFromMethod(IStateCoder *p, UInt64 id, int encodeMode, ISzAllocPtr alloc); ++static const z7_Func_BranchConv g_Funcs_BranchConv_RISC_Enc[] = ++{ ++ Z7_BRANCH_CONV_ENC(PPC), ++ Z7_BRANCH_CONV_ENC(IA64), ++ Z7_BRANCH_CONV_ENC(ARM), ++ Z7_BRANCH_CONV_ENC(ARMT), ++ Z7_BRANCH_CONV_ENC(SPARC), ++ Z7_BRANCH_CONV_ENC(ARM64) ++}; ++ ++static SizeT XzBcFilterStateBase_Filter_Enc(CXzBcFilterStateBase *p, Byte *data, SizeT size) ++{ ++ switch (p->methodId) ++ { ++ case XZ_ID_Delta: ++ Delta_Encode(p->delta_State, p->delta, data, size); ++ break; ++ case XZ_ID_X86: ++ size = (SizeT)(z7_BranchConvSt_X86_Enc(data, size, p->ip, &p->X86_State) - data); ++ break; ++ default: ++ if (p->methodId >= XZ_ID_PPC) ++ { ++ const UInt32 i = p->methodId - XZ_ID_PPC; ++ if (i < Z7_ARRAY_SIZE(g_Funcs_BranchConv_RISC_Enc)) ++ size = (SizeT)(g_Funcs_BranchConv_RISC_Enc[i](data, size, p->ip) - data); ++ } ++ break; ++ } ++ p->ip += (UInt32)size; ++ return size; ++} ++ + + static SRes SeqInFilter_Init(CSeqInFilter *p, const CXzFilter *props, ISzAllocPtr alloc) + { +@@ -335,17 +367,17 @@ static SRes SeqInFilter_Init(CSeqInFilter *p, const CXzFilter *props, ISzAllocPt + } + p->curPos = p->endPos = 0; + p->srcWasFinished = 0; +- RINOK(BraState_SetFromMethod(&p->StateCoder, props->id, 1, alloc)); +- RINOK(p->StateCoder.SetProps(p->StateCoder.p, props->props, props->propsSize, alloc)); ++ RINOK(Xz_StateCoder_Bc_SetFromMethod_Func(&p->StateCoder, props->id, XzBcFilterStateBase_Filter_Enc, alloc)) ++ RINOK(p->StateCoder.SetProps(p->StateCoder.p, props->props, props->propsSize, alloc)) + p->StateCoder.Init(p->StateCoder.p); + return SZ_OK; + } + + +-static SRes SeqInFilter_Read(const ISeqInStream *pp, void *data, size_t *size) ++static SRes SeqInFilter_Read(ISeqInStreamPtr pp, void *data, size_t *size) + { +- CSeqInFilter *p = CONTAINER_FROM_VTBL(pp, CSeqInFilter, p); +- size_t sizeOriginal = *size; ++ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeqInFilter) ++ const size_t sizeOriginal = *size; + if (sizeOriginal == 0) + return SZ_OK; + *size = 0; +@@ -356,7 +388,7 @@ static SRes SeqInFilter_Read(const ISeqInStream *pp, void *data, size_t *size) + { + p->curPos = 0; + p->endPos = FILTER_BUF_SIZE; +- RINOK(ISeqInStream_Read(p->realStream, p->buf, &p->endPos)); ++ RINOK(ISeqInStream_Read(p->realStream, p->buf, &p->endPos)) + if (p->endPos == 0) + p->srcWasFinished = 1; + } +@@ -381,7 +413,7 @@ static void SeqInFilter_Construct(CSeqInFilter *p) + { + p->buf = NULL; + p->StateCoder.p = NULL; +- p->p.Read = SeqInFilter_Read; ++ p->vt.Read = SeqInFilter_Read; + } + + static void SeqInFilter_Free(CSeqInFilter *p, ISzAllocPtr alloc) +@@ -406,13 +438,13 @@ static void SeqInFilter_Free(CSeqInFilter *p, ISzAllocPtr alloc) + typedef struct + { + ISeqInStream vt; +- ISeqInStream *inStream; ++ ISeqInStreamPtr inStream; + CSbEnc enc; + } CSbEncInStream; + +-static SRes SbEncInStream_Read(const ISeqInStream *pp, void *data, size_t *size) ++static SRes SbEncInStream_Read(ISeqInStreamPtr pp, void *data, size_t *size) + { +- CSbEncInStream *p = CONTAINER_FROM_VTBL(pp, CSbEncInStream, vt); ++ CSbEncInStream *p = Z7_CONTAINER_FROM_VTBL(pp, CSbEncInStream, vt); + size_t sizeOriginal = *size; + if (sizeOriginal == 0) + return SZ_OK; +@@ -422,7 +454,7 @@ static SRes SbEncInStream_Read(const ISeqInStream *pp, void *data, size_t *size) + if (p->enc.needRead && !p->enc.readWasFinished) + { + size_t processed = p->enc.needReadSizeMax; +- RINOK(p->inStream->Read(p->inStream, p->enc.buf + p->enc.readPos, &processed)); ++ RINOK(p->inStream->Read(p->inStream, p->enc.buf + p->enc.readPos, &processed)) + p->enc.readPos += processed; + if (processed == 0) + { +@@ -433,7 +465,7 @@ static SRes SbEncInStream_Read(const ISeqInStream *pp, void *data, size_t *size) + } + + *size = sizeOriginal; +- RINOK(SbEnc_Read(&p->enc, data, size)); ++ RINOK(SbEnc_Read(&p->enc, data, size)) + if (*size != 0 || !p->enc.needRead) + return SZ_OK; + } +@@ -473,7 +505,7 @@ void XzFilterProps_Init(CXzFilterProps *p) + void XzProps_Init(CXzProps *p) + { + p->checkId = XZ_CHECK_CRC32; +- p->blockSize = XZ_PROPS__BLOCK_SIZE__AUTO; ++ p->blockSize = XZ_PROPS_BLOCK_SIZE_AUTO; + p->numBlockThreads_Reduced = -1; + p->numBlockThreads_Max = -1; + p->numTotalThreads = -1; +@@ -502,8 +534,8 @@ static void XzEncProps_Normalize_Fixed(CXzProps *p) + t2 = p->numBlockThreads_Max; + t3 = p->numTotalThreads; + +- if (t2 > MTCODER__THREADS_MAX) +- t2 = MTCODER__THREADS_MAX; ++ if (t2 > MTCODER_THREADS_MAX) ++ t2 = MTCODER_THREADS_MAX; + + if (t3 <= 0) + { +@@ -519,8 +551,8 @@ static void XzEncProps_Normalize_Fixed(CXzProps *p) + t1 = 1; + t2 = t3; + } +- if (t2 > MTCODER__THREADS_MAX) +- t2 = MTCODER__THREADS_MAX; ++ if (t2 > MTCODER_THREADS_MAX) ++ t2 = MTCODER_THREADS_MAX; + } + else if (t1 <= 0) + { +@@ -571,7 +603,7 @@ static void XzProps_Normalize(CXzProps *p) + /* we normalize xzProps properties, but we normalize only some of CXzProps::lzma2Props properties. + Lzma2Enc_SetProps() will normalize lzma2Props later. */ + +- if (p->blockSize == XZ_PROPS__BLOCK_SIZE__SOLID) ++ if (p->blockSize == XZ_PROPS_BLOCK_SIZE_SOLID) + { + p->lzma2Props.lzmaProps.reduceSize = p->reduceSize; + p->numBlockThreads_Reduced = 1; +@@ -583,15 +615,15 @@ static void XzProps_Normalize(CXzProps *p) + else + { + CLzma2EncProps *lzma2 = &p->lzma2Props; +- if (p->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO) ++ if (p->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO) + { + // xz-auto + p->lzma2Props.lzmaProps.reduceSize = p->reduceSize; + +- if (lzma2->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID) ++ if (lzma2->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID) + { + // if (xz-auto && lzma2-solid) - we use solid for both +- p->blockSize = XZ_PROPS__BLOCK_SIZE__SOLID; ++ p->blockSize = XZ_PROPS_BLOCK_SIZE_SOLID; + p->numBlockThreads_Reduced = 1; + p->numBlockThreads_Max = 1; + if (p->lzma2Props.numTotalThreads <= 0) +@@ -610,9 +642,9 @@ static void XzProps_Normalize(CXzProps *p) + p->blockSize = tp.blockSize; // fixed or solid + p->numBlockThreads_Reduced = tp.numBlockThreads_Reduced; + p->numBlockThreads_Max = tp.numBlockThreads_Max; +- if (lzma2->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO) +- lzma2->blockSize = tp.blockSize; // fixed or solid, LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID +- if (lzma2->lzmaProps.reduceSize > tp.blockSize && tp.blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID) ++ if (lzma2->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO) ++ lzma2->blockSize = tp.blockSize; // fixed or solid, LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID ++ if (lzma2->lzmaProps.reduceSize > tp.blockSize && tp.blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID) + lzma2->lzmaProps.reduceSize = tp.blockSize; + lzma2->numBlockThreads_Reduced = 1; + lzma2->numBlockThreads_Max = 1; +@@ -631,9 +663,9 @@ static void XzProps_Normalize(CXzProps *p) + r = p->blockSize; + lzma2->lzmaProps.reduceSize = r; + } +- if (lzma2->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO) +- lzma2->blockSize = LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID; +- else if (lzma2->blockSize > p->blockSize && lzma2->blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID) ++ if (lzma2->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO) ++ lzma2->blockSize = LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID; ++ else if (lzma2->blockSize > p->blockSize && lzma2->blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID) + lzma2->blockSize = p->blockSize; + + XzEncProps_Normalize_Fixed(p); +@@ -704,17 +736,17 @@ typedef struct + static SRes Xz_CompressBlock( + CLzma2WithFilters *lzmaf, + +- ISeqOutStream *outStream, ++ ISeqOutStreamPtr outStream, + Byte *outBufHeader, + Byte *outBufData, size_t outBufDataLimit, + +- ISeqInStream *inStream, ++ ISeqInStreamPtr inStream, + // UInt64 expectedSize, + const Byte *inBuf, // used if (!inStream) + size_t inBufSize, // used if (!inStream), it's block size, props->blockSize is ignored + + const CXzProps *props, +- ICompressProgress *progress, ++ ICompressProgressPtr progress, + int *inStreamFinished, /* only for inStream version */ + CXzEncBlockInfo *blockSizes, + ISzAllocPtr alloc, +@@ -731,12 +763,12 @@ static SRes Xz_CompressBlock( + + *inStreamFinished = False7z; + +- RINOK(Lzma2WithFilters_Create(lzmaf, alloc, allocBig)); ++ RINOK(Lzma2WithFilters_Create(lzmaf, alloc, allocBig)) + +- RINOK(Lzma2Enc_SetProps(lzmaf->lzma2, &props->lzma2Props)); ++ RINOK(Lzma2Enc_SetProps(lzmaf->lzma2, &props->lzma2Props)) + +- XzBlock_ClearFlags(&block); +- XzBlock_SetNumFilters(&block, 1 + (fp ? 1 : 0)); ++ // XzBlock_ClearFlags(&block) ++ XzBlock_ClearFlags_SetNumFilters(&block, 1 + (fp ? 1 : 0)) + + if (fp) + { +@@ -752,7 +784,7 @@ static SRes Xz_CompressBlock( + else if (fp->ipDefined) + { + Byte *ptr = filter->props; +- SetUi32(ptr, fp->ip); ++ SetUi32(ptr, fp->ip) + filter->propsSize = 4; + } + } +@@ -777,13 +809,13 @@ static SRes Xz_CompressBlock( + if (props->blockSize != (UInt64)(Int64)-1) + if (expectedSize > props->blockSize) + block.unpackSize = props->blockSize; +- XzBlock_SetHasUnpackSize(&block); ++ XzBlock_SetHasUnpackSize(&block) + } + */ + + if (outStream) + { +- RINOK(XzBlock_WriteHeader(&block, &seqSizeOutStream.vt)); ++ RINOK(XzBlock_WriteHeader(&block, &seqSizeOutStream.vt)) + } + + checkInStream.vt.Read = SeqCheckInStream_Read; +@@ -801,13 +833,13 @@ static SRes Xz_CompressBlock( + if (fp->id == XZ_ID_Subblock) + { + lzmaf->sb.inStream = &checkInStream.vt; +- RINOK(SbEncInStream_Init(&lzmaf->sb)); ++ RINOK(SbEncInStream_Init(&lzmaf->sb)) + } + else + #endif + { + lzmaf->filter.realStream = &checkInStream.vt; +- RINOK(SeqInFilter_Init(&lzmaf->filter, filter, alloc)); ++ RINOK(SeqInFilter_Init(&lzmaf->filter, filter, alloc)) + } + } + +@@ -841,7 +873,7 @@ static SRes Xz_CompressBlock( + #ifdef USE_SUBBLOCK + (fp->id == XZ_ID_Subblock) ? &lzmaf->sb.vt: + #endif +- &lzmaf->filter.p) : ++ &lzmaf->filter.vt) : + &checkInStream.vt) : NULL, + + useStream ? NULL : inBuf, +@@ -852,7 +884,7 @@ static SRes Xz_CompressBlock( + if (outBuf) + seqSizeOutStream.processed += outSize; + +- RINOK(res); ++ RINOK(res) + blockSizes->unpackSize = checkInStream.processed; + } + { +@@ -866,7 +898,7 @@ static SRes Xz_CompressBlock( + buf[3] = 0; + + SeqCheckInStream_GetDigest(&checkInStream, buf + 4); +- RINOK(WriteBytes(&seqSizeOutStream.vt, buf + (4 - padSize), padSize + XzFlags_GetCheckSize((CXzStreamFlags)props->checkId))); ++ RINOK(WriteBytes(&seqSizeOutStream.vt, buf + (4 - padSize), padSize + XzFlags_GetCheckSize((CXzStreamFlags)props->checkId))) + + blockSizes->totalSize = seqSizeOutStream.processed - padSize; + +@@ -877,12 +909,12 @@ static SRes Xz_CompressBlock( + seqSizeOutStream.processed = 0; + + block.unpackSize = blockSizes->unpackSize; +- XzBlock_SetHasUnpackSize(&block); ++ XzBlock_SetHasUnpackSize(&block) + + block.packSize = packSize; +- XzBlock_SetHasPackSize(&block); ++ XzBlock_SetHasPackSize(&block) + +- RINOK(XzBlock_WriteHeader(&block, &seqSizeOutStream.vt)); ++ RINOK(XzBlock_WriteHeader(&block, &seqSizeOutStream.vt)) + + blockSizes->headerSize = (size_t)seqSizeOutStream.processed; + blockSizes->totalSize += seqSizeOutStream.processed; +@@ -906,15 +938,15 @@ static SRes Xz_CompressBlock( + typedef struct + { + ICompressProgress vt; +- ICompressProgress *progress; ++ ICompressProgressPtr progress; + UInt64 inOffset; + UInt64 outOffset; + } CCompressProgress_XzEncOffset; + + +-static SRes CompressProgress_XzEncOffset_Progress(const ICompressProgress *pp, UInt64 inSize, UInt64 outSize) ++static SRes CompressProgress_XzEncOffset_Progress(ICompressProgressPtr pp, UInt64 inSize, UInt64 outSize) + { +- const CCompressProgress_XzEncOffset *p = CONTAINER_FROM_VTBL(pp, CCompressProgress_XzEncOffset, vt); ++ const CCompressProgress_XzEncOffset *p = Z7_CONTAINER_FROM_VTBL_CONST(pp, CCompressProgress_XzEncOffset, vt); + inSize += p->inOffset; + outSize += p->outOffset; + return ICompressProgress_Progress(p->progress, inSize, outSize); +@@ -923,7 +955,7 @@ static SRes CompressProgress_XzEncOffset_Progress(const ICompressProgress *pp, U + + + +-typedef struct ++struct CXzEnc + { + ISzAllocPtr alloc; + ISzAllocPtr allocBig; +@@ -933,20 +965,19 @@ typedef struct + + CXzEncIndex xzIndex; + +- CLzma2WithFilters lzmaf_Items[MTCODER__THREADS_MAX]; ++ CLzma2WithFilters lzmaf_Items[MTCODER_THREADS_MAX]; + + size_t outBufSize; /* size of allocated outBufs[i] */ +- Byte *outBufs[MTCODER__BLOCKS_MAX]; ++ Byte *outBufs[MTCODER_BLOCKS_MAX]; + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + unsigned checkType; +- ISeqOutStream *outStream; ++ ISeqOutStreamPtr outStream; + BoolInt mtCoder_WasConstructed; + CMtCoder mtCoder; +- CXzEncBlockInfo EncBlocks[MTCODER__BLOCKS_MAX]; ++ CXzEncBlockInfo EncBlocks[MTCODER_BLOCKS_MAX]; + #endif +- +-} CXzEnc; ++}; + + + static void XzEnc_Construct(CXzEnc *p) +@@ -955,13 +986,13 @@ static void XzEnc_Construct(CXzEnc *p) + + XzEncIndex_Construct(&p->xzIndex); + +- for (i = 0; i < MTCODER__THREADS_MAX; i++) ++ for (i = 0; i < MTCODER_THREADS_MAX; i++) + Lzma2WithFilters_Construct(&p->lzmaf_Items[i]); + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + p->mtCoder_WasConstructed = False7z; + { +- for (i = 0; i < MTCODER__BLOCKS_MAX; i++) ++ for (i = 0; i < MTCODER_BLOCKS_MAX; i++) + p->outBufs[i] = NULL; + p->outBufSize = 0; + } +@@ -972,7 +1003,7 @@ static void XzEnc_Construct(CXzEnc *p) + static void XzEnc_FreeOutBufs(CXzEnc *p) + { + unsigned i; +- for (i = 0; i < MTCODER__BLOCKS_MAX; i++) ++ for (i = 0; i < MTCODER_BLOCKS_MAX; i++) + if (p->outBufs[i]) + { + ISzAlloc_Free(p->alloc, p->outBufs[i]); +@@ -988,10 +1019,10 @@ static void XzEnc_Free(CXzEnc *p, ISzAllocPtr alloc) + + XzEncIndex_Free(&p->xzIndex, alloc); + +- for (i = 0; i < MTCODER__THREADS_MAX; i++) ++ for (i = 0; i < MTCODER_THREADS_MAX; i++) + Lzma2WithFilters_Free(&p->lzmaf_Items[i], alloc); + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + if (p->mtCoder_WasConstructed) + { + MtCoder_Destruct(&p->mtCoder); +@@ -1013,37 +1044,38 @@ CXzEncHandle XzEnc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig) + p->expectedDataSize = (UInt64)(Int64)-1; + p->alloc = alloc; + p->allocBig = allocBig; +- return p; ++ return (CXzEncHandle)p; + } + ++// #define GET_CXzEnc_p CXzEnc *p = (CXzEnc *)(void *)pp; + +-void XzEnc_Destroy(CXzEncHandle pp) ++void XzEnc_Destroy(CXzEncHandle p) + { +- CXzEnc *p = (CXzEnc *)pp; ++ // GET_CXzEnc_p + XzEnc_Free(p, p->alloc); + ISzAlloc_Free(p->alloc, p); + } + + +-SRes XzEnc_SetProps(CXzEncHandle pp, const CXzProps *props) ++SRes XzEnc_SetProps(CXzEncHandle p, const CXzProps *props) + { +- CXzEnc *p = (CXzEnc *)pp; ++ // GET_CXzEnc_p + p->xzProps = *props; + XzProps_Normalize(&p->xzProps); + return SZ_OK; + } + + +-void XzEnc_SetDataSize(CXzEncHandle pp, UInt64 expectedDataSiize) ++void XzEnc_SetDataSize(CXzEncHandle p, UInt64 expectedDataSiize) + { +- CXzEnc *p = (CXzEnc *)pp; ++ // GET_CXzEnc_p + p->expectedDataSize = expectedDataSiize; + } + + + + +-#ifndef _7ZIP_ST ++#ifndef Z7_ST + + static SRes XzEnc_MtCallback_Code(void *pp, unsigned coderIndex, unsigned outBufIndex, + const Byte *src, size_t srcSize, int finished) +@@ -1073,7 +1105,7 @@ static SRes XzEnc_MtCallback_Code(void *pp, unsigned coderIndex, unsigned outBuf + + MtProgressThunk_CreateVTable(&progressThunk); + progressThunk.mtProgress = &me->mtCoder.mtProgress; +- MtProgressThunk_Init(&progressThunk); ++ MtProgressThunk_INIT(&progressThunk) + + { + CXzEncBlockInfo blockSizes; +@@ -1112,11 +1144,11 @@ static SRes XzEnc_MtCallback_Write(void *pp, unsigned outBufIndex) + const CXzEncBlockInfo *bInfo = &me->EncBlocks[outBufIndex]; + const Byte *data = me->outBufs[outBufIndex]; + +- RINOK(WriteBytes(me->outStream, data, bInfo->headerSize)); ++ RINOK(WriteBytes(me->outStream, data, bInfo->headerSize)) + + { + UInt64 totalPackFull = bInfo->totalSize + XZ_GET_PAD_SIZE(bInfo->totalSize); +- RINOK(WriteBytes(me->outStream, data + XZ_BLOCK_HEADER_SIZE_MAX, (size_t)totalPackFull - bInfo->headerSize)); ++ RINOK(WriteBytes(me->outStream, data + XZ_BLOCK_HEADER_SIZE_MAX, (size_t)totalPackFull - bInfo->headerSize)) + } + + return XzEncIndex_AddIndexRecord(&me->xzIndex, bInfo->unpackSize, bInfo->totalSize, me->alloc); +@@ -1126,9 +1158,9 @@ static SRes XzEnc_MtCallback_Write(void *pp, unsigned outBufIndex) + + + +-SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress) ++SRes XzEnc_Encode(CXzEncHandle p, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, ICompressProgressPtr progress) + { +- CXzEnc *p = (CXzEnc *)pp; ++ // GET_CXzEnc_p + + const CXzProps *props = &p->xzProps; + +@@ -1137,7 +1169,7 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr + UInt64 numBlocks = 1; + UInt64 blockSize = props->blockSize; + +- if (blockSize != XZ_PROPS__BLOCK_SIZE__SOLID ++ if (blockSize != XZ_PROPS_BLOCK_SIZE_SOLID + && props->reduceSize != (UInt64)(Int64)-1) + { + numBlocks = props->reduceSize / blockSize; +@@ -1147,13 +1179,13 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr + else + blockSize = (UInt64)1 << 62; + +- RINOK(XzEncIndex_PreAlloc(&p->xzIndex, numBlocks, blockSize, XZ_GET_ESTIMATED_BLOCK_TOTAL_PACK_SIZE(blockSize), p->alloc)); ++ RINOK(XzEncIndex_PreAlloc(&p->xzIndex, numBlocks, blockSize, XZ_GET_ESTIMATED_BLOCK_TOTAL_PACK_SIZE(blockSize), p->alloc)) + } + +- RINOK(Xz_WriteHeader((CXzStreamFlags)props->checkId, outStream)); ++ RINOK(Xz_WriteHeader((CXzStreamFlags)props->checkId, outStream)) + + +- #ifndef _7ZIP_ST ++ #ifndef Z7_ST + if (props->numBlockThreads_Reduced > 1) + { + IMtCoderCallback2 vt; +@@ -1180,8 +1212,8 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr + p->mtCoder.mtCallback = &vt; + p->mtCoder.mtCallbackObject = p; + +- if ( props->blockSize == XZ_PROPS__BLOCK_SIZE__SOLID +- || props->blockSize == XZ_PROPS__BLOCK_SIZE__AUTO) ++ if ( props->blockSize == XZ_PROPS_BLOCK_SIZE_SOLID ++ || props->blockSize == XZ_PROPS_BLOCK_SIZE_AUTO) + return SZ_ERROR_FAIL; + + p->mtCoder.blockSize = (size_t)props->blockSize; +@@ -1200,7 +1232,7 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr + p->mtCoder.numThreadsMax = (unsigned)props->numBlockThreads_Max; + p->mtCoder.expectedDataSize = p->expectedDataSize; + +- RINOK(MtCoder_Code(&p->mtCoder)); ++ RINOK(MtCoder_Code(&p->mtCoder)) + } + else + #endif +@@ -1217,7 +1249,7 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr + + writeStartSizes = 0; + +- if (props->blockSize != XZ_PROPS__BLOCK_SIZE__SOLID) ++ if (props->blockSize != XZ_PROPS_BLOCK_SIZE_SOLID) + { + writeStartSizes = (props->forceWriteSizesInHeader > 0); + +@@ -1274,18 +1306,18 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr + &inStreamFinished, + &blockSizes, + p->alloc, +- p->allocBig)); ++ p->allocBig)) + + { + UInt64 totalPackFull = blockSizes.totalSize + XZ_GET_PAD_SIZE(blockSizes.totalSize); + + if (writeStartSizes) + { +- RINOK(WriteBytes(outStream, p->outBufs[0], blockSizes.headerSize)); +- RINOK(WriteBytes(outStream, bufData, (size_t)totalPackFull - blockSizes.headerSize)); ++ RINOK(WriteBytes(outStream, p->outBufs[0], blockSizes.headerSize)) ++ RINOK(WriteBytes(outStream, bufData, (size_t)totalPackFull - blockSizes.headerSize)) + } + +- RINOK(XzEncIndex_AddIndexRecord(&p->xzIndex, blockSizes.unpackSize, blockSizes.totalSize, p->alloc)); ++ RINOK(XzEncIndex_AddIndexRecord(&p->xzIndex, blockSizes.unpackSize, blockSizes.totalSize, p->alloc)) + + progress2.inOffset += blockSizes.unpackSize; + progress2.outOffset += totalPackFull; +@@ -1302,8 +1334,8 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr + + #include "Alloc.h" + +-SRes Xz_Encode(ISeqOutStream *outStream, ISeqInStream *inStream, +- const CXzProps *props, ICompressProgress *progress) ++SRes Xz_Encode(ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, ++ const CXzProps *props, ICompressProgressPtr progress) + { + SRes res; + CXzEncHandle xz = XzEnc_Create(&g_Alloc, &g_BigAlloc); +@@ -1317,7 +1349,7 @@ SRes Xz_Encode(ISeqOutStream *outStream, ISeqInStream *inStream, + } + + +-SRes Xz_EncodeEmpty(ISeqOutStream *outStream) ++SRes Xz_EncodeEmpty(ISeqOutStreamPtr outStream) + { + SRes res; + CXzEncIndex xzIndex; +diff --git a/src/lzma/XzEnc.h b/src/lzma/XzEnc.h +index 0c29e7e1e..77b78c014 100644 +--- a/src/lzma/XzEnc.h ++++ b/src/lzma/XzEnc.h +@@ -1,8 +1,8 @@ + /* XzEnc.h -- Xz Encode +-2017-06-27 : Igor Pavlov : Public domain */ ++2023-04-13 : Igor Pavlov : Public domain */ + +-#ifndef __XZ_ENC_H +-#define __XZ_ENC_H ++#ifndef ZIP7_INC_XZ_ENC_H ++#define ZIP7_INC_XZ_ENC_H + + #include "Lzma2Enc.h" + +@@ -11,8 +11,8 @@ + EXTERN_C_BEGIN + + +-#define XZ_PROPS__BLOCK_SIZE__AUTO LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO +-#define XZ_PROPS__BLOCK_SIZE__SOLID LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID ++#define XZ_PROPS_BLOCK_SIZE_AUTO LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO ++#define XZ_PROPS_BLOCK_SIZE_SOLID LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID + + + typedef struct +@@ -41,19 +41,20 @@ typedef struct + + void XzProps_Init(CXzProps *p); + +- +-typedef void * CXzEncHandle; ++typedef struct CXzEnc CXzEnc; ++typedef CXzEnc * CXzEncHandle; ++// Z7_DECLARE_HANDLE(CXzEncHandle) + + CXzEncHandle XzEnc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig); + void XzEnc_Destroy(CXzEncHandle p); + SRes XzEnc_SetProps(CXzEncHandle p, const CXzProps *props); + void XzEnc_SetDataSize(CXzEncHandle p, UInt64 expectedDataSiize); +-SRes XzEnc_Encode(CXzEncHandle p, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress); ++SRes XzEnc_Encode(CXzEncHandle p, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, ICompressProgressPtr progress); + +-SRes Xz_Encode(ISeqOutStream *outStream, ISeqInStream *inStream, +- const CXzProps *props, ICompressProgress *progress); ++SRes Xz_Encode(ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, ++ const CXzProps *props, ICompressProgressPtr progress); + +-SRes Xz_EncodeEmpty(ISeqOutStream *outStream); ++SRes Xz_EncodeEmpty(ISeqOutStreamPtr outStream); + + EXTERN_C_END + +diff --git a/src/lzma/XzIn.c b/src/lzma/XzIn.c +index a293d6bdd..9261bcb09 100644 +--- a/src/lzma/XzIn.c ++++ b/src/lzma/XzIn.c +@@ -1,5 +1,5 @@ + /* XzIn.c - Xz input +-2021-09-04 : Igor Pavlov : Public domain */ ++2023-04-02 : Igor Pavlov : Public domain */ + + #include "Precomp.h" + +@@ -15,11 +15,13 @@ + #define XZ_FOOTER_SIG_CHECK(p) ((p)[0] == XZ_FOOTER_SIG_0 && (p)[1] == XZ_FOOTER_SIG_1) + + +-SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStream *inStream) ++SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStreamPtr inStream) + { + Byte sig[XZ_STREAM_HEADER_SIZE]; +- RINOK(SeqInStream_Read2(inStream, sig, XZ_STREAM_HEADER_SIZE, SZ_ERROR_NO_ARCHIVE)); +- if (memcmp(sig, XZ_SIG, XZ_SIG_SIZE) != 0) ++ size_t processedSize = XZ_STREAM_HEADER_SIZE; ++ RINOK(SeqInStream_ReadMax(inStream, sig, &processedSize)) ++ if (processedSize != XZ_STREAM_HEADER_SIZE ++ || memcmp(sig, XZ_SIG, XZ_SIG_SIZE) != 0) + return SZ_ERROR_NO_ARCHIVE; + return Xz_ParseHeader(p, sig); + } +@@ -29,12 +31,12 @@ SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStream *inStream) + if (s == 0) return SZ_ERROR_ARCHIVE; \ + pos += s; } + +-SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStream *inStream, BoolInt *isIndex, UInt32 *headerSizeRes) ++SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStreamPtr inStream, BoolInt *isIndex, UInt32 *headerSizeRes) + { + Byte header[XZ_BLOCK_HEADER_SIZE_MAX]; + unsigned headerSize; + *headerSizeRes = 0; +- RINOK(SeqInStream_ReadByte(inStream, &header[0])); ++ RINOK(SeqInStream_ReadByte(inStream, &header[0])) + headerSize = (unsigned)header[0]; + if (headerSize == 0) + { +@@ -46,7 +48,12 @@ SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStream *inStream, BoolInt *isIndex, U + *isIndex = False7z; + headerSize = (headerSize << 2) + 4; + *headerSizeRes = headerSize; +- RINOK(SeqInStream_Read(inStream, header + 1, headerSize - 1)); ++ { ++ size_t processedSize = headerSize - 1; ++ RINOK(SeqInStream_ReadMax(inStream, header + 1, &processedSize)) ++ if (processedSize != headerSize - 1) ++ return SZ_ERROR_INPUT_EOF; ++ } + return XzBlock_Parse(p, header); + } + +@@ -58,7 +65,9 @@ UInt64 Xz_GetUnpackSize(const CXzStream *p) + UInt64 size = 0; + size_t i; + for (i = 0; i < p->numBlocks; i++) +- ADD_SIZE_CHECK(size, p->blocks[i].unpackSize); ++ { ++ ADD_SIZE_CHECK(size, p->blocks[i].unpackSize) ++ } + return size; + } + +@@ -67,12 +76,14 @@ UInt64 Xz_GetPackSize(const CXzStream *p) + UInt64 size = 0; + size_t i; + for (i = 0; i < p->numBlocks; i++) +- ADD_SIZE_CHECK(size, (p->blocks[i].totalSize + 3) & ~(UInt64)3); ++ { ++ ADD_SIZE_CHECK(size, (p->blocks[i].totalSize + 3) & ~(UInt64)3) ++ } + return size; + } + + /* +-SRes XzBlock_ReadFooter(CXzBlock *p, CXzStreamFlags f, ISeqInStream *inStream) ++SRes XzBlock_ReadFooter(CXzBlock *p, CXzStreamFlags f, ISeqInStreamPtr inStream) + { + return SeqInStream_Read(inStream, p->check, XzFlags_GetCheckSize(f)); + } +@@ -93,7 +104,7 @@ static SRes Xz_ReadIndex2(CXzStream *p, const Byte *buf, size_t size, ISzAllocPt + + { + UInt64 numBlocks64; +- READ_VARINT_AND_CHECK(buf, pos, size, &numBlocks64); ++ READ_VARINT_AND_CHECK(buf, pos, size, &numBlocks64) + numBlocks = (size_t)numBlocks64; + if (numBlocks != numBlocks64 || numBlocks * 2 > size) + return SZ_ERROR_ARCHIVE; +@@ -110,8 +121,8 @@ static SRes Xz_ReadIndex2(CXzStream *p, const Byte *buf, size_t size, ISzAllocPt + for (i = 0; i < numBlocks; i++) + { + CXzBlockSizes *block = &p->blocks[i]; +- READ_VARINT_AND_CHECK(buf, pos, size, &block->totalSize); +- READ_VARINT_AND_CHECK(buf, pos, size, &block->unpackSize); ++ READ_VARINT_AND_CHECK(buf, pos, size, &block->totalSize) ++ READ_VARINT_AND_CHECK(buf, pos, size, &block->unpackSize) + if (block->totalSize == 0) + return SZ_ERROR_ARCHIVE; + } +@@ -122,7 +133,7 @@ static SRes Xz_ReadIndex2(CXzStream *p, const Byte *buf, size_t size, ISzAllocPt + return (pos == size) ? SZ_OK : SZ_ERROR_ARCHIVE; + } + +-static SRes Xz_ReadIndex(CXzStream *p, ILookInStream *stream, UInt64 indexSize, ISzAllocPtr alloc) ++static SRes Xz_ReadIndex(CXzStream *p, ILookInStreamPtr stream, UInt64 indexSize, ISzAllocPtr alloc) + { + SRes res; + size_t size; +@@ -142,14 +153,14 @@ static SRes Xz_ReadIndex(CXzStream *p, ILookInStream *stream, UInt64 indexSize, + return res; + } + +-static SRes LookInStream_SeekRead_ForArc(ILookInStream *stream, UInt64 offset, void *buf, size_t size) ++static SRes LookInStream_SeekRead_ForArc(ILookInStreamPtr stream, UInt64 offset, void *buf, size_t size) + { +- RINOK(LookInStream_SeekTo(stream, offset)); ++ RINOK(LookInStream_SeekTo(stream, offset)) + return LookInStream_Read(stream, buf, size); + /* return LookInStream_Read2(stream, buf, size, SZ_ERROR_NO_ARCHIVE); */ + } + +-static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOffset, ISzAllocPtr alloc) ++static SRes Xz_ReadBackward(CXzStream *p, ILookInStreamPtr stream, Int64 *startOffset, ISzAllocPtr alloc) + { + UInt64 indexSize; + Byte buf[XZ_STREAM_FOOTER_SIZE]; +@@ -159,7 +170,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff + return SZ_ERROR_NO_ARCHIVE; + + pos -= XZ_STREAM_FOOTER_SIZE; +- RINOK(LookInStream_SeekRead_ForArc(stream, pos, buf, XZ_STREAM_FOOTER_SIZE)); ++ RINOK(LookInStream_SeekRead_ForArc(stream, pos, buf, XZ_STREAM_FOOTER_SIZE)) + + if (!XZ_FOOTER_SIG_CHECK(buf + 10)) + { +@@ -174,7 +185,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff + + i = (pos > TEMP_BUF_SIZE) ? TEMP_BUF_SIZE : (size_t)pos; + pos -= i; +- RINOK(LookInStream_SeekRead_ForArc(stream, pos, temp, i)); ++ RINOK(LookInStream_SeekRead_ForArc(stream, pos, temp, i)) + total += (UInt32)i; + for (; i != 0; i--) + if (temp[i - 1] != 0) +@@ -193,7 +204,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff + if (pos < XZ_STREAM_FOOTER_SIZE) + return SZ_ERROR_NO_ARCHIVE; + pos -= XZ_STREAM_FOOTER_SIZE; +- RINOK(LookInStream_SeekRead_ForArc(stream, pos, buf, XZ_STREAM_FOOTER_SIZE)); ++ RINOK(LookInStream_SeekRead_ForArc(stream, pos, buf, XZ_STREAM_FOOTER_SIZE)) + if (!XZ_FOOTER_SIG_CHECK(buf + 10)) + return SZ_ERROR_NO_ARCHIVE; + } +@@ -217,8 +228,8 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff + return SZ_ERROR_ARCHIVE; + + pos -= indexSize; +- RINOK(LookInStream_SeekTo(stream, pos)); +- RINOK(Xz_ReadIndex(p, stream, indexSize, alloc)); ++ RINOK(LookInStream_SeekTo(stream, pos)) ++ RINOK(Xz_ReadIndex(p, stream, indexSize, alloc)) + + { + UInt64 totalSize = Xz_GetPackSize(p); +@@ -227,7 +238,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff + || pos < totalSize + XZ_STREAM_HEADER_SIZE) + return SZ_ERROR_ARCHIVE; + pos -= (totalSize + XZ_STREAM_HEADER_SIZE); +- RINOK(LookInStream_SeekTo(stream, pos)); ++ RINOK(LookInStream_SeekTo(stream, pos)) + *startOffset = (Int64)pos; + } + { +@@ -236,7 +247,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff + SecToRead_CreateVTable(&secToRead); + secToRead.realStream = stream; + +- RINOK(Xz_ReadHeader(&headerFlags, &secToRead.vt)); ++ RINOK(Xz_ReadHeader(&headerFlags, &secToRead.vt)) + return (p->flags == headerFlags) ? SZ_OK : SZ_ERROR_ARCHIVE; + } + } +@@ -274,7 +285,9 @@ UInt64 Xzs_GetUnpackSize(const CXzs *p) + UInt64 size = 0; + size_t i; + for (i = 0; i < p->num; i++) +- ADD_SIZE_CHECK(size, Xz_GetUnpackSize(&p->streams[i])); ++ { ++ ADD_SIZE_CHECK(size, Xz_GetUnpackSize(&p->streams[i])) ++ } + return size; + } + +@@ -284,15 +297,17 @@ UInt64 Xzs_GetPackSize(const CXzs *p) + UInt64 size = 0; + size_t i; + for (i = 0; i < p->num; i++) +- ADD_SIZE_CHECK(size, Xz_GetTotalSize(&p->streams[i])); ++ { ++ ADD_SIZE_CHECK(size, Xz_GetTotalSize(&p->streams[i])) ++ } + return size; + } + */ + +-SRes Xzs_ReadBackward(CXzs *p, ILookInStream *stream, Int64 *startOffset, ICompressProgress *progress, ISzAllocPtr alloc) ++SRes Xzs_ReadBackward(CXzs *p, ILookInStreamPtr stream, Int64 *startOffset, ICompressProgressPtr progress, ISzAllocPtr alloc) + { + Int64 endOffset = 0; +- RINOK(ILookInStream_Seek(stream, &endOffset, SZ_SEEK_END)); ++ RINOK(ILookInStream_Seek(stream, &endOffset, SZ_SEEK_END)) + *startOffset = endOffset; + for (;;) + { +@@ -301,7 +316,7 @@ SRes Xzs_ReadBackward(CXzs *p, ILookInStream *stream, Int64 *startOffset, ICompr + Xz_Construct(&st); + res = Xz_ReadBackward(&st, stream, startOffset, alloc); + st.startOffset = (UInt64)*startOffset; +- RINOK(res); ++ RINOK(res) + if (p->num == p->numAllocated) + { + const size_t newNum = p->num + p->num / 4 + 1; +@@ -317,7 +332,7 @@ SRes Xzs_ReadBackward(CXzs *p, ILookInStream *stream, Int64 *startOffset, ICompr + p->streams[p->num++] = st; + if (*startOffset == 0) + break; +- RINOK(LookInStream_SeekTo(stream, (UInt64)*startOffset)); ++ RINOK(LookInStream_SeekTo(stream, (UInt64)*startOffset)) + if (progress && ICompressProgress_Progress(progress, (UInt64)(endOffset - *startOffset), (UInt64)(Int64)-1) != SZ_OK) + return SZ_ERROR_PROGRESS; + } +diff --git a/src/lzma/lzma-sdk.txt b/src/lzma/lzma-sdk.txt +index 9621c8d5d..141b0fd4e 100644 +--- a/src/lzma/lzma-sdk.txt ++++ b/src/lzma/lzma-sdk.txt +@@ -1,4 +1,4 @@ +-LZMA SDK 21.07 ++LZMA SDK 23.01 + -------------- + + LZMA SDK provides the documentation, samples, header files, +diff --git a/src/minizip/README.minizip b/src/minizip/README.minizip +index 4940a1e15..7634a8511 100644 +--- a/src/minizip/README.minizip ++++ b/src/minizip/README.minizip +@@ -1 +1 @@ +-This code has been taken from https://github.com/zlib-ng/minizip-ng/releases/tag/3.0.5 ++This code has been taken from https://github.com/zlib-ng/minizip-ng/releases/tag/4.0.4 +diff --git a/src/minizip/mz.h b/src/minizip/mz.h +index bcebe08a2..675cec297 100644 +--- a/src/minizip/mz.h ++++ b/src/minizip/mz.h +@@ -1,7 +1,7 @@ + /* mz.h -- Errors codes, zip flags and magic + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + + This program is distributed under the terms of the same license as zlib. +@@ -14,8 +14,8 @@ + /***************************************************************************/ + + /* MZ_VERSION */ +-#define MZ_VERSION ("3.0.5") +-#define MZ_VERSION_BUILD (030005) ++#define MZ_VERSION ("4.0.4") ++#define MZ_VERSION_BUILD (040004) + + /* MZ_ERROR */ + #define MZ_OK (0) /* zlib */ +@@ -112,13 +112,14 @@ + + /* MZ_AES */ + #define MZ_AES_VERSION (1) +-#define MZ_AES_ENCRYPTION_MODE_128 (0x01) +-#define MZ_AES_ENCRYPTION_MODE_192 (0x02) +-#define MZ_AES_ENCRYPTION_MODE_256 (0x03) +-#define MZ_AES_KEY_LENGTH(MODE) (8 * (MODE & 3) + 8) ++#define MZ_AES_MODE_ECB (0) ++#define MZ_AES_MODE_CBC (1) ++#define MZ_AES_MODE_GCM (2) ++#define MZ_AES_STRENGTH_128 (1) ++#define MZ_AES_STRENGTH_192 (2) ++#define MZ_AES_STRENGTH_256 (3) + #define MZ_AES_KEY_LENGTH_MAX (32) + #define MZ_AES_BLOCK_SIZE (16) +-#define MZ_AES_HEADER_SIZE(MODE) ((4 * (MODE & 3) + 4) + 2) + #define MZ_AES_FOOTER_SIZE (10) + + /* MZ_HASH */ +@@ -146,13 +147,6 @@ + /* MZ_UTILITY */ + #define MZ_UNUSED(SYMBOL) ((void)SYMBOL) + +-#ifndef MZ_CUSTOM_ALLOC +-#define MZ_ALLOC(SIZE) (malloc((SIZE))) +-#endif +-#ifndef MZ_CUSTOM_FREE +-#define MZ_FREE(PTR) (free(PTR)) +-#endif +- + #if defined(_WIN32) && defined(MZ_EXPORTS) + #define MZ_EXPORT __declspec(dllexport) + #else +@@ -175,25 +169,25 @@ + #endif + + #ifndef INT8_MAX +-typedef signed char int8_t; ++typedef signed char int8_t; + #endif + #ifndef INT16_MAX +-typedef short int16_t; ++typedef short int16_t; + #endif + #ifndef INT32_MAX +-typedef int int32_t; ++typedef int int32_t; + #endif + #ifndef INT64_MAX +-typedef long long int64_t; ++typedef long long int64_t; + #endif + #ifndef UINT8_MAX +-typedef unsigned char uint8_t; ++typedef unsigned char uint8_t; + #endif + #ifndef UINT16_MAX +-typedef unsigned short uint16_t; ++typedef unsigned short uint16_t; + #endif + #ifndef UINT32_MAX +-typedef unsigned int uint32_t; ++typedef unsigned int uint32_t; + #endif + #ifndef UINT64_MAX + typedef unsigned long long uint64_t; +@@ -208,13 +202,13 @@ typedef unsigned long long uint64_t; + #endif + + #ifndef PRId8 +-# define PRId8 "hhd" ++# define PRId8 "hhd" + #endif + #ifndef PRIu8 +-# define PRIu8 "hhu" ++# define PRIu8 "hhu" + #endif + #ifndef PRIx8 +-# define PRIx8 "hhx" ++# define PRIx8 "hhx" + #endif + #ifndef PRId16 + # define PRId16 "hd" +@@ -257,22 +251,22 @@ typedef unsigned long long uint64_t; + #endif + + #ifndef INT16_MAX +-# define INT16_MAX 32767 ++# define INT16_MAX 32767 + #endif + #ifndef INT32_MAX +-# define INT32_MAX 2147483647L ++# define INT32_MAX 2147483647L + #endif + #ifndef INT64_MAX +-# define INT64_MAX 9223372036854775807LL ++# define INT64_MAX 9223372036854775807LL + #endif + #ifndef UINT16_MAX +-# define UINT16_MAX 65535U ++# define UINT16_MAX 65535U + #endif + #ifndef UINT32_MAX +-# define UINT32_MAX 4294967295UL ++# define UINT32_MAX 4294967295UL + #endif + #ifndef UINT64_MAX +-# define UINT64_MAX 18446744073709551615ULL ++# define UINT64_MAX 18446744073709551615ULL + #endif + + /***************************************************************************/ +diff --git a/src/minizip/mz_compat.c b/src/minizip/mz_compat.c +index 5a08046a7..872dab8f3 100644 +--- a/src/minizip/mz_compat.c ++++ b/src/minizip/mz_compat.c +@@ -1,7 +1,7 @@ + /* mz_compat.c -- Backwards compatible interface for older versions + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + Copyright (C) 1998-2010 Gilles Vollant + https://www.winimage.com/zLibDll/minizip.html +@@ -10,7 +10,6 @@ + See the accompanying LICENSE file for the full text of the license. + */ + +- + #include "mz.h" + #include "mz_os.h" + #include "mz_strm.h" +@@ -52,7 +51,7 @@ static int64_t mz_stream_ioapi_tell(void *stream); + static int32_t mz_stream_ioapi_seek(void *stream, int64_t offset, int32_t origin); + static int32_t mz_stream_ioapi_close(void *stream); + static int32_t mz_stream_ioapi_error(void *stream); +-static void *mz_stream_ioapi_create(void **stream); ++static void *mz_stream_ioapi_create(void); + static void mz_stream_ioapi_delete(void **stream); + + /***************************************************************************/ +@@ -87,12 +86,12 @@ static int32_t mz_stream_ioapi_open(void *stream, const char *path, int32_t mode + else + return MZ_OPEN_ERROR; + +- if (ioapi->filefunc64.zopen64_file != NULL) ++ if (ioapi->filefunc64.zopen64_file) + ioapi->handle = ioapi->filefunc64.zopen64_file(ioapi->filefunc64.opaque, path, ioapi_mode); +- else if (ioapi->filefunc.zopen_file != NULL) ++ else if (ioapi->filefunc.zopen_file) + ioapi->handle = ioapi->filefunc.zopen_file(ioapi->filefunc.opaque, path, ioapi_mode); + +- if (ioapi->handle == NULL) ++ if (!ioapi->handle) + return MZ_PARAM_ERROR; + + return MZ_OK; +@@ -100,7 +99,7 @@ static int32_t mz_stream_ioapi_open(void *stream, const char *path, int32_t mode + + static int32_t mz_stream_ioapi_is_open(void *stream) { + mz_stream_ioapi *ioapi = (mz_stream_ioapi *)stream; +- if (ioapi->handle == NULL) ++ if (!ioapi->handle) + return MZ_OPEN_ERROR; + return MZ_OK; + } +@@ -113,16 +112,16 @@ static int32_t mz_stream_ioapi_read(void *stream, void *buf, int32_t size) { + if (mz_stream_ioapi_is_open(stream) != MZ_OK) + return MZ_OPEN_ERROR; + +- if (ioapi->filefunc64.zread_file != NULL) { ++ if (ioapi->filefunc64.zread_file) { + zread = ioapi->filefunc64.zread_file; + opaque = ioapi->filefunc64.opaque; +- } else if (ioapi->filefunc.zread_file != NULL) { ++ } else if (ioapi->filefunc.zread_file) { + zread = ioapi->filefunc.zread_file; + opaque = ioapi->filefunc.opaque; + } else + return MZ_PARAM_ERROR; + +- return zread(opaque, ioapi->handle, buf, size); ++ return (int32_t)zread(opaque, ioapi->handle, buf, size); + } + + static int32_t mz_stream_ioapi_write(void *stream, const void *buf, int32_t size) { +@@ -134,16 +133,16 @@ static int32_t mz_stream_ioapi_write(void *stream, const void *buf, int32_t size + if (mz_stream_ioapi_is_open(stream) != MZ_OK) + return MZ_OPEN_ERROR; + +- if (ioapi->filefunc64.zwrite_file != NULL) { ++ if (ioapi->filefunc64.zwrite_file) { + zwrite = ioapi->filefunc64.zwrite_file; + opaque = ioapi->filefunc64.opaque; +- } else if (ioapi->filefunc.zwrite_file != NULL) { ++ } else if (ioapi->filefunc.zwrite_file) { + zwrite = ioapi->filefunc.zwrite_file; + opaque = ioapi->filefunc.opaque; + } else + return MZ_PARAM_ERROR; + +- written = zwrite(opaque, ioapi->handle, buf, size); ++ written = (int32_t)zwrite(opaque, ioapi->handle, buf, size); + return written; + } + +@@ -153,9 +152,9 @@ static int64_t mz_stream_ioapi_tell(void *stream) { + if (mz_stream_ioapi_is_open(stream) != MZ_OK) + return MZ_OPEN_ERROR; + +- if (ioapi->filefunc64.ztell64_file != NULL) ++ if (ioapi->filefunc64.ztell64_file) + return ioapi->filefunc64.ztell64_file(ioapi->filefunc64.opaque, ioapi->handle); +- else if (ioapi->filefunc.ztell_file != NULL) ++ else if (ioapi->filefunc.ztell_file) + return ioapi->filefunc.ztell_file(ioapi->filefunc.opaque, ioapi->handle); + + return MZ_INTERNAL_ERROR; +@@ -163,16 +162,14 @@ static int64_t mz_stream_ioapi_tell(void *stream) { + + static int32_t mz_stream_ioapi_seek(void *stream, int64_t offset, int32_t origin) { + mz_stream_ioapi *ioapi = (mz_stream_ioapi *)stream; +- int32_t written = 0; +- void *opaque = NULL; + + if (mz_stream_ioapi_is_open(stream) != MZ_OK) + return MZ_OPEN_ERROR; + +- if (ioapi->filefunc64.zseek64_file != NULL) { ++ if (ioapi->filefunc64.zseek64_file) { + if (ioapi->filefunc64.zseek64_file(ioapi->filefunc64.opaque, ioapi->handle, offset, origin) != 0) + return MZ_INTERNAL_ERROR; +- } else if (ioapi->filefunc.zseek_file != NULL) { ++ } else if (ioapi->filefunc.zseek_file) { + if (ioapi->filefunc.zseek_file(ioapi->filefunc.opaque, ioapi->handle, (int32_t)offset, origin) != 0) + return MZ_INTERNAL_ERROR; + } else +@@ -189,10 +186,10 @@ static int32_t mz_stream_ioapi_close(void *stream) { + if (mz_stream_ioapi_is_open(stream) != MZ_OK) + return MZ_OPEN_ERROR; + +- if (ioapi->filefunc.zclose_file != NULL) { ++ if (ioapi->filefunc.zclose_file) { + zclose = ioapi->filefunc.zclose_file; + opaque = ioapi->filefunc.opaque; +- } else if (ioapi->filefunc64.zclose_file != NULL) { ++ } else if (ioapi->filefunc64.zclose_file) { + zclose = ioapi->filefunc64.zclose_file; + opaque = ioapi->filefunc64.opaque; + } else +@@ -212,10 +209,10 @@ static int32_t mz_stream_ioapi_error(void *stream) { + if (mz_stream_ioapi_is_open(stream) != MZ_OK) + return MZ_OPEN_ERROR; + +- if (ioapi->filefunc.zerror_file != NULL) { ++ if (ioapi->filefunc.zerror_file) { + zerror = ioapi->filefunc.zerror_file; + opaque = ioapi->filefunc.opaque; +- } else if (ioapi->filefunc64.zerror_file != NULL) { ++ } else if (ioapi->filefunc64.zerror_file) { + zerror = ioapi->filefunc64.zerror_file; + opaque = ioapi->filefunc64.opaque; + } else +@@ -236,27 +233,20 @@ static int32_t mz_stream_ioapi_set_filefunc64(void *stream, zlib_filefunc64_def + return MZ_OK; + } + +-static void *mz_stream_ioapi_create(void **stream) { +- mz_stream_ioapi *ioapi = NULL; +- +- ioapi = (mz_stream_ioapi *)MZ_ALLOC(sizeof(mz_stream_ioapi)); +- if (ioapi != NULL) { +- memset(ioapi, 0, sizeof(mz_stream_ioapi)); ++static void *mz_stream_ioapi_create(void) { ++ mz_stream_ioapi *ioapi = (mz_stream_ioapi *)calloc(1, sizeof(mz_stream_ioapi)); ++ if (ioapi) + ioapi->stream.vtbl = &mz_stream_ioapi_vtbl; +- } +- if (stream != NULL) +- *stream = ioapi; +- + return ioapi; + } + + static void mz_stream_ioapi_delete(void **stream) { + mz_stream_ioapi *ioapi = NULL; +- if (stream == NULL) ++ if (!stream) + return; + ioapi = (mz_stream_ioapi *)*stream; +- if (ioapi != NULL) +- MZ_FREE(ioapi); ++ if (ioapi) ++ free(ioapi); + *stream = NULL; + } + +@@ -264,41 +254,41 @@ static void mz_stream_ioapi_delete(void **stream) { + + void fill_fopen_filefunc(zlib_filefunc_def *pzlib_filefunc_def) { + /* For 32-bit file support only, compile with MZ_FILE32_API */ +- if (pzlib_filefunc_def != NULL) ++ if (pzlib_filefunc_def) + memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc_def)); + } + + void fill_fopen64_filefunc(zlib_filefunc64_def *pzlib_filefunc_def) { + /* All mz_stream_os_* support large files if compilation supports it */ +- if (pzlib_filefunc_def != NULL) ++ if (pzlib_filefunc_def) + memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc64_def)); + } + + void fill_win32_filefunc(zlib_filefunc_def *pzlib_filefunc_def) { + /* Handled by mz_stream_os_win32 */ +- if (pzlib_filefunc_def != NULL) ++ if (pzlib_filefunc_def) + memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc_def)); + } + + void fill_win32_filefunc64(zlib_filefunc64_def *pzlib_filefunc_def) { + /* Automatically supported in mz_stream_os_win32 */ +- if (pzlib_filefunc_def != NULL) ++ if (pzlib_filefunc_def) + memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc64_def)); + } + + void fill_win32_filefunc64A(zlib_filefunc64_def *pzlib_filefunc_def) { + /* Automatically supported in mz_stream_os_win32 */ +- if (pzlib_filefunc_def != NULL) ++ if (pzlib_filefunc_def) + memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc64_def)); + } + +-/* NOTE: fill_win32_filefunc64W is no longer necessary since wide-character +- support is automatically handled by the underlying os stream. Do not ++/* NOTE: fill_win32_filefunc64W is no longer necessary since wide-character ++ support is automatically handled by the underlying os stream. Do not + pass wide-characters to zipOpen or unzOpen. */ + + void fill_memory_filefunc(zlib_filefunc_def *pzlib_filefunc_def) { + /* Use opaque to indicate which stream interface to create */ +- if (pzlib_filefunc_def != NULL) { ++ if (pzlib_filefunc_def) { + memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc_def)); + pzlib_filefunc_def->opaque = mz_stream_mem_get_interface(); + } +@@ -330,25 +320,28 @@ zipFile zipOpen64(const void *path, int append) { + return zipOpen2(path, append, NULL, NULL); + } + +-zipFile zipOpen2(const char *path, int append, const char **globalcomment, ++zipFile zipOpen2(const char *path, int append, const char **globalcomment, + zlib_filefunc_def *pzlib_filefunc_def) { + zipFile zip = NULL; + int32_t mode = zipConvertAppendToStreamMode(append); + void *stream = NULL; + + if (pzlib_filefunc_def) { +- if (pzlib_filefunc_def->zopen_file != NULL) { +- if (mz_stream_ioapi_create(&stream) == NULL) ++ if (pzlib_filefunc_def->zopen_file) { ++ stream = mz_stream_ioapi_create(); ++ if (!stream) + return NULL; + mz_stream_ioapi_set_filefunc(stream, pzlib_filefunc_def); +- } else if (pzlib_filefunc_def->opaque != NULL) { +- if (mz_stream_create(&stream, (mz_stream_vtbl *)pzlib_filefunc_def->opaque) == NULL) ++ } else if (pzlib_filefunc_def->opaque) { ++ stream = mz_stream_create((mz_stream_vtbl *)pzlib_filefunc_def->opaque); ++ if (!stream) + return NULL; + } + } + +- if (stream == NULL) { +- if (mz_stream_os_create(&stream) == NULL) ++ if (!stream) { ++ stream = mz_stream_os_create(); ++ if (!stream) + return NULL; + } + +@@ -359,7 +352,7 @@ zipFile zipOpen2(const char *path, int append, const char **globalcomment, + + zip = zipOpen_MZ(stream, append, globalcomment); + +- if (zip == NULL) { ++ if (!zip) { + mz_stream_delete(&stream); + return NULL; + } +@@ -367,25 +360,28 @@ zipFile zipOpen2(const char *path, int append, const char **globalcomment, + return zip; + } + +-zipFile zipOpen2_64(const void *path, int append, const char **globalcomment, ++zipFile zipOpen2_64(const void *path, int append, const char **globalcomment, + zlib_filefunc64_def *pzlib_filefunc_def) { + zipFile zip = NULL; + int32_t mode = zipConvertAppendToStreamMode(append); + void *stream = NULL; + + if (pzlib_filefunc_def) { +- if (pzlib_filefunc_def->zopen64_file != NULL) { +- if (mz_stream_ioapi_create(&stream) == NULL) ++ if (pzlib_filefunc_def->zopen64_file) { ++ stream = mz_stream_ioapi_create(); ++ if (!stream) + return NULL; + mz_stream_ioapi_set_filefunc64(stream, pzlib_filefunc_def); +- } else if (pzlib_filefunc_def->opaque != NULL) { +- if (mz_stream_create(&stream, (mz_stream_vtbl *)pzlib_filefunc_def->opaque) == NULL) ++ } else if (pzlib_filefunc_def->opaque) { ++ stream = mz_stream_create((mz_stream_vtbl *)pzlib_filefunc_def->opaque); ++ if (!stream) + return NULL; + } + } + +- if (stream == NULL) { +- if (mz_stream_os_create(&stream) == NULL) ++ if (!stream) { ++ stream = mz_stream_os_create(); ++ if (!stream) + return NULL; + } + +@@ -396,7 +392,7 @@ zipFile zipOpen2_64(const void *path, int append, const char **globalcomment, + + zip = zipOpen_MZ(stream, append, globalcomment); + +- if (zip == NULL) { ++ if (!zip) { + mz_stream_delete(&stream); + return NULL; + } +@@ -410,7 +406,10 @@ zipFile zipOpen_MZ(void *stream, int append, const char **globalcomment) { + int32_t mode = zipConvertAppendToStreamMode(append); + void *handle = NULL; + +- mz_zip_create(&handle); ++ handle = mz_zip_create(); ++ if (!handle) ++ return NULL; ++ + err = mz_zip_open(handle, stream, mode); + + if (err != MZ_OK) { +@@ -418,11 +417,11 @@ zipFile zipOpen_MZ(void *stream, int append, const char **globalcomment) { + return NULL; + } + +- if (globalcomment != NULL) ++ if (globalcomment) + mz_zip_get_comment(handle, globalcomment); + +- compat = (mz_compat *)MZ_ALLOC(sizeof(mz_compat)); +- if (compat != NULL) { ++ compat = (mz_compat *)calloc(1, sizeof(mz_compat)); ++ if (compat) { + compat->handle = handle; + compat->stream = stream; + } else { +@@ -434,14 +433,14 @@ zipFile zipOpen_MZ(void *stream, int append, const char **globalcomment) { + + void* zipGetHandle_MZ(zipFile file) { + mz_compat *compat = (mz_compat *)file; +- if (compat == NULL) ++ if (!compat) + return NULL; + return compat->handle; + } + + void* zipGetStream_MZ(zipFile file) { + mz_compat *compat = (mz_compat *)file; +- if (compat == NULL) ++ if (!compat) + return NULL; + return (void *)compat->stream; + } +@@ -461,12 +460,18 @@ int zipOpenNewFileInZip5(zipFile file, const char *filename, const zip_fileinfo + MZ_UNUSED(extrafield_local); + MZ_UNUSED(crc_for_crypting); + +- if (compat == NULL) ++ if (!compat) ++ return ZIP_PARAMERROR; ++ ++ /* The filename and comment length must fit in 16 bits. */ ++ if (filename && strlen(filename) > 0xffff) ++ return ZIP_PARAMERROR; ++ if (comment && strlen(comment) > 0xffff) + return ZIP_PARAMERROR; + + memset(&file_info, 0, sizeof(file_info)); + +- if (zipfi != NULL) { ++ if (zipfi) { + uint64_t dos_date = 0; + + if (zipfi->mz_dos_date != 0) +@@ -475,11 +480,11 @@ int zipOpenNewFileInZip5(zipFile file, const char *filename, const zip_fileinfo + dos_date = mz_zip_tm_to_dosdate(&zipfi->tmz_date); + + file_info.modified_date = mz_zip_dosdate_to_time_t(dos_date); +- file_info.external_fa = zipfi->external_fa; +- file_info.internal_fa = zipfi->internal_fa; ++ file_info.external_fa = (uint32_t)zipfi->external_fa; ++ file_info.internal_fa = (uint16_t)zipfi->internal_fa; + } + +- if (filename == NULL) ++ if (!filename) + filename = "-"; + + file_info.compression_method = (uint16_t)compression_method; +@@ -490,7 +495,7 @@ int zipOpenNewFileInZip5(zipFile file, const char *filename, const zip_fileinfo + file_info.extrafield_size = size_extrafield_global; + file_info.version_madeby = (uint16_t)version_madeby; + file_info.comment = comment; +- if (file_info.comment != NULL) ++ if (file_info.comment) + file_info.comment_size = (uint16_t)strlen(file_info.comment); + file_info.flag = (uint16_t)flag_base; + if (zip64) +@@ -498,7 +503,7 @@ int zipOpenNewFileInZip5(zipFile file, const char *filename, const zip_fileinfo + else + file_info.zip64 = MZ_ZIP64_DISABLE; + #ifdef HAVE_WZAES +- if ((password != NULL) || (raw && (file_info.flag & MZ_ZIP_FLAG_ENCRYPTED))) ++ if (password || (raw && (file_info.flag & MZ_ZIP_FLAG_ENCRYPTED))) + file_info.aes_version = MZ_AES_VERSION; + #endif + +@@ -539,7 +544,7 @@ int zipOpenNewFileInZip3_64(zipFile file, const char *filename, const zip_filein + const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, + uint16_t size_extrafield_global, const char *comment, int compression_method, int level, + int raw, int windowBits, int memLevel, int strategy, const char *password, +- uint32_t crc_for_crypting, int zip64) { ++ unsigned long crc_for_crypting, int zip64) { + return zipOpenNewFileInZip4_64(file, filename, zipfi, extrafield_local, size_extrafield_local, + extrafield_global, size_extrafield_global, comment, compression_method, level, raw, windowBits, + memLevel, strategy, password, crc_for_crypting, MZ_VERSION_MADEBY, 0, zip64); +@@ -581,7 +586,7 @@ int zipOpenNewFileInZip_64(zipFile file, const char *filename, const zip_fileinf + int zipWriteInFileInZip(zipFile file, const void *buf, uint32_t len) { + mz_compat *compat = (mz_compat *)file; + int32_t written = 0; +- if (compat == NULL || len >= INT32_MAX) ++ if (!compat || len >= INT32_MAX) + return ZIP_PARAMERROR; + written = mz_zip_entry_write(compat->handle, buf, (int32_t)len); + if ((written < 0) || ((uint32_t)written != len)) +@@ -595,9 +600,9 @@ int zipCloseFileInZipRaw(zipFile file, unsigned long uncompressed_size, unsigned + + int zipCloseFileInZipRaw64(zipFile file, uint64_t uncompressed_size, unsigned long crc32) { + mz_compat *compat = (mz_compat *)file; +- if (compat == NULL) ++ if (!compat) + return ZIP_PARAMERROR; +- return mz_zip_entry_close_raw(compat->handle, (int64_t)uncompressed_size, crc32); ++ return mz_zip_entry_close_raw(compat->handle, (int64_t)uncompressed_size, (uint32_t)crc32); + } + + int zipCloseFileInZip(zipFile file) { +@@ -606,7 +611,7 @@ int zipCloseFileInZip(zipFile file) { + + int zipCloseFileInZip64(zipFile file) { + mz_compat *compat = (mz_compat *)file; +- if (compat == NULL) ++ if (!compat) + return ZIP_PARAMERROR; + return mz_zip_entry_close(compat->handle); + } +@@ -623,15 +628,15 @@ int zipClose2_64(zipFile file, const char *global_comment, uint16_t version_made + mz_compat *compat = (mz_compat *)file; + int32_t err = MZ_OK; + +- if (compat->handle != NULL) ++ if (compat->handle) + err = zipClose2_MZ(file, global_comment, version_madeby); + +- if (compat->stream != NULL) { ++ if (compat->stream) { + mz_stream_close(compat->stream); + mz_stream_delete(&compat->stream); + } + +- MZ_FREE(compat); ++ free(compat); + + return err; + } +@@ -646,12 +651,12 @@ int zipClose2_MZ(zipFile file, const char *global_comment, uint16_t version_made + mz_compat *compat = (mz_compat *)file; + int32_t err = MZ_OK; + +- if (compat == NULL) ++ if (!compat) + return ZIP_PARAMERROR; +- if (compat->handle == NULL) ++ if (!compat->handle) + return err; + +- if (global_comment != NULL) ++ if (global_comment) + mz_zip_set_comment(compat->handle, global_comment); + + mz_zip_set_version_madeby(compat->handle, version_madeby); +@@ -676,18 +681,21 @@ unzFile unzOpen2(const char *path, zlib_filefunc_def *pzlib_filefunc_def) { + void *stream = NULL; + + if (pzlib_filefunc_def) { +- if (pzlib_filefunc_def->zopen_file != NULL) { +- if (mz_stream_ioapi_create(&stream) == NULL) ++ if (pzlib_filefunc_def->zopen_file) { ++ stream = mz_stream_ioapi_create(); ++ if (!stream) + return NULL; + mz_stream_ioapi_set_filefunc(stream, pzlib_filefunc_def); +- } else if (pzlib_filefunc_def->opaque != NULL) { +- if (mz_stream_create(&stream, (mz_stream_vtbl *)pzlib_filefunc_def->opaque) == NULL) ++ } else if (pzlib_filefunc_def->opaque) { ++ stream = mz_stream_create((mz_stream_vtbl *)pzlib_filefunc_def->opaque); ++ if (!stream) + return NULL; + } + } + +- if (stream == NULL) { +- if (mz_stream_os_create(&stream) == NULL) ++ if (!stream) { ++ stream = mz_stream_os_create(); ++ if (!stream) + return NULL; + } + +@@ -697,7 +705,7 @@ unzFile unzOpen2(const char *path, zlib_filefunc_def *pzlib_filefunc_def) { + } + + unz = unzOpen_MZ(stream); +- if (unz == NULL) { ++ if (!unz) { + mz_stream_close(stream); + mz_stream_delete(&stream); + return NULL; +@@ -710,18 +718,21 @@ unzFile unzOpen2_64(const void *path, zlib_filefunc64_def *pzlib_filefunc_def) { + void *stream = NULL; + + if (pzlib_filefunc_def) { +- if (pzlib_filefunc_def->zopen64_file != NULL) { +- if (mz_stream_ioapi_create(&stream) == NULL) ++ if (pzlib_filefunc_def->zopen64_file) { ++ stream = mz_stream_ioapi_create(); ++ if (!stream) + return NULL; + mz_stream_ioapi_set_filefunc64(stream, pzlib_filefunc_def); +- } else if (pzlib_filefunc_def->opaque != NULL) { +- if (mz_stream_create(&stream, (mz_stream_vtbl *)pzlib_filefunc_def->opaque) == NULL) ++ } else if (pzlib_filefunc_def->opaque) { ++ stream = mz_stream_create((mz_stream_vtbl *)pzlib_filefunc_def->opaque); ++ if (!stream) + return NULL; + } + } + +- if (stream == NULL) { +- if (mz_stream_os_create(&stream) == NULL) ++ if (!stream) { ++ stream = mz_stream_os_create(); ++ if (!stream) + return NULL; + } + +@@ -731,7 +742,7 @@ unzFile unzOpen2_64(const void *path, zlib_filefunc64_def *pzlib_filefunc_def) { + } + + unz = unzOpen_MZ(stream); +- if (unz == NULL) { ++ if (!unz) { + mz_stream_close(stream); + mz_stream_delete(&stream); + return NULL; +@@ -741,14 +752,14 @@ unzFile unzOpen2_64(const void *path, zlib_filefunc64_def *pzlib_filefunc_def) { + + void* unzGetHandle_MZ(unzFile file) { + mz_compat *compat = (mz_compat *)file; +- if (compat == NULL) ++ if (!compat) + return NULL; + return compat->handle; + } + + void* unzGetStream_MZ(unzFile file) { + mz_compat *compat = (mz_compat *)file; +- if (compat == NULL) ++ if (!compat) + return NULL; + return compat->stream; + } +@@ -758,16 +769,18 @@ unzFile unzOpen_MZ(void *stream) { + int32_t err = MZ_OK; + void *handle = NULL; + +- mz_zip_create(&handle); +- err = mz_zip_open(handle, stream, MZ_OPEN_MODE_READ); ++ handle = mz_zip_create(); ++ if (!handle) ++ return NULL; + ++ err = mz_zip_open(handle, stream, MZ_OPEN_MODE_READ); + if (err != MZ_OK) { + mz_zip_delete(&handle); + return NULL; + } + +- compat = (mz_compat *)MZ_ALLOC(sizeof(mz_compat)); +- if (compat != NULL) { ++ compat = (mz_compat *)calloc(1, sizeof(mz_compat)); ++ if (compat) { + compat->handle = handle; + compat->stream = stream; + +@@ -783,18 +796,18 @@ int unzClose(unzFile file) { + mz_compat *compat = (mz_compat *)file; + int32_t err = MZ_OK; + +- if (compat == NULL) ++ if (!compat) + return UNZ_PARAMERROR; + +- if (compat->handle != NULL) ++ if (compat->handle) + err = unzClose_MZ(file); + +- if (compat->stream != NULL) { ++ if (compat->stream) { + mz_stream_close(compat->stream); + mz_stream_delete(&compat->stream); + } + +- MZ_FREE(compat); ++ free(compat); + + return err; + } +@@ -804,7 +817,7 @@ int unzClose_MZ(unzFile file) { + mz_compat *compat = (mz_compat *)file; + int32_t err = MZ_OK; + +- if (compat == NULL) ++ if (!compat) + return UNZ_PARAMERROR; + + err = mz_zip_close(compat->handle); +@@ -819,7 +832,7 @@ int unzGetGlobalInfo(unzFile file, unz_global_info* pglobal_info32) { + int32_t err = MZ_OK; + + memset(pglobal_info32, 0, sizeof(unz_global_info)); +- if (compat == NULL) ++ if (!compat) + return UNZ_PARAMERROR; + + err = unzGetGlobalInfo64(file, &global_info64); +@@ -837,7 +850,7 @@ int unzGetGlobalInfo64(unzFile file, unz_global_info64 *pglobal_info) { + int32_t err = MZ_OK; + + memset(pglobal_info, 0, sizeof(unz_global_info64)); +- if (compat == NULL) ++ if (!compat) + return UNZ_PARAMERROR; + err = mz_zip_get_comment(compat->handle, &comment_ptr); + if (err == MZ_OK) +@@ -854,7 +867,7 @@ int unzGetGlobalComment(unzFile file, char *comment, unsigned long comment_size) + const char *comment_ptr = NULL; + int32_t err = MZ_OK; + +- if (comment == NULL || comment_size == 0) ++ if (!comment || !comment_size) + return UNZ_PARAMERROR; + err = mz_zip_get_comment(compat->handle, &comment_ptr); + if (err == MZ_OK) { +@@ -870,23 +883,28 @@ int unzOpenCurrentFile3(unzFile file, int *method, int *level, int raw, const ch + int32_t err = MZ_OK; + void *stream = NULL; + +- if (compat == NULL) ++ if (!compat) + return UNZ_PARAMERROR; +- if (method != NULL) ++ if (method) + *method = 0; +- if (level != NULL) ++ if (level) + *level = 0; + ++ if (mz_zip_entry_is_open(compat->handle) == MZ_OK) { ++ /* zlib minizip does not error out here if close returns errors */ ++ unzCloseCurrentFile(file); ++ } ++ + compat->total_out = 0; + err = mz_zip_entry_read_open(compat->handle, (uint8_t)raw, password); + if (err == MZ_OK) + err = mz_zip_entry_get_info(compat->handle, &file_info); + if (err == MZ_OK) { +- if (method != NULL) { ++ if (method) { + *method = file_info->compression_method; + } + +- if (level != NULL) { ++ if (level) { + *level = 6; + switch (file_info->flag & 0x06) { + case MZ_ZIP_FLAG_DEFLATE_SUPER_FAST: +@@ -923,7 +941,7 @@ int unzOpenCurrentFile2(unzFile file, int *method, int *level, int raw) { + int unzReadCurrentFile(unzFile file, void *buf, uint32_t len) { + mz_compat *compat = (mz_compat *)file; + int32_t err = MZ_OK; +- if (compat == NULL || len >= INT32_MAX) ++ if (!compat || len >= INT32_MAX) + return UNZ_PARAMERROR; + err = mz_zip_entry_read(compat->handle, buf, (int32_t)len); + if (err > 0) +@@ -934,7 +952,7 @@ int unzReadCurrentFile(unzFile file, void *buf, uint32_t len) { + int unzCloseCurrentFile(unzFile file) { + mz_compat *compat = (mz_compat *)file; + int32_t err = MZ_OK; +- if (compat == NULL) ++ if (!compat) + return UNZ_PARAMERROR; + err = mz_zip_entry_close(compat->handle); + return err; +@@ -948,14 +966,14 @@ int unzGetCurrentFileInfo(unzFile file, unz_file_info *pfile_info, char *filenam + uint16_t bytes_to_copy = 0; + int32_t err = MZ_OK; + +- if (compat == NULL) ++ if (!compat) + return UNZ_PARAMERROR; + + err = mz_zip_entry_get_info(compat->handle, &file_info); + if (err != MZ_OK) + return err; + +- if (pfile_info != NULL) { ++ if (pfile_info) { + pfile_info->version = file_info->version_madeby; + pfile_info->version_needed = file_info->version_needed; + pfile_info->flag = file_info->flag; +@@ -976,7 +994,7 @@ int unzGetCurrentFileInfo(unzFile file, unz_file_info *pfile_info, char *filenam + pfile_info->compressed_size = (uint32_t)file_info->compressed_size; + pfile_info->uncompressed_size = (uint32_t)file_info->uncompressed_size; + } +- if (filename_size > 0 && filename != NULL && file_info->filename != NULL) { ++ if (filename_size > 0 && filename && file_info->filename) { + bytes_to_copy = (uint16_t)filename_size; + if (bytes_to_copy > file_info->filename_size) + bytes_to_copy = file_info->filename_size; +@@ -984,13 +1002,13 @@ int unzGetCurrentFileInfo(unzFile file, unz_file_info *pfile_info, char *filenam + if (bytes_to_copy < filename_size) + filename[bytes_to_copy] = 0; + } +- if (extrafield_size > 0 && extrafield != NULL) { ++ if (extrafield_size > 0 && extrafield) { + bytes_to_copy = (uint16_t)extrafield_size; + if (bytes_to_copy > file_info->extrafield_size) + bytes_to_copy = file_info->extrafield_size; + memcpy(extrafield, file_info->extrafield, bytes_to_copy); + } +- if (comment_size > 0 && comment != NULL && file_info->comment != NULL) { ++ if (comment_size > 0 && comment && file_info->comment) { + bytes_to_copy = (uint16_t)comment_size; + if (bytes_to_copy > file_info->comment_size) + bytes_to_copy = file_info->comment_size; +@@ -1009,14 +1027,14 @@ int unzGetCurrentFileInfo64(unzFile file, unz_file_info64 * pfile_info, char *fi + uint16_t bytes_to_copy = 0; + int32_t err = MZ_OK; + +- if (compat == NULL) ++ if (!compat) + return UNZ_PARAMERROR; + + err = mz_zip_entry_get_info(compat->handle, &file_info); + if (err != MZ_OK) + return err; + +- if (pfile_info != NULL) { ++ if (pfile_info) { + pfile_info->version = file_info->version_madeby; + pfile_info->version_needed = file_info->version_needed; + pfile_info->flag = file_info->flag; +@@ -1037,7 +1055,7 @@ int unzGetCurrentFileInfo64(unzFile file, unz_file_info64 * pfile_info, char *fi + pfile_info->compressed_size = (uint64_t)file_info->compressed_size; + pfile_info->uncompressed_size = (uint64_t)file_info->uncompressed_size; + } +- if (filename_size > 0 && filename != NULL && file_info->filename != NULL) { ++ if (filename_size > 0 && filename && file_info->filename) { + bytes_to_copy = (uint16_t)filename_size; + if (bytes_to_copy > file_info->filename_size) + bytes_to_copy = file_info->filename_size; +@@ -1045,13 +1063,13 @@ int unzGetCurrentFileInfo64(unzFile file, unz_file_info64 * pfile_info, char *fi + if (bytes_to_copy < filename_size) + filename[bytes_to_copy] = 0; + } +- if (extrafield_size > 0 && extrafield != NULL) { ++ if (extrafield_size > 0 && extrafield) { + bytes_to_copy = (uint16_t)extrafield_size; + if (bytes_to_copy > file_info->extrafield_size) + bytes_to_copy = file_info->extrafield_size; + memcpy(extrafield, file_info->extrafield, bytes_to_copy); + } +- if (comment_size > 0 && comment != NULL && file_info->comment != NULL) { ++ if (comment_size > 0 && comment && file_info->comment) { + bytes_to_copy = (uint16_t)comment_size; + if (bytes_to_copy > file_info->comment_size) + bytes_to_copy = file_info->comment_size; +@@ -1064,7 +1082,7 @@ int unzGetCurrentFileInfo64(unzFile file, unz_file_info64 * pfile_info, char *fi + + int unzGoToFirstFile(unzFile file) { + mz_compat *compat = (mz_compat *)file; +- if (compat == NULL) ++ if (!compat) + return UNZ_PARAMERROR; + compat->entry_index = 0; + return mz_zip_goto_first_entry(compat->handle); +@@ -1073,7 +1091,7 @@ int unzGoToFirstFile(unzFile file) { + int unzGoToNextFile(unzFile file) { + mz_compat *compat = (mz_compat *)file; + int32_t err = MZ_OK; +- if (compat == NULL) ++ if (!compat) + return UNZ_PARAMERROR; + err = mz_zip_goto_next_entry(compat->handle); + if (err != MZ_END_OF_LIST) +@@ -1081,14 +1099,58 @@ int unzGoToNextFile(unzFile file) { + return err; + } + +-int unzLocateFile(unzFile file, const char *filename, unzFileNameComparer filename_compare_func) { ++#if !defined(MZ_COMPAT_VERSION) || MZ_COMPAT_VERSION < 110 ++#ifdef WIN32 ++# define UNZ_DEFAULT_IGNORE_CASE 1 ++#else ++# define UNZ_DEFAULT_IGNORE_CASE 0 ++#endif ++ ++int unzLocateFile(unzFile file, const char *filename, unzFileNameCase filename_case) { + mz_compat *compat = (mz_compat *)file; + mz_zip_file *file_info = NULL; + uint64_t preserve_index = 0; + int32_t err = MZ_OK; + int32_t result = 0; ++ uint8_t ignore_case = UNZ_DEFAULT_IGNORE_CASE; ++ ++ if (!compat) ++ return UNZ_PARAMERROR; ++ ++ if (filename_case == 1) { ++ ignore_case = 0; ++ } else if (filename_case > 1) { ++ ignore_case = 1; ++ } ++ ++ preserve_index = compat->entry_index; ++ ++ err = mz_zip_goto_first_entry(compat->handle); ++ while (err == MZ_OK) { ++ err = mz_zip_entry_get_info(compat->handle, &file_info); ++ if (err != MZ_OK) ++ break; ++ ++ result = mz_path_compare_wc(filename, file_info->filename, !ignore_case); ++ ++ if (result == 0) ++ return MZ_OK; ++ ++ err = mz_zip_goto_next_entry(compat->handle); ++ } ++ ++ compat->entry_index = preserve_index; ++ return err; ++} ++#else ++int unzLocateFile(unzFile file, const char* filename, unzFileNameComparer filename_compare_func) { ++ mz_compat* compat = (mz_compat*)file; ++ mz_zip_file* file_info = NULL; ++ uint64_t preserve_index = 0; ++ int32_t err = MZ_OK; ++ int32_t result = 0; + +- if (compat == NULL) ++ if (!compat) + return UNZ_PARAMERROR; + + preserve_index = compat->entry_index; +@@ -1101,7 +1163,8 @@ int unzLocateFile(unzFile file, const char *filename, unzFileNameComparer filena + + if ((intptr_t)filename_compare_func > 2) { + result = filename_compare_func(file, filename, file_info->filename); +- } else { ++ } ++ else { + int32_t case_sensitive = (int32_t)(intptr_t)filename_compare_func; + result = mz_path_compare_wc(filename, file_info->filename, !case_sensitive); + } +@@ -1115,6 +1178,7 @@ int unzLocateFile(unzFile file, const char *filename, unzFileNameComparer filena + compat->entry_index = preserve_index; + return err; + } ++#endif + + /***************************************************************************/ + +@@ -1135,7 +1199,7 @@ int unzGoToFilePos(unzFile file, unz_file_pos *file_pos) { + mz_compat *compat = (mz_compat *)file; + unz64_file_pos file_pos64; + +- if (compat == NULL || file_pos == NULL) ++ if (!compat || !file_pos) + return UNZ_PARAMERROR; + + file_pos64.pos_in_zip_directory = file_pos->pos_in_zip_directory; +@@ -1148,7 +1212,7 @@ int unzGetFilePos64(unzFile file, unz64_file_pos *file_pos) { + mz_compat *compat = (mz_compat *)file; + int64_t offset = 0; + +- if (compat == NULL || file_pos == NULL) ++ if (!compat || !file_pos) + return UNZ_PARAMERROR; + + offset = unzGetOffset64(file); +@@ -1164,7 +1228,7 @@ int unzGoToFilePos64(unzFile file, const unz64_file_pos *file_pos) { + mz_compat *compat = (mz_compat *)file; + int32_t err = MZ_OK; + +- if (compat == NULL || file_pos == NULL) ++ if (!compat || !file_pos) + return UNZ_PARAMERROR; + + err = mz_zip_goto_entry(compat->handle, file_pos->pos_in_zip_directory); +@@ -1179,7 +1243,7 @@ unsigned long unzGetOffset(unzFile file) { + + int64_t unzGetOffset64(unzFile file) { + mz_compat *compat = (mz_compat *)file; +- if (compat == NULL) ++ if (!compat) + return UNZ_PARAMERROR; + return mz_zip_get_entry(compat->handle); + } +@@ -1190,7 +1254,7 @@ int unzSetOffset(unzFile file, unsigned long pos) { + + int unzSetOffset64(unzFile file, int64_t pos) { + mz_compat *compat = (mz_compat *)file; +- if (compat == NULL) ++ if (!compat) + return UNZ_PARAMERROR; + return (int)mz_zip_goto_entry(compat->handle, pos); + } +@@ -1201,7 +1265,7 @@ int unzGetLocalExtrafield(unzFile file, void *buf, unsigned int len) { + int32_t err = MZ_OK; + int32_t bytes_to_copy = 0; + +- if (compat == NULL || buf == NULL || len >= INT32_MAX) ++ if (!compat || !buf || len >= INT32_MAX) + return UNZ_PARAMERROR; + + err = mz_zip_entry_get_local_info(compat->handle, &file_info); +@@ -1230,7 +1294,7 @@ uint64_t unzTell64(unzFile file) { + + uint64_t unztell64(unzFile file) { + mz_compat *compat = (mz_compat *)file; +- if (compat == NULL) ++ if (!compat) + return UNZ_PARAMERROR; + return compat->total_out; + } +@@ -1246,7 +1310,7 @@ int unzSeek64(unzFile file, int64_t offset, int origin) { + int32_t err = MZ_OK; + void *stream = NULL; + +- if (compat == NULL) ++ if (!compat) + return UNZ_PARAMERROR; + err = mz_zip_entry_get_info(compat->handle, &file_info); + if (err != MZ_OK) +@@ -1283,7 +1347,7 @@ int unzeof(unzFile file) { + mz_zip_file *file_info = NULL; + int32_t err = MZ_OK; + +- if (compat == NULL) ++ if (!compat) + return UNZ_PARAMERROR; + err = mz_zip_entry_get_info(compat->handle, &file_info); + if (err != MZ_OK) +@@ -1295,7 +1359,7 @@ int unzeof(unzFile file) { + + void* unzGetStream(unzFile file) { + mz_compat *compat = (mz_compat *)file; +- if (compat == NULL) ++ if (!compat) + return NULL; + return (void *)compat->stream; + } +diff --git a/src/minizip/mz_compat.h b/src/minizip/mz_compat.h +index 808cc74e1..47153ea24 100644 +--- a/src/minizip/mz_compat.h ++++ b/src/minizip/mz_compat.h +@@ -1,7 +1,7 @@ + /* mz_compat.h -- Backwards compatible interface for older versions + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + Copyright (C) 1998-2010 Gilles Vollant + https://www.winimage.com/zLibDll/minizip.html +@@ -63,7 +63,7 @@ typedef uint64_t ZPOS64_T; + typedef void* (ZCALLBACK *open_file_func) (void *opaque, const char *filename, int mode); + typedef void* (ZCALLBACK *open64_file_func) (void *opaque, const void *filename, int mode); + typedef unsigned long (ZCALLBACK *read_file_func) (void *opaque, void *stream, void* buf, unsigned long size); +-typedef unsigned long (ZCALLBACK *write_file_func) (void *opaque, void *stream, const void* buf, ++typedef unsigned long (ZCALLBACK *write_file_func) (void *opaque, void *stream, const void* buf, + unsigned long size); + typedef int (ZCALLBACK *close_file_func) (void *opaque, void *stream); + typedef int (ZCALLBACK *testerror_file_func)(void *opaque, void *stream); +@@ -120,7 +120,7 @@ ZEXPORT void fill_memory_filefunc(zlib_filefunc_def *pzlib_filefunc_def); + + /***************************************************************************/ + +-#if MZ_COMPAT_VERSION <= 110 ++#if !defined(MZ_COMPAT_VERSION) || MZ_COMPAT_VERSION <= 110 + #define mz_dos_date dosDate + #else + #define mz_dos_date dos_date +@@ -130,10 +130,10 @@ typedef struct tm tm_unz; + typedef struct tm tm_zip; + + typedef struct { +- uint32_t mz_dos_date; +- struct tm tmz_date; +- uint16_t internal_fa; /* internal file attributes 2 bytes */ +- uint32_t external_fa; /* external file attributes 4 bytes */ ++ struct tm tmz_date; /* date in understandable format */ ++ unsigned long mz_dos_date; /* if dos_date == 0, tmz_date is used */ ++ unsigned long internal_fa; /* internal file attributes 2 bytes */ ++ unsigned long external_fa; /* external file attributes 4 bytes */ + } zip_fileinfo; + + typedef const char *zipcharpc; +@@ -195,7 +195,7 @@ ZEXPORT int zipOpenNewFileInZip3_64(zipFile file, const char *filename, cons + const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, + uint16_t size_extrafield_global, const char *comment, int compression_method, int level, + int raw, int windowBits, int memLevel, int strategy, const char *password, +- uint32_t crc_for_crypting, int zip64); ++ unsigned long crc_for_crypting, int zip64); + ZEXPORT int zipOpenNewFileInZip4(zipFile file, const char *filename, const zip_fileinfo *zipfi, + const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, + uint16_t size_extrafield_global, const char *comment, int compression_method, int level, +@@ -252,33 +252,34 @@ typedef void *unzFile; + + typedef struct unz_global_info64_s { + uint64_t number_entry; /* total number of entries in the central dir on this disk */ ++ unsigned long size_comment; /* size of the global comment of the zipfile */ + uint32_t number_disk_with_CD; /* number the the disk with central dir, used for spanning ZIP */ +- uint16_t size_comment; /* size of the global comment of the zipfile */ + } unz_global_info64; + + typedef struct unz_global_info_s { +- uint32_t number_entry; /* total number of entries in the central dir on this disk */ ++ unsigned long number_entry; /* total number of entries in the central dir on this disk */ ++ unsigned long size_comment; /* size of the global comment of the zipfile */ + uint32_t number_disk_with_CD; /* number the the disk with central dir, used for spanning ZIP */ +- uint16_t size_comment; /* size of the global comment of the zipfile */ + } unz_global_info; + + typedef struct unz_file_info64_s { +- uint16_t version; /* version made by 2 bytes */ +- uint16_t version_needed; /* version needed to extract 2 bytes */ +- uint16_t flag; /* general purpose bit flag 2 bytes */ +- uint16_t compression_method; /* compression method 2 bytes */ +- uint32_t mz_dos_date; /* last mod file date in Dos fmt 4 bytes */ +- struct tm tmu_date; +- uint32_t crc; /* crc-32 4 bytes */ +- uint64_t compressed_size; /* compressed size 8 bytes */ +- uint64_t uncompressed_size; /* uncompressed size 8 bytes */ +- uint16_t size_filename; /* filename length 2 bytes */ +- uint16_t size_file_extra; /* extra field length 2 bytes */ +- uint16_t size_file_comment; /* file comment length 2 bytes */ ++ unsigned long version; /* version made by 2 bytes */ ++ unsigned long version_needed; /* version needed to extract 2 bytes */ ++ unsigned long flag; /* general purpose bit flag 2 bytes */ ++ unsigned long compression_method; /* compression method 2 bytes */ ++ unsigned long mz_dos_date; /* last mod file date in Dos fmt 4 bytes */ ++ unsigned long crc; /* crc-32 4 bytes */ ++ uint64_t compressed_size; /* compressed size 8 bytes */ ++ uint64_t uncompressed_size; /* uncompressed size 8 bytes */ ++ unsigned long size_filename; /* filename length 2 bytes */ ++ unsigned long size_file_extra; /* extra field length 2 bytes */ ++ unsigned long size_file_comment; /* file comment length 2 bytes */ ++ ++ unsigned long disk_num_start; /* disk number start 4 bytes */ ++ unsigned long internal_fa; /* internal file attributes 2 bytes */ ++ unsigned long external_fa; /* external file attributes 4 bytes */ + +- uint32_t disk_num_start; /* disk number start 4 bytes */ +- uint16_t internal_fa; /* internal file attributes 2 bytes */ +- uint32_t external_fa; /* external file attributes 4 bytes */ ++ struct tm tmu_date; + + uint64_t disk_offset; + +@@ -286,29 +287,39 @@ typedef struct unz_file_info64_s { + } unz_file_info64; + + typedef struct unz_file_info_s { +- uint16_t version; /* version made by 2 bytes */ +- uint16_t version_needed; /* version needed to extract 2 bytes */ +- uint16_t flag; /* general purpose bit flag 2 bytes */ +- uint16_t compression_method; /* compression method 2 bytes */ +- uint32_t mz_dos_date; /* last mod file date in Dos fmt 4 bytes */ +- struct tm tmu_date; +- uint32_t crc; /* crc-32 4 bytes */ +- uint32_t compressed_size; /* compressed size 4 bytes */ +- uint32_t uncompressed_size; /* uncompressed size 4 bytes */ +- uint16_t size_filename; /* filename length 2 bytes */ +- uint16_t size_file_extra; /* extra field length 2 bytes */ +- uint16_t size_file_comment; /* file comment length 2 bytes */ ++ unsigned long version; /* version made by 2 bytes */ ++ unsigned long version_needed; /* version needed to extract 2 bytes */ ++ unsigned long flag; /* general purpose bit flag 2 bytes */ ++ unsigned long compression_method; /* compression method 2 bytes */ ++ unsigned long mz_dos_date; /* last mod file date in Dos fmt 4 bytes */ ++ unsigned long crc; /* crc-32 4 bytes */ ++ unsigned long compressed_size; /* compressed size 4 bytes */ ++ unsigned long uncompressed_size; /* uncompressed size 4 bytes */ ++ unsigned long size_filename; /* filename length 2 bytes */ ++ unsigned long size_file_extra; /* extra field length 2 bytes */ ++ unsigned long size_file_comment; /* file comment length 2 bytes */ ++ ++ unsigned long disk_num_start; /* disk number start 2 bytes */ ++ unsigned long internal_fa; /* internal file attributes 2 bytes */ ++ unsigned long external_fa; /* external file attributes 4 bytes */ + +- uint16_t disk_num_start; /* disk number start 2 bytes */ +- uint16_t internal_fa; /* internal file attributes 2 bytes */ +- uint32_t external_fa; /* external file attributes 4 bytes */ ++ struct tm tmu_date; + + uint64_t disk_offset; + } unz_file_info; + + /***************************************************************************/ + +-typedef int (*unzFileNameComparer)(unzFile file, const char *filename1, const char *filename2); ++#if !defined(MZ_COMPAT_VERSION) || MZ_COMPAT_VERSION < 110 ++/* Possible values: ++ 0 - Uses OS default, e.g. Windows ignores case. ++ 1 - Is case sensitive. ++ >= 2 - Ignore case. ++*/ ++typedef int unzFileNameCase; ++#else ++typedef int (*unzFileNameComparer)(unzFile file, const char* filename1, const char* filename2); ++#endif + typedef int (*unzIteratorFunction)(unzFile file); + typedef int (*unzIteratorFunction2)(unzFile file, unz_file_info64 *pfile_info, char *filename, + uint16_t filename_size, void *extrafield, uint16_t extrafield_size, char *comment, +@@ -349,7 +360,11 @@ ZEXPORT int unzGetCurrentFileInfo64(unzFile file, unz_file_info64 * pfile_in + + ZEXPORT int unzGoToFirstFile(unzFile file); + ZEXPORT int unzGoToNextFile(unzFile file); +-ZEXPORT int unzLocateFile(unzFile file, const char *filename, unzFileNameComparer filename_compare_func); ++#if !defined(MZ_COMPAT_VERSION) || MZ_COMPAT_VERSION < 110 ++ZEXPORT int unzLocateFile(unzFile file, const char *filename, unzFileNameCase filename_case); ++#else ++ZEXPORT int unzLocateFile(unzFile file, const char* filename, unzFileNameComparer filename_compare_func); ++#endif + + ZEXPORT int unzGetLocalExtrafield(unzFile file, void *buf, unsigned int len); + +diff --git a/src/minizip/mz_crypt.c b/src/minizip/mz_crypt.c +index f21b3a1ab..4c8d6596c 100644 +--- a/src/minizip/mz_crypt.c ++++ b/src/minizip/mz_crypt.c +@@ -1,14 +1,13 @@ + /* mz_crypt.c -- Crypto/hash functions + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + + This program is distributed under the terms of the same license as zlib. + See the accompanying LICENSE file for the full text of the license. + */ + +- + #include "mz.h" + #include "mz_os.h" + #include "mz_crypt.h" +@@ -16,7 +15,7 @@ + #if defined(HAVE_ZLIB) + # if !defined(ZLIB_COMPAT) + # include "zlib-ng.h" +-# define ZLIB_PREFIX(x) zng_ ## x ++# define ZLIB_PREFIX(x) zng_##x + # else + # include "zlib.h" + # define ZLIB_PREFIX(x) x +@@ -105,26 +104,31 @@ uint32_t mz_crypt_crc32_update(uint32_t value, const uint8_t *buf, int32_t size) + + #if defined(HAVE_WZAES) + int32_t mz_crypt_pbkdf2(uint8_t *password, int32_t password_length, uint8_t *salt, +- int32_t salt_length, int32_t iteration_count, uint8_t *key, int32_t key_length) { ++ int32_t salt_length, uint32_t iteration_count, uint8_t *key, uint16_t key_length) { + void *hmac1 = NULL; + void *hmac2 = NULL; + void *hmac3 = NULL; + int32_t err = MZ_OK; + uint16_t i = 0; +- uint16_t j = 0; ++ uint32_t j = 0; + uint16_t k = 0; + uint16_t block_count = 0; + uint8_t uu[MZ_HASH_SHA1_SIZE]; + uint8_t ux[MZ_HASH_SHA1_SIZE]; + +- if (password == NULL || salt == NULL || key == NULL) ++ if (!password || !salt || !key) + return MZ_PARAM_ERROR; + + memset(key, 0, key_length); + +- mz_crypt_hmac_create(&hmac1); +- mz_crypt_hmac_create(&hmac2); +- mz_crypt_hmac_create(&hmac3); ++ hmac1 = mz_crypt_hmac_create(); ++ hmac2 = mz_crypt_hmac_create(); ++ hmac3 = mz_crypt_hmac_create(); ++ ++ if (!hmac1 || !hmac2 || !hmac3) { ++ err = MZ_MEM_ERROR; ++ goto pbkdf2_cleanup; ++ } + + mz_crypt_hmac_set_algorithm(hmac1, MZ_HASH_SHA1); + mz_crypt_hmac_set_algorithm(hmac2, MZ_HASH_SHA1); +@@ -157,7 +161,7 @@ int32_t mz_crypt_pbkdf2(uint8_t *password, int32_t password_length, uint8_t *sa + if (err != MZ_OK) + break; + +- for(k = 0; k < MZ_HASH_SHA1_SIZE; k += 1) ++ for (k = 0; k < MZ_HASH_SHA1_SIZE; k += 1) + ux[k] ^= uu[k]; + + err = mz_crypt_hmac_copy(hmac1, hmac3); +@@ -175,6 +179,7 @@ int32_t mz_crypt_pbkdf2(uint8_t *password, int32_t password_length, uint8_t *sa + key[k++] = ux[j++]; + } + ++pbkdf2_cleanup: + /* hmac3 uses the same provider as hmac2, so it must be deleted + before the context is destroyed. */ + mz_crypt_hmac_delete(&hmac3); +diff --git a/src/minizip/mz_crypt.h b/src/minizip/mz_crypt.h +index 59a193c02..1837af800 100644 +--- a/src/minizip/mz_crypt.h ++++ b/src/minizip/mz_crypt.h +@@ -1,7 +1,7 @@ + /* mz_crypt.h -- Crypto/hash functions + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + + This program is distributed under the terms of the same license as zlib. +@@ -20,7 +20,7 @@ extern "C" { + uint32_t mz_crypt_crc32_update(uint32_t value, const uint8_t *buf, int32_t size); + + int32_t mz_crypt_pbkdf2(uint8_t *password, int32_t password_length, uint8_t *salt, +- int32_t salt_length, int32_t iteration_count, uint8_t *key, int32_t key_length); ++ int32_t salt_length, uint32_t iteration_count, uint8_t *key, uint16_t key_length); + + /***************************************************************************/ + +@@ -30,17 +30,21 @@ void mz_crypt_sha_reset(void *handle); + int32_t mz_crypt_sha_begin(void *handle); + int32_t mz_crypt_sha_update(void *handle, const void *buf, int32_t size); + int32_t mz_crypt_sha_end(void *handle, uint8_t *digest, int32_t digest_size); +-void mz_crypt_sha_set_algorithm(void *handle, uint16_t algorithm); +-void* mz_crypt_sha_create(void **handle); ++int32_t mz_crypt_sha_set_algorithm(void *handle, uint16_t algorithm); ++void* mz_crypt_sha_create(void); + void mz_crypt_sha_delete(void **handle); + + void mz_crypt_aes_reset(void *handle); +-int32_t mz_crypt_aes_encrypt(void *handle, uint8_t *buf, int32_t size); +-int32_t mz_crypt_aes_decrypt(void *handle, uint8_t *buf, int32_t size); +-int32_t mz_crypt_aes_set_encrypt_key(void *handle, const void *key, int32_t key_length); +-int32_t mz_crypt_aes_set_decrypt_key(void *handle, const void *key, int32_t key_length); ++int32_t mz_crypt_aes_encrypt(void *handle, const void *aad, int32_t aad_size, uint8_t *buf, int32_t size); ++int32_t mz_crypt_aes_encrypt_final(void *handle, uint8_t *buf, int32_t size, uint8_t *tag, int32_t tag_size); ++int32_t mz_crypt_aes_decrypt(void *handle, const void *aad, int32_t aad_size, uint8_t *buf, int32_t size); ++int32_t mz_crypt_aes_decrypt_final(void *handle, uint8_t *buf, int32_t size, const uint8_t *tag, int32_t tag_size); ++int32_t mz_crypt_aes_set_encrypt_key(void *handle, const void *key, int32_t key_length, ++ const void *iv, int32_t iv_length); ++int32_t mz_crypt_aes_set_decrypt_key(void *handle, const void *key, int32_t key_length, ++ const void *iv, int32_t iv_length); + void mz_crypt_aes_set_mode(void *handle, int32_t mode); +-void* mz_crypt_aes_create(void **handle); ++void* mz_crypt_aes_create(void); + void mz_crypt_aes_delete(void **handle); + + void mz_crypt_hmac_reset(void *handle); +@@ -49,13 +53,9 @@ int32_t mz_crypt_hmac_update(void *handle, const void *buf, int32_t size); + int32_t mz_crypt_hmac_end(void *handle, uint8_t *digest, int32_t digest_size); + int32_t mz_crypt_hmac_copy(void *src_handle, void *target_handle); + void mz_crypt_hmac_set_algorithm(void *handle, uint16_t algorithm); +-void* mz_crypt_hmac_create(void **handle); ++void* mz_crypt_hmac_create(void); + void mz_crypt_hmac_delete(void **handle); + +-int32_t mz_crypt_sign(uint8_t *message, int32_t message_size, uint8_t *cert_data, int32_t cert_data_size, +- const char *cert_pwd, uint8_t **signature, int32_t *signature_size); +-int32_t mz_crypt_sign_verify(uint8_t *message, int32_t message_size, uint8_t *signature, int32_t signature_size); +- + /***************************************************************************/ + + #ifdef __cplusplus +diff --git a/src/minizip/mz_os.c b/src/minizip/mz_os.c +index c93ed0475..57b1722fc 100644 +--- a/src/minizip/mz_os.c ++++ b/src/minizip/mz_os.c +@@ -1,7 +1,7 @@ + /* mz_os.c -- System functions + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + Copyright (C) 1998-2010 Gilles Vollant + https://www.winimage.com/zLibDll/minizip.html +@@ -17,13 +17,14 @@ + #include "mz_strm_os.h" + + #include /* tolower */ ++#include + + /***************************************************************************/ + + int32_t mz_path_combine(char *path, const char *join, int32_t max_path) { + int32_t path_len = 0; + +- if (path == NULL || join == NULL || max_path == 0) ++ if (!path || !join || !max_path) + return MZ_PARAM_ERROR; + + path_len = (int32_t)strlen(path); +@@ -67,7 +68,7 @@ int32_t mz_path_remove_slash(char *path) { + + int32_t mz_path_has_slash(const char *path) { + int32_t path_len = (int32_t)strlen(path); +- if (path[path_len - 1] != '\\' && path[path_len - 1] != '/') ++ if (path_len > 0 && path[path_len - 1] != '\\' && path[path_len - 1] != '/') + return MZ_EXIST_ERROR; + return MZ_OK; + } +@@ -130,7 +131,6 @@ int32_t mz_path_resolve(const char *path, char *output, int32_t max_output) { + const char *check = output; + char *target = output; + +- + if (max_output <= 0) + return MZ_PARAM_ERROR; + +@@ -171,11 +171,11 @@ int32_t mz_path_resolve(const char *path, char *output, int32_t max_output) { + if ((*check == 0) || (*check == '\\' || *check == '/')) { + source += (check - source); + +- /* Search backwards for previous slash */ ++ /* Search backwards for previous slash or the start of the output string */ + if (target != output) { + target -= 1; + do { +- if ((*target == '\\') || (*target == '/')) ++ if ((target == output) ||(*target == '\\') || (*target == '/')) + break; + + target -= 1; +@@ -213,7 +213,7 @@ int32_t mz_path_resolve(const char *path, char *output, int32_t max_output) { + int32_t mz_path_remove_filename(char *path) { + char *path_ptr = NULL; + +- if (path == NULL) ++ if (!path) + return MZ_PARAM_ERROR; + + path_ptr = path + strlen(path) - 1; +@@ -236,7 +236,7 @@ int32_t mz_path_remove_filename(char *path) { + int32_t mz_path_remove_extension(char *path) { + char *path_ptr = NULL; + +- if (path == NULL) ++ if (!path) + return MZ_PARAM_ERROR; + + path_ptr = path + strlen(path) - 1; +@@ -261,7 +261,7 @@ int32_t mz_path_remove_extension(char *path) { + int32_t mz_path_get_filename(const char *path, const char **filename) { + const char *match = NULL; + +- if (path == NULL || filename == NULL) ++ if (!path || !filename) + return MZ_PARAM_ERROR; + + *filename = NULL; +@@ -271,7 +271,7 @@ int32_t mz_path_get_filename(const char *path, const char **filename) { + *filename = match + 1; + } + +- if (*filename == NULL) ++ if (!*filename) + return MZ_EXIST_ERROR; + + return MZ_OK; +@@ -279,21 +279,17 @@ int32_t mz_path_get_filename(const char *path, const char **filename) { + + int32_t mz_dir_make(const char *path) { + int32_t err = MZ_OK; +- size_t len = 0; + char *current_dir = NULL; + char *match = NULL; + char hold = 0; + ++ if (!*path) ++ return MZ_OK; + +- len = strlen(path); +- if (len <= 0 || len > INT16_MAX) +- return 0; +- +- current_dir = (char *)MZ_ALLOC(len + 1); +- if (current_dir == NULL) ++ current_dir = strdup(path); ++ if (!current_dir) + return MZ_MEM_ERROR; + +- strcpy(current_dir, path); + mz_path_remove_slash(current_dir); + + err = mz_os_make_dir(current_dir); +@@ -316,7 +312,7 @@ int32_t mz_dir_make(const char *path) { + } + } + +- MZ_FREE(current_dir); ++ free(current_dir); + return err; + } + +@@ -327,10 +323,11 @@ int32_t mz_file_get_crc(const char *path, uint32_t *result_crc) { + int32_t err = MZ_OK; + uint8_t buf[16384]; + +- mz_stream_os_create(&stream); ++ stream = mz_stream_os_create(); ++ if (!stream) ++ return MZ_MEM_ERROR; + + err = mz_stream_os_open(stream, path, MZ_OPEN_MODE_READ); +- + if (err == MZ_OK) { + do { + read = mz_stream_os_read(stream, buf, sizeof(buf)); +diff --git a/src/minizip/mz_os.h b/src/minizip/mz_os.h +index b3e2a58c1..ad6ea4f11 100644 +--- a/src/minizip/mz_os.h ++++ b/src/minizip/mz_os.h +@@ -1,7 +1,7 @@ + /* mz_os.h -- System functions + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + + This program is distributed under the terms of the same license as zlib. +@@ -41,8 +41,9 @@ extern "C" { + (MZ_VERSION_MADEBY_ZIP_VERSION)) + + #define MZ_PATH_SLASH_UNIX ('/') ++#define MZ_PATH_SLASH_WINDOWS ('\\') + #if defined(_WIN32) +-# define MZ_PATH_SLASH_PLATFORM ('\\') ++# define MZ_PATH_SLASH_PLATFORM (MZ_PATH_SLASH_WINDOWS) + #else + # define MZ_PATH_SLASH_PLATFORM (MZ_PATH_SLASH_UNIX) + #endif +@@ -106,10 +107,10 @@ wchar_t *mz_os_unicode_string_create(const char *string, int32_t encoding); + void mz_os_unicode_string_delete(wchar_t **string); + /* Delete a unicode string that was created */ + +-uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding); ++char *mz_os_utf8_string_create(const char *string, int32_t encoding); + /* Create a utf8 string from a string with another encoding */ + +-void mz_os_utf8_string_delete(uint8_t **string); ++void mz_os_utf8_string_delete(char **string); + /* Delete a utf8 string that was created */ + + int32_t mz_os_rand(uint8_t *buf, int32_t size); +diff --git a/src/minizip/mz_os_posix.c b/src/minizip/mz_os_posix.c +index 85615ac0c..6736d0997 100644 +--- a/src/minizip/mz_os_posix.c ++++ b/src/minizip/mz_os_posix.c +@@ -1,7 +1,7 @@ + /* mz_os_posix.c -- System functions for posix + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + + This program is distributed under the terms of the same license as zlib. +@@ -17,7 +17,7 @@ + #if defined(HAVE_ICONV) + #include + #endif +- ++#include + #include + #include + +@@ -34,26 +34,22 @@ + # include + #endif + #if defined(HAVE_LIBBSD) +-# include +-# ifndef __u_char_defined +- typedef unsigned char u_char; +-# endif +-# include /* arc4random_buf */ ++# include /* arc4random_buf */ + #endif + + /***************************************************************************/ + + #if defined(HAVE_ICONV) +-uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { ++char *mz_os_utf8_string_create(const char *string, int32_t encoding) { + iconv_t cd; + const char *from_encoding = NULL; + size_t result = 0; + size_t string_length = 0; + size_t string_utf8_size = 0; +- uint8_t *string_utf8 = NULL; +- uint8_t *string_utf8_ptr = NULL; ++ char *string_utf8 = NULL; ++ char *string_utf8_ptr = NULL; + +- if (string == NULL) ++ if (!string) + return NULL; + + if (encoding == MZ_ENCODING_CODEPAGE_437) +@@ -75,12 +71,10 @@ uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { + + string_length = strlen(string); + string_utf8_size = string_length * 2; +- string_utf8 = (uint8_t *)MZ_ALLOC((int32_t)(string_utf8_size + 1)); ++ string_utf8 = (char *)calloc((int32_t)(string_utf8_size + 1), sizeof(char)); + string_utf8_ptr = string_utf8; + + if (string_utf8) { +- memset(string_utf8, 0, string_utf8_size + 1); +- + result = iconv(cd, (char **)&string, &string_length, + (char **)&string_utf8_ptr, &string_utf8_size); + } +@@ -88,36 +82,43 @@ uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { + iconv_close(cd); + + if (result == (size_t)-1) { +- MZ_FREE(string_utf8); ++ free(string_utf8); + string_utf8 = NULL; + } + + return string_utf8; + } + #else +-uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { +- size_t string_length = 0; +- uint8_t *string_copy = NULL; +- +- string_length = strlen(string); +- string_copy = (uint8_t *)MZ_ALLOC((int32_t)(string_length + 1)); +- strncpy((char *)string_copy, string, string_length); +- string_copy[string_length] = 0; +- +- return string_copy; ++char *mz_os_utf8_string_create(const char *string, int32_t encoding) { ++ return strdup(string); + } + #endif + +-void mz_os_utf8_string_delete(uint8_t **string) { +- if (string != NULL) { +- MZ_FREE(*string); ++void mz_os_utf8_string_delete(char **string) { ++ if (string) { ++ free(*string); + *string = NULL; + } + } + + /***************************************************************************/ + +-#if defined(HAVE_ARC4RANDOM_BUF) ++#if defined(HAVE_GETRANDOM) ++int32_t mz_os_rand(uint8_t *buf, int32_t size) { ++ int32_t left = size; ++ int32_t written = 0; ++ ++ while (left > 0) { ++ written = getrandom(buf, left, 0); ++ if (written < 0) ++ return MZ_INTERNAL_ERROR; ++ ++ buf += written; ++ left -= written; ++ } ++ return size - left; ++} ++#elif defined(HAVE_ARC4RANDOM_BUF) + int32_t mz_os_rand(uint8_t *buf, int32_t size) { + if (size < 0) + return 0; +@@ -139,21 +140,6 @@ int32_t mz_os_rand(uint8_t *buf, int32_t size) { + } + return size - left; + } +-#elif defined(HAVE_GETRANDOM) +-int32_t mz_os_rand(uint8_t *buf, int32_t size) { +- int32_t left = size; +- int32_t written = 0; +- +- while (left > 0) { +- written = getrandom(buf, left, 0); +- if (written < 0) +- return MZ_INTERNAL_ERROR; +- +- buf += written; +- left -= written; +- } +- return size - left; +-} + #else + int32_t mz_os_rand(uint8_t *buf, int32_t size) { + static unsigned calls = 0; +@@ -213,26 +199,22 @@ int64_t mz_os_get_file_size(const char *path) { + int32_t mz_os_get_file_date(const char *path, time_t *modified_date, time_t *accessed_date, time_t *creation_date) { + struct stat path_stat; + char *name = NULL; +- size_t len = 0; + int32_t err = MZ_INTERNAL_ERROR; + + memset(&path_stat, 0, sizeof(path_stat)); + + if (strcmp(path, "-") != 0) { + /* Not all systems allow stat'ing a file with / appended */ +- len = strlen(path); +- name = (char *)malloc(len + 1); +- strncpy(name, path, len); +- name[len - 1] = 0; ++ name = strdup(path); + mz_path_remove_slash(name); + + if (stat(name, &path_stat) == 0) { +- if (modified_date != NULL) ++ if (modified_date) + *modified_date = path_stat.st_mtime; +- if (accessed_date != NULL) ++ if (accessed_date) + *accessed_date = path_stat.st_atime; + /* Creation date not supported */ +- if (creation_date != NULL) ++ if (creation_date) + *creation_date = 0; + + err = MZ_OK; +@@ -295,13 +277,13 @@ DIR* mz_os_open_dir(const char *path) { + } + + struct dirent* mz_os_read_dir(DIR *dir) { +- if (dir == NULL) ++ if (!dir) + return NULL; + return readdir(dir); + } + + int32_t mz_os_close_dir(DIR *dir) { +- if (dir == NULL) ++ if (!dir) + return MZ_PARAM_ERROR; + if (closedir(dir) == -1) + return MZ_INTERNAL_ERROR; +@@ -360,8 +342,15 @@ uint64_t mz_os_ms_time(void) { + + ts.tv_sec = mts.tv_sec; + ts.tv_nsec = mts.tv_nsec; +-#else ++#elif !defined(_POSIX_MONOTONIC_CLOCK) || _POSIX_MONOTONIC_CLOCK < 0 ++ clock_gettime(CLOCK_REALTIME, &ts); ++#elif _POSIX_MONOTONIC_CLOCK > 0 + clock_gettime(CLOCK_MONOTONIC, &ts); ++#else ++ if (sysconf(_SC_MONOTONIC_CLOCK) > 0) ++ clock_gettime(CLOCK_MONOTONIC, &ts); ++ else ++ clock_gettime(CLOCK_REALTIME, &ts); + #endif + + return ((uint64_t)ts.tv_sec * 1000) + ((uint64_t)ts.tv_nsec / 1000000); +diff --git a/src/minizip/mz_os_win32.c b/src/minizip/mz_os_win32.c +index 7effef731..808749b5d 100644 +--- a/src/minizip/mz_os_win32.c ++++ b/src/minizip/mz_os_win32.c +@@ -1,32 +1,30 @@ + /* mz_os_win32.c -- System functions for Windows + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + + This program is distributed under the terms of the same license as zlib. + See the accompanying LICENSE file for the full text of the license. + */ + +- + #include "mz.h" + #include "mz_os.h" + #include "mz_strm_os.h" + + #include ++#include + + /***************************************************************************/ + +-#if defined(WINAPI_FAMILY_PARTITION) && (!(defined(MZ_WINRT_API))) +-# if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +-# define MZ_WINRT_API 1 +-# endif +-#endif +- + #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY + # define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1 + #endif + ++#ifndef _WIN32_WINNT_WIN8 ++# define _WIN32_WINNT_WIN8 0x0602 ++#endif ++ + /***************************************************************************/ + + typedef struct DIR_int_s { +@@ -45,37 +43,33 @@ wchar_t *mz_os_unicode_string_create(const char *string, int32_t encoding) { + string_wide_size = MultiByteToWideChar(encoding, 0, string, -1, NULL, 0); + if (string_wide_size == 0) + return NULL; +- string_wide = (wchar_t *)MZ_ALLOC((string_wide_size + 1) * sizeof(wchar_t)); +- if (string_wide == NULL) ++ string_wide = (wchar_t *)calloc(string_wide_size + 1, sizeof(wchar_t)); ++ if (!string_wide) + return NULL; + +- memset(string_wide, 0, sizeof(wchar_t) * (string_wide_size + 1)); + MultiByteToWideChar(encoding, 0, string, -1, string_wide, string_wide_size); +- + return string_wide; + } + + void mz_os_unicode_string_delete(wchar_t **string) { +- if (string != NULL) { +- MZ_FREE(*string); ++ if (string) { ++ free(*string); + *string = NULL; + } + } + +-uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { ++char *mz_os_utf8_string_create(const char *string, int32_t encoding) { + wchar_t *string_wide = NULL; +- uint8_t *string_utf8 = NULL; ++ char *string_utf8 = NULL; + uint32_t string_utf8_size = 0; + + string_wide = mz_os_unicode_string_create(string, encoding); + if (string_wide) { + string_utf8_size = WideCharToMultiByte(CP_UTF8, 0, string_wide, -1, NULL, 0, NULL, NULL); +- string_utf8 = (uint8_t *)MZ_ALLOC((string_utf8_size + 1) * sizeof(wchar_t)); ++ string_utf8 = (char *)calloc(string_utf8_size + 1, sizeof(char)); + +- if (string_utf8) { +- memset(string_utf8, 0, string_utf8_size + 1); +- WideCharToMultiByte(CP_UTF8, 0, string_wide, -1, (char *)string_utf8, string_utf8_size, NULL, NULL); +- } ++ if (string_utf8) ++ WideCharToMultiByte(CP_UTF8, 0, string_wide, -1, string_utf8, string_utf8_size, NULL, NULL); + + mz_os_unicode_string_delete(&string_wide); + } +@@ -83,26 +77,24 @@ uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { + return string_utf8; + } + +-uint8_t *mz_os_utf8_string_create_from_unicode(const wchar_t *string, int32_t encoding) { +- uint8_t *string_utf8 = NULL; ++char *mz_os_utf8_string_create_from_unicode(const wchar_t *string, int32_t encoding) { ++ char *string_utf8 = NULL; + uint32_t string_utf8_size = 0; + + MZ_UNUSED(encoding); + + string_utf8_size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL); +- string_utf8 = (uint8_t *)MZ_ALLOC((string_utf8_size + 1) * sizeof(wchar_t)); ++ string_utf8 = (char *)calloc(string_utf8_size + 1, sizeof(char)); + +- if (string_utf8) { +- memset(string_utf8, 0, string_utf8_size + 1); +- WideCharToMultiByte(CP_UTF8, 0, string, -1, (char *)string_utf8, string_utf8_size, NULL, NULL); +- } ++ if (string_utf8) ++ WideCharToMultiByte(CP_UTF8, 0, string, -1, string_utf8, string_utf8_size, NULL, NULL); + + return string_utf8; + } + +-void mz_os_utf8_string_delete(uint8_t **string) { +- if (string != NULL) { +- MZ_FREE(*string); ++void mz_os_utf8_string_delete(char **string) { ++ if (string) { ++ free(*string); + *string = NULL; + } + } +@@ -116,7 +108,7 @@ int32_t mz_os_rand(uint8_t *buf, int32_t size) { + for (len = 0; len < (int)size; len += 1) { + if (len % 8 == 0) + QueryPerformanceCounter((LARGE_INTEGER *)pentium_tsc); +- buf[len] = ((unsigned char*)pentium_tsc)[len % 8]; ++ buf[len] = ((unsigned char *)pentium_tsc)[len % 8]; + } + + return len; +@@ -128,20 +120,20 @@ int32_t mz_os_rename(const char *source_path, const char *target_path) { + int32_t result = 0; + int32_t err = MZ_OK; + +- if (source_path == NULL || target_path == NULL) ++ if (!source_path || !target_path) + return MZ_PARAM_ERROR; + + source_path_wide = mz_os_unicode_string_create(source_path, MZ_ENCODING_UTF8); +- if (source_path_wide == NULL) { ++ if (!source_path_wide) { + err = MZ_PARAM_ERROR; + } else { + target_path_wide = mz_os_unicode_string_create(target_path, MZ_ENCODING_UTF8); +- if (target_path_wide == NULL) ++ if (!target_path_wide) + err = MZ_PARAM_ERROR; + } + + if (err == MZ_OK) { +-#ifdef MZ_WINRT_API ++#if _WIN32_WINNT >= _WIN32_WINNT_WINXP + result = MoveFileExW(source_path_wide, target_path_wide, MOVEFILE_WRITE_THROUGH); + #else + result = MoveFileW(source_path_wide, target_path_wide); +@@ -162,10 +154,10 @@ int32_t mz_os_unlink(const char *path) { + wchar_t *path_wide = NULL; + int32_t result = 0; + +- if (path == NULL) ++ if (!path) + return MZ_PARAM_ERROR; + path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); +- if (path_wide == NULL) ++ if (!path_wide) + return MZ_PARAM_ERROR; + + if (mz_os_is_dir(path) == MZ_OK) +@@ -185,10 +177,10 @@ int32_t mz_os_file_exists(const char *path) { + wchar_t *path_wide = NULL; + DWORD attribs = 0; + +- if (path == NULL) ++ if (!path) + return MZ_PARAM_ERROR; + path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); +- if (path_wide == NULL) ++ if (!path_wide) + return MZ_PARAM_ERROR; + + attribs = GetFileAttributesW(path_wide); +@@ -205,12 +197,12 @@ int64_t mz_os_get_file_size(const char *path) { + LARGE_INTEGER large_size; + wchar_t *path_wide = NULL; + +- if (path == NULL) ++ if (!path) + return MZ_PARAM_ERROR; + path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); +- if (path_wide == NULL) ++ if (!path_wide) + return MZ_PARAM_ERROR; +-#ifdef MZ_WINRT_API ++#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 + handle = CreateFile2(path_wide, GENERIC_READ, 0, OPEN_EXISTING, NULL); + #else + handle = CreateFileW(path_wide, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); +@@ -247,21 +239,21 @@ int32_t mz_os_get_file_date(const char *path, time_t *modified_date, time_t *acc + wchar_t *path_wide = NULL; + int32_t err = MZ_INTERNAL_ERROR; + +- if (path == NULL) ++ if (!path) + return MZ_PARAM_ERROR; + path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); +- if (path_wide == NULL) ++ if (!path_wide) + return MZ_PARAM_ERROR; + + handle = FindFirstFileW(path_wide, &ff32); +- MZ_FREE(path_wide); ++ free(path_wide); + + if (handle != INVALID_HANDLE_VALUE) { +- if (modified_date != NULL) ++ if (modified_date) + mz_os_file_to_unix_time(ff32.ftLastWriteTime, modified_date); +- if (accessed_date != NULL) ++ if (accessed_date) + mz_os_file_to_unix_time(ff32.ftLastAccessTime, accessed_date); +- if (creation_date != NULL) ++ if (creation_date) + mz_os_file_to_unix_time(ff32.ftCreationTime, creation_date); + + FindClose(handle); +@@ -277,13 +269,13 @@ int32_t mz_os_set_file_date(const char *path, time_t modified_date, time_t acces + wchar_t *path_wide = NULL; + int32_t err = MZ_OK; + +- if (path == NULL) ++ if (!path) + return MZ_PARAM_ERROR; + path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); +- if (path_wide == NULL) ++ if (!path_wide) + return MZ_PARAM_ERROR; + +-#ifdef MZ_WINRT_API ++#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 + handle = CreateFile2(path_wide, GENERIC_READ | GENERIC_WRITE, 0, OPEN_EXISTING, NULL); + #else + handle = CreateFileW(path_wide, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); +@@ -313,10 +305,10 @@ int32_t mz_os_get_file_attribs(const char *path, uint32_t *attributes) { + wchar_t *path_wide = NULL; + int32_t err = MZ_OK; + +- if (path == NULL || attributes == NULL) ++ if (!path || !attributes) + return MZ_PARAM_ERROR; + path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); +- if (path_wide == NULL) ++ if (!path_wide) + return MZ_PARAM_ERROR; + + *attributes = GetFileAttributesW(path_wide); +@@ -332,10 +324,10 @@ int32_t mz_os_set_file_attribs(const char *path, uint32_t attributes) { + wchar_t *path_wide = NULL; + int32_t err = MZ_OK; + +- if (path == NULL) ++ if (!path) + return MZ_PARAM_ERROR; + path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); +- if (path_wide == NULL) ++ if (!path_wide) + return MZ_PARAM_ERROR; + + if (SetFileAttributesW(path_wide, attributes) == 0) +@@ -349,7 +341,7 @@ int32_t mz_os_make_dir(const char *path) { + wchar_t *path_wide = NULL; + int32_t err = MZ_OK; + +- if (path == NULL) ++ if (!path) + return MZ_PARAM_ERROR; + + /* Don't try to create a drive letter */ +@@ -357,7 +349,7 @@ int32_t mz_os_make_dir(const char *path) { + return mz_os_is_dir(path); + + path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); +- if (path_wide == NULL) ++ if (!path_wide) + return MZ_PARAM_ERROR; + + if (CreateDirectoryW(path_wide, NULL) == 0) { +@@ -377,8 +369,7 @@ DIR *mz_os_open_dir(const char *path) { + char fixed_path[320]; + void *handle = NULL; + +- +- if (path == NULL) ++ if (!path) + return NULL; + + strncpy(fixed_path, path, sizeof(fixed_path) - 1); +@@ -388,7 +379,7 @@ DIR *mz_os_open_dir(const char *path) { + mz_path_combine(fixed_path, "*", sizeof(fixed_path)); + + path_wide = mz_os_unicode_string_create(fixed_path, MZ_ENCODING_UTF8); +- if (path_wide == NULL) ++ if (!path_wide) + return NULL; + + handle = FindFirstFileW(path_wide, &find_data); +@@ -397,9 +388,11 @@ DIR *mz_os_open_dir(const char *path) { + if (handle == INVALID_HANDLE_VALUE) + return NULL; + +- dir_int = (DIR_int *)MZ_ALLOC(sizeof(DIR_int)); +- if (dir_int == NULL) ++ dir_int = (DIR_int *)malloc(sizeof(DIR_int)); ++ if (!dir_int) { ++ FindClose(handle); + return NULL; ++ } + dir_int->find_handle = handle; + dir_int->end = 0; + +@@ -411,7 +404,7 @@ DIR *mz_os_open_dir(const char *path) { + struct dirent* mz_os_read_dir(DIR *dir) { + DIR_int *dir_int; + +- if (dir == NULL) ++ if (!dir) + return NULL; + + dir_int = (DIR_int *)dir; +@@ -434,13 +427,13 @@ struct dirent* mz_os_read_dir(DIR *dir) { + int32_t mz_os_close_dir(DIR *dir) { + DIR_int *dir_int; + +- if (dir == NULL) ++ if (!dir) + return MZ_PARAM_ERROR; + + dir_int = (DIR_int *)dir; + if (dir_int->find_handle != INVALID_HANDLE_VALUE) + FindClose(dir_int->find_handle); +- MZ_FREE(dir_int); ++ free(dir_int); + return MZ_OK; + } + +@@ -448,10 +441,10 @@ int32_t mz_os_is_dir(const char *path) { + wchar_t *path_wide = NULL; + uint32_t attribs = 0; + +- if (path == NULL) ++ if (!path) + return MZ_PARAM_ERROR; + path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); +- if (path_wide == NULL) ++ if (!path_wide) + return MZ_PARAM_ERROR; + + attribs = GetFileAttributesW(path_wide); +@@ -469,10 +462,10 @@ int32_t mz_os_is_symlink(const char *path) { + wchar_t *path_wide = NULL; + uint32_t attribs = 0; + +- if (path == NULL) ++ if (!path) + return MZ_PARAM_ERROR; + path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); +- if (path_wide == NULL) ++ if (!path_wide) + return MZ_PARAM_ERROR; + + attribs = GetFileAttributesW(path_wide); +@@ -488,6 +481,7 @@ int32_t mz_os_is_symlink(const char *path) { + + int32_t mz_os_make_symlink(const char *path, const char *target_path) { + typedef BOOLEAN (WINAPI *LPCREATESYMBOLICLINKW)(LPCWSTR, LPCWSTR, DWORD); ++ MEMORY_BASIC_INFORMATION mbi; + LPCREATESYMBOLICLINKW create_symbolic_link_w = NULL; + HMODULE kernel32_mod = NULL; + wchar_t *path_wide = NULL; +@@ -495,33 +489,29 @@ int32_t mz_os_make_symlink(const char *path, const char *target_path) { + int32_t err = MZ_OK; + int32_t flags = 0; + +- if (path == NULL) ++ if (!path) + return MZ_PARAM_ERROR; + +-#ifdef MZ_WINRT_API +- MEMORY_BASIC_INFORMATION mbi; ++ /* Use VirtualQuery instead of GetModuleHandleW for UWP */ + memset(&mbi, 0, sizeof(mbi)); + VirtualQuery(VirtualQuery, &mbi, sizeof(mbi)); + kernel32_mod = (HMODULE)mbi.AllocationBase; +-#else +- kernel32_mod = GetModuleHandleW(L"kernel32.dll"); +-#endif + +- if (kernel32_mod == NULL) ++ if (!kernel32_mod) + return MZ_SUPPORT_ERROR; + + create_symbolic_link_w = (LPCREATESYMBOLICLINKW)GetProcAddress(kernel32_mod, "CreateSymbolicLinkW"); +- if (create_symbolic_link_w == NULL) { ++ if (!create_symbolic_link_w) { + return MZ_SUPPORT_ERROR; + } + + path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); +- if (path_wide == NULL) { ++ if (!path_wide) { + return MZ_PARAM_ERROR; + } + + target_path_wide = mz_os_unicode_string_create(target_path, MZ_ENCODING_UTF8); +- if (target_path_wide != NULL) { ++ if (target_path_wide) { + if (mz_path_has_slash(target_path) == MZ_OK) + flags |= SYMBOLIC_LINK_FLAG_DIRECTORY; + +@@ -573,15 +563,15 @@ int32_t mz_os_read_symlink(const char *path, char *target_path, int32_t max_targ + int32_t target_path_len = 0; + int32_t target_path_idx = 0; + int32_t err = MZ_OK; +- uint8_t *target_path_utf8 = NULL; ++ char *target_path_utf8 = NULL; + +- if (path == NULL) ++ if (!path) + return MZ_PARAM_ERROR; + path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); +- if (path_wide == NULL) ++ if (!path_wide) + return MZ_PARAM_ERROR; + +-#ifdef MZ_WINRT_API ++#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 + CREATEFILE2_EXTENDED_PARAMETERS extended_params; + memset(&extended_params, 0, sizeof(extended_params)); + extended_params.dwSize = sizeof(extended_params); +@@ -609,7 +599,7 @@ int32_t mz_os_read_symlink(const char *path, char *target_path, int32_t max_targ + if (target_path_len > reparse_data->SymbolicLinkReparseBuffer.PrintNameLength) + target_path_len = reparse_data->SymbolicLinkReparseBuffer.PrintNameLength; + +- target_path_wide = (wchar_t *)MZ_ALLOC(target_path_len + sizeof(wchar_t)); ++ target_path_wide = (wchar_t *)malloc(target_path_len + sizeof(wchar_t)); + if (target_path_wide) { + target_path_idx = reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset / sizeof(wchar_t); + memcpy(target_path_wide, &reparse_data->SymbolicLinkReparseBuffer.PathBuffer[target_path_idx], +@@ -619,17 +609,17 @@ int32_t mz_os_read_symlink(const char *path, char *target_path, int32_t max_targ + target_path_utf8 = mz_os_utf8_string_create_from_unicode(target_path_wide, MZ_ENCODING_UTF8); + + if (target_path_utf8) { +- strncpy(target_path, (const char *)target_path_utf8, max_target_path - 1); ++ strncpy(target_path, target_path_utf8, max_target_path - 1); + target_path[max_target_path - 1] = 0; + /* Ensure directories have slash at the end so we can recreate them later */ +- if (mz_os_is_dir((const char *)target_path_utf8) == MZ_OK) ++ if (mz_os_is_dir(target_path_utf8) == MZ_OK) + mz_path_append_slash(target_path, max_target_path, MZ_PATH_SLASH_PLATFORM); + mz_os_utf8_string_delete(&target_path_utf8); + } else { + err = MZ_MEM_ERROR; + } + +- MZ_FREE(target_path_wide); ++ free(target_path_wide); + } else { + err = MZ_MEM_ERROR; + } +diff --git a/src/minizip/mz_strm.c b/src/minizip/mz_strm.c +index da7d5872d..edcbafa0c 100644 +--- a/src/minizip/mz_strm.c ++++ b/src/minizip/mz_strm.c +@@ -1,7 +1,7 @@ + /* mz_strm.c -- Stream interface + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + + This program is distributed under the terms of the same license as zlib. +@@ -19,21 +19,21 @@ + + int32_t mz_stream_open(void *stream, const char *path, int32_t mode) { + mz_stream *strm = (mz_stream *)stream; +- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->open == NULL) ++ if (!strm || !strm->vtbl || !strm->vtbl->open) + return MZ_STREAM_ERROR; + return strm->vtbl->open(strm, path, mode); + } + + int32_t mz_stream_is_open(void *stream) { + mz_stream *strm = (mz_stream *)stream; +- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->is_open == NULL) ++ if (!strm || !strm->vtbl || !strm->vtbl->is_open) + return MZ_STREAM_ERROR; + return strm->vtbl->is_open(strm); + } + + int32_t mz_stream_read(void *stream, void *buf, int32_t size) { + mz_stream *strm = (mz_stream *)stream; +- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->read == NULL) ++ if (!strm || !strm->vtbl || !strm->vtbl->read) + return MZ_PARAM_ERROR; + if (mz_stream_is_open(stream) != MZ_OK) + return MZ_STREAM_ERROR; +@@ -102,7 +102,7 @@ int32_t mz_stream_write(void *stream, const void *buf, int32_t size) { + mz_stream *strm = (mz_stream *)stream; + if (size == 0) + return size; +- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->write == NULL) ++ if (!strm || !strm->vtbl || !strm->vtbl->write) + return MZ_PARAM_ERROR; + if (mz_stream_is_open(stream) != MZ_OK) + return MZ_STREAM_ERROR; +@@ -165,9 +165,9 @@ int32_t mz_stream_copy_stream(void *target, mz_stream_write_cb write_cb, void *s + int32_t read = 0; + int32_t written = 0; + +- if (write_cb == NULL) ++ if (!write_cb) + write_cb = mz_stream_write; +- if (read_cb == NULL) ++ if (!read_cb) + read_cb = mz_stream_read; + + while (len > 0) { +@@ -192,9 +192,9 @@ int32_t mz_stream_copy_stream_to_end(void *target, mz_stream_write_cb write_cb, + int32_t read = 0; + int32_t written = 0; + +- if (write_cb == NULL) ++ if (!write_cb) + write_cb = mz_stream_write; +- if (read_cb == NULL) ++ if (!read_cb) + read_cb = mz_stream_read; + + read = read_cb(source, buf, sizeof(buf)); +@@ -213,7 +213,7 @@ int32_t mz_stream_copy_stream_to_end(void *target, mz_stream_write_cb write_cb, + + int64_t mz_stream_tell(void *stream) { + mz_stream *strm = (mz_stream *)stream; +- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->tell == NULL) ++ if (!strm || !strm->vtbl || !strm->vtbl->tell) + return MZ_PARAM_ERROR; + if (mz_stream_is_open(stream) != MZ_OK) + return MZ_STREAM_ERROR; +@@ -222,7 +222,7 @@ int64_t mz_stream_tell(void *stream) { + + int32_t mz_stream_seek(void *stream, int64_t offset, int32_t origin) { + mz_stream *strm = (mz_stream *)stream; +- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->seek == NULL) ++ if (!strm || !strm->vtbl || !strm->vtbl->seek) + return MZ_PARAM_ERROR; + if (mz_stream_is_open(stream) != MZ_OK) + return MZ_STREAM_ERROR; +@@ -243,7 +243,7 @@ int32_t mz_stream_find(void *stream, const void *find, int32_t find_size, int64_ + uint8_t first = 1; + int32_t err = MZ_OK; + +- if (stream == NULL || find == NULL || position == NULL) ++ if (!stream || !find || !position) + return MZ_PARAM_ERROR; + if (find_size < 0 || find_size >= (int32_t)sizeof(buf)) + return MZ_PARAM_ERROR; +@@ -301,7 +301,7 @@ int32_t mz_stream_find_reverse(void *stream, const void *find, int32_t find_size + int32_t i = 0; + int32_t err = MZ_OK; + +- if (stream == NULL || find == NULL || position == NULL) ++ if (!stream || !find || !position) + return MZ_PARAM_ERROR; + if (find_size < 0 || find_size >= (int32_t)sizeof(buf)) + return MZ_PARAM_ERROR; +@@ -356,7 +356,7 @@ int32_t mz_stream_find_reverse(void *stream, const void *find, int32_t find_size + + int32_t mz_stream_close(void *stream) { + mz_stream *strm = (mz_stream *)stream; +- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->close == NULL) ++ if (!strm || !strm->vtbl || !strm->vtbl->close) + return MZ_PARAM_ERROR; + if (mz_stream_is_open(stream) != MZ_OK) + return MZ_STREAM_ERROR; +@@ -365,7 +365,7 @@ int32_t mz_stream_close(void *stream) { + + int32_t mz_stream_error(void *stream) { + mz_stream *strm = (mz_stream *)stream; +- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->error == NULL) ++ if (!strm || !strm->vtbl || !strm->vtbl->error) + return MZ_PARAM_ERROR; + return strm->vtbl->error(strm); + } +@@ -378,39 +378,37 @@ int32_t mz_stream_set_base(void *stream, void *base) { + + void* mz_stream_get_interface(void *stream) { + mz_stream *strm = (mz_stream *)stream; +- if (strm == NULL || strm->vtbl == NULL) ++ if (!strm || !strm->vtbl) + return NULL; + return (void *)strm->vtbl; + } + + int32_t mz_stream_get_prop_int64(void *stream, int32_t prop, int64_t *value) { + mz_stream *strm = (mz_stream *)stream; +- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->get_prop_int64 == NULL) ++ if (!strm || !strm->vtbl || !strm->vtbl->get_prop_int64) + return MZ_PARAM_ERROR; + return strm->vtbl->get_prop_int64(stream, prop, value); + } + + int32_t mz_stream_set_prop_int64(void *stream, int32_t prop, int64_t value) { + mz_stream *strm = (mz_stream *)stream; +- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->set_prop_int64 == NULL) ++ if (!strm || !strm->vtbl || !strm->vtbl->set_prop_int64) + return MZ_PARAM_ERROR; + return strm->vtbl->set_prop_int64(stream, prop, value); + } + +-void *mz_stream_create(void **stream, mz_stream_vtbl *vtbl) { +- if (stream == NULL) ++void *mz_stream_create(mz_stream_vtbl *vtbl) { ++ if (!vtbl || !vtbl->create) + return NULL; +- if (vtbl == NULL || vtbl->create == NULL) +- return NULL; +- return vtbl->create(stream); ++ return vtbl->create(); + } + + void mz_stream_delete(void **stream) { + mz_stream *strm = NULL; +- if (stream == NULL) ++ if (!stream) + return; + strm = (mz_stream *)*stream; +- if (strm != NULL && strm->vtbl != NULL && strm->vtbl->destroy != NULL) ++ if (strm && strm->vtbl && strm->vtbl->destroy) + strm->vtbl->destroy(stream); + *stream = NULL; + } +@@ -535,26 +533,19 @@ static mz_stream_vtbl mz_stream_raw_vtbl = { + + /***************************************************************************/ + +-void *mz_stream_raw_create(void **stream) { +- mz_stream_raw *raw = NULL; +- +- raw = (mz_stream_raw *)MZ_ALLOC(sizeof(mz_stream_raw)); +- if (raw != NULL) { +- memset(raw, 0, sizeof(mz_stream_raw)); ++void *mz_stream_raw_create(void) { ++ mz_stream_raw *raw = (mz_stream_raw *)calloc(1, sizeof(mz_stream_raw)); ++ if (raw) + raw->stream.vtbl = &mz_stream_raw_vtbl; +- } +- if (stream != NULL) +- *stream = raw; +- + return raw; + } + + void mz_stream_raw_delete(void **stream) { + mz_stream_raw *raw = NULL; +- if (stream == NULL) ++ if (!stream) + return; + raw = (mz_stream_raw *)*stream; +- if (raw != NULL) +- MZ_FREE(raw); ++ if (raw) ++ free(raw); + *stream = NULL; + } +diff --git a/src/minizip/mz_strm.h b/src/minizip/mz_strm.h +index 8b0027cf5..f65baabfb 100644 +--- a/src/minizip/mz_strm.h ++++ b/src/minizip/mz_strm.h +@@ -1,7 +1,7 @@ + /* mz_strm.h -- Stream interface + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + + This program is distributed under the terms of the same license as zlib. +@@ -39,7 +39,7 @@ typedef int64_t (*mz_stream_tell_cb) (void *stream); + typedef int32_t (*mz_stream_seek_cb) (void *stream, int64_t offset, int32_t origin); + typedef int32_t (*mz_stream_close_cb) (void *stream); + typedef int32_t (*mz_stream_error_cb) (void *stream); +-typedef void* (*mz_stream_create_cb) (void **stream); ++typedef void* (*mz_stream_create_cb) (void); + typedef void (*mz_stream_destroy_cb) (void **stream); + + typedef int32_t (*mz_stream_get_prop_int64_cb) (void *stream, int32_t prop, int64_t *value); +@@ -103,7 +103,7 @@ void* mz_stream_get_interface(void *stream); + int32_t mz_stream_get_prop_int64(void *stream, int32_t prop, int64_t *value); + int32_t mz_stream_set_prop_int64(void *stream, int32_t prop, int64_t value); + +-void* mz_stream_create(void **stream, mz_stream_vtbl *vtbl); ++void* mz_stream_create(mz_stream_vtbl *vtbl); + void mz_stream_delete(void **stream); + + /***************************************************************************/ +@@ -120,7 +120,7 @@ int32_t mz_stream_raw_error(void *stream); + int32_t mz_stream_raw_get_prop_int64(void *stream, int32_t prop, int64_t *value); + int32_t mz_stream_raw_set_prop_int64(void *stream, int32_t prop, int64_t value); + +-void* mz_stream_raw_create(void **stream); ++void* mz_stream_raw_create(void); + void mz_stream_raw_delete(void **stream); + + /***************************************************************************/ +diff --git a/src/minizip/mz_strm_mem.c b/src/minizip/mz_strm_mem.c +index f4a882d92..45881b2ba 100644 +--- a/src/minizip/mz_strm_mem.c ++++ b/src/minizip/mz_strm_mem.c +@@ -6,7 +6,7 @@ + + Based on Unzip ioapi.c version 0.22, May 19th, 2003 + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + Copyright (C) 2003 Justin Fletcher + Copyright (C) 1998-2003 Gilles Vollant +@@ -16,7 +16,6 @@ + See the accompanying LICENSE file for the full text of the license. + */ + +- + #include "mz.h" + #include "mz_strm.h" + #include "mz_strm_mem.h" +@@ -57,14 +56,13 @@ static int32_t mz_stream_mem_set_size(void *stream, int32_t size) { + int32_t new_size = size; + uint8_t *new_buf = NULL; + +- +- new_buf = (uint8_t *)MZ_ALLOC((uint32_t)new_size); +- if (new_buf == NULL) ++ new_buf = (uint8_t *)malloc((uint32_t)new_size); ++ if (!new_buf) + return MZ_BUF_ERROR; + + if (mem->buffer) { + memcpy(new_buf, mem->buffer, mem->size); +- MZ_FREE(mem->buffer); ++ free(mem->buffer); + } + + mem->buffer = new_buf; +@@ -92,7 +90,7 @@ int32_t mz_stream_mem_open(void *stream, const char *path, int32_t mode) { + + int32_t mz_stream_mem_is_open(void *stream) { + mz_stream_mem *mem = (mz_stream_mem *)stream; +- if (mem->buffer == NULL) ++ if (!mem->buffer) + return MZ_OPEN_ERROR; + return MZ_OK; + } +@@ -119,7 +117,7 @@ int32_t mz_stream_mem_write(void *stream, const void *buf, int32_t size) { + int32_t new_size = 0; + int32_t err = MZ_OK; + +- if (size == 0) ++ if (!size) + return size; + + if (size > mem->size - mem->position) { +@@ -213,7 +211,7 @@ int32_t mz_stream_mem_get_buffer(void *stream, const void **buf) { + + int32_t mz_stream_mem_get_buffer_at(void *stream, int64_t position, const void **buf) { + mz_stream_mem *mem = (mz_stream_mem *)stream; +- if (buf == NULL || position < 0 || mem->size < position || mem->buffer == NULL) ++ if (!buf || position < 0 || !mem->buffer|| mem->size < position) + return MZ_SEEK_ERROR; + *buf = mem->buffer + position; + return MZ_OK; +@@ -239,30 +237,24 @@ void mz_stream_mem_set_grow_size(void *stream, int32_t grow_size) { + mem->grow_size = grow_size; + } + +-void *mz_stream_mem_create(void **stream) { +- mz_stream_mem *mem = NULL; +- +- mem = (mz_stream_mem *)MZ_ALLOC(sizeof(mz_stream_mem)); +- if (mem != NULL) { +- memset(mem, 0, sizeof(mz_stream_mem)); ++void *mz_stream_mem_create(void) { ++ mz_stream_mem *mem = (mz_stream_mem *)calloc(1, sizeof(mz_stream_mem)); ++ if (mem) { + mem->stream.vtbl = &mz_stream_mem_vtbl; + mem->grow_size = 4096; + } +- if (stream != NULL) +- *stream = mem; +- + return mem; + } + + void mz_stream_mem_delete(void **stream) { + mz_stream_mem *mem = NULL; +- if (stream == NULL) ++ if (!stream) + return; + mem = (mz_stream_mem *)*stream; +- if (mem != NULL) { +- if ((mem->mode & MZ_OPEN_MODE_CREATE) && (mem->buffer != NULL)) +- MZ_FREE(mem->buffer); +- MZ_FREE(mem); ++ if (mem) { ++ if ((mem->mode & MZ_OPEN_MODE_CREATE) && (mem->buffer)) ++ free(mem->buffer); ++ free(mem); + } + *stream = NULL; + } +diff --git a/src/minizip/mz_strm_mem.h b/src/minizip/mz_strm_mem.h +index 5bfa13d8a..ed6f9574e 100644 +--- a/src/minizip/mz_strm_mem.h ++++ b/src/minizip/mz_strm_mem.h +@@ -1,7 +1,7 @@ + /* mz_strm_mem.h -- Stream for memory access + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + + This program is distributed under the terms of the same license as zlib. +@@ -34,7 +34,7 @@ void mz_stream_mem_get_buffer_length(void *stream, int32_t *length); + void mz_stream_mem_set_buffer_limit(void *stream, int32_t limit); + void mz_stream_mem_set_grow_size(void *stream, int32_t grow_size); + +-void* mz_stream_mem_create(void **stream); ++void* mz_stream_mem_create(void); + void mz_stream_mem_delete(void **stream); + + void* mz_stream_mem_get_interface(void); +diff --git a/src/minizip/mz_strm_os.h b/src/minizip/mz_strm_os.h +index 614e25520..0ed279f5f 100644 +--- a/src/minizip/mz_strm_os.h ++++ b/src/minizip/mz_strm_os.h +@@ -1,7 +1,7 @@ + /* mz_sstrm_os.h -- Stream for filesystem access + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + + This program is distributed under the terms of the same license as zlib. +@@ -26,7 +26,7 @@ int32_t mz_stream_os_seek(void *stream, int64_t offset, int32_t origin); + int32_t mz_stream_os_close(void *stream); + int32_t mz_stream_os_error(void *stream); + +-void* mz_stream_os_create(void **stream); ++void* mz_stream_os_create(void); + void mz_stream_os_delete(void **stream); + + void* mz_stream_os_get_interface(void); +diff --git a/src/minizip/mz_strm_os_posix.c b/src/minizip/mz_strm_os_posix.c +index f0b5bd335..b351ebb70 100644 +--- a/src/minizip/mz_strm_os_posix.c ++++ b/src/minizip/mz_strm_os_posix.c +@@ -1,7 +1,7 @@ + /* mz_strm_posix.c -- Stream for filesystem access for posix/linux + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + Modifications for Zip64 support + Copyright (C) 2009-2010 Mathias Svensson +@@ -13,7 +13,6 @@ + See the accompanying LICENSE file for the full text of the license. + */ + +- + #include "mz.h" + #include "mz_strm.h" + #include "mz_strm_os.h" +@@ -71,7 +70,7 @@ int32_t mz_stream_os_open(void *stream, const char *path, int32_t mode) { + mz_stream_posix *posix = (mz_stream_posix *)stream; + const char *mode_fopen = NULL; + +- if (path == NULL) ++ if (!path) + return MZ_PARAM_ERROR; + + if ((mode & MZ_OPEN_MODE_READWRITE) == MZ_OPEN_MODE_READ) +@@ -84,7 +83,7 @@ int32_t mz_stream_os_open(void *stream, const char *path, int32_t mode) { + return MZ_OPEN_ERROR; + + posix->handle = fopen64(path, mode_fopen); +- if (posix->handle == NULL) { ++ if (!posix->handle) { + posix->error = errno; + return MZ_OPEN_ERROR; + } +@@ -96,14 +95,14 @@ int32_t mz_stream_os_open(void *stream, const char *path, int32_t mode) { + } + + int32_t mz_stream_os_is_open(void *stream) { +- mz_stream_posix *posix = (mz_stream_posix*)stream; +- if (posix->handle == NULL) ++ mz_stream_posix *posix = (mz_stream_posix *)stream; ++ if (!posix->handle) + return MZ_OPEN_ERROR; + return MZ_OK; + } + + int32_t mz_stream_os_read(void *stream, void *buf, int32_t size) { +- mz_stream_posix *posix = (mz_stream_posix*)stream; ++ mz_stream_posix *posix = (mz_stream_posix *)stream; + int32_t read = (int32_t)fread(buf, 1, (size_t)size, posix->handle); + if (read < size && ferror(posix->handle)) { + posix->error = errno; +@@ -113,7 +112,7 @@ int32_t mz_stream_os_read(void *stream, void *buf, int32_t size) { + } + + int32_t mz_stream_os_write(void *stream, const void *buf, int32_t size) { +- mz_stream_posix *posix = (mz_stream_posix*)stream; ++ mz_stream_posix *posix = (mz_stream_posix *)stream; + int32_t written = (int32_t)fwrite(buf, 1, (size_t)size, posix->handle); + if (written < size && ferror(posix->handle)) { + posix->error = errno; +@@ -123,7 +122,7 @@ int32_t mz_stream_os_write(void *stream, const void *buf, int32_t size) { + } + + int64_t mz_stream_os_tell(void *stream) { +- mz_stream_posix *posix = (mz_stream_posix*)stream; ++ mz_stream_posix *posix = (mz_stream_posix *)stream; + int64_t position = ftello64(posix->handle); + if (position == -1) { + posix->error = errno; +@@ -133,7 +132,7 @@ int64_t mz_stream_os_tell(void *stream) { + } + + int32_t mz_stream_os_seek(void *stream, int64_t offset, int32_t origin) { +- mz_stream_posix *posix = (mz_stream_posix*)stream; ++ mz_stream_posix *posix = (mz_stream_posix *)stream; + int32_t fseek_origin = 0; + + switch (origin) { +@@ -159,9 +158,9 @@ int32_t mz_stream_os_seek(void *stream, int64_t offset, int32_t origin) { + } + + int32_t mz_stream_os_close(void *stream) { +- mz_stream_posix *posix = (mz_stream_posix*)stream; ++ mz_stream_posix *posix = (mz_stream_posix *)stream; + int32_t closed = 0; +- if (posix->handle != NULL) { ++ if (posix->handle) { + closed = fclose(posix->handle); + posix->handle = NULL; + } +@@ -173,31 +172,24 @@ int32_t mz_stream_os_close(void *stream) { + } + + int32_t mz_stream_os_error(void *stream) { +- mz_stream_posix *posix = (mz_stream_posix*)stream; ++ mz_stream_posix *posix = (mz_stream_posix *)stream; + return posix->error; + } + +-void *mz_stream_os_create(void **stream) { +- mz_stream_posix *posix = NULL; +- +- posix = (mz_stream_posix *)MZ_ALLOC(sizeof(mz_stream_posix)); +- if (posix != NULL) { +- memset(posix, 0, sizeof(mz_stream_posix)); ++void *mz_stream_os_create(void) { ++ mz_stream_posix *posix = (mz_stream_posix *)calloc(1, sizeof(mz_stream_posix)); ++ if (posix) + posix->stream.vtbl = &mz_stream_os_vtbl; +- } +- if (stream != NULL) +- *stream = posix; +- + return posix; + } + + void mz_stream_os_delete(void **stream) { + mz_stream_posix *posix = NULL; +- if (stream == NULL) ++ if (!stream) + return; + posix = (mz_stream_posix *)*stream; +- if (posix != NULL) +- MZ_FREE(posix); ++ if (posix) ++ free(posix); + *stream = NULL; + } + +diff --git a/src/minizip/mz_strm_os_win32.c b/src/minizip/mz_strm_os_win32.c +index 893df5418..c4198ccf2 100644 +--- a/src/minizip/mz_strm_os_win32.c ++++ b/src/minizip/mz_strm_os_win32.c +@@ -1,7 +1,7 @@ + /* mz_strm_win32.c -- Stream for filesystem access for windows + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + Copyright (C) 2009-2010 Mathias Svensson + Modifications for Zip64 support +@@ -13,7 +13,6 @@ + See the accompanying LICENSE file for the full text of the license. + */ + +- + #include "mz.h" + #include "mz_os.h" + #include "mz_strm.h" +@@ -24,17 +23,15 @@ + /***************************************************************************/ + + #ifndef INVALID_HANDLE_VALUE +-# define INVALID_HANDLE_VALUE (0xFFFFFFFF) ++# define INVALID_HANDLE_VALUE 0xFFFFFFFF + #endif + + #ifndef INVALID_SET_FILE_POINTER +-# define INVALID_SET_FILE_POINTER ((DWORD)-1) ++# define INVALID_SET_FILE_POINTER (DWORD)-1 + #endif + +-#if defined(WINAPI_FAMILY_ONE_PARTITION) && !defined(MZ_WINRT_API) +-# if WINAPI_FAMILY_ONE_PARTITION(WINAPI_FAMILY, WINAPI_PARTITION_APP) +-# define MZ_WINRT_API 1 +-# endif ++#ifndef _WIN32_WINNT_WIN8 ++# define _WIN32_WINNT_WIN8 0x0602 + #endif + + /***************************************************************************/ +@@ -67,7 +64,7 @@ typedef struct mz_stream_win32_s { + #if 0 + # define mz_stream_os_print printf + #else +-# define mz_stream_os_print(fmt,...) ++# define mz_stream_os_print(fmt, ...) + #endif + + /***************************************************************************/ +@@ -80,8 +77,7 @@ int32_t mz_stream_os_open(void *stream, const char *path, int32_t mode) { + uint32_t flags_attribs = FILE_ATTRIBUTE_NORMAL; + wchar_t *path_wide = NULL; + +- +- if (path == NULL) ++ if (!path) + return MZ_PARAM_ERROR; + + /* Some use cases require write sharing as well */ +@@ -103,10 +99,10 @@ int32_t mz_stream_os_open(void *stream, const char *path, int32_t mode) { + mz_stream_os_print("Win32 - Open - %s (mode %" PRId32 ")\n", path); + + path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); +- if (path_wide == NULL) ++ if (!path_wide) + return MZ_PARAM_ERROR; + +-#ifdef MZ_WINRT_API ++#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 + win32->handle = CreateFile2(path_wide, desired_access, share_mode, + creation_disposition, NULL); + #else +@@ -129,7 +125,7 @@ int32_t mz_stream_os_open(void *stream, const char *path, int32_t mode) { + + int32_t mz_stream_os_is_open(void *stream) { + mz_stream_win32 *win32 = (mz_stream_win32 *)stream; +- if (win32->handle == NULL || win32->handle == INVALID_HANDLE_VALUE) ++ if (!win32->handle || win32->handle == INVALID_HANDLE_VALUE) + return MZ_OPEN_ERROR; + return MZ_OK; + } +@@ -172,7 +168,7 @@ int32_t mz_stream_os_write(void *stream, const void *buf, int32_t size) { + + static int32_t mz_stream_os_seekinternal(HANDLE handle, LARGE_INTEGER large_pos, + LARGE_INTEGER *new_pos, uint32_t move_method) { +-#ifdef MZ_WINRT_API ++#if _WIN32_WINNT >= _WIN32_WINNT_WINXP + BOOL success = FALSE; + success = SetFilePointerEx(handle, large_pos, new_pos, move_method); + if ((success == FALSE) && (GetLastError() != NO_ERROR)) +@@ -189,7 +185,7 @@ static int32_t mz_stream_os_seekinternal(HANDLE handle, LARGE_INTEGER large_pos, + if ((pos == INVALID_SET_FILE_POINTER) && (GetLastError() != NO_ERROR)) + return MZ_SEEK_ERROR; + +- if (new_pos != NULL) { ++ if (new_pos) { + new_pos->LowPart = pos; + new_pos->HighPart = high_part; + } +@@ -221,7 +217,6 @@ int32_t mz_stream_os_seek(void *stream, int64_t offset, int32_t origin) { + int32_t err = MZ_OK; + LARGE_INTEGER large_pos; + +- + if (mz_stream_os_is_open(stream) != MZ_OK) + return MZ_OPEN_ERROR; + +@@ -255,7 +250,7 @@ int32_t mz_stream_os_seek(void *stream, int64_t offset, int32_t origin) { + int32_t mz_stream_os_close(void *stream) { + mz_stream_win32 *win32 = (mz_stream_win32 *)stream; + +- if (win32->handle != NULL) ++ if (win32->handle) + CloseHandle(win32->handle); + mz_stream_os_print("Win32 - Close\n"); + win32->handle = NULL; +@@ -267,27 +262,20 @@ int32_t mz_stream_os_error(void *stream) { + return win32->error; + } + +-void *mz_stream_os_create(void **stream) { +- mz_stream_win32 *win32 = NULL; +- +- win32 = (mz_stream_win32 *)MZ_ALLOC(sizeof(mz_stream_win32)); +- if (win32 != NULL) { +- memset(win32, 0, sizeof(mz_stream_win32)); ++void *mz_stream_os_create(void) { ++ mz_stream_win32 *win32 = (mz_stream_win32 *)calloc(1, sizeof(mz_stream_win32)); ++ if (win32) + win32->stream.vtbl = &mz_stream_os_vtbl; +- } +- if (stream != NULL) +- *stream = win32; +- + return win32; + } + + void mz_stream_os_delete(void **stream) { + mz_stream_win32 *win32 = NULL; +- if (stream == NULL) ++ if (!stream) + return; + win32 = (mz_stream_win32 *)*stream; +- if (win32 != NULL) +- MZ_FREE(win32); ++ if (win32) ++ free(win32); + *stream = NULL; + } + +diff --git a/src/minizip/mz_strm_zlib.c b/src/minizip/mz_strm_zlib.c +index f76d7ffc4..cba63fb2f 100644 +--- a/src/minizip/mz_strm_zlib.c ++++ b/src/minizip/mz_strm_zlib.c +@@ -1,14 +1,13 @@ + /* mz_strm_zlib.c -- Stream for zlib inflate/deflate + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + + This program is distributed under the terms of the same license as zlib. + See the accompanying LICENSE file for the full text of the license. + */ + +- + #include "mz.h" + #include "mz_strm.h" + #include "mz_strm_zlib.h" +@@ -144,8 +143,7 @@ int32_t mz_stream_zlib_read(void *stream, void *buf, int32_t size) { + int32_t read = 0; + int32_t err = Z_OK; + +- +- zlib->zstream.next_out = (Bytef*)buf; ++ zlib->zstream.next_out = (Bytef *)buf; + zlib->zstream.avail_out = (uInt)size; + + do { +@@ -168,7 +166,7 @@ int32_t mz_stream_zlib_read(void *stream, void *buf, int32_t size) { + total_out_before = zlib->zstream.total_out; + + err = ZLIB_PREFIX(inflate)(&zlib->zstream, Z_SYNC_FLUSH); +- if ((err >= Z_OK) && (zlib->zstream.msg != NULL)) { ++ if ((err >= Z_OK) && (zlib->zstream.msg)) { + zlib->error = Z_DATA_ERROR; + break; + } +@@ -193,6 +191,8 @@ int32_t mz_stream_zlib_read(void *stream, void *buf, int32_t size) { + } + } while (zlib->zstream.avail_out > 0); + ++ MZ_UNUSED(total_in); ++ + if (zlib->error != 0) { + /* Zlib errors are compatible with MZ */ + return zlib->error; +@@ -217,7 +217,6 @@ static int32_t mz_stream_zlib_deflate(void *stream, int flush) { + int32_t out_bytes = 0; + int32_t err = Z_OK; + +- + do { + if (zlib->zstream.avail_out == 0) { + err = mz_stream_zlib_flush(zlib); +@@ -261,7 +260,7 @@ int32_t mz_stream_zlib_write(void *stream, const void *buf, int32_t size) { + mz_stream_zlib *zlib = (mz_stream_zlib *)stream; + int32_t err = MZ_OK; + +- zlib->zstream.next_in = (Bytef*)(intptr_t)buf; ++ zlib->zstream.next_in = (Bytef *)(intptr_t)buf; + zlib->zstream.avail_in = (uInt)size; + + err = mz_stream_zlib_deflate(stream, Z_NO_FLUSH); +@@ -291,7 +290,6 @@ int32_t mz_stream_zlib_seek(void *stream, int64_t offset, int32_t origin) { + int32_t mz_stream_zlib_close(void *stream) { + mz_stream_zlib *zlib = (mz_stream_zlib *)stream; + +- + if (zlib->mode & MZ_OPEN_MODE_WRITE) { + #ifdef MZ_ZIP_NO_COMPRESSION + return MZ_SUPPORT_ERROR; +@@ -349,7 +347,10 @@ int32_t mz_stream_zlib_set_prop_int64(void *stream, int32_t prop, int64_t value) + mz_stream_zlib *zlib = (mz_stream_zlib *)stream; + switch (prop) { + case MZ_STREAM_PROP_COMPRESS_LEVEL: +- zlib->level = (int16_t)value; ++ if (value == MZ_COMPRESS_LEVEL_DEFAULT) ++ zlib->level = Z_DEFAULT_COMPRESSION; ++ else ++ zlib->level = (int16_t)value; + break; + case MZ_STREAM_PROP_TOTAL_IN_MAX: + zlib->max_total_in = value; +@@ -363,29 +364,23 @@ int32_t mz_stream_zlib_set_prop_int64(void *stream, int32_t prop, int64_t value) + return MZ_OK; + } + +-void *mz_stream_zlib_create(void **stream) { +- mz_stream_zlib *zlib = NULL; +- +- zlib = (mz_stream_zlib *)MZ_ALLOC(sizeof(mz_stream_zlib)); +- if (zlib != NULL) { +- memset(zlib, 0, sizeof(mz_stream_zlib)); ++void *mz_stream_zlib_create(void) { ++ mz_stream_zlib *zlib = zlib = (mz_stream_zlib *)calloc(1, sizeof(mz_stream_zlib)); ++ if (zlib) { + zlib->stream.vtbl = &mz_stream_zlib_vtbl; + zlib->level = Z_DEFAULT_COMPRESSION; + zlib->window_bits = -MAX_WBITS; + } +- if (stream != NULL) +- *stream = zlib; +- + return zlib; + } + + void mz_stream_zlib_delete(void **stream) { + mz_stream_zlib *zlib = NULL; +- if (stream == NULL) ++ if (!stream) + return; + zlib = (mz_stream_zlib *)*stream; +- if (zlib != NULL) +- MZ_FREE(zlib); ++ if (zlib) ++ free(zlib); + *stream = NULL; + } + +diff --git a/src/minizip/mz_strm_zlib.h b/src/minizip/mz_strm_zlib.h +index 47f74804f..bba0991ca 100644 +--- a/src/minizip/mz_strm_zlib.h ++++ b/src/minizip/mz_strm_zlib.h +@@ -1,7 +1,7 @@ + /* mz_strm_zlib.h -- Stream for zlib inflate/deflate + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + + This program is distributed under the terms of the same license as zlib. +@@ -29,7 +29,7 @@ int32_t mz_stream_zlib_error(void *stream); + int32_t mz_stream_zlib_get_prop_int64(void *stream, int32_t prop, int64_t *value); + int32_t mz_stream_zlib_set_prop_int64(void *stream, int32_t prop, int64_t value); + +-void* mz_stream_zlib_create(void **stream); ++void* mz_stream_zlib_create(void); + void mz_stream_zlib_delete(void **stream); + + void* mz_stream_zlib_get_interface(void); +diff --git a/src/minizip/mz_zip.c b/src/minizip/mz_zip.c +index cc4f57d0b..019fcbf28 100644 +--- a/src/minizip/mz_zip.c ++++ b/src/minizip/mz_zip.c +@@ -1,7 +1,7 @@ + /* zip.c -- Zip manipulation + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + Copyright (C) 2009-2010 Mathias Svensson + Modifications for Zip64 support +@@ -15,7 +15,6 @@ + See the accompanying LICENSE file for the full text of the license. + */ + +- + #include "mz.h" + #include "mz_crypt.h" + #include "mz_strm.h" +@@ -48,7 +47,7 @@ + #include /* snprintf */ + + #if defined(_MSC_VER) || defined(__MINGW32__) +-# define localtime_r(t1,t2) (localtime_s(t2,t1) == 0 ? t1 : NULL) ++# define localtime_r(t1, t2) (localtime_s(t2, t1) == 0 ? t1 : NULL) + #endif + #if defined(_MSC_VER) && (_MSC_VER < 1900) + # define snprintf _snprintf +@@ -122,7 +121,7 @@ typedef struct mz_zip_s { + #if 0 + # define mz_zip_print printf + #else +-# define mz_zip_print(fmt,...) ++# define mz_zip_print(fmt, ...) + #endif + + /***************************************************************************/ +@@ -152,7 +151,6 @@ static int32_t mz_zip_search_zip64_eocd(void *stream, const int64_t end_central_ + uint32_t value32 = 0; + int32_t err = MZ_OK; + +- + *central_pos = 0; + + /* Zip64 end of central directory locator */ +@@ -188,6 +186,7 @@ static int32_t mz_zip_search_zip64_eocd(void *stream, const int64_t end_central_ + return err; + } + ++#ifdef HAVE_PKCRYPT + /* Get PKWARE traditional encryption verifier */ + static uint16_t mz_zip_get_pk_verify(uint32_t dos_date, uint64_t crc, uint16_t flag) + { +@@ -197,6 +196,7 @@ static uint16_t mz_zip_get_pk_verify(uint32_t dos_date, uint64_t crc, uint16_t f + return ((dos_date >> 16) & 0xff) << 8 | ((dos_date >> 8) & 0xff); + return ((crc >> 16) & 0xff) << 8 | ((crc >> 24) & 0xff); + } ++#endif + + /* Get info about the current file in the zip file */ + static int32_t mz_zip_entry_read_header(void *stream, uint8_t local, mz_zip_file *file_info, void *file_extra_stream) { +@@ -220,7 +220,6 @@ static int32_t mz_zip_entry_read_header(void *stream, uint8_t local, mz_zip_file + int32_t err = MZ_OK; + char *linkname = NULL; + +- + memset(file_info, 0, sizeof(mz_zip_file)); + + /* Check the magic */ +@@ -394,8 +393,8 @@ static int32_t mz_zip_entry_read_header(void *stream, uint8_t local, mz_zip_file + terminated string */ + linkname_size = field_length - 12; + if ((err == MZ_OK) && (linkname_size > 0)) { +- linkname = (char *)MZ_ALLOC(linkname_size); +- if (linkname != NULL) { ++ linkname = (char *)malloc(linkname_size); ++ if (linkname) { + if (mz_stream_read(file_extra_stream, linkname, linkname_size) != linkname_size) + err = MZ_READ_ERROR; + if (err == MZ_OK) { +@@ -407,7 +406,7 @@ static int32_t mz_zip_entry_read_header(void *stream, uint8_t local, mz_zip_file + + mz_stream_seek(file_extra_stream, saved_pos, MZ_SEEK_SET); + } +- MZ_FREE(linkname); ++ free(linkname); + } + } + } +@@ -432,7 +431,7 @@ static int32_t mz_zip_entry_read_header(void *stream, uint8_t local, mz_zip_file + /* Get AES encryption strength and actual compression method */ + if (err == MZ_OK) { + err = mz_stream_read_uint8(file_extra_stream, &value8); +- file_info->aes_encryption_mode = value8; ++ file_info->aes_strength = value8; + } + if (err == MZ_OK) { + err = mz_stream_read_uint16(file_extra_stream, &value16); +@@ -455,13 +454,13 @@ static int32_t mz_zip_entry_read_header(void *stream, uint8_t local, mz_zip_file + mz_stream_mem_get_buffer_at(file_extra_stream, linkname_pos, (const void **)&file_info->linkname); + + /* Set to empty string just in-case */ +- if (file_info->filename == NULL) ++ if (!file_info->filename) + file_info->filename = ""; +- if (file_info->extrafield == NULL) ++ if (!file_info->extrafield) + file_info->extrafield_size = 0; +- if (file_info->comment == NULL) ++ if (!file_info->comment) + file_info->comment = ""; +- if (file_info->linkname == NULL) ++ if (!file_info->linkname) + file_info->linkname = ""; + + if (err == MZ_OK) { +@@ -485,13 +484,12 @@ static int32_t mz_zip_entry_read_descriptor(void *stream, uint8_t zip64, uint32_ + int64_t value64 = 0; + int32_t err = MZ_OK; + +- + err = mz_stream_read_uint32(stream, &value32); + if (value32 != MZ_ZIP_MAGIC_DATADESCRIPTOR) + err = MZ_FORMAT_ERROR; + if (err == MZ_OK) + err = mz_stream_read_uint32(stream, &value32); +- if ((err == MZ_OK) && (crc32 != NULL)) ++ if (err == MZ_OK && crc32) + *crc32 = value32; + if (err == MZ_OK) { + /* If zip 64 extension is enabled then read as 8 byte */ +@@ -503,7 +501,7 @@ static int32_t mz_zip_entry_read_descriptor(void *stream, uint8_t zip64, uint32_ + if (value64 < 0) + err = MZ_FORMAT_ERROR; + } +- if ((err == MZ_OK) && (compressed_size != NULL)) ++ if (err == MZ_OK && compressed_size) + *compressed_size = value64; + } + if (err == MZ_OK) { +@@ -515,7 +513,7 @@ static int32_t mz_zip_entry_read_descriptor(void *stream, uint8_t zip64, uint32_ + if (value64 < 0) + err = MZ_FORMAT_ERROR; + } +- if ((err == MZ_OK) && (uncompressed_size != NULL)) ++ if (err == MZ_OK && uncompressed_size) + *uncompressed_size = value64; + } + +@@ -554,7 +552,7 @@ static int32_t mz_zip_entry_needs_zip64(mz_zip_file *file_info, uint8_t local, u + uint32_t max_uncompressed_size = UINT32_MAX; + uint8_t needs_zip64 = 0; + +- if (zip64 == NULL) ++ if (!zip64) + return MZ_PARAM_ERROR; + + *zip64 = 0; +@@ -621,7 +619,7 @@ static int32_t mz_zip_entry_write_header(void *stream, uint8_t local, mz_zip_fil + char masked_name[64]; + void *file_extra_stream = NULL; + +- if (file_info == NULL) ++ if (!file_info) + return MZ_PARAM_ERROR; + + if ((local) && (file_info->flag & MZ_ZIP_FLAG_MASK_LOCAL_INFO)) +@@ -645,7 +643,9 @@ static int32_t mz_zip_entry_write_header(void *stream, uint8_t local, mz_zip_fil + + /* Calculate extra field size and check for duplicates */ + if (file_info->extrafield_size > 0) { +- mz_stream_mem_create(&file_extra_stream); ++ file_extra_stream = mz_stream_mem_create(); ++ if (!file_extra_stream) ++ return MZ_MEM_ERROR; + mz_stream_mem_set_buffer(file_extra_stream, (void *)file_info->extrafield, + file_info->extrafield_size); + +@@ -690,7 +690,7 @@ static int32_t mz_zip_entry_write_header(void *stream, uint8_t local, mz_zip_fil + } + + /* Unix1 symbolic links */ +- if (file_info->linkname != NULL && *file_info->linkname != 0) { ++ if (file_info->linkname && *file_info->linkname != 0) { + linkname_size = (uint16_t)strlen(file_info->linkname); + field_length_unix1 = 12 + linkname_size; + extrafield_size += 4 + field_length_unix1; +@@ -765,7 +765,7 @@ static int32_t mz_zip_entry_write_header(void *stream, uint8_t local, mz_zip_fil + err = mz_stream_write_uint16(stream, extrafield_size); + + if (!local) { +- if (file_info->comment != NULL) { ++ if (file_info->comment) { + comment_size = (int32_t)strlen(file_info->comment); + if (comment_size > UINT16_MAX) + comment_size = UINT16_MAX; +@@ -787,8 +787,26 @@ static int32_t mz_zip_entry_write_header(void *stream, uint8_t local, mz_zip_fil + } + + if (err == MZ_OK) { +- if (mz_stream_write(stream, filename, filename_length) != filename_length) +- err = MZ_WRITE_ERROR; ++ const char *backslash = NULL; ++ const char *next = filename; ++ int32_t left = filename_length; ++ ++ /* Ensure all slashes are written as forward slashes according to 4.4.17.1 */ ++ while ((err == MZ_OK) && (backslash = strchr(next, '\\'))) { ++ int32_t part_length = (int32_t)(backslash - next); ++ ++ if (mz_stream_write(stream, next, part_length) != part_length || ++ mz_stream_write(stream, "/", 1) != 1) ++ err = MZ_WRITE_ERROR; ++ ++ left -= part_length + 1; ++ next = backslash + 1; ++ } ++ ++ if (err == MZ_OK && left > 0) { ++ if (mz_stream_write(stream, next, left) != left) ++ err = MZ_WRITE_ERROR; ++ } + + /* Ensure that directories have a slash appended to them for compatibility */ + if (err == MZ_OK && write_end_slash) +@@ -860,7 +878,7 @@ static int32_t mz_zip_entry_write_header(void *stream, uint8_t local, mz_zip_fil + if (err == MZ_OK) + err = mz_stream_write_uint8(stream, 'E'); + if (err == MZ_OK) +- err = mz_stream_write_uint8(stream, file_info->aes_encryption_mode); ++ err = mz_stream_write_uint8(stream, file_info->aes_strength); + if (err == MZ_OK) + err = mz_stream_write_uint16(stream, file_info->compression_method); + } +@@ -892,7 +910,7 @@ static int32_t mz_zip_entry_write_header(void *stream, uint8_t local, mz_zip_fil + mz_stream_mem_delete(&file_extra_stream); + } + +- if ((err == MZ_OK) && (!local) && (file_info->comment != NULL)) { ++ if (err == MZ_OK && !local && file_info->comment) { + if (mz_stream_write(stream, file_info->comment, file_info->comment_size) != file_info->comment_size) + err = MZ_WRITE_ERROR; + } +@@ -939,8 +957,7 @@ static int32_t mz_zip_read_cd(void *handle) { + int32_t comment_read = 0; + int32_t err = MZ_OK; + +- +- if (zip == NULL) ++ if (!zip) + return MZ_PARAM_ERROR; + + /* Read and cache central directory records */ +@@ -979,8 +996,8 @@ static int32_t mz_zip_read_cd(void *handle) { + if (err == MZ_OK) + err = mz_stream_read_uint16(zip->stream, &comment_size); + if ((err == MZ_OK) && (comment_size > 0)) { +- zip->comment = (char *)MZ_ALLOC(comment_size + 1); +- if (zip->comment != NULL) { ++ zip->comment = (char *)malloc(comment_size + 1); ++ if (zip->comment) { + comment_read = mz_stream_read(zip->stream, zip->comment, comment_size); + /* Don't fail if incorrect comment length read, not critical */ + if (comment_read < 0) +@@ -1058,7 +1075,6 @@ static int32_t mz_zip_read_cd(void *handle) { + if (err == MZ_OK) + err = mz_stream_read_uint32(zip->stream, &zip->cd_signature); + if ((err == MZ_OK) && (zip->cd_signature == MZ_ZIP_MAGIC_CENTRALHEADER)) { +- + /* If found compensate for incorrect locations */ + value64i = zip->cd_offset; + zip->cd_offset = eocd_pos - zip->cd_size; +@@ -1089,8 +1105,7 @@ static int32_t mz_zip_write_cd(void *handle) { + int32_t comment_size = 0; + int32_t err = MZ_OK; + +- +- if (zip == NULL) ++ if (!zip) + return MZ_PARAM_ERROR; + + if (mz_stream_get_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, &disk_number) == MZ_OK) +@@ -1099,7 +1114,7 @@ static int32_t mz_zip_write_cd(void *handle) { + zip->disk_number_with_cd += 1; + mz_stream_set_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, -1); + if ((zip->disk_number_with_cd > 0) && (zip->open_mode & MZ_OPEN_MODE_APPEND)) { +- // Overwrite existing central directory if using split disks ++ /* Overwrite existing central directory if using split disks */ + mz_stream_seek(zip->stream, 0, MZ_SEEK_SET); + } + +@@ -1114,7 +1129,7 @@ static int32_t mz_zip_write_cd(void *handle) { + zip->disk_number_with_cd, zip->number_entry, zip->cd_offset, zip->cd_size); + + if (zip->cd_size == 0 && zip->number_entry > 0) { +- // Zip does not contain central directory, open with recovery option ++ /* Zip does not contain central directory, open with recovery option */ + return MZ_FORMAT_ERROR; + } + +@@ -1202,7 +1217,7 @@ static int32_t mz_zip_write_cd(void *handle) { + } + + /* Write global comment */ +- if (zip->comment != NULL) { ++ if (zip->comment) { + comment_size = (int32_t)strlen(zip->comment); + if (comment_size > UINT16_MAX) + comment_size = UINT16_MAX; +@@ -1239,7 +1254,6 @@ static int32_t mz_zip_recover_cd(void *handle) { + uint8_t zip64 = 0; + uint8_t eof = 0; + +- + mz_zip_print("Zip - Recover - Start\n"); + + mz_zip_get_cd_mem_stream(handle, &cd_mem_stream); +@@ -1252,10 +1266,13 @@ static int32_t mz_zip_recover_cd(void *handle) { + } else + disk_number_with_cd = 1; + ++ local_file_info_stream = mz_stream_mem_create(); ++ if (!local_file_info_stream) ++ return MZ_MEM_ERROR; ++ + if (mz_stream_is_open(cd_mem_stream) != MZ_OK) + err = mz_stream_mem_open(cd_mem_stream, NULL, MZ_OPEN_MODE_CREATE); + +- mz_stream_mem_create(&local_file_info_stream); + mz_stream_mem_open(local_file_info_stream, NULL, MZ_OPEN_MODE_CREATE); + + if (err == MZ_OK) { +@@ -1385,27 +1402,20 @@ static int32_t mz_zip_recover_cd(void *handle) { + return MZ_OK; + } + +-void *mz_zip_create(void **handle) { +- mz_zip *zip = NULL; +- +- zip = (mz_zip *)MZ_ALLOC(sizeof(mz_zip)); +- if (zip != NULL) { +- memset(zip, 0, sizeof(mz_zip)); ++void *mz_zip_create(void) { ++ mz_zip *zip = (mz_zip *)calloc(1, sizeof(mz_zip)); ++ if (zip) + zip->data_descriptor = 1; +- } +- if (handle != NULL) +- *handle = zip; +- + return zip; + } + + void mz_zip_delete(void **handle) { + mz_zip *zip = NULL; +- if (handle == NULL) ++ if (!handle) + return; + zip = (mz_zip *)*handle; +- if (zip != NULL) { +- MZ_FREE(zip); ++ if (zip) { ++ free(zip); + } + *handle = NULL; + } +@@ -1414,15 +1424,15 @@ int32_t mz_zip_open(void *handle, void *stream, int32_t mode) { + mz_zip *zip = (mz_zip *)handle; + int32_t err = MZ_OK; + +- +- if (zip == NULL) ++ if (!zip) + return MZ_PARAM_ERROR; + + mz_zip_print("Zip - Open\n"); + + zip->stream = stream; +- +- mz_stream_mem_create(&zip->cd_mem_stream); ++ zip->cd_mem_stream = mz_stream_mem_create(); ++ if (!zip->cd_mem_stream) ++ return MZ_MEM_ERROR; + + if (mode & MZ_OPEN_MODE_WRITE) { + mz_stream_mem_open(zip->cd_mem_stream, NULL, MZ_OPEN_MODE_CREATE); +@@ -1474,10 +1484,18 @@ int32_t mz_zip_open(void *handle, void *stream, int32_t mode) { + } + + /* Memory streams used to store variable length file info data */ +- mz_stream_mem_create(&zip->file_info_stream); ++ zip->file_info_stream = mz_stream_mem_create(); ++ if (!zip->file_info_stream) ++ return MZ_MEM_ERROR; ++ + mz_stream_mem_open(zip->file_info_stream, NULL, MZ_OPEN_MODE_CREATE); + +- mz_stream_mem_create(&zip->local_file_info_stream); ++ zip->local_file_info_stream = mz_stream_mem_create(); ++ if (!zip->local_file_info_stream) { ++ mz_stream_delete(&zip->file_info_stream); ++ return MZ_MEM_ERROR; ++ } ++ + mz_stream_mem_open(zip->local_file_info_stream, NULL, MZ_OPEN_MODE_CREATE); + + zip->open_mode = mode; +@@ -1489,7 +1507,7 @@ int32_t mz_zip_close(void *handle) { + mz_zip *zip = (mz_zip *)handle; + int32_t err = MZ_OK; + +- if (zip == NULL) ++ if (!zip) + return MZ_PARAM_ERROR; + + mz_zip_print("Zip - Close\n"); +@@ -1500,22 +1518,22 @@ int32_t mz_zip_close(void *handle) { + if ((err == MZ_OK) && (zip->open_mode & MZ_OPEN_MODE_WRITE)) + err = mz_zip_write_cd(handle); + +- if (zip->cd_mem_stream != NULL) { ++ if (zip->cd_mem_stream) { + mz_stream_close(zip->cd_mem_stream); + mz_stream_delete(&zip->cd_mem_stream); + } + +- if (zip->file_info_stream != NULL) { ++ if (zip->file_info_stream) { + mz_stream_mem_close(zip->file_info_stream); + mz_stream_mem_delete(&zip->file_info_stream); + } +- if (zip->local_file_info_stream != NULL) { ++ if (zip->local_file_info_stream) { + mz_stream_mem_close(zip->local_file_info_stream); + mz_stream_mem_delete(&zip->local_file_info_stream); + } + + if (zip->comment) { +- MZ_FREE(zip->comment); ++ free(zip->comment); + zip->comment = NULL; + } + +@@ -1527,9 +1545,9 @@ int32_t mz_zip_close(void *handle) { + + int32_t mz_zip_get_comment(void *handle, const char **comment) { + mz_zip *zip = (mz_zip *)handle; +- if (zip == NULL || comment == NULL) ++ if (!zip || !comment) + return MZ_PARAM_ERROR; +- if (zip->comment == NULL) ++ if (!zip->comment) + return MZ_EXIST_ERROR; + *comment = zip->comment; + return MZ_OK; +@@ -1538,24 +1556,23 @@ int32_t mz_zip_get_comment(void *handle, const char **comment) { + int32_t mz_zip_set_comment(void *handle, const char *comment) { + mz_zip *zip = (mz_zip *)handle; + int32_t comment_size = 0; +- if (zip == NULL || comment == NULL) ++ if (!zip || !comment) + return MZ_PARAM_ERROR; +- if (zip->comment != NULL) +- MZ_FREE(zip->comment); ++ if (zip->comment) ++ free(zip->comment); + comment_size = (int32_t)strlen(comment); + if (comment_size > UINT16_MAX) + return MZ_PARAM_ERROR; +- zip->comment = (char *)MZ_ALLOC(comment_size+1); +- if (zip->comment == NULL) ++ zip->comment = (char *)calloc(comment_size + 1, sizeof(char)); ++ if (!zip->comment) + return MZ_MEM_ERROR; +- memset(zip->comment, 0, comment_size+1); + strncpy(zip->comment, comment, comment_size); + return MZ_OK; + } + + int32_t mz_zip_get_version_madeby(void *handle, uint16_t *version_madeby) { + mz_zip *zip = (mz_zip *)handle; +- if (zip == NULL || version_madeby == NULL) ++ if (!zip || !version_madeby) + return MZ_PARAM_ERROR; + *version_madeby = zip->version_madeby; + return MZ_OK; +@@ -1563,7 +1580,7 @@ int32_t mz_zip_get_version_madeby(void *handle, uint16_t *version_madeby) { + + int32_t mz_zip_set_version_madeby(void *handle, uint16_t version_madeby) { + mz_zip *zip = (mz_zip *)handle; +- if (zip == NULL) ++ if (!zip) + return MZ_PARAM_ERROR; + zip->version_madeby = version_madeby; + return MZ_OK; +@@ -1571,7 +1588,7 @@ int32_t mz_zip_set_version_madeby(void *handle, uint16_t version_madeby) { + + int32_t mz_zip_set_recover(void *handle, uint8_t recover) { + mz_zip *zip = (mz_zip *)handle; +- if (zip == NULL) ++ if (!zip) + return MZ_PARAM_ERROR; + zip->recover = recover; + return MZ_OK; +@@ -1579,7 +1596,7 @@ int32_t mz_zip_set_recover(void *handle, uint8_t recover) { + + int32_t mz_zip_set_data_descriptor(void *handle, uint8_t data_descriptor) { + mz_zip *zip = (mz_zip *)handle; +- if (zip == NULL) ++ if (!zip) + return MZ_PARAM_ERROR; + zip->data_descriptor = data_descriptor; + return MZ_OK; +@@ -1587,17 +1604,17 @@ int32_t mz_zip_set_data_descriptor(void *handle, uint8_t data_descriptor) { + + int32_t mz_zip_get_stream(void *handle, void **stream) { + mz_zip *zip = (mz_zip *)handle; +- if (zip == NULL || stream == NULL) ++ if (!zip || !stream) + return MZ_PARAM_ERROR; + *stream = zip->stream; +- if (*stream == NULL) ++ if (!*stream) + return MZ_EXIST_ERROR; + return MZ_OK; + } + + int32_t mz_zip_set_cd_stream(void *handle, int64_t cd_start_pos, void *cd_stream) { + mz_zip *zip = (mz_zip *)handle; +- if (zip == NULL || cd_stream == NULL) ++ if (!zip || !cd_stream) + return MZ_PARAM_ERROR; + zip->cd_offset = 0; + zip->cd_stream = cd_stream; +@@ -1607,17 +1624,17 @@ int32_t mz_zip_set_cd_stream(void *handle, int64_t cd_start_pos, void *cd_stream + + int32_t mz_zip_get_cd_mem_stream(void *handle, void **cd_mem_stream) { + mz_zip *zip = (mz_zip *)handle; +- if (zip == NULL || cd_mem_stream == NULL) ++ if (!zip || !cd_mem_stream) + return MZ_PARAM_ERROR; + *cd_mem_stream = zip->cd_mem_stream; +- if (*cd_mem_stream == NULL) ++ if (!*cd_mem_stream) + return MZ_EXIST_ERROR; + return MZ_OK; + } + + int32_t mz_zip_set_number_entry(void *handle, uint64_t number_entry) { + mz_zip *zip = (mz_zip *)handle; +- if (zip == NULL) ++ if (!zip) + return MZ_PARAM_ERROR; + zip->number_entry = number_entry; + return MZ_OK; +@@ -1625,7 +1642,7 @@ int32_t mz_zip_set_number_entry(void *handle, uint64_t number_entry) { + + int32_t mz_zip_get_number_entry(void *handle, uint64_t *number_entry) { + mz_zip *zip = (mz_zip *)handle; +- if (zip == NULL || number_entry == NULL) ++ if (!zip || !number_entry) + return MZ_PARAM_ERROR; + *number_entry = zip->number_entry; + return MZ_OK; +@@ -1633,7 +1650,7 @@ int32_t mz_zip_get_number_entry(void *handle, uint64_t *number_entry) { + + int32_t mz_zip_set_disk_number_with_cd(void *handle, uint32_t disk_number_with_cd) { + mz_zip *zip = (mz_zip *)handle; +- if (zip == NULL) ++ if (!zip) + return MZ_PARAM_ERROR; + zip->disk_number_with_cd = disk_number_with_cd; + return MZ_OK; +@@ -1641,7 +1658,7 @@ int32_t mz_zip_set_disk_number_with_cd(void *handle, uint32_t disk_number_with_c + + int32_t mz_zip_get_disk_number_with_cd(void *handle, uint32_t *disk_number_with_cd) { + mz_zip *zip = (mz_zip *)handle; +- if (zip == NULL || disk_number_with_cd == NULL) ++ if (!zip || !disk_number_with_cd) + return MZ_PARAM_ERROR; + *disk_number_with_cd = zip->disk_number_with_cd; + return MZ_OK; +@@ -1650,10 +1667,10 @@ int32_t mz_zip_get_disk_number_with_cd(void *handle, uint32_t *disk_number_with_ + static int32_t mz_zip_entry_close_int(void *handle) { + mz_zip *zip = (mz_zip *)handle; + +- if (zip->crypt_stream != NULL) ++ if (zip->crypt_stream) + mz_stream_delete(&zip->crypt_stream); + zip->crypt_stream = NULL; +- if (zip->compress_stream != NULL) ++ if (zip->compress_stream) + mz_stream_delete(&zip->compress_stream); + zip->compress_stream = NULL; + +@@ -1670,7 +1687,7 @@ static int32_t mz_zip_entry_open_int(void *handle, uint8_t raw, int16_t compress + int32_t err = MZ_OK; + uint8_t use_crypt = 0; + +- if (zip == NULL) ++ if (!zip) + return MZ_PARAM_ERROR; + + switch (zip->file_info.compression_method) { +@@ -1701,7 +1718,7 @@ static int32_t mz_zip_entry_open_int(void *handle, uint8_t raw, int16_t compress + + zip->entry_raw = raw; + +- if ((zip->file_info.flag & MZ_ZIP_FLAG_ENCRYPTED) && (password != NULL)) { ++ if ((zip->file_info.flag & MZ_ZIP_FLAG_ENCRYPTED) && (password)) { + if (zip->open_mode & MZ_OPEN_MODE_WRITE) { + /* Encrypt only when we are not trying to write raw and password is supplied. */ + if (!zip->entry_raw) +@@ -1716,9 +1733,11 @@ static int32_t mz_zip_entry_open_int(void *handle, uint8_t raw, int16_t compress + if ((err == MZ_OK) && (use_crypt)) { + #ifdef HAVE_WZAES + if (zip->file_info.aes_version) { +- mz_stream_wzaes_create(&zip->crypt_stream); ++ zip->crypt_stream = mz_stream_wzaes_create(); ++ if (!zip->crypt_stream) ++ return MZ_MEM_ERROR; + mz_stream_wzaes_set_password(zip->crypt_stream, password); +- mz_stream_wzaes_set_encryption_mode(zip->crypt_stream, zip->file_info.aes_encryption_mode); ++ mz_stream_wzaes_set_strength(zip->crypt_stream, zip->file_info.aes_strength); + } else + #endif + { +@@ -1726,7 +1745,9 @@ static int32_t mz_zip_entry_open_int(void *handle, uint8_t raw, int16_t compress + uint8_t verify1 = (uint8_t)((zip->file_info.pk_verify >> 8) & 0xff); + uint8_t verify2 = (uint8_t)((zip->file_info.pk_verify) & 0xff); + +- mz_stream_pkcrypt_create(&zip->crypt_stream); ++ zip->crypt_stream = mz_stream_pkcrypt_create(); ++ if (!zip->crypt_stream) ++ return MZ_MEM_ERROR; + mz_stream_pkcrypt_set_password(zip->crypt_stream, password); + mz_stream_pkcrypt_set_verify(zip->crypt_stream, verify1, verify2); + #endif +@@ -1734,8 +1755,10 @@ static int32_t mz_zip_entry_open_int(void *handle, uint8_t raw, int16_t compress + } + + if (err == MZ_OK) { +- if (zip->crypt_stream == NULL) +- mz_stream_raw_create(&zip->crypt_stream); ++ if (!zip->crypt_stream) ++ zip->crypt_stream = mz_stream_raw_create(); ++ if (!zip->crypt_stream) ++ return MZ_MEM_ERROR; + + mz_stream_set_base(zip->crypt_stream, zip->stream); + +@@ -1744,39 +1767,44 @@ static int32_t mz_zip_entry_open_int(void *handle, uint8_t raw, int16_t compress + + if (err == MZ_OK) { + if (zip->entry_raw || zip->file_info.compression_method == MZ_COMPRESS_METHOD_STORE) +- mz_stream_raw_create(&zip->compress_stream); ++ zip->compress_stream = mz_stream_raw_create(); + #ifdef HAVE_ZLIB + else if (zip->file_info.compression_method == MZ_COMPRESS_METHOD_DEFLATE) +- mz_stream_zlib_create(&zip->compress_stream); ++ zip->compress_stream = mz_stream_zlib_create(); + #endif + #ifdef HAVE_BZIP2 + else if (zip->file_info.compression_method == MZ_COMPRESS_METHOD_BZIP2) +- mz_stream_bzip_create(&zip->compress_stream); ++ zip->compress_stream = mz_stream_bzip_create(); + #endif + #ifdef HAVE_LIBCOMP + else if (zip->file_info.compression_method == MZ_COMPRESS_METHOD_DEFLATE || + zip->file_info.compression_method == MZ_COMPRESS_METHOD_XZ) { +- mz_stream_libcomp_create(&zip->compress_stream); +- mz_stream_set_prop_int64(zip->compress_stream, MZ_STREAM_PROP_COMPRESS_METHOD, +- zip->file_info.compression_method); ++ zip->compress_stream = mz_stream_libcomp_create(); ++ if (zip->compress_stream) ++ mz_stream_set_prop_int64(zip->compress_stream, MZ_STREAM_PROP_COMPRESS_METHOD, ++ zip->file_info.compression_method); + } + #endif + #ifdef HAVE_LZMA + else if (zip->file_info.compression_method == MZ_COMPRESS_METHOD_LZMA || + zip->file_info.compression_method == MZ_COMPRESS_METHOD_XZ) { +- mz_stream_lzma_create(&zip->compress_stream); +- mz_stream_set_prop_int64(zip->compress_stream, MZ_STREAM_PROP_COMPRESS_METHOD, +- zip->file_info.compression_method); ++ zip->compress_stream = mz_stream_lzma_create(); ++ if (zip->compress_stream) ++ mz_stream_set_prop_int64(zip->compress_stream, MZ_STREAM_PROP_COMPRESS_METHOD, ++ zip->file_info.compression_method); + } + #endif + #ifdef HAVE_ZSTD + else if (zip->file_info.compression_method == MZ_COMPRESS_METHOD_ZSTD) +- mz_stream_zstd_create(&zip->compress_stream); ++ zip->compress_stream = mz_stream_zstd_create(); + #endif + else + err = MZ_PARAM_ERROR; + } + ++ if (err == MZ_OK && !zip->compress_stream) ++ err = MZ_MEM_ERROR; ++ + if (err == MZ_OK) { + if (zip->open_mode & MZ_OPEN_MODE_WRITE) { + mz_stream_set_prop_int64(zip->compress_stream, MZ_STREAM_PROP_COMPRESS_LEVEL, compress_level); +@@ -1833,7 +1861,7 @@ static int32_t mz_zip_entry_open_int(void *handle, uint8_t raw, int16_t compress + + int32_t mz_zip_entry_is_open(void *handle) { + mz_zip *zip = (mz_zip *)handle; +- if (zip == NULL) ++ if (!zip) + return MZ_PARAM_ERROR; + if (zip->entry_opened == 0) + return MZ_EXIST_ERROR; +@@ -1846,15 +1874,13 @@ int32_t mz_zip_entry_read_open(void *handle, uint8_t raw, const char *password) + int32_t err_shift = MZ_OK; + + #if defined(MZ_ZIP_NO_ENCRYPTION) +- if (password != NULL) ++ if (password) + return MZ_SUPPORT_ERROR; + #endif +- if (zip == NULL) ++ if (!zip || !zip->entry_scanned) + return MZ_PARAM_ERROR; + if ((zip->open_mode & MZ_OPEN_MODE_READ) == 0) + return MZ_PARAM_ERROR; +- if (zip->entry_scanned == 0) +- return MZ_PARAM_ERROR; + + mz_zip_print("Zip - Entry - Read open (raw %" PRId32 ")\n", raw); + +@@ -1894,10 +1920,10 @@ int32_t mz_zip_entry_write_open(void *handle, const mz_zip_file *file_info, int1 + int32_t err = MZ_OK; + + #if defined(MZ_ZIP_NO_ENCRYPTION) +- if (password != NULL) ++ if (password) + return MZ_SUPPORT_ERROR; + #endif +- if (zip == NULL || file_info == NULL || file_info->filename == NULL) ++ if (!zip || !file_info || !file_info->filename) + return MZ_PARAM_ERROR; + + if (mz_zip_entry_is_open(handle) == MZ_OK) { +@@ -1916,22 +1942,22 @@ int32_t mz_zip_entry_write_open(void *handle, const mz_zip_file *file_info, int1 + + /* Copy filename, extrafield, and comment internally */ + filename_pos = mz_stream_tell(zip->file_info_stream); +- if (file_info->filename != NULL) ++ if (file_info->filename) + mz_stream_write(zip->file_info_stream, file_info->filename, (int32_t)strlen(file_info->filename)); + mz_stream_write_uint8(zip->file_info_stream, 0); + + extrafield_pos = mz_stream_tell(zip->file_info_stream); +- if (file_info->extrafield != NULL) ++ if (file_info->extrafield) + mz_stream_write(zip->file_info_stream, file_info->extrafield, file_info->extrafield_size); + mz_stream_write_uint8(zip->file_info_stream, 0); + + comment_pos = mz_stream_tell(zip->file_info_stream); +- if (file_info->comment != NULL) ++ if (file_info->comment) + mz_stream_write(zip->file_info_stream, file_info->comment, file_info->comment_size); + mz_stream_write_uint8(zip->file_info_stream, 0); + + linkname_pos = mz_stream_tell(zip->file_info_stream); +- if (file_info->linkname != NULL) ++ if (file_info->linkname) + mz_stream_write(zip->file_info_stream, file_info->linkname, (int32_t)strlen(file_info->linkname)); + mz_stream_write_uint8(zip->file_info_stream, 0); + +@@ -1960,7 +1986,7 @@ int32_t mz_zip_entry_write_open(void *handle, const mz_zip_file *file_info, int1 + if (!is_dir) { + if (zip->data_descriptor) + zip->file_info.flag |= MZ_ZIP_FLAG_DATA_DESCRIPTOR; +- if (password != NULL) ++ if (password) + zip->file_info.flag |= MZ_ZIP_FLAG_ENCRYPTED; + } + +@@ -1975,8 +2001,8 @@ int32_t mz_zip_entry_write_open(void *handle, const mz_zip_file *file_info, int1 + zip->file_info.pk_verify = mz_zip_get_pk_verify(dos_date, zip->file_info.crc, zip->file_info.flag); + #endif + #ifdef HAVE_WZAES +- if (zip->file_info.aes_version && zip->file_info.aes_encryption_mode == 0) +- zip->file_info.aes_encryption_mode = MZ_AES_ENCRYPTION_MODE_256; ++ if (zip->file_info.aes_version && zip->file_info.aes_strength == 0) ++ zip->file_info.aes_strength = MZ_AES_STRENGTH_256; + #endif + } + +@@ -2002,7 +2028,7 @@ int32_t mz_zip_entry_read(void *handle, void *buf, int32_t len) { + mz_zip *zip = (mz_zip *)handle; + int32_t read = 0; + +- if (zip == NULL || mz_zip_entry_is_open(handle) != MZ_OK) ++ if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) + return MZ_PARAM_ERROR; + if (UINT_MAX == UINT16_MAX && len > UINT16_MAX) /* zlib limitation */ + return MZ_PARAM_ERROR; +@@ -2027,7 +2053,7 @@ int32_t mz_zip_entry_write(void *handle, const void *buf, int32_t len) { + mz_zip *zip = (mz_zip *)handle; + int32_t written = 0; + +- if (zip == NULL || mz_zip_entry_is_open(handle) != MZ_OK) ++ if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) + return MZ_PARAM_ERROR; + written = mz_stream_write(zip->compress_stream, buf, len); + if (written > 0) +@@ -2045,25 +2071,25 @@ int32_t mz_zip_entry_read_close(void *handle, uint32_t *crc32, int64_t *compress + int32_t err = MZ_OK; + uint8_t zip64 = 0; + +- if (zip == NULL || mz_zip_entry_is_open(handle) != MZ_OK) ++ if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) + return MZ_PARAM_ERROR; + + mz_stream_close(zip->compress_stream); + + mz_zip_print("Zip - Entry - Read Close\n"); + +- if (crc32 != NULL) ++ if (crc32) + *crc32 = zip->file_info.crc; +- if (compressed_size != NULL) ++ if (compressed_size) + *compressed_size = zip->file_info.compressed_size; +- if (uncompressed_size != NULL) ++ if (uncompressed_size) + *uncompressed_size = zip->file_info.uncompressed_size; + + mz_stream_get_prop_int64(zip->compress_stream, MZ_STREAM_PROP_TOTAL_IN, &total_in); + + if ((zip->file_info.flag & MZ_ZIP_FLAG_DATA_DESCRIPTOR) && + ((zip->file_info.flag & MZ_ZIP_FLAG_MASK_LOCAL_INFO) == 0) && +- (crc32 != NULL || compressed_size != NULL || uncompressed_size != NULL)) { ++ (crc32 || compressed_size || uncompressed_size)) { + /* Check to see if data descriptor is zip64 bit format or not */ + if (mz_zip_extrafield_contains(zip->local_file_info.extrafield, + zip->local_file_info.extrafield_size, MZ_ZIP_EXTENSION_ZIP64, NULL) == MZ_OK) +@@ -2085,7 +2111,7 @@ int32_t mz_zip_entry_read_close(void *handle, uint32_t *crc32, int64_t *compress + } + + /* If entire entry was not read verification will fail */ +- if ((err == MZ_OK) && (total_in > 0) && (!zip->entry_raw)) { ++ if ((err == MZ_OK) && (total_in == zip->file_info.compressed_size) && (!zip->entry_raw)) { + #ifdef HAVE_WZAES + /* AES zip version AE-1 will expect a valid crc as well */ + if (zip->file_info.aes_version <= 0x0001) +@@ -2112,7 +2138,7 @@ int32_t mz_zip_entry_write_close(void *handle, uint32_t crc32, int64_t compresse + int32_t err = MZ_OK; + uint8_t zip64 = 0; + +- if (zip == NULL || mz_zip_entry_is_open(handle) != MZ_OK) ++ if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) + return MZ_PARAM_ERROR; + + mz_stream_close(zip->compress_stream); +@@ -2173,7 +2199,8 @@ int32_t mz_zip_entry_write_close(void *handle, uint32_t crc32, int64_t compresse + + if (err == MZ_OK) { + /* Seek to crc32 and sizes offset in local header */ +- err = mz_stream_seek(zip->stream, MZ_ZIP_OFFSET_CRC_SIZES, MZ_SEEK_CUR); ++ mz_stream_set_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, zip->file_info.disk_number); ++ err = mz_stream_seek(zip->stream, zip->file_info.disk_offset + MZ_ZIP_OFFSET_CRC_SIZES, MZ_SEEK_SET); + } + + if (err == MZ_OK) +@@ -2230,6 +2257,16 @@ int32_t mz_zip_entry_seek_local_header(void *handle) { + return mz_stream_seek(zip->stream, zip->file_info.disk_offset + zip->disk_offset_shift, MZ_SEEK_SET); + } + ++int32_t mz_zip_entry_get_compress_stream(void *handle, void **compress_stream) { ++ mz_zip *zip = (mz_zip *)handle; ++ if (!zip || !compress_stream) ++ return MZ_PARAM_ERROR; ++ *compress_stream = zip->compress_stream; ++ if (!*compress_stream) ++ return MZ_EXIST_ERROR; ++ return MZ_OK; ++} ++ + int32_t mz_zip_entry_close(void *handle) { + return mz_zip_entry_close_raw(handle, UINT64_MAX, 0); + } +@@ -2238,7 +2275,7 @@ int32_t mz_zip_entry_close_raw(void *handle, int64_t uncompressed_size, uint32_t + mz_zip *zip = (mz_zip *)handle; + int32_t err = MZ_OK; + +- if (zip == NULL || mz_zip_entry_is_open(handle) != MZ_OK) ++ if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) + return MZ_PARAM_ERROR; + + if (zip->open_mode & MZ_OPEN_MODE_WRITE) +@@ -2253,9 +2290,7 @@ int32_t mz_zip_entry_is_dir(void *handle) { + mz_zip *zip = (mz_zip *)handle; + int32_t filename_length = 0; + +- if (zip == NULL) +- return MZ_PARAM_ERROR; +- if (zip->entry_scanned == 0) ++ if (!zip || !zip->entry_scanned) + return MZ_PARAM_ERROR; + if (mz_zip_attrib_is_dir(zip->file_info.external_fa, zip->file_info.version_madeby) == MZ_OK) + return MZ_OK; +@@ -2272,14 +2307,10 @@ int32_t mz_zip_entry_is_dir(void *handle) { + int32_t mz_zip_entry_is_symlink(void *handle) { + mz_zip *zip = (mz_zip *)handle; + +- if (zip == NULL) +- return MZ_PARAM_ERROR; +- if (zip->entry_scanned == 0) ++ if (!zip || !zip->entry_scanned) + return MZ_PARAM_ERROR; + if (mz_zip_attrib_is_symlink(zip->file_info.external_fa, zip->file_info.version_madeby) != MZ_OK) + return MZ_EXIST_ERROR; +- if (zip->file_info.linkname == NULL || *zip->file_info.linkname == 0) +- return MZ_EXIST_ERROR; + + return MZ_OK; + } +@@ -2287,7 +2318,7 @@ int32_t mz_zip_entry_is_symlink(void *handle) { + int32_t mz_zip_entry_get_info(void *handle, mz_zip_file **file_info) { + mz_zip *zip = (mz_zip *)handle; + +- if (zip == NULL) ++ if (!zip) + return MZ_PARAM_ERROR; + + if ((zip->open_mode & MZ_OPEN_MODE_WRITE) == 0) { +@@ -2301,7 +2332,7 @@ int32_t mz_zip_entry_get_info(void *handle, mz_zip_file **file_info) { + + int32_t mz_zip_entry_get_local_info(void *handle, mz_zip_file **local_file_info) { + mz_zip *zip = (mz_zip *)handle; +- if (zip == NULL || mz_zip_entry_is_open(handle) != MZ_OK) ++ if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) + return MZ_PARAM_ERROR; + *local_file_info = &zip->local_file_info; + return MZ_OK; +@@ -2310,7 +2341,7 @@ int32_t mz_zip_entry_get_local_info(void *handle, mz_zip_file **local_file_info) + int32_t mz_zip_entry_set_extrafield(void *handle, const uint8_t *extrafield, uint16_t extrafield_size) { + mz_zip *zip = (mz_zip *)handle; + +- if (zip == NULL || mz_zip_entry_is_open(handle) != MZ_OK) ++ if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) + return MZ_PARAM_ERROR; + + zip->file_info.extrafield = extrafield; +@@ -2322,7 +2353,7 @@ static int32_t mz_zip_goto_next_entry_int(void *handle) { + mz_zip *zip = (mz_zip *)handle; + int32_t err = MZ_OK; + +- if (zip == NULL) ++ if (!zip) + return MZ_PARAM_ERROR; + + zip->entry_scanned = 0; +@@ -2340,7 +2371,7 @@ static int32_t mz_zip_goto_next_entry_int(void *handle) { + int64_t mz_zip_get_entry(void *handle) { + mz_zip *zip = (mz_zip *)handle; + +- if (zip == NULL) ++ if (!zip) + return MZ_PARAM_ERROR; + + return zip->cd_current_pos; +@@ -2349,7 +2380,7 @@ int64_t mz_zip_get_entry(void *handle) { + int32_t mz_zip_goto_entry(void *handle, int64_t cd_pos) { + mz_zip *zip = (mz_zip *)handle; + +- if (zip == NULL) ++ if (!zip) + return MZ_PARAM_ERROR; + + if (cd_pos < zip->cd_start_pos || cd_pos > zip->cd_start_pos + zip->cd_size) +@@ -2363,7 +2394,7 @@ int32_t mz_zip_goto_entry(void *handle, int64_t cd_pos) { + int32_t mz_zip_goto_first_entry(void *handle) { + mz_zip *zip = (mz_zip *)handle; + +- if (zip == NULL) ++ if (!zip) + return MZ_PARAM_ERROR; + + zip->cd_current_pos = zip->cd_start_pos; +@@ -2374,7 +2405,7 @@ int32_t mz_zip_goto_first_entry(void *handle) { + int32_t mz_zip_goto_next_entry(void *handle) { + mz_zip *zip = (mz_zip *)handle; + +- if (zip == NULL) ++ if (!zip) + return MZ_PARAM_ERROR; + + zip->cd_current_pos += (int64_t)MZ_ZIP_SIZE_CD_ITEM + zip->file_info.filename_size + +@@ -2388,11 +2419,11 @@ int32_t mz_zip_locate_entry(void *handle, const char *filename, uint8_t ignore_c + int32_t err = MZ_OK; + int32_t result = 0; + +- if (zip == NULL || filename == NULL) ++ if (!zip || !filename) + return MZ_PARAM_ERROR; + + /* If we are already on the current entry, no need to search */ +- if ((zip->entry_scanned) && (zip->file_info.filename != NULL)) { ++ if (zip->entry_scanned && zip->file_info.filename) { + result = mz_zip_path_compare(zip->file_info.filename, filename, ignore_case); + if (result == 0) + return MZ_OK; +@@ -2477,7 +2508,7 @@ int32_t mz_zip_attrib_is_symlink(uint32_t attrib, int32_t version_madeby) { + } + + int32_t mz_zip_attrib_convert(uint8_t src_sys, uint32_t src_attrib, uint8_t target_sys, uint32_t *target_attrib) { +- if (target_attrib == NULL) ++ if (!target_attrib) + return MZ_PARAM_ERROR; + + *target_attrib = 0; +@@ -2490,11 +2521,11 @@ int32_t mz_zip_attrib_convert(uint8_t src_sys, uint32_t src_attrib, uint8_t targ + if ((target_sys == MZ_HOST_SYSTEM_UNIX) || (target_sys == MZ_HOST_SYSTEM_OSX_DARWIN) || (target_sys == MZ_HOST_SYSTEM_RISCOS)) + return mz_zip_attrib_win32_to_posix(src_attrib, target_attrib); + } else if ((src_sys == MZ_HOST_SYSTEM_UNIX) || (src_sys == MZ_HOST_SYSTEM_OSX_DARWIN) || (src_sys == MZ_HOST_SYSTEM_RISCOS)) { +- if ((target_sys == MZ_HOST_SYSTEM_UNIX) || (target_sys == MZ_HOST_SYSTEM_OSX_DARWIN) || (target_sys == MZ_HOST_SYSTEM_RISCOS)) { +- /* If high bytes are set, it contains unix specific attributes */ +- if ((src_attrib >> 16) != 0) +- src_attrib >>= 16; ++ /* If high bytes are set, it contains unix specific attributes */ ++ if ((src_attrib >> 16) != 0) ++ src_attrib >>= 16; + ++ if ((target_sys == MZ_HOST_SYSTEM_UNIX) || (target_sys == MZ_HOST_SYSTEM_OSX_DARWIN) || (target_sys == MZ_HOST_SYSTEM_RISCOS)) { + *target_attrib = src_attrib; + return MZ_OK; + } +@@ -2506,7 +2537,7 @@ int32_t mz_zip_attrib_convert(uint8_t src_sys, uint32_t src_attrib, uint8_t targ + } + + int32_t mz_zip_attrib_posix_to_win32(uint32_t posix_attrib, uint32_t *win32_attrib) { +- if (win32_attrib == NULL) ++ if (!win32_attrib) + return MZ_PARAM_ERROR; + + *win32_attrib = 0; +@@ -2528,7 +2559,7 @@ int32_t mz_zip_attrib_posix_to_win32(uint32_t posix_attrib, uint32_t *win32_attr + } + + int32_t mz_zip_attrib_win32_to_posix(uint32_t win32_attrib, uint32_t *posix_attrib) { +- if (posix_attrib == NULL) ++ if (!posix_attrib) + return MZ_PARAM_ERROR; + + *posix_attrib = 0000444; /* S_IRUSR | S_IRGRP | S_IROTH */ +@@ -2554,7 +2585,6 @@ int32_t mz_zip_extrafield_find(void *stream, uint16_t type, int32_t max_seek, ui + uint16_t field_type = 0; + uint16_t field_length = 0; + +- + if (max_seek < 4) + return MZ_EXIST_ERROR; + +@@ -2566,7 +2596,7 @@ int32_t mz_zip_extrafield_find(void *stream, uint16_t type, int32_t max_seek, ui + break; + + if (type == field_type) { +- if (length != NULL) ++ if (length) + *length = field_length; + return MZ_OK; + } +@@ -2586,22 +2616,22 @@ int32_t mz_zip_extrafield_contains(const uint8_t *extrafield, int32_t extrafield + void *file_extra_stream = NULL; + int32_t err = MZ_OK; + +- if (extrafield == NULL || extrafield_size == 0) ++ if (!extrafield || !extrafield_size) + return MZ_PARAM_ERROR; + +- mz_stream_mem_create(&file_extra_stream); +- mz_stream_mem_set_buffer(file_extra_stream, (void *)extrafield, extrafield_size); ++ file_extra_stream = mz_stream_mem_create(); ++ if (!file_extra_stream) ++ return MZ_MEM_ERROR; + ++ mz_stream_mem_set_buffer(file_extra_stream, (void *)extrafield, extrafield_size); + err = mz_zip_extrafield_find(file_extra_stream, type, extrafield_size, length); +- + mz_stream_mem_delete(&file_extra_stream); +- + return err; + } + + int32_t mz_zip_extrafield_read(void *stream, uint16_t *type, uint16_t *length) { + int32_t err = MZ_OK; +- if (type == NULL || length == NULL) ++ if (!type || !length) + return MZ_PARAM_ERROR; + err = mz_stream_read_uint16(stream, type); + if (err == MZ_OK) +@@ -2643,7 +2673,7 @@ static void mz_zip_dosdate_to_raw_tm(uint64_t dos_date, struct tm *ptm) { + } + + int32_t mz_zip_dosdate_to_tm(uint64_t dos_date, struct tm *ptm) { +- if (ptm == NULL) ++ if (!ptm) + return MZ_PARAM_ERROR; + + mz_zip_dosdate_to_raw_tm(dos_date, ptm); +@@ -2664,9 +2694,9 @@ time_t mz_zip_dosdate_to_time_t(uint64_t dos_date) { + + int32_t mz_zip_time_t_to_tm(time_t unix_time, struct tm *ptm) { + struct tm ltm; +- if (ptm == NULL) ++ if (!ptm) + return MZ_PARAM_ERROR; +- if (localtime_r(&unix_time, <m) == NULL) { /* Returns a 1900-based year */ ++ if (!localtime_r(&unix_time, <m)) { /* Returns a 1900-based year */ + /* Invalid date stored, so don't return it */ + memset(ptm, 0, sizeof(struct tm)); + return MZ_INTERNAL_ERROR; +diff --git a/src/minizip/mz_zip.h b/src/minizip/mz_zip.h +index e3d1fbd52..cc01ee5a0 100644 +--- a/src/minizip/mz_zip.h ++++ b/src/minizip/mz_zip.h +@@ -1,7 +1,7 @@ + /* mz_zip.h -- Zip manipulation + part of the minizip-ng project + +- Copyright (C) 2010-2021 Nathan Moinvaziri ++ Copyright (C) Nathan Moinvaziri + https://github.com/zlib-ng/minizip-ng + Copyright (C) 2009-2010 Mathias Svensson + Modifications for Zip64 support +@@ -48,7 +48,7 @@ typedef struct mz_zip_file_s { + + uint16_t zip64; /* zip64 extension mode */ + uint16_t aes_version; /* winzip aes extension if not 0 */ +- uint8_t aes_encryption_mode; /* winzip aes encryption mode */ ++ uint8_t aes_strength; /* winzip aes encryption strength */ + uint16_t pk_verify; /* pkware encryption verifier */ + + } mz_zip_file, mz_zip_entry; +@@ -59,7 +59,7 @@ typedef int32_t (*mz_zip_locate_entry_cb)(void *handle, void *userdata, mz_zip_f + + /***************************************************************************/ + +-void * mz_zip_create(void **handle); ++void * mz_zip_create(void); + /* Create zip instance for opening */ + + void mz_zip_delete(void **handle); +@@ -139,6 +139,9 @@ int32_t mz_zip_entry_write_close(void *handle, uint32_t crc32, int64_t compresse + int32_t mz_zip_entry_seek_local_header(void *handle); + /* Seeks to the local header for the entry */ + ++int32_t mz_zip_entry_get_compress_stream(void *handle, void **compress_stream); ++/* Get a pointer to the compression stream used for the current entry */ ++ + int32_t mz_zip_entry_close_raw(void *handle, int64_t uncompressed_size, uint32_t crc32); + /* Close the current file in the zip file where raw is compressed data */ + +diff --git a/src/sevenzipfile.cpp b/src/sevenzipfile.cpp +index 7a539a5b3..e65dd3378 100644 +--- a/src/sevenzipfile.cpp ++++ b/src/sevenzipfile.cpp +@@ -283,7 +283,7 @@ bool SevenZipFile::open(QString fileName) + } + m_lookStream.bufSize = kInputBufSize; + m_lookStream.realStream = &m_archiveStream.vt; +- LookToRead2_Init(&m_lookStream); ++ LookToRead2_INIT(&m_lookStream); + CrcGenerateTable(); + SzArEx_Init(db()); + +diff --git a/src/zlib/README.zlib b/src/zlib/README.zlib +index 024b79d3d..c5f917540 100644 +--- a/src/zlib/README.zlib ++++ b/src/zlib/README.zlib +@@ -1,6 +1,6 @@ + ZLIB DATA COMPRESSION LIBRARY + +-zlib 1.2.12 is a general purpose data compression library. All the code is ++zlib 1.3.1 is a general purpose data compression library. All the code is + thread safe. The data format used by the zlib library is described by RFCs + (Request for Comments) 1950 to 1952 in the files + http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and +@@ -29,18 +29,17 @@ PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help. + + Mark Nelson wrote an article about zlib for the Jan. 1997 + issue of Dr. Dobb's Journal; a copy of the article is available at +-http://marknelson.us/1997/01/01/zlib-engine/ . ++https://marknelson.us/posts/1997/01/01/zlib-engine.html . + +-The changes made in version 1.2.12 are documented in the file ChangeLog. ++The changes made in version 1.3.1 are documented in the file ChangeLog. + + Unsupported third party contributions are provided in directory contrib/ . + +-zlib is available in Java using the java.util.zip package, documented at +-http://java.sun.com/developer/technicalArticles/Programming/compression/ . ++zlib is available in Java using the java.util.zip package. Follow the API ++Documentation link at: https://docs.oracle.com/search/?q=java.util.zip . + +-A Perl interface to zlib written by Paul Marquess is available +-at CPAN (Comprehensive Perl Archive Network) sites, including +-http://search.cpan.org/~pmqs/IO-Compress-Zlib/ . ++A Perl interface to zlib and bzip2 written by Paul Marquess ++can be found at https://github.com/pmqs/IO-Compress . + + A Python interface to zlib written by A.M. Kuchling is + available in Python 1.5 and later versions, see +@@ -64,7 +63,7 @@ Notes for some targets: + - zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works + when compiled with cc. + +-- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is ++- On Digital Unix 4.0D (formerly OSF/1) on AlphaServer, the cc option -std1 is + necessary to get gzprintf working correctly. This is done by configure. + + - zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with +@@ -84,7 +83,7 @@ Acknowledgments: + + Copyright notice: + +- (C) 1995-2022 Jean-loup Gailly and Mark Adler ++ (C) 1995-2024 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages +diff --git a/src/zlib/adler32.c b/src/zlib/adler32.c +index d0be4380a..04b81d29b 100644 +--- a/src/zlib/adler32.c ++++ b/src/zlib/adler32.c +@@ -7,8 +7,6 @@ + + #include "zutil.h" + +-local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2)); +- + #define BASE 65521U /* largest prime smaller than 65536 */ + #define NMAX 5552 + /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ +@@ -60,11 +58,7 @@ local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2)); + #endif + + /* ========================================================================= */ +-uLong ZEXPORT adler32_z(adler, buf, len) +- uLong adler; +- const Bytef *buf; +- z_size_t len; +-{ ++uLong ZEXPORT adler32_z(uLong adler, const Bytef *buf, z_size_t len) { + unsigned long sum2; + unsigned n; + +@@ -131,20 +125,12 @@ uLong ZEXPORT adler32_z(adler, buf, len) + } + + /* ========================================================================= */ +-uLong ZEXPORT adler32(adler, buf, len) +- uLong adler; +- const Bytef *buf; +- uInt len; +-{ ++uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len) { + return adler32_z(adler, buf, len); + } + + /* ========================================================================= */ +-local uLong adler32_combine_(adler1, adler2, len2) +- uLong adler1; +- uLong adler2; +- z_off64_t len2; +-{ ++local uLong adler32_combine_(uLong adler1, uLong adler2, z_off64_t len2) { + unsigned long sum1; + unsigned long sum2; + unsigned rem; +@@ -169,18 +155,10 @@ local uLong adler32_combine_(adler1, adler2, len2) + } + + /* ========================================================================= */ +-uLong ZEXPORT adler32_combine(adler1, adler2, len2) +- uLong adler1; +- uLong adler2; +- z_off_t len2; +-{ ++uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2) { + return adler32_combine_(adler1, adler2, len2); + } + +-uLong ZEXPORT adler32_combine64(adler1, adler2, len2) +- uLong adler1; +- uLong adler2; +- z_off64_t len2; +-{ ++uLong ZEXPORT adler32_combine64(uLong adler1, uLong adler2, z_off64_t len2) { + return adler32_combine_(adler1, adler2, len2); + } +diff --git a/src/zlib/compress.c b/src/zlib/compress.c +index e2db404ab..f43bacf7a 100644 +--- a/src/zlib/compress.c ++++ b/src/zlib/compress.c +@@ -19,13 +19,8 @@ + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. + */ +-int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) +- Bytef *dest; +- uLongf *destLen; +- const Bytef *source; +- uLong sourceLen; +- int level; +-{ ++int ZEXPORT compress2(Bytef *dest, uLongf *destLen, const Bytef *source, ++ uLong sourceLen, int level) { + z_stream stream; + int err; + const uInt max = (uInt)-1; +@@ -65,12 +60,8 @@ int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) + + /* =========================================================================== + */ +-int ZEXPORT compress (dest, destLen, source, sourceLen) +- Bytef *dest; +- uLongf *destLen; +- const Bytef *source; +- uLong sourceLen; +-{ ++int ZEXPORT compress(Bytef *dest, uLongf *destLen, const Bytef *source, ++ uLong sourceLen) { + return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); + } + +@@ -78,9 +69,7 @@ int ZEXPORT compress (dest, destLen, source, sourceLen) + If the default memLevel or windowBits for deflateInit() is changed, then + this function needs to be updated. + */ +-uLong ZEXPORT compressBound (sourceLen) +- uLong sourceLen; +-{ ++uLong ZEXPORT compressBound(uLong sourceLen) { + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13; + } +diff --git a/src/zlib/crc32.c b/src/zlib/crc32.c +index a1bdce5c2..6c38f5c04 100644 +--- a/src/zlib/crc32.c ++++ b/src/zlib/crc32.c +@@ -98,10 +98,6 @@ + # endif + #endif + +-/* Local functions. */ +-local z_crc_t multmodp OF((z_crc_t a, z_crc_t b)); +-local z_crc_t x2nmodp OF((z_off64_t n, unsigned k)); +- + /* If available, use the ARM processor CRC32 instruction. */ + #if defined(__aarch64__) && defined(__ARM_FEATURE_CRC32) && W == 8 + # define ARMCRC32 +@@ -114,9 +110,7 @@ local z_crc_t x2nmodp OF((z_off64_t n, unsigned k)); + instruction, if one is available. This assumes that word_t is either 32 bits + or 64 bits. + */ +-local z_word_t byte_swap(word) +- z_word_t word; +-{ ++local z_word_t byte_swap(z_word_t word) { + # if W == 8 + return + (word & 0xff00000000000000) >> 56 | +@@ -137,24 +131,77 @@ local z_word_t byte_swap(word) + } + #endif + ++#ifdef DYNAMIC_CRC_TABLE ++/* ========================================================================= ++ * Table of powers of x for combining CRC-32s, filled in by make_crc_table() ++ * below. ++ */ ++ local z_crc_t FAR x2n_table[32]; ++#else ++/* ========================================================================= ++ * Tables for byte-wise and braided CRC-32 calculations, and a table of powers ++ * of x for combining CRC-32s, all made by make_crc_table(). ++ */ ++# include "crc32.h" ++#endif ++ + /* CRC polynomial. */ + #define POLY 0xedb88320 /* p(x) reflected, with x^32 implied */ + +-#ifdef DYNAMIC_CRC_TABLE ++/* ++ Return a(x) multiplied by b(x) modulo p(x), where p(x) is the CRC polynomial, ++ reflected. For speed, this requires that a not be zero. ++ */ ++local z_crc_t multmodp(z_crc_t a, z_crc_t b) { ++ z_crc_t m, p; ++ ++ m = (z_crc_t)1 << 31; ++ p = 0; ++ for (;;) { ++ if (a & m) { ++ p ^= b; ++ if ((a & (m - 1)) == 0) ++ break; ++ } ++ m >>= 1; ++ b = b & 1 ? (b >> 1) ^ POLY : b >> 1; ++ } ++ return p; ++} ++ ++/* ++ Return x^(n * 2^k) modulo p(x). Requires that x2n_table[] has been ++ initialized. ++ */ ++local z_crc_t x2nmodp(z_off64_t n, unsigned k) { ++ z_crc_t p; ++ ++ p = (z_crc_t)1 << 31; /* x^0 == 1 */ ++ while (n) { ++ if (n & 1) ++ p = multmodp(x2n_table[k & 31], p); ++ n >>= 1; ++ k++; ++ } ++ return p; ++} + ++#ifdef DYNAMIC_CRC_TABLE ++/* ========================================================================= ++ * Build the tables for byte-wise and braided CRC-32 calculations, and a table ++ * of powers of x for combining CRC-32s. ++ */ + local z_crc_t FAR crc_table[256]; +-local z_crc_t FAR x2n_table[32]; +-local void make_crc_table OF((void)); + #ifdef W + local z_word_t FAR crc_big_table[256]; + local z_crc_t FAR crc_braid_table[W][256]; + local z_word_t FAR crc_braid_big_table[W][256]; +- local void braid OF((z_crc_t [][256], z_word_t [][256], int, int)); ++ local void braid(z_crc_t [][256], z_word_t [][256], int, int); + #endif + #ifdef MAKECRCH +- local void write_table OF((FILE *, const z_crc_t FAR *, int)); +- local void write_table32hi OF((FILE *, const z_word_t FAR *, int)); +- local void write_table64 OF((FILE *, const z_word_t FAR *, int)); ++ local void write_table(FILE *, const z_crc_t FAR *, int); ++ local void write_table32hi(FILE *, const z_word_t FAR *, int); ++ local void write_table64(FILE *, const z_word_t FAR *, int); + #endif /* MAKECRCH */ + + /* +@@ -167,7 +214,6 @@ local void make_crc_table OF((void)); + + /* Definition of once functionality. */ + typedef struct once_s once_t; +-local void once OF((once_t *, void (*)(void))); + + /* Check for the availability of atomics. */ + #if defined(__STDC__) && __STDC_VERSION__ >= 201112L && \ +@@ -187,10 +233,7 @@ struct once_s { + invoke once() at the same time. The state must be a once_t initialized with + ONCE_INIT. + */ +-local void once(state, init) +- once_t *state; +- void (*init)(void); +-{ ++local void once(once_t *state, void (*init)(void)) { + if (!atomic_load(&state->done)) { + if (atomic_flag_test_and_set(&state->begun)) + while (!atomic_load(&state->done)) +@@ -213,10 +256,7 @@ struct once_s { + + /* Test and set. Alas, not atomic, but tries to minimize the period of + vulnerability. */ +-local int test_and_set OF((int volatile *)); +-local int test_and_set(flag) +- int volatile *flag; +-{ ++local int test_and_set(int volatile *flag) { + int was; + + was = *flag; +@@ -225,10 +265,7 @@ local int test_and_set(flag) + } + + /* Run the provided init() function once. This is not thread-safe. */ +-local void once(state, init) +- once_t *state; +- void (*init)(void); +-{ ++local void once(once_t *state, void (*init)(void)) { + if (!state->done) { + if (test_and_set(&state->begun)) + while (!state->done) +@@ -270,8 +307,7 @@ local once_t made = ONCE_INIT; + combinations of CRC register values and incoming bytes. + */ + +-local void make_crc_table() +-{ ++local void make_crc_table(void) { + unsigned i, j, n; + z_crc_t p; + +@@ -438,11 +474,7 @@ local void make_crc_table() + Write the 32-bit values in table[0..k-1] to out, five per line in + hexadecimal separated by commas. + */ +-local void write_table(out, table, k) +- FILE *out; +- const z_crc_t FAR *table; +- int k; +-{ ++local void write_table(FILE *out, const z_crc_t FAR *table, int k) { + int n; + + for (n = 0; n < k; n++) +@@ -455,11 +487,7 @@ local void write_table(out, table, k) + Write the high 32-bits of each value in table[0..k-1] to out, five per line + in hexadecimal separated by commas. + */ +-local void write_table32hi(out, table, k) +-FILE *out; +-const z_word_t FAR *table; +-int k; +-{ ++local void write_table32hi(FILE *out, const z_word_t FAR *table, int k) { + int n; + + for (n = 0; n < k; n++) +@@ -475,11 +503,7 @@ int k; + bits. If not, then the type cast and format string can be adjusted + accordingly. + */ +-local void write_table64(out, table, k) +- FILE *out; +- const z_word_t FAR *table; +- int k; +-{ ++local void write_table64(FILE *out, const z_word_t FAR *table, int k) { + int n; + + for (n = 0; n < k; n++) +@@ -489,8 +513,7 @@ local void write_table64(out, table, k) + } + + /* Actually do the deed. */ +-int main() +-{ ++int main(void) { + make_crc_table(); + return 0; + } +@@ -502,12 +525,7 @@ int main() + Generate the little and big-endian braid tables for the given n and z_word_t + size w. Each array must have room for w blocks of 256 elements. + */ +-local void braid(ltl, big, n, w) +- z_crc_t ltl[][256]; +- z_word_t big[][256]; +- int n; +- int w; +-{ ++local void braid(z_crc_t ltl[][256], z_word_t big[][256], int n, int w) { + int k; + z_crc_t i, p, q; + for (k = 0; k < w; k++) { +@@ -522,69 +540,13 @@ local void braid(ltl, big, n, w) + } + #endif + +-#else /* !DYNAMIC_CRC_TABLE */ +-/* ======================================================================== +- * Tables for byte-wise and braided CRC-32 calculations, and a table of powers +- * of x for combining CRC-32s, all made by make_crc_table(). +- */ +-#include "crc32.h" + #endif /* DYNAMIC_CRC_TABLE */ + +-/* ======================================================================== +- * Routines used for CRC calculation. Some are also required for the table +- * generation above. +- */ +- +-/* +- Return a(x) multiplied by b(x) modulo p(x), where p(x) is the CRC polynomial, +- reflected. For speed, this requires that a not be zero. +- */ +-local z_crc_t multmodp(a, b) +- z_crc_t a; +- z_crc_t b; +-{ +- z_crc_t m, p; +- +- m = (z_crc_t)1 << 31; +- p = 0; +- for (;;) { +- if (a & m) { +- p ^= b; +- if ((a & (m - 1)) == 0) +- break; +- } +- m >>= 1; +- b = b & 1 ? (b >> 1) ^ POLY : b >> 1; +- } +- return p; +-} +- +-/* +- Return x^(n * 2^k) modulo p(x). Requires that x2n_table[] has been +- initialized. +- */ +-local z_crc_t x2nmodp(n, k) +- z_off64_t n; +- unsigned k; +-{ +- z_crc_t p; +- +- p = (z_crc_t)1 << 31; /* x^0 == 1 */ +- while (n) { +- if (n & 1) +- p = multmodp(x2n_table[k & 31], p); +- n >>= 1; +- k++; +- } +- return p; +-} +- + /* ========================================================================= + * This function can be used by asm versions of crc32(), and to force the + * generation of the CRC tables in a threaded application. + */ +-const z_crc_t FAR * ZEXPORT get_crc_table() +-{ ++const z_crc_t FAR * ZEXPORT get_crc_table(void) { + #ifdef DYNAMIC_CRC_TABLE + once(&made, make_crc_table); + #endif /* DYNAMIC_CRC_TABLE */ +@@ -610,11 +572,8 @@ const z_crc_t FAR * ZEXPORT get_crc_table() + #define Z_BATCH_ZEROS 0xa10d3d0c /* computed from Z_BATCH = 3990 */ + #define Z_BATCH_MIN 800 /* fewest words in a final batch */ + +-unsigned long ZEXPORT crc32_z(crc, buf, len) +- unsigned long crc; +- const unsigned char FAR *buf; +- z_size_t len; +-{ ++unsigned long ZEXPORT crc32_z(unsigned long crc, const unsigned char FAR *buf, ++ z_size_t len) { + z_crc_t val; + z_word_t crc1, crc2; + const z_word_t *word; +@@ -630,7 +589,7 @@ unsigned long ZEXPORT crc32_z(crc, buf, len) + #endif /* DYNAMIC_CRC_TABLE */ + + /* Pre-condition the CRC */ +- crc ^= 0xffffffff; ++ crc = (~crc) & 0xffffffff; + + /* Compute the CRC up to a word boundary. */ + while (len && ((z_size_t)buf & 7) != 0) { +@@ -645,8 +604,8 @@ unsigned long ZEXPORT crc32_z(crc, buf, len) + len &= 7; + + /* Do three interleaved CRCs to realize the throughput of one crc32x +- instruction per cycle. Each CRC is calcuated on Z_BATCH words. The three +- CRCs are combined into a single CRC after each set of batches. */ ++ instruction per cycle. Each CRC is calculated on Z_BATCH words. The ++ three CRCs are combined into a single CRC after each set of batches. */ + while (num >= 3 * Z_BATCH) { + crc1 = 0; + crc2 = 0; +@@ -714,18 +673,14 @@ unsigned long ZEXPORT crc32_z(crc, buf, len) + least-significant byte of the word as the first byte of data, without any pre + or post conditioning. This is used to combine the CRCs of each braid. + */ +-local z_crc_t crc_word(data) +- z_word_t data; +-{ ++local z_crc_t crc_word(z_word_t data) { + int k; + for (k = 0; k < W; k++) + data = (data >> 8) ^ crc_table[data & 0xff]; + return (z_crc_t)data; + } + +-local z_word_t crc_word_big(data) +- z_word_t data; +-{ ++local z_word_t crc_word_big(z_word_t data) { + int k; + for (k = 0; k < W; k++) + data = (data << 8) ^ +@@ -736,11 +691,8 @@ local z_word_t crc_word_big(data) + #endif + + /* ========================================================================= */ +-unsigned long ZEXPORT crc32_z(crc, buf, len) +- unsigned long crc; +- const unsigned char FAR *buf; +- z_size_t len; +-{ ++unsigned long ZEXPORT crc32_z(unsigned long crc, const unsigned char FAR *buf, ++ z_size_t len) { + /* Return initial CRC, if requested. */ + if (buf == Z_NULL) return 0; + +@@ -749,7 +701,7 @@ unsigned long ZEXPORT crc32_z(crc, buf, len) + #endif /* DYNAMIC_CRC_TABLE */ + + /* Pre-condition the CRC */ +- crc ^= 0xffffffff; ++ crc = (~crc) & 0xffffffff; + + #ifdef W + +@@ -772,8 +724,8 @@ unsigned long ZEXPORT crc32_z(crc, buf, len) + words = (z_word_t const *)buf; + + /* Do endian check at execution time instead of compile time, since ARM +- processors can change the endianess at execution time. If the +- compiler knows what the endianess will be, it can optimize out the ++ processors can change the endianness at execution time. If the ++ compiler knows what the endianness will be, it can optimize out the + check and the unused branch. */ + endian = 1; + if (*(unsigned char *)&endian) { +@@ -1060,39 +1012,26 @@ unsigned long ZEXPORT crc32_z(crc, buf, len) + #endif + + /* ========================================================================= */ +-unsigned long ZEXPORT crc32(crc, buf, len) +- unsigned long crc; +- const unsigned char FAR *buf; +- uInt len; +-{ ++unsigned long ZEXPORT crc32(unsigned long crc, const unsigned char FAR *buf, ++ uInt len) { + return crc32_z(crc, buf, len); + } + + /* ========================================================================= */ +-uLong ZEXPORT crc32_combine64(crc1, crc2, len2) +- uLong crc1; +- uLong crc2; +- z_off64_t len2; +-{ ++uLong ZEXPORT crc32_combine64(uLong crc1, uLong crc2, z_off64_t len2) { + #ifdef DYNAMIC_CRC_TABLE + once(&made, make_crc_table); + #endif /* DYNAMIC_CRC_TABLE */ +- return multmodp(x2nmodp(len2, 3), crc1) ^ crc2; ++ return multmodp(x2nmodp(len2, 3), crc1) ^ (crc2 & 0xffffffff); + } + + /* ========================================================================= */ +-uLong ZEXPORT crc32_combine(crc1, crc2, len2) +- uLong crc1; +- uLong crc2; +- z_off_t len2; +-{ +- return crc32_combine64(crc1, crc2, len2); ++uLong ZEXPORT crc32_combine(uLong crc1, uLong crc2, z_off_t len2) { ++ return crc32_combine64(crc1, crc2, (z_off64_t)len2); + } + + /* ========================================================================= */ +-uLong ZEXPORT crc32_combine_gen64(len2) +- z_off64_t len2; +-{ ++uLong ZEXPORT crc32_combine_gen64(z_off64_t len2) { + #ifdef DYNAMIC_CRC_TABLE + once(&made, make_crc_table); + #endif /* DYNAMIC_CRC_TABLE */ +@@ -1100,17 +1039,11 @@ uLong ZEXPORT crc32_combine_gen64(len2) + } + + /* ========================================================================= */ +-uLong ZEXPORT crc32_combine_gen(len2) +- z_off_t len2; +-{ +- return crc32_combine_gen64(len2); ++uLong ZEXPORT crc32_combine_gen(z_off_t len2) { ++ return crc32_combine_gen64((z_off64_t)len2); + } + + /* ========================================================================= */ +-uLong crc32_combine_op(crc1, crc2, op) +- uLong crc1; +- uLong crc2; +- uLong op; +-{ +- return multmodp(op, crc1) ^ crc2; ++uLong ZEXPORT crc32_combine_op(uLong crc1, uLong crc2, uLong op) { ++ return multmodp(op, crc1) ^ (crc2 & 0xffffffff); + } +diff --git a/src/zlib/deflate.c b/src/zlib/deflate.c +index 799fb93cc..012ea8148 100644 +--- a/src/zlib/deflate.c ++++ b/src/zlib/deflate.c +@@ -1,5 +1,5 @@ + /* deflate.c -- compress data using the deflation algorithm +- * Copyright (C) 1995-2022 Jean-loup Gailly and Mark Adler ++ * Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +@@ -52,7 +52,7 @@ + #include "deflate.h" + + const char deflate_copyright[] = +- " deflate 1.2.12 Copyright 1995-2022 Jean-loup Gailly and Mark Adler "; ++ " deflate 1.3.1 Copyright 1995-2024 Jean-loup Gailly and Mark Adler "; + /* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot +@@ -60,9 +60,6 @@ const char deflate_copyright[] = + copyright string in the executable of your product. + */ + +-/* =========================================================================== +- * Function prototypes. +- */ + typedef enum { + need_more, /* block not completed, need more input or more output */ + block_done, /* block flush performed */ +@@ -70,35 +67,16 @@ typedef enum { + finish_done /* finish done, accept no more input or output */ + } block_state; + +-typedef block_state (*compress_func) OF((deflate_state *s, int flush)); ++typedef block_state (*compress_func)(deflate_state *s, int flush); + /* Compression function. Returns the block state after the call. */ + +-local int deflateStateCheck OF((z_streamp strm)); +-local void slide_hash OF((deflate_state *s)); +-local void fill_window OF((deflate_state *s)); +-local block_state deflate_stored OF((deflate_state *s, int flush)); +-local block_state deflate_fast OF((deflate_state *s, int flush)); ++local block_state deflate_stored(deflate_state *s, int flush); ++local block_state deflate_fast(deflate_state *s, int flush); + #ifndef FASTEST +-local block_state deflate_slow OF((deflate_state *s, int flush)); +-#endif +-local block_state deflate_rle OF((deflate_state *s, int flush)); +-local block_state deflate_huff OF((deflate_state *s, int flush)); +-local void lm_init OF((deflate_state *s)); +-local void putShortMSB OF((deflate_state *s, uInt b)); +-local void flush_pending OF((z_streamp strm)); +-local unsigned read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); +-#ifdef ASMV +-# pragma message("Assembler code may have bugs -- use at your own risk") +- void match_init OF((void)); /* asm code initialization */ +- uInt longest_match OF((deflate_state *s, IPos cur_match)); +-#else +-local uInt longest_match OF((deflate_state *s, IPos cur_match)); +-#endif +- +-#ifdef ZLIB_DEBUG +-local void check_match OF((deflate_state *s, IPos start, IPos match, +- int length)); ++local block_state deflate_slow(deflate_state *s, int flush); + #endif ++local block_state deflate_rle(deflate_state *s, int flush); ++local block_state deflate_huff(deflate_state *s, int flush); + + /* =========================================================================== + * Local data +@@ -160,7 +138,7 @@ local const config configuration_table[10] = { + * characters, so that a running hash key can be computed from the previous + * key instead of complete recalculation each time. + */ +-#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) ++#define UPDATE_HASH(s,h,c) (h = (((h) << s->hash_shift) ^ (c)) & s->hash_mask) + + + /* =========================================================================== +@@ -191,9 +169,9 @@ local const config configuration_table[10] = { + */ + #define CLEAR_HASH(s) \ + do { \ +- s->head[s->hash_size-1] = NIL; \ ++ s->head[s->hash_size - 1] = NIL; \ + zmemzero((Bytef *)s->head, \ +- (unsigned)(s->hash_size-1)*sizeof(*s->head)); \ ++ (unsigned)(s->hash_size - 1)*sizeof(*s->head)); \ + } while (0) + + /* =========================================================================== +@@ -201,9 +179,12 @@ local const config configuration_table[10] = { + * bit values at the expense of memory usage). We slide even when level == 0 to + * keep the hash table consistent if we switch back to level > 0 later. + */ +-local void slide_hash(s) +- deflate_state *s; +-{ ++#if defined(__has_feature) ++# if __has_feature(memory_sanitizer) ++ __attribute__((no_sanitize("memory"))) ++# endif ++#endif ++local void slide_hash(deflate_state *s) { + unsigned n, m; + Posf *p; + uInt wsize = s->w_size; +@@ -227,30 +208,177 @@ local void slide_hash(s) + #endif + } + ++/* =========================================================================== ++ * Read a new buffer from the current input stream, update the adler32 ++ * and total number of bytes read. All deflate() input goes through ++ * this function so some applications may wish to modify it to avoid ++ * allocating a large strm->next_in buffer and copying from it. ++ * (See also flush_pending()). ++ */ ++local unsigned read_buf(z_streamp strm, Bytef *buf, unsigned size) { ++ unsigned len = strm->avail_in; ++ ++ if (len > size) len = size; ++ if (len == 0) return 0; ++ ++ strm->avail_in -= len; ++ ++ zmemcpy(buf, strm->next_in, len); ++ if (strm->state->wrap == 1) { ++ strm->adler = adler32(strm->adler, buf, len); ++ } ++#ifdef GZIP ++ else if (strm->state->wrap == 2) { ++ strm->adler = crc32(strm->adler, buf, len); ++ } ++#endif ++ strm->next_in += len; ++ strm->total_in += len; ++ ++ return len; ++} ++ ++/* =========================================================================== ++ * Fill the window when the lookahead becomes insufficient. ++ * Updates strstart and lookahead. ++ * ++ * IN assertion: lookahead < MIN_LOOKAHEAD ++ * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD ++ * At least one byte has been read, or avail_in == 0; reads are ++ * performed for at least two bytes (required for the zip translate_eol ++ * option -- not supported here). ++ */ ++local void fill_window(deflate_state *s) { ++ unsigned n; ++ unsigned more; /* Amount of free space at the end of the window. */ ++ uInt wsize = s->w_size; ++ ++ Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); ++ ++ do { ++ more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); ++ ++ /* Deal with !@#$% 64K limit: */ ++ if (sizeof(int) <= 2) { ++ if (more == 0 && s->strstart == 0 && s->lookahead == 0) { ++ more = wsize; ++ ++ } else if (more == (unsigned)(-1)) { ++ /* Very unlikely, but possible on 16 bit machine if ++ * strstart == 0 && lookahead == 1 (input done a byte at time) ++ */ ++ more--; ++ } ++ } ++ ++ /* If the window is almost full and there is insufficient lookahead, ++ * move the upper half to the lower one to make room in the upper half. ++ */ ++ if (s->strstart >= wsize + MAX_DIST(s)) { ++ ++ zmemcpy(s->window, s->window + wsize, (unsigned)wsize - more); ++ s->match_start -= wsize; ++ s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ ++ s->block_start -= (long) wsize; ++ if (s->insert > s->strstart) ++ s->insert = s->strstart; ++ slide_hash(s); ++ more += wsize; ++ } ++ if (s->strm->avail_in == 0) break; ++ ++ /* If there was no sliding: ++ * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && ++ * more == window_size - lookahead - strstart ++ * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) ++ * => more >= window_size - 2*WSIZE + 2 ++ * In the BIG_MEM or MMAP case (not yet supported), ++ * window_size == input_size + MIN_LOOKAHEAD && ++ * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. ++ * Otherwise, window_size == 2*WSIZE so more >= 2. ++ * If there was sliding, more >= WSIZE. So in all cases, more >= 2. ++ */ ++ Assert(more >= 2, "more < 2"); ++ ++ n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); ++ s->lookahead += n; ++ ++ /* Initialize the hash value now that we have some input: */ ++ if (s->lookahead + s->insert >= MIN_MATCH) { ++ uInt str = s->strstart - s->insert; ++ s->ins_h = s->window[str]; ++ UPDATE_HASH(s, s->ins_h, s->window[str + 1]); ++#if MIN_MATCH != 3 ++ Call UPDATE_HASH() MIN_MATCH-3 more times ++#endif ++ while (s->insert) { ++ UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); ++#ifndef FASTEST ++ s->prev[str & s->w_mask] = s->head[s->ins_h]; ++#endif ++ s->head[s->ins_h] = (Pos)str; ++ str++; ++ s->insert--; ++ if (s->lookahead + s->insert < MIN_MATCH) ++ break; ++ } ++ } ++ /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, ++ * but this is not important since only literal bytes will be emitted. ++ */ ++ ++ } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); ++ ++ /* If the WIN_INIT bytes after the end of the current data have never been ++ * written, then zero those bytes in order to avoid memory check reports of ++ * the use of uninitialized (or uninitialised as Julian writes) bytes by ++ * the longest match routines. Update the high water mark for the next ++ * time through here. WIN_INIT is set to MAX_MATCH since the longest match ++ * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. ++ */ ++ if (s->high_water < s->window_size) { ++ ulg curr = s->strstart + (ulg)(s->lookahead); ++ ulg init; ++ ++ if (s->high_water < curr) { ++ /* Previous high water mark below current data -- zero WIN_INIT ++ * bytes or up to end of window, whichever is less. ++ */ ++ init = s->window_size - curr; ++ if (init > WIN_INIT) ++ init = WIN_INIT; ++ zmemzero(s->window + curr, (unsigned)init); ++ s->high_water = curr + init; ++ } ++ else if (s->high_water < (ulg)curr + WIN_INIT) { ++ /* High water mark at or above current data, but below current data ++ * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up ++ * to end of window, whichever is less. ++ */ ++ init = (ulg)curr + WIN_INIT - s->high_water; ++ if (init > s->window_size - s->high_water) ++ init = s->window_size - s->high_water; ++ zmemzero(s->window + s->high_water, (unsigned)init); ++ s->high_water += init; ++ } ++ } ++ ++ Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, ++ "not enough room for search"); ++} ++ + /* ========================================================================= */ +-int ZEXPORT deflateInit_(strm, level, version, stream_size) +- z_streamp strm; +- int level; +- const char *version; +- int stream_size; +-{ ++int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, ++ int stream_size) { + return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, + Z_DEFAULT_STRATEGY, version, stream_size); + /* To do: ignore strm->next_in if we use it as window */ + } + + /* ========================================================================= */ +-int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, +- version, stream_size) +- z_streamp strm; +- int level; +- int method; +- int windowBits; +- int memLevel; +- int strategy; +- const char *version; +- int stream_size; +-{ ++int ZEXPORT deflateInit2_(z_streamp strm, int level, int method, ++ int windowBits, int memLevel, int strategy, ++ const char *version, int stream_size) { + deflate_state *s; + int wrap = 1; + static const char my_version[] = ZLIB_VERSION; +@@ -285,6 +413,8 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; ++ if (windowBits < -15) ++ return Z_STREAM_ERROR; + windowBits = -windowBits; + } + #ifdef GZIP +@@ -314,7 +444,7 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + s->hash_bits = (uInt)memLevel + 7; + s->hash_size = 1 << s->hash_bits; + s->hash_mask = s->hash_size - 1; +- s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); ++ s->hash_shift = ((s->hash_bits + MIN_MATCH-1) / MIN_MATCH); + + s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); + s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); +@@ -340,11 +470,11 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + * sym_buf value to read moves forward three bytes. From that symbol, up to + * 31 bits are written to pending_buf. The closest the written pending_buf + * bits gets to the next sym_buf symbol to read is just before the last +- * code is written. At that time, 31*(n-2) bits have been written, just +- * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at +- * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1 ++ * code is written. At that time, 31*(n - 2) bits have been written, just ++ * after 24*(n - 2) bits have been consumed from sym_buf. sym_buf starts at ++ * 8*n bits into pending_buf. (Note that the symbol buffer fills when n - 1 + * symbols are written.) The closest the writing gets to what is unread is +- * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and ++ * then n + 14 bits. Here n is lit_bufsize, which is 16384 by default, and + * can range from 128 to 32768. + * + * Therefore, at a minimum, there are 142 bits of space between what is +@@ -363,7 +493,7 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + * symbols from which it is being constructed. + */ + +- s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 4); ++ s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, LIT_BUFS); + s->pending_buf_size = (ulg)s->lit_bufsize * 4; + + if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || +@@ -373,8 +503,14 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + deflateEnd (strm); + return Z_MEM_ERROR; + } ++#ifdef LIT_MEM ++ s->d_buf = (ushf *)(s->pending_buf + (s->lit_bufsize << 1)); ++ s->l_buf = s->pending_buf + (s->lit_bufsize << 2); ++ s->sym_end = s->lit_bufsize - 1; ++#else + s->sym_buf = s->pending_buf + s->lit_bufsize; + s->sym_end = (s->lit_bufsize - 1) * 3; ++#endif + /* We avoid equality with lit_bufsize*3 because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. +@@ -390,9 +526,7 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + /* ========================================================================= + * Check for a valid deflate stream state. Return 0 if ok, 1 if not. + */ +-local int deflateStateCheck (strm) +- z_streamp strm; +-{ ++local int deflateStateCheck(z_streamp strm) { + deflate_state *s; + if (strm == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) +@@ -413,11 +547,8 @@ local int deflateStateCheck (strm) + } + + /* ========================================================================= */ +-int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) +- z_streamp strm; +- const Bytef *dictionary; +- uInt dictLength; +-{ ++int ZEXPORT deflateSetDictionary(z_streamp strm, const Bytef *dictionary, ++ uInt dictLength) { + deflate_state *s; + uInt str, n; + int wrap; +@@ -482,11 +613,8 @@ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) + } + + /* ========================================================================= */ +-int ZEXPORT deflateGetDictionary (strm, dictionary, dictLength) +- z_streamp strm; +- Bytef *dictionary; +- uInt *dictLength; +-{ ++int ZEXPORT deflateGetDictionary(z_streamp strm, Bytef *dictionary, ++ uInt *dictLength) { + deflate_state *s; + uInt len; + +@@ -504,9 +632,7 @@ int ZEXPORT deflateGetDictionary (strm, dictionary, dictLength) + } + + /* ========================================================================= */ +-int ZEXPORT deflateResetKeep (strm) +- z_streamp strm; +-{ ++int ZEXPORT deflateResetKeep(z_streamp strm) { + deflate_state *s; + + if (deflateStateCheck(strm)) { +@@ -541,10 +667,32 @@ int ZEXPORT deflateResetKeep (strm) + return Z_OK; + } + ++/* =========================================================================== ++ * Initialize the "longest match" routines for a new zlib stream ++ */ ++local void lm_init(deflate_state *s) { ++ s->window_size = (ulg)2L*s->w_size; ++ ++ CLEAR_HASH(s); ++ ++ /* Set the default configuration parameters: ++ */ ++ s->max_lazy_match = configuration_table[s->level].max_lazy; ++ s->good_match = configuration_table[s->level].good_length; ++ s->nice_match = configuration_table[s->level].nice_length; ++ s->max_chain_length = configuration_table[s->level].max_chain; ++ ++ s->strstart = 0; ++ s->block_start = 0L; ++ s->lookahead = 0; ++ s->insert = 0; ++ s->match_length = s->prev_length = MIN_MATCH-1; ++ s->match_available = 0; ++ s->ins_h = 0; ++} ++ + /* ========================================================================= */ +-int ZEXPORT deflateReset (strm) +- z_streamp strm; +-{ ++int ZEXPORT deflateReset(z_streamp strm) { + int ret; + + ret = deflateResetKeep(strm); +@@ -554,10 +702,7 @@ int ZEXPORT deflateReset (strm) + } + + /* ========================================================================= */ +-int ZEXPORT deflateSetHeader (strm, head) +- z_streamp strm; +- gz_headerp head; +-{ ++int ZEXPORT deflateSetHeader(z_streamp strm, gz_headerp head) { + if (deflateStateCheck(strm) || strm->state->wrap != 2) + return Z_STREAM_ERROR; + strm->state->gzhead = head; +@@ -565,11 +710,7 @@ int ZEXPORT deflateSetHeader (strm, head) + } + + /* ========================================================================= */ +-int ZEXPORT deflatePending (strm, pending, bits) +- unsigned *pending; +- int *bits; +- z_streamp strm; +-{ ++int ZEXPORT deflatePending(z_streamp strm, unsigned *pending, int *bits) { + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + if (pending != Z_NULL) + *pending = strm->state->pending; +@@ -579,19 +720,21 @@ int ZEXPORT deflatePending (strm, pending, bits) + } + + /* ========================================================================= */ +-int ZEXPORT deflatePrime (strm, bits, value) +- z_streamp strm; +- int bits; +- int value; +-{ ++int ZEXPORT deflatePrime(z_streamp strm, int bits, int value) { + deflate_state *s; + int put; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + s = strm->state; ++#ifdef LIT_MEM ++ if (bits < 0 || bits > 16 || ++ (uchf *)s->d_buf < s->pending_out + ((Buf_size + 7) >> 3)) ++ return Z_BUF_ERROR; ++#else + if (bits < 0 || bits > 16 || + s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3)) + return Z_BUF_ERROR; ++#endif + do { + put = Buf_size - s->bi_valid; + if (put > bits) +@@ -606,11 +749,7 @@ int ZEXPORT deflatePrime (strm, bits, value) + } + + /* ========================================================================= */ +-int ZEXPORT deflateParams(strm, level, strategy) +- z_streamp strm; +- int level; +- int strategy; +-{ ++int ZEXPORT deflateParams(z_streamp strm, int level, int strategy) { + deflate_state *s; + compress_func func; + +@@ -655,13 +794,8 @@ int ZEXPORT deflateParams(strm, level, strategy) + } + + /* ========================================================================= */ +-int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) +- z_streamp strm; +- int good_length; +- int max_lazy; +- int nice_length; +- int max_chain; +-{ ++int ZEXPORT deflateTune(z_streamp strm, int good_length, int max_lazy, ++ int nice_length, int max_chain) { + deflate_state *s; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; +@@ -674,36 +808,47 @@ int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) + } + + /* ========================================================================= +- * For the default windowBits of 15 and memLevel of 8, this function returns +- * a close to exact, as well as small, upper bound on the compressed size. +- * They are coded as constants here for a reason--if the #define's are +- * changed, then this function needs to be changed as well. The return +- * value for 15 and 8 only works for those exact settings. ++ * For the default windowBits of 15 and memLevel of 8, this function returns a ++ * close to exact, as well as small, upper bound on the compressed size. This ++ * is an expansion of ~0.03%, plus a small constant. ++ * ++ * For any setting other than those defaults for windowBits and memLevel, one ++ * of two worst case bounds is returned. This is at most an expansion of ~4% or ++ * ~13%, plus a small constant. + * +- * For any setting other than those defaults for windowBits and memLevel, +- * the value returned is a conservative worst case for the maximum expansion +- * resulting from using fixed blocks instead of stored blocks, which deflate +- * can emit on compressed data for some combinations of the parameters. ++ * Both the 0.03% and 4% derive from the overhead of stored blocks. The first ++ * one is for stored blocks of 16383 bytes (memLevel == 8), whereas the second ++ * is for stored blocks of 127 bytes (the worst case memLevel == 1). The ++ * expansion results from five bytes of header for each stored block. + * +- * This function could be more sophisticated to provide closer upper bounds for +- * every combination of windowBits and memLevel. But even the conservative +- * upper bound of about 14% expansion does not seem onerous for output buffer +- * allocation. ++ * The larger expansion of 13% results from a window size less than or equal to ++ * the symbols buffer size (windowBits <= memLevel + 7). In that case some of ++ * the data being compressed may have slid out of the sliding window, impeding ++ * a stored block from being emitted. Then the only choice is a fixed or ++ * dynamic block, where a fixed block limits the maximum expansion to 9 bits ++ * per 8-bit byte, plus 10 bits for every block. The smallest block size for ++ * which this can occur is 255 (memLevel == 2). ++ * ++ * Shifts are used to approximate divisions, for speed. + */ +-uLong ZEXPORT deflateBound(strm, sourceLen) +- z_streamp strm; +- uLong sourceLen; +-{ ++uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen) { + deflate_state *s; +- uLong complen, wraplen; ++ uLong fixedlen, storelen, wraplen; ++ ++ /* upper bound for fixed blocks with 9-bit literals and length 255 ++ (memLevel == 2, which is the lowest that may not use stored blocks) -- ++ ~13% overhead plus a small constant */ ++ fixedlen = sourceLen + (sourceLen >> 3) + (sourceLen >> 8) + ++ (sourceLen >> 9) + 4; + +- /* conservative upper bound for compressed data */ +- complen = sourceLen + +- ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5; ++ /* upper bound for stored blocks with length 127 (memLevel == 1) -- ++ ~4% overhead plus a small constant */ ++ storelen = sourceLen + (sourceLen >> 5) + (sourceLen >> 7) + ++ (sourceLen >> 11) + 7; + +- /* if can't get parameters, return conservative bound plus zlib wrapper */ ++ /* if can't get parameters, return larger bound plus a zlib wrapper */ + if (deflateStateCheck(strm)) +- return complen + 6; ++ return (fixedlen > storelen ? fixedlen : storelen) + 6; + + /* compute wrapper length */ + s = strm->state; +@@ -740,11 +885,13 @@ uLong ZEXPORT deflateBound(strm, sourceLen) + wraplen = 6; + } + +- /* if not default parameters, return conservative bound */ ++ /* if not default parameters, return one of the conservative bounds */ + if (s->w_bits != 15 || s->hash_bits != 8 + 7) +- return complen + wraplen; ++ return (s->w_bits <= s->hash_bits && s->level ? fixedlen : storelen) + ++ wraplen; + +- /* default settings: return tight bound for that case */ ++ /* default settings: return tight bound for that case -- ~0.03% overhead ++ plus a small constant */ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13 - 6 + wraplen; + } +@@ -754,10 +901,7 @@ uLong ZEXPORT deflateBound(strm, sourceLen) + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +-local void putShortMSB (s, b) +- deflate_state *s; +- uInt b; +-{ ++local void putShortMSB(deflate_state *s, uInt b) { + put_byte(s, (Byte)(b >> 8)); + put_byte(s, (Byte)(b & 0xff)); + } +@@ -768,9 +912,7 @@ local void putShortMSB (s, b) + * applications may wish to modify it to avoid allocating a large + * strm->next_out buffer and copying into it. (See also read_buf()). + */ +-local void flush_pending(strm) +- z_streamp strm; +-{ ++local void flush_pending(z_streamp strm) { + unsigned len; + deflate_state *s = strm->state; + +@@ -801,10 +943,7 @@ local void flush_pending(strm) + } while (0) + + /* ========================================================================= */ +-int ZEXPORT deflate (strm, flush) +- z_streamp strm; +- int flush; +-{ ++int ZEXPORT deflate(z_streamp strm, int flush) { + int old_flush; /* value of flush param for previous deflate call */ + deflate_state *s; + +@@ -856,7 +995,7 @@ int ZEXPORT deflate (strm, flush) + s->status = BUSY_STATE; + if (s->status == INIT_STATE) { + /* zlib header */ +- uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; ++ uInt header = (Z_DEFLATED + ((s->w_bits - 8) << 4)) << 8; + uInt level_flags; + + if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) +@@ -1116,9 +1255,7 @@ int ZEXPORT deflate (strm, flush) + } + + /* ========================================================================= */ +-int ZEXPORT deflateEnd (strm) +- z_streamp strm; +-{ ++int ZEXPORT deflateEnd(z_streamp strm) { + int status; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; +@@ -1142,11 +1279,10 @@ int ZEXPORT deflateEnd (strm) + * To simplify the source, this is not supported for 16-bit MSDOS (which + * doesn't have enough memory anyway to duplicate compression states). + */ +-int ZEXPORT deflateCopy (dest, source) +- z_streamp dest; +- z_streamp source; +-{ ++int ZEXPORT deflateCopy(z_streamp dest, z_streamp source) { + #ifdef MAXSEG_64K ++ (void)dest; ++ (void)source; + return Z_STREAM_ERROR; + #else + deflate_state *ds; +@@ -1170,7 +1306,7 @@ int ZEXPORT deflateCopy (dest, source) + ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); + ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); + ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); +- ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, 4); ++ ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, LIT_BUFS); + + if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || + ds->pending_buf == Z_NULL) { +@@ -1181,10 +1317,15 @@ int ZEXPORT deflateCopy (dest, source) + zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); + zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos)); + zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos)); +- zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); ++ zmemcpy(ds->pending_buf, ss->pending_buf, ds->lit_bufsize * LIT_BUFS); + + ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); ++#ifdef LIT_MEM ++ ds->d_buf = (ushf *)(ds->pending_buf + (ds->lit_bufsize << 1)); ++ ds->l_buf = ds->pending_buf + (ds->lit_bufsize << 2); ++#else + ds->sym_buf = ds->pending_buf + ds->lit_bufsize; ++#endif + + ds->l_desc.dyn_tree = ds->dyn_ltree; + ds->d_desc.dyn_tree = ds->dyn_dtree; +@@ -1194,71 +1335,6 @@ int ZEXPORT deflateCopy (dest, source) + #endif /* MAXSEG_64K */ + } + +-/* =========================================================================== +- * Read a new buffer from the current input stream, update the adler32 +- * and total number of bytes read. All deflate() input goes through +- * this function so some applications may wish to modify it to avoid +- * allocating a large strm->next_in buffer and copying from it. +- * (See also flush_pending()). +- */ +-local unsigned read_buf(strm, buf, size) +- z_streamp strm; +- Bytef *buf; +- unsigned size; +-{ +- unsigned len = strm->avail_in; +- +- if (len > size) len = size; +- if (len == 0) return 0; +- +- strm->avail_in -= len; +- +- zmemcpy(buf, strm->next_in, len); +- if (strm->state->wrap == 1) { +- strm->adler = adler32(strm->adler, buf, len); +- } +-#ifdef GZIP +- else if (strm->state->wrap == 2) { +- strm->adler = crc32(strm->adler, buf, len); +- } +-#endif +- strm->next_in += len; +- strm->total_in += len; +- +- return len; +-} +- +-/* =========================================================================== +- * Initialize the "longest match" routines for a new zlib stream +- */ +-local void lm_init (s) +- deflate_state *s; +-{ +- s->window_size = (ulg)2L*s->w_size; +- +- CLEAR_HASH(s); +- +- /* Set the default configuration parameters: +- */ +- s->max_lazy_match = configuration_table[s->level].max_lazy; +- s->good_match = configuration_table[s->level].good_length; +- s->nice_match = configuration_table[s->level].nice_length; +- s->max_chain_length = configuration_table[s->level].max_chain; +- +- s->strstart = 0; +- s->block_start = 0L; +- s->lookahead = 0; +- s->insert = 0; +- s->match_length = s->prev_length = MIN_MATCH-1; +- s->match_available = 0; +- s->ins_h = 0; +-#ifndef FASTEST +-#ifdef ASMV +- match_init(); /* initialize the asm code */ +-#endif +-#endif +-} +- + #ifndef FASTEST + /* =========================================================================== + * Set match_start to the longest match starting at the given string and +@@ -1269,14 +1345,7 @@ local void lm_init (s) + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +-#ifndef ASMV +-/* For 80x86 and 680x0, an optimized version will be provided in match.asm or +- * match.S. The code will be functionally equivalent. +- */ +-local uInt longest_match(s, cur_match) +- deflate_state *s; +- IPos cur_match; /* current match */ +-{ ++local uInt longest_match(deflate_state *s, IPos cur_match) { + unsigned chain_length = s->max_chain_length;/* max hash chain length */ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ +@@ -1297,10 +1366,10 @@ local uInt longest_match(s, cur_match) + */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; + register ush scan_start = *(ushf*)scan; +- register ush scan_end = *(ushf*)(scan+best_len-1); ++ register ush scan_end = *(ushf*)(scan + best_len - 1); + #else + register Bytef *strend = s->window + s->strstart + MAX_MATCH; +- register Byte scan_end1 = scan[best_len-1]; ++ register Byte scan_end1 = scan[best_len - 1]; + register Byte scan_end = scan[best_len]; + #endif + +@@ -1318,7 +1387,8 @@ local uInt longest_match(s, cur_match) + */ + if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead; + +- Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); ++ Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, ++ "need lookahead"); + + do { + Assert(cur_match < s->strstart, "no future"); +@@ -1336,43 +1406,44 @@ local uInt longest_match(s, cur_match) + /* This code assumes sizeof(unsigned short) == 2. Do not use + * UNALIGNED_OK if your compiler uses a different size. + */ +- if (*(ushf*)(match+best_len-1) != scan_end || ++ if (*(ushf*)(match + best_len - 1) != scan_end || + *(ushf*)match != scan_start) continue; + + /* It is not necessary to compare scan[2] and match[2] since they are + * always equal when the other bytes match, given that the hash keys + * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at +- * strstart+3, +5, ... up to strstart+257. We check for insufficient ++ * strstart + 3, + 5, up to strstart + 257. We check for insufficient + * lookahead only every 4th comparison; the 128th check will be made +- * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is ++ * at strstart + 257. If MAX_MATCH-2 is not a multiple of 8, it is + * necessary to put more guard bytes at the end of the window, or + * to check more often for insufficient lookahead. + */ + Assert(scan[2] == match[2], "scan[2]?"); + scan++, match++; + do { +- } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && +- *(ushf*)(scan+=2) == *(ushf*)(match+=2) && +- *(ushf*)(scan+=2) == *(ushf*)(match+=2) && +- *(ushf*)(scan+=2) == *(ushf*)(match+=2) && ++ } while (*(ushf*)(scan += 2) == *(ushf*)(match += 2) && ++ *(ushf*)(scan += 2) == *(ushf*)(match += 2) && ++ *(ushf*)(scan += 2) == *(ushf*)(match += 2) && ++ *(ushf*)(scan += 2) == *(ushf*)(match += 2) && + scan < strend); + /* The funny "do {}" generates better code on most compilers */ + +- /* Here, scan <= window+strstart+257 */ +- Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); ++ /* Here, scan <= window + strstart + 257 */ ++ Assert(scan <= s->window + (unsigned)(s->window_size - 1), ++ "wild scan"); + if (*scan == *match) scan++; + +- len = (MAX_MATCH - 1) - (int)(strend-scan); ++ len = (MAX_MATCH - 1) - (int)(strend - scan); + scan = strend - (MAX_MATCH-1); + + #else /* UNALIGNED_OK */ + +- if (match[best_len] != scan_end || +- match[best_len-1] != scan_end1 || +- *match != *scan || +- *++match != scan[1]) continue; ++ if (match[best_len] != scan_end || ++ match[best_len - 1] != scan_end1 || ++ *match != *scan || ++ *++match != scan[1]) continue; + +- /* The check at best_len-1 can be removed because it will be made ++ /* The check at best_len - 1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that +@@ -1382,7 +1453,7 @@ local uInt longest_match(s, cur_match) + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; +- * the 256th check will be made at strstart+258. ++ * the 256th check will be made at strstart + 258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && +@@ -1391,7 +1462,8 @@ local uInt longest_match(s, cur_match) + *++scan == *++match && *++scan == *++match && + scan < strend); + +- Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); ++ Assert(scan <= s->window + (unsigned)(s->window_size - 1), ++ "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + scan = strend - MAX_MATCH; +@@ -1403,9 +1475,9 @@ local uInt longest_match(s, cur_match) + best_len = len; + if (len >= nice_match) break; + #ifdef UNALIGNED_OK +- scan_end = *(ushf*)(scan+best_len-1); ++ scan_end = *(ushf*)(scan + best_len - 1); + #else +- scan_end1 = scan[best_len-1]; ++ scan_end1 = scan[best_len - 1]; + scan_end = scan[best_len]; + #endif + } +@@ -1415,17 +1487,13 @@ local uInt longest_match(s, cur_match) + if ((uInt)best_len <= s->lookahead) return (uInt)best_len; + return s->lookahead; + } +-#endif /* ASMV */ + + #else /* FASTEST */ + + /* --------------------------------------------------------------------------- + * Optimized version for FASTEST only + */ +-local uInt longest_match(s, cur_match) +- deflate_state *s; +- IPos cur_match; /* current match */ +-{ ++local uInt longest_match(deflate_state *s, IPos cur_match) { + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ +@@ -1436,7 +1504,8 @@ local uInt longest_match(s, cur_match) + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + +- Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); ++ Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, ++ "need lookahead"); + + Assert(cur_match < s->strstart, "no future"); + +@@ -1446,7 +1515,7 @@ local uInt longest_match(s, cur_match) + */ + if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; + +- /* The check at best_len-1 can be removed because it will be made ++ /* The check at best_len - 1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that +@@ -1456,7 +1525,7 @@ local uInt longest_match(s, cur_match) + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; +- * the 256th check will be made at strstart+258. ++ * the 256th check will be made at strstart + 258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && +@@ -1465,7 +1534,7 @@ local uInt longest_match(s, cur_match) + *++scan == *++match && *++scan == *++match && + scan < strend); + +- Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); ++ Assert(scan <= s->window + (unsigned)(s->window_size - 1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + +@@ -1485,23 +1554,27 @@ local uInt longest_match(s, cur_match) + /* =========================================================================== + * Check that the match at match_start is indeed a match. + */ +-local void check_match(s, start, match, length) +- deflate_state *s; +- IPos start, match; +- int length; +-{ ++local void check_match(deflate_state *s, IPos start, IPos match, int length) { + /* check that the match is indeed a match */ +- if (zmemcmp(s->window + match, +- s->window + start, length) != EQUAL) { +- fprintf(stderr, " start %u, match %u, length %d\n", +- start, match, length); ++ Bytef *back = s->window + (int)match, *here = s->window + start; ++ IPos len = length; ++ if (match == (IPos)-1) { ++ /* match starts one byte before the current window -- just compare the ++ subsequent length-1 bytes */ ++ back++; ++ here++; ++ len--; ++ } ++ if (zmemcmp(back, here, len) != EQUAL) { ++ fprintf(stderr, " start %u, match %d, length %d\n", ++ start, (int)match, length); + do { +- fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); +- } while (--length != 0); ++ fprintf(stderr, "(%02x %02x)", *back++, *here++); ++ } while (--len != 0); + z_error("invalid match"); + } + if (z_verbose > 1) { +- fprintf(stderr,"\\[%d,%d]", start-match, length); ++ fprintf(stderr,"\\[%d,%d]", start - match, length); + do { putc(s->window[start++], stderr); } while (--length != 0); + } + } +@@ -1509,137 +1582,6 @@ local void check_match(s, start, match, length) + # define check_match(s, start, match, length) + #endif /* ZLIB_DEBUG */ + +-/* =========================================================================== +- * Fill the window when the lookahead becomes insufficient. +- * Updates strstart and lookahead. +- * +- * IN assertion: lookahead < MIN_LOOKAHEAD +- * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD +- * At least one byte has been read, or avail_in == 0; reads are +- * performed for at least two bytes (required for the zip translate_eol +- * option -- not supported here). +- */ +-local void fill_window(s) +- deflate_state *s; +-{ +- unsigned n; +- unsigned more; /* Amount of free space at the end of the window. */ +- uInt wsize = s->w_size; +- +- Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); +- +- do { +- more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); +- +- /* Deal with !@#$% 64K limit: */ +- if (sizeof(int) <= 2) { +- if (more == 0 && s->strstart == 0 && s->lookahead == 0) { +- more = wsize; +- +- } else if (more == (unsigned)(-1)) { +- /* Very unlikely, but possible on 16 bit machine if +- * strstart == 0 && lookahead == 1 (input done a byte at time) +- */ +- more--; +- } +- } +- +- /* If the window is almost full and there is insufficient lookahead, +- * move the upper half to the lower one to make room in the upper half. +- */ +- if (s->strstart >= wsize+MAX_DIST(s)) { +- +- zmemcpy(s->window, s->window+wsize, (unsigned)wsize - more); +- s->match_start -= wsize; +- s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ +- s->block_start -= (long) wsize; +- if (s->insert > s->strstart) +- s->insert = s->strstart; +- slide_hash(s); +- more += wsize; +- } +- if (s->strm->avail_in == 0) break; +- +- /* If there was no sliding: +- * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && +- * more == window_size - lookahead - strstart +- * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) +- * => more >= window_size - 2*WSIZE + 2 +- * In the BIG_MEM or MMAP case (not yet supported), +- * window_size == input_size + MIN_LOOKAHEAD && +- * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. +- * Otherwise, window_size == 2*WSIZE so more >= 2. +- * If there was sliding, more >= WSIZE. So in all cases, more >= 2. +- */ +- Assert(more >= 2, "more < 2"); +- +- n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); +- s->lookahead += n; +- +- /* Initialize the hash value now that we have some input: */ +- if (s->lookahead + s->insert >= MIN_MATCH) { +- uInt str = s->strstart - s->insert; +- s->ins_h = s->window[str]; +- UPDATE_HASH(s, s->ins_h, s->window[str + 1]); +-#if MIN_MATCH != 3 +- Call UPDATE_HASH() MIN_MATCH-3 more times +-#endif +- while (s->insert) { +- UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +-#ifndef FASTEST +- s->prev[str & s->w_mask] = s->head[s->ins_h]; +-#endif +- s->head[s->ins_h] = (Pos)str; +- str++; +- s->insert--; +- if (s->lookahead + s->insert < MIN_MATCH) +- break; +- } +- } +- /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, +- * but this is not important since only literal bytes will be emitted. +- */ +- +- } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); +- +- /* If the WIN_INIT bytes after the end of the current data have never been +- * written, then zero those bytes in order to avoid memory check reports of +- * the use of uninitialized (or uninitialised as Julian writes) bytes by +- * the longest match routines. Update the high water mark for the next +- * time through here. WIN_INIT is set to MAX_MATCH since the longest match +- * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. +- */ +- if (s->high_water < s->window_size) { +- ulg curr = s->strstart + (ulg)(s->lookahead); +- ulg init; +- +- if (s->high_water < curr) { +- /* Previous high water mark below current data -- zero WIN_INIT +- * bytes or up to end of window, whichever is less. +- */ +- init = s->window_size - curr; +- if (init > WIN_INIT) +- init = WIN_INIT; +- zmemzero(s->window + curr, (unsigned)init); +- s->high_water = curr + init; +- } +- else if (s->high_water < (ulg)curr + WIN_INIT) { +- /* High water mark at or above current data, but below current data +- * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +- * to end of window, whichever is less. +- */ +- init = (ulg)curr + WIN_INIT - s->high_water; +- if (init > s->window_size - s->high_water) +- init = s->window_size - s->high_water; +- zmemzero(s->window + s->high_water, (unsigned)init); +- s->high_water += init; +- } +- } +- +- Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +- "not enough room for search"); +-} +- + /* =========================================================================== + * Flush the current block, with given end-of-file flag. + * IN assertion: strstart is set to the end of the current match. +@@ -1680,12 +1622,9 @@ local void fill_window(s) + * + * deflate_stored() is written to minimize the number of times an input byte is + * copied. It is most efficient with large input and output buffers, which +- * maximizes the opportunites to have a single copy from next_in to next_out. ++ * maximizes the opportunities to have a single copy from next_in to next_out. + */ +-local block_state deflate_stored(s, flush) +- deflate_state *s; +- int flush; +-{ ++local block_state deflate_stored(deflate_state *s, int flush) { + /* Smallest worthy block size when not flushing or finishing. By default + * this is 32K. This can be as small as 507 bytes for memLevel == 1. For + * large input and output buffers, the stored block size will be larger. +@@ -1869,10 +1808,7 @@ local block_state deflate_stored(s, flush) + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +-local block_state deflate_fast(s, flush) +- deflate_state *s; +- int flush; +-{ ++local block_state deflate_fast(deflate_state *s, int flush) { + IPos hash_head; /* head of the hash chain */ + int bflush; /* set if current block must be flushed */ + +@@ -1890,7 +1826,7 @@ local block_state deflate_fast(s, flush) + if (s->lookahead == 0) break; /* flush the current block */ + } + +- /* Insert the string window[strstart .. strstart+2] in the ++ /* Insert the string window[strstart .. strstart + 2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; +@@ -1938,7 +1874,7 @@ local block_state deflate_fast(s, flush) + s->strstart += s->match_length; + s->match_length = 0; + s->ins_h = s->window[s->strstart]; +- UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); ++ UPDATE_HASH(s, s->ins_h, s->window[s->strstart + 1]); + #if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times + #endif +@@ -1949,7 +1885,7 @@ local block_state deflate_fast(s, flush) + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); +- _tr_tally_lit (s, s->window[s->strstart], bflush); ++ _tr_tally_lit(s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } +@@ -1971,10 +1907,7 @@ local block_state deflate_fast(s, flush) + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +-local block_state deflate_slow(s, flush) +- deflate_state *s; +- int flush; +-{ ++local block_state deflate_slow(deflate_state *s, int flush) { + IPos hash_head; /* head of hash chain */ + int bflush; /* set if current block must be flushed */ + +@@ -1993,7 +1926,7 @@ local block_state deflate_slow(s, flush) + if (s->lookahead == 0) break; /* flush the current block */ + } + +- /* Insert the string window[strstart .. strstart+2] in the ++ /* Insert the string window[strstart .. strstart + 2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; +@@ -2035,17 +1968,17 @@ local block_state deflate_slow(s, flush) + uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + +- check_match(s, s->strstart-1, s->prev_match, s->prev_length); ++ check_match(s, s->strstart - 1, s->prev_match, s->prev_length); + +- _tr_tally_dist(s, s->strstart -1 - s->prev_match, ++ _tr_tally_dist(s, s->strstart - 1 - s->prev_match, + s->prev_length - MIN_MATCH, bflush); + + /* Insert in hash table all strings up to the end of the match. +- * strstart-1 and strstart are already inserted. If there is not ++ * strstart - 1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ +- s->lookahead -= s->prev_length-1; ++ s->lookahead -= s->prev_length - 1; + s->prev_length -= 2; + do { + if (++s->strstart <= max_insert) { +@@ -2063,8 +1996,8 @@ local block_state deflate_slow(s, flush) + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ +- Tracevv((stderr,"%c", s->window[s->strstart-1])); +- _tr_tally_lit(s, s->window[s->strstart-1], bflush); ++ Tracevv((stderr,"%c", s->window[s->strstart - 1])); ++ _tr_tally_lit(s, s->window[s->strstart - 1], bflush); + if (bflush) { + FLUSH_BLOCK_ONLY(s, 0); + } +@@ -2082,8 +2015,8 @@ local block_state deflate_slow(s, flush) + } + Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s->match_available) { +- Tracevv((stderr,"%c", s->window[s->strstart-1])); +- _tr_tally_lit(s, s->window[s->strstart-1], bflush); ++ Tracevv((stderr,"%c", s->window[s->strstart - 1])); ++ _tr_tally_lit(s, s->window[s->strstart - 1], bflush); + s->match_available = 0; + } + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; +@@ -2102,10 +2035,7 @@ local block_state deflate_slow(s, flush) + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +-local block_state deflate_rle(s, flush) +- deflate_state *s; +- int flush; +-{ ++local block_state deflate_rle(deflate_state *s, int flush) { + int bflush; /* set if current block must be flushed */ + uInt prev; /* byte at distance one to match */ + Bytef *scan, *strend; /* scan goes up to strend for length of run */ +@@ -2140,7 +2070,8 @@ local block_state deflate_rle(s, flush) + if (s->match_length > s->lookahead) + s->match_length = s->lookahead; + } +- Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); ++ Assert(scan <= s->window + (uInt)(s->window_size - 1), ++ "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ +@@ -2155,7 +2086,7 @@ local block_state deflate_rle(s, flush) + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); +- _tr_tally_lit (s, s->window[s->strstart], bflush); ++ _tr_tally_lit(s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } +@@ -2175,10 +2106,7 @@ local block_state deflate_rle(s, flush) + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +-local block_state deflate_huff(s, flush) +- deflate_state *s; +- int flush; +-{ ++local block_state deflate_huff(deflate_state *s, int flush) { + int bflush; /* set if current block must be flushed */ + + for (;;) { +@@ -2195,7 +2123,7 @@ local block_state deflate_huff(s, flush) + /* Output a literal byte */ + s->match_length = 0; + Tracevv((stderr,"%c", s->window[s->strstart])); +- _tr_tally_lit (s, s->window[s->strstart], bflush); ++ _tr_tally_lit(s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + if (bflush) FLUSH_BLOCK(s, 0); +diff --git a/src/zlib/deflate.h b/src/zlib/deflate.h +index 17c226113..300c6ada6 100644 +--- a/src/zlib/deflate.h ++++ b/src/zlib/deflate.h +@@ -1,5 +1,5 @@ + /* deflate.h -- internal compression state +- * Copyright (C) 1995-2018 Jean-loup Gailly ++ * Copyright (C) 1995-2024 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +@@ -23,6 +23,10 @@ + # define GZIP + #endif + ++/* define LIT_MEM to slightly increase the speed of deflate (order 1% to 2%) at ++ the cost of a larger memory footprint */ ++/* #define LIT_MEM */ ++ + /* =========================================================================== + * Internal compression state. + */ +@@ -217,7 +221,14 @@ typedef struct internal_state { + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + ++#ifdef LIT_MEM ++# define LIT_BUFS 5 ++ ushf *d_buf; /* buffer for distances */ ++ uchf *l_buf; /* buffer for literals/lengths */ ++#else ++# define LIT_BUFS 4 + uchf *sym_buf; /* buffer for distances and literals/lengths */ ++#endif + + uInt lit_bufsize; + /* Size of match buffer for literals/lengths. There are 4 reasons for +@@ -239,7 +250,7 @@ typedef struct internal_state { + * - I can't count above 4 + */ + +- uInt sym_next; /* running index in sym_buf */ ++ uInt sym_next; /* running index in symbol buffer */ + uInt sym_end; /* symbol table full when sym_next reaches this */ + + ulg opt_len; /* bit length of current block with optimal trees */ +@@ -291,14 +302,14 @@ typedef struct internal_state { + memory checker errors from longest match routines */ + + /* in trees.c */ +-void ZLIB_INTERNAL _tr_init OF((deflate_state *s)); +-int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); +-void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf, +- ulg stored_len, int last)); +-void ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s)); +-void ZLIB_INTERNAL _tr_align OF((deflate_state *s)); +-void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, +- ulg stored_len, int last)); ++void ZLIB_INTERNAL _tr_init(deflate_state *s); ++int ZLIB_INTERNAL _tr_tally(deflate_state *s, unsigned dist, unsigned lc); ++void ZLIB_INTERNAL _tr_flush_block(deflate_state *s, charf *buf, ++ ulg stored_len, int last); ++void ZLIB_INTERNAL _tr_flush_bits(deflate_state *s); ++void ZLIB_INTERNAL _tr_align(deflate_state *s); ++void ZLIB_INTERNAL _tr_stored_block(deflate_state *s, charf *buf, ++ ulg stored_len, int last); + + #define d_code(dist) \ + ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) +@@ -318,6 +329,25 @@ void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, + extern const uch ZLIB_INTERNAL _dist_code[]; + #endif + ++#ifdef LIT_MEM ++# define _tr_tally_lit(s, c, flush) \ ++ { uch cc = (c); \ ++ s->d_buf[s->sym_next] = 0; \ ++ s->l_buf[s->sym_next++] = cc; \ ++ s->dyn_ltree[cc].Freq++; \ ++ flush = (s->sym_next == s->sym_end); \ ++ } ++# define _tr_tally_dist(s, distance, length, flush) \ ++ { uch len = (uch)(length); \ ++ ush dist = (ush)(distance); \ ++ s->d_buf[s->sym_next] = dist; \ ++ s->l_buf[s->sym_next++] = len; \ ++ dist--; \ ++ s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ ++ s->dyn_dtree[d_code(dist)].Freq++; \ ++ flush = (s->sym_next == s->sym_end); \ ++ } ++#else + # define _tr_tally_lit(s, c, flush) \ + { uch cc = (c); \ + s->sym_buf[s->sym_next++] = 0; \ +@@ -329,14 +359,15 @@ void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, + # define _tr_tally_dist(s, distance, length, flush) \ + { uch len = (uch)(length); \ + ush dist = (ush)(distance); \ +- s->sym_buf[s->sym_next++] = dist; \ +- s->sym_buf[s->sym_next++] = dist >> 8; \ ++ s->sym_buf[s->sym_next++] = (uch)dist; \ ++ s->sym_buf[s->sym_next++] = (uch)(dist >> 8); \ + s->sym_buf[s->sym_next++] = len; \ + dist--; \ + s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ + s->dyn_dtree[d_code(dist)].Freq++; \ + flush = (s->sym_next == s->sym_end); \ + } ++#endif + #else + # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) + # define _tr_tally_dist(s, distance, length, flush) \ +diff --git a/src/zlib/gzclose.c b/src/zlib/gzclose.c +index caeb99a31..48d6a86f0 100644 +--- a/src/zlib/gzclose.c ++++ b/src/zlib/gzclose.c +@@ -8,9 +8,7 @@ + /* gzclose() is in a separate file so that it is linked in only if it is used. + That way the other gzclose functions can be used instead to avoid linking in + unneeded compression or decompression routines. */ +-int ZEXPORT gzclose(file) +- gzFile file; +-{ ++int ZEXPORT gzclose(gzFile file) { + #ifndef NO_GZCOMPRESS + gz_statep state; + +diff --git a/src/zlib/gzguts.h b/src/zlib/gzguts.h +index 57faf3716..eba72085b 100644 +--- a/src/zlib/gzguts.h ++++ b/src/zlib/gzguts.h +@@ -1,5 +1,5 @@ + /* gzguts.h -- zlib internal header definitions for gz* operations +- * Copyright (C) 2004-2019 Mark Adler ++ * Copyright (C) 2004-2024 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +@@ -7,9 +7,8 @@ + # ifndef _LARGEFILE_SOURCE + # define _LARGEFILE_SOURCE 1 + # endif +-# ifdef _FILE_OFFSET_BITS +-# undef _FILE_OFFSET_BITS +-# endif ++# undef _FILE_OFFSET_BITS ++# undef _TIME_BITS + #endif + + #ifdef HAVE_HIDDEN +@@ -119,8 +118,8 @@ + + /* gz* functions always use library allocation functions */ + #ifndef STDC +- extern voidp malloc OF((uInt size)); +- extern void free OF((voidpf ptr)); ++ extern voidp malloc(uInt size); ++ extern void free(voidpf ptr); + #endif + + /* get errno and strerror definition */ +@@ -138,10 +137,10 @@ + + /* provide prototypes for these when building zlib without LFS */ + #if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0 +- ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); +- ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); +- ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); +- ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); ++ ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *); ++ ZEXTERN z_off64_t ZEXPORT gzseek64(gzFile, z_off64_t, int); ++ ZEXTERN z_off64_t ZEXPORT gztell64(gzFile); ++ ZEXTERN z_off64_t ZEXPORT gzoffset64(gzFile); + #endif + + /* default memLevel */ +@@ -203,17 +202,13 @@ typedef struct { + typedef gz_state FAR *gz_statep; + + /* shared functions */ +-void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *)); ++void ZLIB_INTERNAL gz_error(gz_statep, int, const char *); + #if defined UNDER_CE +-char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error)); ++char ZLIB_INTERNAL *gz_strwinerror(DWORD error); + #endif + + /* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t + value -- needed when comparing unsigned to z_off64_t, which is signed + (possible z_off64_t types off_t, off64_t, and long are all signed) */ +-#ifdef INT_MAX +-# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX) +-#else +-unsigned ZLIB_INTERNAL gz_intmax OF((void)); +-# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax()) +-#endif ++unsigned ZLIB_INTERNAL gz_intmax(void); ++#define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax()) +diff --git a/src/zlib/gzlib.c b/src/zlib/gzlib.c +index dddaf2687..983153cc8 100644 +--- a/src/zlib/gzlib.c ++++ b/src/zlib/gzlib.c +@@ -1,5 +1,5 @@ + /* gzlib.c -- zlib functions common to reading and writing gzip files +- * Copyright (C) 2004-2019 Mark Adler ++ * Copyright (C) 2004-2024 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +@@ -15,10 +15,6 @@ + #endif + #endif + +-/* Local functions */ +-local void gz_reset OF((gz_statep)); +-local gzFile gz_open OF((const void *, int, const char *)); +- + #if defined UNDER_CE + + /* Map the Windows error number in ERROR to a locale-dependent error message +@@ -30,9 +26,7 @@ local gzFile gz_open OF((const void *, int, const char *)); + + The gz_strwinerror function does not change the current setting of + GetLastError. */ +-char ZLIB_INTERNAL *gz_strwinerror (error) +- DWORD error; +-{ ++char ZLIB_INTERNAL *gz_strwinerror(DWORD error) { + static char buf[1024]; + + wchar_t *msgbuf; +@@ -72,9 +66,7 @@ char ZLIB_INTERNAL *gz_strwinerror (error) + #endif /* UNDER_CE */ + + /* Reset gzip file state */ +-local void gz_reset(state) +- gz_statep state; +-{ ++local void gz_reset(gz_statep state) { + state->x.have = 0; /* no output data available */ + if (state->mode == GZ_READ) { /* for reading ... */ + state->eof = 0; /* not at end of file */ +@@ -90,11 +82,7 @@ local void gz_reset(state) + } + + /* Open a gzip file either by name or file descriptor. */ +-local gzFile gz_open(path, fd, mode) +- const void *path; +- int fd; +- const char *mode; +-{ ++local gzFile gz_open(const void *path, int fd, const char *mode) { + gz_statep state; + z_size_t len; + int oflag; +@@ -269,26 +257,17 @@ local gzFile gz_open(path, fd, mode) + } + + /* -- see zlib.h -- */ +-gzFile ZEXPORT gzopen(path, mode) +- const char *path; +- const char *mode; +-{ ++gzFile ZEXPORT gzopen(const char *path, const char *mode) { + return gz_open(path, -1, mode); + } + + /* -- see zlib.h -- */ +-gzFile ZEXPORT gzopen64(path, mode) +- const char *path; +- const char *mode; +-{ ++gzFile ZEXPORT gzopen64(const char *path, const char *mode) { + return gz_open(path, -1, mode); + } + + /* -- see zlib.h -- */ +-gzFile ZEXPORT gzdopen(fd, mode) +- int fd; +- const char *mode; +-{ ++gzFile ZEXPORT gzdopen(int fd, const char *mode) { + char *path; /* identifier for error messages */ + gzFile gz; + +@@ -306,19 +285,13 @@ gzFile ZEXPORT gzdopen(fd, mode) + + /* -- see zlib.h -- */ + #ifdef WIDECHAR +-gzFile ZEXPORT gzopen_w(path, mode) +- const wchar_t *path; +- const char *mode; +-{ ++gzFile ZEXPORT gzopen_w(const wchar_t *path, const char *mode) { + return gz_open(path, -2, mode); + } + #endif + + /* -- see zlib.h -- */ +-int ZEXPORT gzbuffer(file, size) +- gzFile file; +- unsigned size; +-{ ++int ZEXPORT gzbuffer(gzFile file, unsigned size) { + gz_statep state; + + /* get internal structure and check integrity */ +@@ -335,16 +308,14 @@ int ZEXPORT gzbuffer(file, size) + /* check and set requested size */ + if ((size << 1) < size) + return -1; /* need to be able to double it */ +- if (size < 2) +- size = 2; /* need two bytes to check magic header */ ++ if (size < 8) ++ size = 8; /* needed to behave well with flushing */ + state->want = size; + return 0; + } + + /* -- see zlib.h -- */ +-int ZEXPORT gzrewind(file) +- gzFile file; +-{ ++int ZEXPORT gzrewind(gzFile file) { + gz_statep state; + + /* get internal structure */ +@@ -365,11 +336,7 @@ int ZEXPORT gzrewind(file) + } + + /* -- see zlib.h -- */ +-z_off64_t ZEXPORT gzseek64(file, offset, whence) +- gzFile file; +- z_off64_t offset; +- int whence; +-{ ++z_off64_t ZEXPORT gzseek64(gzFile file, z_off64_t offset, int whence) { + unsigned n; + z_off64_t ret; + gz_statep state; +@@ -442,11 +409,7 @@ z_off64_t ZEXPORT gzseek64(file, offset, whence) + } + + /* -- see zlib.h -- */ +-z_off_t ZEXPORT gzseek(file, offset, whence) +- gzFile file; +- z_off_t offset; +- int whence; +-{ ++z_off_t ZEXPORT gzseek(gzFile file, z_off_t offset, int whence) { + z_off64_t ret; + + ret = gzseek64(file, (z_off64_t)offset, whence); +@@ -454,9 +417,7 @@ z_off_t ZEXPORT gzseek(file, offset, whence) + } + + /* -- see zlib.h -- */ +-z_off64_t ZEXPORT gztell64(file) +- gzFile file; +-{ ++z_off64_t ZEXPORT gztell64(gzFile file) { + gz_statep state; + + /* get internal structure and check integrity */ +@@ -471,9 +432,7 @@ z_off64_t ZEXPORT gztell64(file) + } + + /* -- see zlib.h -- */ +-z_off_t ZEXPORT gztell(file) +- gzFile file; +-{ ++z_off_t ZEXPORT gztell(gzFile file) { + z_off64_t ret; + + ret = gztell64(file); +@@ -481,9 +440,7 @@ z_off_t ZEXPORT gztell(file) + } + + /* -- see zlib.h -- */ +-z_off64_t ZEXPORT gzoffset64(file) +- gzFile file; +-{ ++z_off64_t ZEXPORT gzoffset64(gzFile file) { + z_off64_t offset; + gz_statep state; + +@@ -504,9 +461,7 @@ z_off64_t ZEXPORT gzoffset64(file) + } + + /* -- see zlib.h -- */ +-z_off_t ZEXPORT gzoffset(file) +- gzFile file; +-{ ++z_off_t ZEXPORT gzoffset(gzFile file) { + z_off64_t ret; + + ret = gzoffset64(file); +@@ -514,9 +469,7 @@ z_off_t ZEXPORT gzoffset(file) + } + + /* -- see zlib.h -- */ +-int ZEXPORT gzeof(file) +- gzFile file; +-{ ++int ZEXPORT gzeof(gzFile file) { + gz_statep state; + + /* get internal structure and check integrity */ +@@ -531,10 +484,7 @@ int ZEXPORT gzeof(file) + } + + /* -- see zlib.h -- */ +-const char * ZEXPORT gzerror(file, errnum) +- gzFile file; +- int *errnum; +-{ ++const char * ZEXPORT gzerror(gzFile file, int *errnum) { + gz_statep state; + + /* get internal structure and check integrity */ +@@ -552,9 +502,7 @@ const char * ZEXPORT gzerror(file, errnum) + } + + /* -- see zlib.h -- */ +-void ZEXPORT gzclearerr(file) +- gzFile file; +-{ ++void ZEXPORT gzclearerr(gzFile file) { + gz_statep state; + + /* get internal structure and check integrity */ +@@ -578,11 +526,7 @@ void ZEXPORT gzclearerr(file) + memory). Simply save the error message as a static string. If there is an + allocation failure constructing the error message, then convert the error to + out of memory. */ +-void ZLIB_INTERNAL gz_error(state, err, msg) +- gz_statep state; +- int err; +- const char *msg; +-{ ++void ZLIB_INTERNAL gz_error(gz_statep state, int err, const char *msg) { + /* free previously allocated message and clear */ + if (state->msg != NULL) { + if (state->err != Z_MEM_ERROR) +@@ -619,21 +563,20 @@ void ZLIB_INTERNAL gz_error(state, err, msg) + #endif + } + +-#ifndef INT_MAX + /* portably return maximum value for an int (when limits.h presumed not + available) -- we need to do this to cover cases where 2's complement not + used, since C standard permits 1's complement and sign-bit representations, + otherwise we could just use ((unsigned)-1) >> 1 */ +-unsigned ZLIB_INTERNAL gz_intmax() +-{ +- unsigned p, q; +- +- p = 1; ++unsigned ZLIB_INTERNAL gz_intmax(void) { ++#ifdef INT_MAX ++ return INT_MAX; ++#else ++ unsigned p = 1, q; + do { + q = p; + p <<= 1; + p++; + } while (p > q); + return q >> 1; +-} + #endif ++} +diff --git a/src/zlib/gzread.c b/src/zlib/gzread.c +index 884c9bfe4..4168cbc88 100644 +--- a/src/zlib/gzread.c ++++ b/src/zlib/gzread.c +@@ -5,25 +5,12 @@ + + #include "gzguts.h" + +-/* Local functions */ +-local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *)); +-local int gz_avail OF((gz_statep)); +-local int gz_look OF((gz_statep)); +-local int gz_decomp OF((gz_statep)); +-local int gz_fetch OF((gz_statep)); +-local int gz_skip OF((gz_statep, z_off64_t)); +-local z_size_t gz_read OF((gz_statep, voidp, z_size_t)); +- + /* Use read() to load a buffer -- return -1 on error, otherwise 0. Read from + state->fd, and update state->eof, state->err, and state->msg as appropriate. + This function needs to loop on read(), since read() is not guaranteed to + read the number of bytes requested, depending on the type of descriptor. */ +-local int gz_load(state, buf, len, have) +- gz_statep state; +- unsigned char *buf; +- unsigned len; +- unsigned *have; +-{ ++local int gz_load(gz_statep state, unsigned char *buf, unsigned len, ++ unsigned *have) { + int ret; + unsigned get, max = ((unsigned)-1 >> 2) + 1; + +@@ -53,9 +40,7 @@ local int gz_load(state, buf, len, have) + If strm->avail_in != 0, then the current data is moved to the beginning of + the input buffer, and then the remainder of the buffer is loaded with the + available data from the input file. */ +-local int gz_avail(state) +- gz_statep state; +-{ ++local int gz_avail(gz_statep state) { + unsigned got; + z_streamp strm = &(state->strm); + +@@ -88,9 +73,7 @@ local int gz_avail(state) + case, all further file reads will be directly to either the output buffer or + a user buffer. If decompressing, the inflate state will be initialized. + gz_look() will return 0 on success or -1 on failure. */ +-local int gz_look(state) +- gz_statep state; +-{ ++local int gz_look(gz_statep state) { + z_streamp strm = &(state->strm); + + /* allocate read buffers and inflate memory */ +@@ -157,11 +140,9 @@ local int gz_look(state) + the output buffer is larger than the input buffer, which also assures + space for gzungetc() */ + state->x.next = state->out; +- if (strm->avail_in) { +- memcpy(state->x.next, strm->next_in, strm->avail_in); +- state->x.have = strm->avail_in; +- strm->avail_in = 0; +- } ++ memcpy(state->x.next, strm->next_in, strm->avail_in); ++ state->x.have = strm->avail_in; ++ strm->avail_in = 0; + state->how = COPY; + state->direct = 1; + return 0; +@@ -172,9 +153,7 @@ local int gz_look(state) + data. If the gzip stream completes, state->how is reset to LOOK to look for + the next gzip stream or raw data, once state->x.have is depleted. Returns 0 + on success, -1 on failure. */ +-local int gz_decomp(state) +- gz_statep state; +-{ ++local int gz_decomp(gz_statep state) { + int ret = Z_OK; + unsigned had; + z_streamp strm = &(state->strm); +@@ -226,9 +205,7 @@ local int gz_decomp(state) + looked for to determine whether to copy or decompress. Returns -1 on error, + otherwise 0. gz_fetch() will leave state->how as COPY or GZIP unless the + end of the input file has been reached and all data has been processed. */ +-local int gz_fetch(state) +- gz_statep state; +-{ ++local int gz_fetch(gz_statep state) { + z_streamp strm = &(state->strm); + + do { +@@ -256,10 +233,7 @@ local int gz_fetch(state) + } + + /* Skip len uncompressed bytes of output. Return -1 on error, 0 on success. */ +-local int gz_skip(state, len) +- gz_statep state; +- z_off64_t len; +-{ ++local int gz_skip(gz_statep state, z_off64_t len) { + unsigned n; + + /* skip over len bytes or reach end-of-file, whichever comes first */ +@@ -291,11 +265,7 @@ local int gz_skip(state, len) + input. Return the number of bytes read. If zero is returned, either the + end of file was reached, or there was an error. state->err must be + consulted in that case to determine which. */ +-local z_size_t gz_read(state, buf, len) +- gz_statep state; +- voidp buf; +- z_size_t len; +-{ ++local z_size_t gz_read(gz_statep state, voidp buf, z_size_t len) { + z_size_t got; + unsigned n; + +@@ -372,11 +342,7 @@ local z_size_t gz_read(state, buf, len) + } + + /* -- see zlib.h -- */ +-int ZEXPORT gzread(file, buf, len) +- gzFile file; +- voidp buf; +- unsigned len; +-{ ++int ZEXPORT gzread(gzFile file, voidp buf, unsigned len) { + gz_statep state; + + /* get internal structure */ +@@ -408,12 +374,7 @@ int ZEXPORT gzread(file, buf, len) + } + + /* -- see zlib.h -- */ +-z_size_t ZEXPORT gzfread(buf, size, nitems, file) +- voidp buf; +- z_size_t size; +- z_size_t nitems; +- gzFile file; +-{ ++z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems, gzFile file) { + z_size_t len; + gz_statep state; + +@@ -444,9 +405,7 @@ z_size_t ZEXPORT gzfread(buf, size, nitems, file) + #else + # undef gzgetc + #endif +-int ZEXPORT gzgetc(file) +- gzFile file; +-{ ++int ZEXPORT gzgetc(gzFile file) { + unsigned char buf[1]; + gz_statep state; + +@@ -471,17 +430,12 @@ int ZEXPORT gzgetc(file) + return gz_read(state, buf, 1) < 1 ? -1 : buf[0]; + } + +-int ZEXPORT gzgetc_(file) +-gzFile file; +-{ ++int ZEXPORT gzgetc_(gzFile file) { + return gzgetc(file); + } + + /* -- see zlib.h -- */ +-int ZEXPORT gzungetc(c, file) +- int c; +- gzFile file; +-{ ++int ZEXPORT gzungetc(int c, gzFile file) { + gz_statep state; + + /* get internal structure */ +@@ -489,6 +443,10 @@ int ZEXPORT gzungetc(c, file) + return -1; + state = (gz_statep)file; + ++ /* in case this was just opened, set up the input buffer */ ++ if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0) ++ (void)gz_look(state); ++ + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) +@@ -538,11 +496,7 @@ int ZEXPORT gzungetc(c, file) + } + + /* -- see zlib.h -- */ +-char * ZEXPORT gzgets(file, buf, len) +- gzFile file; +- char *buf; +- int len; +-{ ++char * ZEXPORT gzgets(gzFile file, char *buf, int len) { + unsigned left, n; + char *str; + unsigned char *eol; +@@ -602,9 +556,7 @@ char * ZEXPORT gzgets(file, buf, len) + } + + /* -- see zlib.h -- */ +-int ZEXPORT gzdirect(file) +- gzFile file; +-{ ++int ZEXPORT gzdirect(gzFile file) { + gz_statep state; + + /* get internal structure */ +@@ -622,9 +574,7 @@ int ZEXPORT gzdirect(file) + } + + /* -- see zlib.h -- */ +-int ZEXPORT gzclose_r(file) +- gzFile file; +-{ ++int ZEXPORT gzclose_r(gzFile file) { + int ret, err; + gz_statep state; + +diff --git a/src/zlib/gzwrite.c b/src/zlib/gzwrite.c +index a8ffc8f53..435b4621b 100644 +--- a/src/zlib/gzwrite.c ++++ b/src/zlib/gzwrite.c +@@ -5,18 +5,10 @@ + + #include "gzguts.h" + +-/* Local functions */ +-local int gz_init OF((gz_statep)); +-local int gz_comp OF((gz_statep, int)); +-local int gz_zero OF((gz_statep, z_off64_t)); +-local z_size_t gz_write OF((gz_statep, voidpc, z_size_t)); +- + /* Initialize state for writing a gzip file. Mark initialization by setting + state->size to non-zero. Return -1 on a memory allocation failure, or 0 on + success. */ +-local int gz_init(state) +- gz_statep state; +-{ ++local int gz_init(gz_statep state) { + int ret; + z_streamp strm = &(state->strm); + +@@ -70,10 +62,7 @@ local int gz_init(state) + deflate() flush value. If flush is Z_FINISH, then the deflate() state is + reset to start a new gzip stream. If gz->direct is true, then simply write + to the output file without compressing, and ignore flush. */ +-local int gz_comp(state, flush) +- gz_statep state; +- int flush; +-{ ++local int gz_comp(gz_statep state, int flush) { + int ret, writ; + unsigned have, put, max = ((unsigned)-1 >> 2) + 1; + z_streamp strm = &(state->strm); +@@ -151,10 +140,7 @@ local int gz_comp(state, flush) + + /* Compress len zeros to output. Return -1 on a write error or memory + allocation failure by gz_comp(), or 0 on success. */ +-local int gz_zero(state, len) +- gz_statep state; +- z_off64_t len; +-{ ++local int gz_zero(gz_statep state, z_off64_t len) { + int first; + unsigned n; + z_streamp strm = &(state->strm); +@@ -184,11 +170,7 @@ local int gz_zero(state, len) + + /* Write len bytes from buf to file. Return the number of bytes written. If + the returned value is less than len, then there was an error. */ +-local z_size_t gz_write(state, buf, len) +- gz_statep state; +- voidpc buf; +- z_size_t len; +-{ ++local z_size_t gz_write(gz_statep state, voidpc buf, z_size_t len) { + z_size_t put = len; + + /* if len is zero, avoid unnecessary operations */ +@@ -252,11 +234,7 @@ local z_size_t gz_write(state, buf, len) + } + + /* -- see zlib.h -- */ +-int ZEXPORT gzwrite(file, buf, len) +- gzFile file; +- voidpc buf; +- unsigned len; +-{ ++int ZEXPORT gzwrite(gzFile file, voidpc buf, unsigned len) { + gz_statep state; + + /* get internal structure */ +@@ -280,12 +258,8 @@ int ZEXPORT gzwrite(file, buf, len) + } + + /* -- see zlib.h -- */ +-z_size_t ZEXPORT gzfwrite(buf, size, nitems, file) +- voidpc buf; +- z_size_t size; +- z_size_t nitems; +- gzFile file; +-{ ++z_size_t ZEXPORT gzfwrite(voidpc buf, z_size_t size, z_size_t nitems, ++ gzFile file) { + z_size_t len; + gz_statep state; + +@@ -310,10 +284,7 @@ z_size_t ZEXPORT gzfwrite(buf, size, nitems, file) + } + + /* -- see zlib.h -- */ +-int ZEXPORT gzputc(file, c) +- gzFile file; +- int c; +-{ ++int ZEXPORT gzputc(gzFile file, int c) { + unsigned have; + unsigned char buf[1]; + gz_statep state; +@@ -358,10 +329,7 @@ int ZEXPORT gzputc(file, c) + } + + /* -- see zlib.h -- */ +-int ZEXPORT gzputs(file, s) +- gzFile file; +- const char *s; +-{ ++int ZEXPORT gzputs(gzFile file, const char *s) { + z_size_t len, put; + gz_statep state; + +@@ -388,8 +356,7 @@ int ZEXPORT gzputs(file, s) + #include + + /* -- see zlib.h -- */ +-int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) +-{ ++int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) { + int len; + unsigned left; + char *next; +@@ -460,8 +427,7 @@ int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) + return len; + } + +-int ZEXPORTVA gzprintf(gzFile file, const char *format, ...) +-{ ++int ZEXPORTVA gzprintf(gzFile file, const char *format, ...) { + va_list va; + int ret; + +@@ -474,13 +440,10 @@ int ZEXPORTVA gzprintf(gzFile file, const char *format, ...) + #else /* !STDC && !Z_HAVE_STDARG_H */ + + /* -- see zlib.h -- */ +-int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, +- a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) +- gzFile file; +- const char *format; +- int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, +- a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; +-{ ++int ZEXPORTVA gzprintf(gzFile file, const char *format, int a1, int a2, int a3, ++ int a4, int a5, int a6, int a7, int a8, int a9, int a10, ++ int a11, int a12, int a13, int a14, int a15, int a16, ++ int a17, int a18, int a19, int a20) { + unsigned len, left; + char *next; + gz_statep state; +@@ -562,10 +525,7 @@ int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + #endif + + /* -- see zlib.h -- */ +-int ZEXPORT gzflush(file, flush) +- gzFile file; +- int flush; +-{ ++int ZEXPORT gzflush(gzFile file, int flush) { + gz_statep state; + + /* get internal structure */ +@@ -594,11 +554,7 @@ int ZEXPORT gzflush(file, flush) + } + + /* -- see zlib.h -- */ +-int ZEXPORT gzsetparams(file, level, strategy) +- gzFile file; +- int level; +- int strategy; +-{ ++int ZEXPORT gzsetparams(gzFile file, int level, int strategy) { + gz_statep state; + z_streamp strm; + +@@ -609,7 +565,7 @@ int ZEXPORT gzsetparams(file, level, strategy) + strm = &(state->strm); + + /* check that we're writing and that there's no error */ +- if (state->mode != GZ_WRITE || state->err != Z_OK) ++ if (state->mode != GZ_WRITE || state->err != Z_OK || state->direct) + return Z_STREAM_ERROR; + + /* if no change is requested, then do nothing */ +@@ -636,9 +592,7 @@ int ZEXPORT gzsetparams(file, level, strategy) + } + + /* -- see zlib.h -- */ +-int ZEXPORT gzclose_w(file) +- gzFile file; +-{ ++int ZEXPORT gzclose_w(gzFile file) { + int ret = Z_OK; + gz_statep state; + +diff --git a/src/zlib/infback.c b/src/zlib/infback.c +index a390c58e8..e7b25b307 100644 +--- a/src/zlib/infback.c ++++ b/src/zlib/infback.c +@@ -15,9 +15,6 @@ + #include "inflate.h" + #include "inffast.h" + +-/* function prototypes */ +-local void fixedtables OF((struct inflate_state FAR *state)); +- + /* + strm provides memory allocation functions in zalloc and zfree, or + Z_NULL to use the library memory allocation functions. +@@ -25,13 +22,9 @@ local void fixedtables OF((struct inflate_state FAR *state)); + windowBits is in the range 8..15, and window is a user-supplied + window and output buffer that is 2**windowBits bytes. + */ +-int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) +-z_streamp strm; +-int windowBits; +-unsigned char FAR *window; +-const char *version; +-int stream_size; +-{ ++int ZEXPORT inflateBackInit_(z_streamp strm, int windowBits, ++ unsigned char FAR *window, const char *version, ++ int stream_size) { + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || +@@ -66,6 +59,7 @@ int stream_size; + state->window = window; + state->wnext = 0; + state->whave = 0; ++ state->sane = 1; + return Z_OK; + } + +@@ -79,9 +73,7 @@ int stream_size; + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +-local void fixedtables(state) +-struct inflate_state FAR *state; +-{ ++local void fixedtables(struct inflate_state FAR *state) { + #ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; +@@ -247,13 +239,8 @@ struct inflate_state FAR *state; + inflateBack() can also return Z_STREAM_ERROR if the input parameters + are not correct, i.e. strm is Z_NULL or the state was not initialized. + */ +-int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) +-z_streamp strm; +-in_func in; +-void FAR *in_desc; +-out_func out; +-void FAR *out_desc; +-{ ++int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc, ++ out_func out, void FAR *out_desc) { + struct inflate_state FAR *state; + z_const unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ +@@ -605,33 +592,33 @@ void FAR *out_desc; + break; + + case DONE: +- /* inflate stream terminated properly -- write leftover output */ ++ /* inflate stream terminated properly */ + ret = Z_STREAM_END; +- if (left < state->wsize) { +- if (out(out_desc, state->window, state->wsize - left)) +- ret = Z_BUF_ERROR; +- } + goto inf_leave; + + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + +- default: /* can't happen, but makes compilers happy */ ++ default: ++ /* can't happen, but makes compilers happy */ + ret = Z_STREAM_ERROR; + goto inf_leave; + } + +- /* Return unused input */ ++ /* Write leftover output and return unused input */ + inf_leave: ++ if (left < state->wsize) { ++ if (out(out_desc, state->window, state->wsize - left) && ++ ret == Z_STREAM_END) ++ ret = Z_BUF_ERROR; ++ } + strm->next_in = next; + strm->avail_in = have; + return ret; + } + +-int ZEXPORT inflateBackEnd(strm) +-z_streamp strm; +-{ ++int ZEXPORT inflateBackEnd(z_streamp strm) { + if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) + return Z_STREAM_ERROR; + ZFREE(strm, strm->state); +diff --git a/src/zlib/inffast.c b/src/zlib/inffast.c +index 1fec7f363..9354676e7 100644 +--- a/src/zlib/inffast.c ++++ b/src/zlib/inffast.c +@@ -47,10 +47,7 @@ + requires strm->avail_out >= 258 for each loop to avoid checking for + output space. + */ +-void ZLIB_INTERNAL inflate_fast(strm, start) +-z_streamp strm; +-unsigned start; /* inflate()'s starting value for strm->avail_out */ +-{ ++void ZLIB_INTERNAL inflate_fast(z_streamp strm, unsigned start) { + struct inflate_state FAR *state; + z_const unsigned char FAR *in; /* local strm->next_in */ + z_const unsigned char FAR *last; /* have enough input while in < last */ +diff --git a/src/zlib/inffast.h b/src/zlib/inffast.h +index e5c1aa4ca..49c6d156c 100644 +--- a/src/zlib/inffast.h ++++ b/src/zlib/inffast.h +@@ -8,4 +8,4 @@ + subject to change. Applications should only use zlib.h. + */ + +-void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start)); ++void ZLIB_INTERNAL inflate_fast(z_streamp strm, unsigned start); +diff --git a/src/zlib/inflate.c b/src/zlib/inflate.c +index 7be8c6366..94ecff015 100644 +--- a/src/zlib/inflate.c ++++ b/src/zlib/inflate.c +@@ -91,20 +91,7 @@ + # endif + #endif + +-/* function prototypes */ +-local int inflateStateCheck OF((z_streamp strm)); +-local void fixedtables OF((struct inflate_state FAR *state)); +-local int updatewindow OF((z_streamp strm, const unsigned char FAR *end, +- unsigned copy)); +-#ifdef BUILDFIXED +- void makefixed OF((void)); +-#endif +-local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf, +- unsigned len)); +- +-local int inflateStateCheck(strm) +-z_streamp strm; +-{ ++local int inflateStateCheck(z_streamp strm) { + struct inflate_state FAR *state; + if (strm == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) +@@ -116,9 +103,7 @@ z_streamp strm; + return 0; + } + +-int ZEXPORT inflateResetKeep(strm) +-z_streamp strm; +-{ ++int ZEXPORT inflateResetKeep(z_streamp strm) { + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; +@@ -142,9 +127,7 @@ z_streamp strm; + return Z_OK; + } + +-int ZEXPORT inflateReset(strm) +-z_streamp strm; +-{ ++int ZEXPORT inflateReset(z_streamp strm) { + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; +@@ -155,10 +138,7 @@ z_streamp strm; + return inflateResetKeep(strm); + } + +-int ZEXPORT inflateReset2(strm, windowBits) +-z_streamp strm; +-int windowBits; +-{ ++int ZEXPORT inflateReset2(z_streamp strm, int windowBits) { + int wrap; + struct inflate_state FAR *state; + +@@ -168,6 +148,8 @@ int windowBits; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { ++ if (windowBits < -15) ++ return Z_STREAM_ERROR; + wrap = 0; + windowBits = -windowBits; + } +@@ -193,12 +175,8 @@ int windowBits; + return inflateReset(strm); + } + +-int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) +-z_streamp strm; +-int windowBits; +-const char *version; +-int stream_size; +-{ ++int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, ++ const char *version, int stream_size) { + int ret; + struct inflate_state FAR *state; + +@@ -237,22 +215,17 @@ int stream_size; + return ret; + } + +-int ZEXPORT inflateInit_(strm, version, stream_size) +-z_streamp strm; +-const char *version; +-int stream_size; +-{ ++int ZEXPORT inflateInit_(z_streamp strm, const char *version, ++ int stream_size) { + return inflateInit2_(strm, DEF_WBITS, version, stream_size); + } + +-int ZEXPORT inflatePrime(strm, bits, value) +-z_streamp strm; +-int bits; +-int value; +-{ ++int ZEXPORT inflatePrime(z_streamp strm, int bits, int value) { + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; ++ if (bits == 0) ++ return Z_OK; + state = (struct inflate_state FAR *)strm->state; + if (bits < 0) { + state->hold = 0; +@@ -276,9 +249,7 @@ int value; + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +-local void fixedtables(state) +-struct inflate_state FAR *state; +-{ ++local void fixedtables(struct inflate_state FAR *state) { + #ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; +@@ -340,7 +311,7 @@ struct inflate_state FAR *state; + + a.out > inffixed.h + */ +-void makefixed() ++void makefixed(void) + { + unsigned low, size; + struct inflate_state state; +@@ -394,11 +365,7 @@ void makefixed() + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +-local int updatewindow(strm, end, copy) +-z_streamp strm; +-const Bytef *end; +-unsigned copy; +-{ ++local int updatewindow(z_streamp strm, const Bytef *end, unsigned copy) { + struct inflate_state FAR *state; + unsigned dist; + +@@ -620,10 +587,7 @@ unsigned copy; + will return Z_BUF_ERROR if it has not reached the end of the stream. + */ + +-int ZEXPORT inflate(strm, flush) +-z_streamp strm; +-int flush; +-{ ++int ZEXPORT inflate(z_streamp strm, int flush) { + struct inflate_state FAR *state; + z_const unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ +@@ -764,8 +728,9 @@ int flush; + if (copy > have) copy = have; + if (copy) { + if (state->head != Z_NULL && +- state->head->extra != Z_NULL) { +- len = state->head->extra_len - state->length; ++ state->head->extra != Z_NULL && ++ (len = state->head->extra_len - state->length) < ++ state->head->extra_max) { + zmemcpy(state->head->extra + len, next, + len + copy > state->head->extra_max ? + state->head->extra_max - len : copy); +@@ -1298,9 +1263,7 @@ int flush; + return ret; + } + +-int ZEXPORT inflateEnd(strm) +-z_streamp strm; +-{ ++int ZEXPORT inflateEnd(z_streamp strm) { + struct inflate_state FAR *state; + if (inflateStateCheck(strm)) + return Z_STREAM_ERROR; +@@ -1312,11 +1275,8 @@ z_streamp strm; + return Z_OK; + } + +-int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength) +-z_streamp strm; +-Bytef *dictionary; +-uInt *dictLength; +-{ ++int ZEXPORT inflateGetDictionary(z_streamp strm, Bytef *dictionary, ++ uInt *dictLength) { + struct inflate_state FAR *state; + + /* check state */ +@@ -1335,11 +1295,8 @@ uInt *dictLength; + return Z_OK; + } + +-int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) +-z_streamp strm; +-const Bytef *dictionary; +-uInt dictLength; +-{ ++int ZEXPORT inflateSetDictionary(z_streamp strm, const Bytef *dictionary, ++ uInt dictLength) { + struct inflate_state FAR *state; + unsigned long dictid; + int ret; +@@ -1370,10 +1327,7 @@ uInt dictLength; + return Z_OK; + } + +-int ZEXPORT inflateGetHeader(strm, head) +-z_streamp strm; +-gz_headerp head; +-{ ++int ZEXPORT inflateGetHeader(z_streamp strm, gz_headerp head) { + struct inflate_state FAR *state; + + /* check state */ +@@ -1398,11 +1352,8 @@ gz_headerp head; + called again with more data and the *have state. *have is initialized to + zero for the first call. + */ +-local unsigned syncsearch(have, buf, len) +-unsigned FAR *have; +-const unsigned char FAR *buf; +-unsigned len; +-{ ++local unsigned syncsearch(unsigned FAR *have, const unsigned char FAR *buf, ++ unsigned len) { + unsigned got; + unsigned next; + +@@ -1421,9 +1372,7 @@ unsigned len; + return next; + } + +-int ZEXPORT inflateSync(strm) +-z_streamp strm; +-{ ++int ZEXPORT inflateSync(z_streamp strm) { + unsigned len; /* number of bytes to look at or looked at */ + int flags; /* temporary to save header status */ + unsigned long in, out; /* temporary to save total_in and total_out */ +@@ -1438,7 +1387,7 @@ z_streamp strm; + /* if first time, start search in bit buffer */ + if (state->mode != SYNC) { + state->mode = SYNC; +- state->hold <<= state->bits & 7; ++ state->hold >>= state->bits & 7; + state->bits -= state->bits & 7; + len = 0; + while (state->bits >= 8) { +@@ -1479,9 +1428,7 @@ z_streamp strm; + block. When decompressing, PPP checks that at the end of input packet, + inflate is waiting for these length bytes. + */ +-int ZEXPORT inflateSyncPoint(strm) +-z_streamp strm; +-{ ++int ZEXPORT inflateSyncPoint(z_streamp strm) { + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; +@@ -1489,10 +1436,7 @@ z_streamp strm; + return state->mode == STORED && state->bits == 0; + } + +-int ZEXPORT inflateCopy(dest, source) +-z_streamp dest; +-z_streamp source; +-{ ++int ZEXPORT inflateCopy(z_streamp dest, z_streamp source) { + struct inflate_state FAR *state; + struct inflate_state FAR *copy; + unsigned char FAR *window; +@@ -1536,10 +1480,7 @@ z_streamp source; + return Z_OK; + } + +-int ZEXPORT inflateUndermine(strm, subvert) +-z_streamp strm; +-int subvert; +-{ ++int ZEXPORT inflateUndermine(z_streamp strm, int subvert) { + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; +@@ -1554,10 +1495,7 @@ int subvert; + #endif + } + +-int ZEXPORT inflateValidate(strm, check) +-z_streamp strm; +-int check; +-{ ++int ZEXPORT inflateValidate(z_streamp strm, int check) { + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; +@@ -1569,9 +1507,7 @@ int check; + return Z_OK; + } + +-long ZEXPORT inflateMark(strm) +-z_streamp strm; +-{ ++long ZEXPORT inflateMark(z_streamp strm) { + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) +@@ -1582,9 +1518,7 @@ z_streamp strm; + (state->mode == MATCH ? state->was - state->length : 0)); + } + +-unsigned long ZEXPORT inflateCodesUsed(strm) +-z_streamp strm; +-{ ++unsigned long ZEXPORT inflateCodesUsed(z_streamp strm) { + struct inflate_state FAR *state; + if (inflateStateCheck(strm)) return (unsigned long)-1; + state = (struct inflate_state FAR *)strm->state; +diff --git a/src/zlib/inftrees.c b/src/zlib/inftrees.c +index 09462a740..98cfe1644 100644 +--- a/src/zlib/inftrees.c ++++ b/src/zlib/inftrees.c +@@ -1,5 +1,5 @@ + /* inftrees.c -- generate Huffman trees for efficient decoding +- * Copyright (C) 1995-2022 Mark Adler ++ * Copyright (C) 1995-2024 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +@@ -9,7 +9,7 @@ + #define MAXBITS 15 + + const char inflate_copyright[] = +- " inflate 1.2.12 Copyright 1995-2022 Mark Adler "; ++ " inflate 1.3.1 Copyright 1995-2024 Mark Adler "; + /* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot +@@ -29,14 +29,9 @@ const char inflate_copyright[] = + table index bits. It will differ if the request is greater than the + longest code or if it is less than the shortest code. + */ +-int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work) +-codetype type; +-unsigned short FAR *lens; +-unsigned codes; +-code FAR * FAR *table; +-unsigned FAR *bits; +-unsigned short FAR *work; +-{ ++int ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens, ++ unsigned codes, code FAR * FAR *table, ++ unsigned FAR *bits, unsigned short FAR *work) { + unsigned len; /* a code's length in bits */ + unsigned sym; /* index of code symbols */ + unsigned min, max; /* minimum and maximum code lengths */ +@@ -62,7 +57,7 @@ unsigned short FAR *work; + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; + static const unsigned short lext[31] = { /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, +- 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 199, 202}; ++ 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 203, 77}; + static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, +diff --git a/src/zlib/inftrees.h b/src/zlib/inftrees.h +index baa53a0b1..396f74b5d 100644 +--- a/src/zlib/inftrees.h ++++ b/src/zlib/inftrees.h +@@ -38,11 +38,11 @@ typedef struct { + /* Maximum size of the dynamic table. The maximum number of code structures is + 1444, which is the sum of 852 for literal/length codes and 592 for distance + codes. These values were found by exhaustive searches using the program +- examples/enough.c found in the zlib distribtution. The arguments to that ++ examples/enough.c found in the zlib distribution. The arguments to that + program are the number of symbols, the initial root table size, and the + maximum bit length of a code. "enough 286 9 15" for literal/length codes +- returns returns 852, and "enough 30 6 15" for distance codes returns 592. +- The initial root table size (9 or 6) is found in the fifth argument of the ++ returns 852, and "enough 30 6 15" for distance codes returns 592. The ++ initial root table size (9 or 6) is found in the fifth argument of the + inflate_table() calls in inflate.c and infback.c. If the root table size is + changed, then these maximum sizes would be need to be recalculated and + updated. */ +@@ -57,6 +57,6 @@ typedef enum { + DISTS + } codetype; + +-int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens, +- unsigned codes, code FAR * FAR *table, +- unsigned FAR *bits, unsigned short FAR *work)); ++int ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens, ++ unsigned codes, code FAR * FAR *table, ++ unsigned FAR *bits, unsigned short FAR *work); +diff --git a/src/zlib/trees.c b/src/zlib/trees.c +index f73fd99c3..6a523ef34 100644 +--- a/src/zlib/trees.c ++++ b/src/zlib/trees.c +@@ -1,5 +1,5 @@ + /* trees.c -- output deflated data using Huffman coding +- * Copyright (C) 1995-2021 Jean-loup Gailly ++ * Copyright (C) 1995-2024 Jean-loup Gailly + * detect_data_type() function provided freely by Cosmin Truta, 2006 + * For conditions of distribution and use, see copyright notice in zlib.h + */ +@@ -122,39 +122,116 @@ struct static_tree_desc_s { + int max_length; /* max bit length for the codes */ + }; + +-local const static_tree_desc static_l_desc = ++#ifdef NO_INIT_GLOBAL_POINTERS ++# define TCONST ++#else ++# define TCONST const ++#endif ++ ++local TCONST static_tree_desc static_l_desc = + {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; + +-local const static_tree_desc static_d_desc = ++local TCONST static_tree_desc static_d_desc = + {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; + +-local const static_tree_desc static_bl_desc = ++local TCONST static_tree_desc static_bl_desc = + {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; + + /* =========================================================================== +- * Local (static) routines in this file. ++ * Output a short LSB first on the stream. ++ * IN assertion: there is enough room in pendingBuf. ++ */ ++#define put_short(s, w) { \ ++ put_byte(s, (uch)((w) & 0xff)); \ ++ put_byte(s, (uch)((ush)(w) >> 8)); \ ++} ++ ++/* =========================================================================== ++ * Reverse the first len bits of a code, using straightforward code (a faster ++ * method would use a table) ++ * IN assertion: 1 <= len <= 15 ++ */ ++local unsigned bi_reverse(unsigned code, int len) { ++ register unsigned res = 0; ++ do { ++ res |= code & 1; ++ code >>= 1, res <<= 1; ++ } while (--len > 0); ++ return res >> 1; ++} ++ ++/* =========================================================================== ++ * Flush the bit buffer, keeping at most 7 bits in it. ++ */ ++local void bi_flush(deflate_state *s) { ++ if (s->bi_valid == 16) { ++ put_short(s, s->bi_buf); ++ s->bi_buf = 0; ++ s->bi_valid = 0; ++ } else if (s->bi_valid >= 8) { ++ put_byte(s, (Byte)s->bi_buf); ++ s->bi_buf >>= 8; ++ s->bi_valid -= 8; ++ } ++} ++ ++/* =========================================================================== ++ * Flush the bit buffer and align the output on a byte boundary ++ */ ++local void bi_windup(deflate_state *s) { ++ if (s->bi_valid > 8) { ++ put_short(s, s->bi_buf); ++ } else if (s->bi_valid > 0) { ++ put_byte(s, (Byte)s->bi_buf); ++ } ++ s->bi_buf = 0; ++ s->bi_valid = 0; ++#ifdef ZLIB_DEBUG ++ s->bits_sent = (s->bits_sent + 7) & ~7; ++#endif ++} ++ ++/* =========================================================================== ++ * Generate the codes for a given tree and bit counts (which need not be ++ * optimal). ++ * IN assertion: the array bl_count contains the bit length statistics for ++ * the given tree and the field len is set for all tree elements. ++ * OUT assertion: the field code is set for all tree elements of non ++ * zero code length. + */ ++local void gen_codes(ct_data *tree, int max_code, ushf *bl_count) { ++ ush next_code[MAX_BITS+1]; /* next code value for each bit length */ ++ unsigned code = 0; /* running code value */ ++ int bits; /* bit index */ ++ int n; /* code index */ + +-local void tr_static_init OF((void)); +-local void init_block OF((deflate_state *s)); +-local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); +-local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); +-local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); +-local void build_tree OF((deflate_state *s, tree_desc *desc)); +-local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); +-local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); +-local int build_bl_tree OF((deflate_state *s)); +-local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, +- int blcodes)); +-local void compress_block OF((deflate_state *s, const ct_data *ltree, +- const ct_data *dtree)); +-local int detect_data_type OF((deflate_state *s)); +-local unsigned bi_reverse OF((unsigned code, int len)); +-local void bi_windup OF((deflate_state *s)); +-local void bi_flush OF((deflate_state *s)); ++ /* The distribution counts are first used to generate the code values ++ * without bit reversal. ++ */ ++ for (bits = 1; bits <= MAX_BITS; bits++) { ++ code = (code + bl_count[bits - 1]) << 1; ++ next_code[bits] = (ush)code; ++ } ++ /* Check that the bit counts in bl_count are consistent. The last code ++ * must be all ones. ++ */ ++ Assert (code + bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1, ++ "inconsistent bit counts"); ++ Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); ++ ++ for (n = 0; n <= max_code; n++) { ++ int len = tree[n].Len; ++ if (len == 0) continue; ++ /* Now reverse the bits */ ++ tree[n].Code = (ush)bi_reverse(next_code[len]++, len); ++ ++ Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", ++ n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len] - 1)); ++ } ++} + + #ifdef GEN_TREES_H +-local void gen_trees_header OF((void)); ++local void gen_trees_header(void); + #endif + + #ifndef ZLIB_DEBUG +@@ -167,33 +244,18 @@ local void gen_trees_header OF((void)); + send_bits(s, tree[c].Code, tree[c].Len); } + #endif + +-/* =========================================================================== +- * Output a short LSB first on the stream. +- * IN assertion: there is enough room in pendingBuf. +- */ +-#define put_short(s, w) { \ +- put_byte(s, (uch)((w) & 0xff)); \ +- put_byte(s, (uch)((ush)(w) >> 8)); \ +-} +- + /* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ + #ifdef ZLIB_DEBUG +-local void send_bits OF((deflate_state *s, int value, int length)); +- +-local void send_bits(s, value, length) +- deflate_state *s; +- int value; /* value to send */ +- int length; /* number of bits */ +-{ ++local void send_bits(deflate_state *s, int value, int length) { + Tracevv((stderr," l %2d v %4x ", length, value)); + Assert(length > 0 && length <= 15, "invalid length"); + s->bits_sent += (ulg)length; + + /* If not enough room in bi_buf, use (valid) bits from bi_buf and +- * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) ++ * (16 - bi_valid) bits from value, leaving (width - (16 - bi_valid)) + * unused bits in value. + */ + if (s->bi_valid > (int)Buf_size - length) { +@@ -229,8 +291,7 @@ local void send_bits(s, value, length) + /* =========================================================================== + * Initialize the various 'constant' tables. + */ +-local void tr_static_init() +-{ ++local void tr_static_init(void) { + #if defined(GEN_TREES_H) || !defined(STDC) + static int static_init_done = 0; + int n; /* iterates over tree elements */ +@@ -256,7 +317,7 @@ local void tr_static_init() + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; +- for (n = 0; n < (1< dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + base_dist[code] = dist; +- for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ + for ( ; code < D_CODES; code++) { + base_dist[code] = dist << 7; +- for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { ++ for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = (uch)code; + } + } +- Assert (dist == 256, "tr_static_init: 256+dist != 512"); ++ Assert (dist == 256, "tr_static_init: 256 + dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; +@@ -312,7 +373,7 @@ local void tr_static_init() + } + + /* =========================================================================== +- * Genererate the file trees.h describing the static trees. ++ * Generate the file trees.h describing the static trees. + */ + #ifdef GEN_TREES_H + # ifndef ZLIB_DEBUG +@@ -321,10 +382,9 @@ local void tr_static_init() + + # define SEPARATOR(i, last, width) \ + ((i) == (last)? "\n};\n\n" : \ +- ((i) % (width) == (width)-1 ? ",\n" : ", ")) ++ ((i) % (width) == (width) - 1 ? ",\n" : ", ")) + +-void gen_trees_header() +-{ ++void gen_trees_header(void) { + FILE *header = fopen("trees.h", "w"); + int i; + +@@ -373,12 +433,26 @@ void gen_trees_header() + } + #endif /* GEN_TREES_H */ + ++/* =========================================================================== ++ * Initialize a new block. ++ */ ++local void init_block(deflate_state *s) { ++ int n; /* iterates over tree elements */ ++ ++ /* Initialize the trees. */ ++ for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; ++ for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; ++ for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; ++ ++ s->dyn_ltree[END_BLOCK].Freq = 1; ++ s->opt_len = s->static_len = 0L; ++ s->sym_next = s->matches = 0; ++} ++ + /* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +-void ZLIB_INTERNAL _tr_init(s) +- deflate_state *s; +-{ ++void ZLIB_INTERNAL _tr_init(deflate_state *s) { + tr_static_init(); + + s->l_desc.dyn_tree = s->dyn_ltree; +@@ -401,24 +475,6 @@ void ZLIB_INTERNAL _tr_init(s) + init_block(s); + } + +-/* =========================================================================== +- * Initialize a new block. +- */ +-local void init_block(s) +- deflate_state *s; +-{ +- int n; /* iterates over tree elements */ +- +- /* Initialize the trees. */ +- for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; +- for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; +- for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; +- +- s->dyn_ltree[END_BLOCK].Freq = 1; +- s->opt_len = s->static_len = 0L; +- s->sym_next = s->matches = 0; +-} +- + #define SMALLEST 1 + /* Index within the heap array of least frequent node in the Huffman tree */ + +@@ -448,17 +504,13 @@ local void init_block(s) + * when the heap property is re-established (each father smaller than its + * two sons). + */ +-local void pqdownheap(s, tree, k) +- deflate_state *s; +- ct_data *tree; /* the tree to restore */ +- int k; /* node to move down */ +-{ ++local void pqdownheap(deflate_state *s, ct_data *tree, int k) { + int v = s->heap[k]; + int j = k << 1; /* left son of k */ + while (j <= s->heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s->heap_len && +- smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { ++ smaller(tree, s->heap[j + 1], s->heap[j], s->depth)) { + j++; + } + /* Exit if v is smaller than both sons */ +@@ -483,10 +535,7 @@ local void pqdownheap(s, tree, k) + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +-local void gen_bitlen(s, desc) +- deflate_state *s; +- tree_desc *desc; /* the tree descriptor */ +-{ ++local void gen_bitlen(deflate_state *s, tree_desc *desc) { + ct_data *tree = desc->dyn_tree; + int max_code = desc->max_code; + const ct_data *stree = desc->stat_desc->static_tree; +@@ -507,7 +556,7 @@ local void gen_bitlen(s, desc) + */ + tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ + +- for (h = s->heap_max+1; h < HEAP_SIZE; h++) { ++ for (h = s->heap_max + 1; h < HEAP_SIZE; h++) { + n = s->heap[h]; + bits = tree[tree[n].Dad].Len + 1; + if (bits > max_length) bits = max_length, overflow++; +@@ -518,7 +567,7 @@ local void gen_bitlen(s, desc) + + s->bl_count[bits]++; + xbits = 0; +- if (n >= base) xbits = extra[n-base]; ++ if (n >= base) xbits = extra[n - base]; + f = tree[n].Freq; + s->opt_len += (ulg)f * (unsigned)(bits + xbits); + if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits); +@@ -530,10 +579,10 @@ local void gen_bitlen(s, desc) + + /* Find the first bit length which could increase: */ + do { +- bits = max_length-1; ++ bits = max_length - 1; + while (s->bl_count[bits] == 0) bits--; +- s->bl_count[bits]--; /* move one leaf down the tree */ +- s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ ++ s->bl_count[bits]--; /* move one leaf down the tree */ ++ s->bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s->bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] +@@ -561,48 +610,9 @@ local void gen_bitlen(s, desc) + } + } + +-/* =========================================================================== +- * Generate the codes for a given tree and bit counts (which need not be +- * optimal). +- * IN assertion: the array bl_count contains the bit length statistics for +- * the given tree and the field len is set for all tree elements. +- * OUT assertion: the field code is set for all tree elements of non +- * zero code length. +- */ +-local void gen_codes (tree, max_code, bl_count) +- ct_data *tree; /* the tree to decorate */ +- int max_code; /* largest code with non zero frequency */ +- ushf *bl_count; /* number of codes at each bit length */ +-{ +- ush next_code[MAX_BITS+1]; /* next code value for each bit length */ +- unsigned code = 0; /* running code value */ +- int bits; /* bit index */ +- int n; /* code index */ +- +- /* The distribution counts are first used to generate the code values +- * without bit reversal. +- */ +- for (bits = 1; bits <= MAX_BITS; bits++) { +- code = (code + bl_count[bits-1]) << 1; +- next_code[bits] = (ush)code; +- } +- /* Check that the bit counts in bl_count are consistent. The last code +- * must be all ones. +- */ +- Assert (code + bl_count[MAX_BITS]-1 == (1< ++#endif + + /* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. +@@ -612,10 +622,7 @@ local void gen_codes (tree, max_code, bl_count) + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +-local void build_tree(s, desc) +- deflate_state *s; +- tree_desc *desc; /* the tree descriptor */ +-{ ++local void build_tree(deflate_state *s, tree_desc *desc) { + ct_data *tree = desc->dyn_tree; + const ct_data *stree = desc->stat_desc->static_tree; + int elems = desc->stat_desc->elems; +@@ -624,7 +631,7 @@ local void build_tree(s, desc) + int node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in +- * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. ++ * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n + 1]. + * heap[0] is not used. + */ + s->heap_len = 0, s->heap_max = HEAP_SIZE; +@@ -652,7 +659,7 @@ local void build_tree(s, desc) + } + desc->max_code = max_code; + +- /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, ++ /* The elements heap[heap_len/2 + 1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); +@@ -700,11 +707,7 @@ local void build_tree(s, desc) + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +-local void scan_tree (s, tree, max_code) +- deflate_state *s; +- ct_data *tree; /* the tree to be scanned */ +- int max_code; /* and its largest code of non zero frequency */ +-{ ++local void scan_tree(deflate_state *s, ct_data *tree, int max_code) { + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ +@@ -714,10 +717,10 @@ local void scan_tree (s, tree, max_code) + int min_count = 4; /* min repeat count */ + + if (nextlen == 0) max_count = 138, min_count = 3; +- tree[max_code+1].Len = (ush)0xffff; /* guard */ ++ tree[max_code + 1].Len = (ush)0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { +- curlen = nextlen; nextlen = tree[n+1].Len; ++ curlen = nextlen; nextlen = tree[n + 1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { +@@ -745,11 +748,7 @@ local void scan_tree (s, tree, max_code) + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +-local void send_tree (s, tree, max_code) +- deflate_state *s; +- ct_data *tree; /* the tree to be scanned */ +- int max_code; /* and its largest code of non zero frequency */ +-{ ++local void send_tree(deflate_state *s, ct_data *tree, int max_code) { + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ +@@ -758,11 +757,11 @@ local void send_tree (s, tree, max_code) + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + +- /* tree[max_code+1].Len = -1; */ /* guard already set */ ++ /* tree[max_code + 1].Len = -1; */ /* guard already set */ + if (nextlen == 0) max_count = 138, min_count = 3; + + for (n = 0; n <= max_code; n++) { +- curlen = nextlen; nextlen = tree[n+1].Len; ++ curlen = nextlen; nextlen = tree[n + 1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { +@@ -773,13 +772,13 @@ local void send_tree (s, tree, max_code) + send_code(s, curlen, s->bl_tree); count--; + } + Assert(count >= 3 && count <= 6, " 3_6?"); +- send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); ++ send_code(s, REP_3_6, s->bl_tree); send_bits(s, count - 3, 2); + + } else if (count <= 10) { +- send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); ++ send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count - 3, 3); + + } else { +- send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); ++ send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count - 11, 7); + } + count = 0; prevlen = curlen; + if (nextlen == 0) { +@@ -796,9 +795,7 @@ local void send_tree (s, tree, max_code) + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +-local int build_bl_tree(s) +- deflate_state *s; +-{ ++local int build_bl_tree(deflate_state *s) { + int max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ +@@ -807,8 +804,8 @@ local int build_bl_tree(s) + + /* Build the bit length tree: */ + build_tree(s, (tree_desc *)(&(s->bl_desc))); +- /* opt_len now includes the length of the tree representations, except +- * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. ++ /* opt_len now includes the length of the tree representations, except the ++ * lengths of the bit lengths codes and the 5 + 5 + 4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format +@@ -819,7 +816,7 @@ local int build_bl_tree(s) + if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; + } + /* Update opt_len to include the bit length tree and counts */ +- s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4; ++ s->opt_len += 3*((ulg)max_blindex + 1) + 5 + 5 + 4; + Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + s->opt_len, s->static_len)); + +@@ -831,42 +828,36 @@ local int build_bl_tree(s) + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +-local void send_all_trees(s, lcodes, dcodes, blcodes) +- deflate_state *s; +- int lcodes, dcodes, blcodes; /* number of codes for each tree */ +-{ ++local void send_all_trees(deflate_state *s, int lcodes, int dcodes, ++ int blcodes) { + int rank; /* index in bl_order */ + + Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + "too many codes"); + Tracev((stderr, "\nbl counts: ")); +- send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ +- send_bits(s, dcodes-1, 5); +- send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ ++ send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ ++ send_bits(s, dcodes - 1, 5); ++ send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); + } + Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + +- send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ ++ send_tree(s, (ct_data *)s->dyn_ltree, lcodes - 1); /* literal tree */ + Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + +- send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ ++ send_tree(s, (ct_data *)s->dyn_dtree, dcodes - 1); /* distance tree */ + Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); + } + + /* =========================================================================== + * Send a stored block + */ +-void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) +- deflate_state *s; +- charf *buf; /* input block */ +- ulg stored_len; /* length of input block */ +- int last; /* one if this is the last block for a file */ +-{ +- send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */ ++void ZLIB_INTERNAL _tr_stored_block(deflate_state *s, charf *buf, ++ ulg stored_len, int last) { ++ send_bits(s, (STORED_BLOCK<<1) + last, 3); /* send block type */ + bi_windup(s); /* align on byte boundary */ + put_short(s, (ush)stored_len); + put_short(s, (ush)~stored_len); +@@ -877,16 +868,14 @@ void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) + s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; + s->compressed_len += (stored_len + 4) << 3; + s->bits_sent += 2*16; +- s->bits_sent += stored_len<<3; ++ s->bits_sent += stored_len << 3; + #endif + } + + /* =========================================================================== + * Flush the bits in the bit buffer to pending output (leaves at most 7 bits) + */ +-void ZLIB_INTERNAL _tr_flush_bits(s) +- deflate_state *s; +-{ ++void ZLIB_INTERNAL _tr_flush_bits(deflate_state *s) { + bi_flush(s); + } + +@@ -894,9 +883,7 @@ void ZLIB_INTERNAL _tr_flush_bits(s) + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +-void ZLIB_INTERNAL _tr_align(s) +- deflate_state *s; +-{ ++void ZLIB_INTERNAL _tr_align(deflate_state *s) { + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); + #ifdef ZLIB_DEBUG +@@ -905,16 +892,108 @@ void ZLIB_INTERNAL _tr_align(s) + bi_flush(s); + } + ++/* =========================================================================== ++ * Send the block data compressed using the given Huffman trees ++ */ ++local void compress_block(deflate_state *s, const ct_data *ltree, ++ const ct_data *dtree) { ++ unsigned dist; /* distance of matched string */ ++ int lc; /* match length or unmatched char (if dist == 0) */ ++ unsigned sx = 0; /* running index in symbol buffers */ ++ unsigned code; /* the code to send */ ++ int extra; /* number of extra bits to send */ ++ ++ if (s->sym_next != 0) do { ++#ifdef LIT_MEM ++ dist = s->d_buf[sx]; ++ lc = s->l_buf[sx++]; ++#else ++ dist = s->sym_buf[sx++] & 0xff; ++ dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8; ++ lc = s->sym_buf[sx++]; ++#endif ++ if (dist == 0) { ++ send_code(s, lc, ltree); /* send a literal byte */ ++ Tracecv(isgraph(lc), (stderr," '%c' ", lc)); ++ } else { ++ /* Here, lc is the match length - MIN_MATCH */ ++ code = _length_code[lc]; ++ send_code(s, code + LITERALS + 1, ltree); /* send length code */ ++ extra = extra_lbits[code]; ++ if (extra != 0) { ++ lc -= base_length[code]; ++ send_bits(s, lc, extra); /* send the extra length bits */ ++ } ++ dist--; /* dist is now the match distance - 1 */ ++ code = d_code(dist); ++ Assert (code < D_CODES, "bad d_code"); ++ ++ send_code(s, code, dtree); /* send the distance code */ ++ extra = extra_dbits[code]; ++ if (extra != 0) { ++ dist -= (unsigned)base_dist[code]; ++ send_bits(s, dist, extra); /* send the extra distance bits */ ++ } ++ } /* literal or match pair ? */ ++ ++ /* Check for no overlay of pending_buf on needed symbols */ ++#ifdef LIT_MEM ++ Assert(s->pending < 2 * (s->lit_bufsize + sx), "pendingBuf overflow"); ++#else ++ Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow"); ++#endif ++ ++ } while (sx < s->sym_next); ++ ++ send_code(s, END_BLOCK, ltree); ++} ++ ++/* =========================================================================== ++ * Check if the data type is TEXT or BINARY, using the following algorithm: ++ * - TEXT if the two conditions below are satisfied: ++ * a) There are no non-portable control characters belonging to the ++ * "block list" (0..6, 14..25, 28..31). ++ * b) There is at least one printable character belonging to the ++ * "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). ++ * - BINARY otherwise. ++ * - The following partially-portable control characters form a ++ * "gray list" that is ignored in this detection algorithm: ++ * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). ++ * IN assertion: the fields Freq of dyn_ltree are set. ++ */ ++local int detect_data_type(deflate_state *s) { ++ /* block_mask is the bit mask of block-listed bytes ++ * set bits 0..6, 14..25, and 28..31 ++ * 0xf3ffc07f = binary 11110011111111111100000001111111 ++ */ ++ unsigned long block_mask = 0xf3ffc07fUL; ++ int n; ++ ++ /* Check for non-textual ("block-listed") bytes. */ ++ for (n = 0; n <= 31; n++, block_mask >>= 1) ++ if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0)) ++ return Z_BINARY; ++ ++ /* Check for textual ("allow-listed") bytes. */ ++ if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 ++ || s->dyn_ltree[13].Freq != 0) ++ return Z_TEXT; ++ for (n = 32; n < LITERALS; n++) ++ if (s->dyn_ltree[n].Freq != 0) ++ return Z_TEXT; ++ ++ /* There are no "block-listed" or "allow-listed" bytes: ++ * this stream either is empty or has tolerated ("gray-listed") bytes only. ++ */ ++ return Z_BINARY; ++} ++ + /* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and write out the encoded block. + */ +-void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) +- deflate_state *s; +- charf *buf; /* input block, or NULL if too old */ +- ulg stored_len; /* length of input block */ +- int last; /* one if this is the last block for a file */ +-{ ++void ZLIB_INTERNAL _tr_flush_block(deflate_state *s, charf *buf, ++ ulg stored_len, int last) { + ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + int max_blindex = 0; /* index of last bit length code of non zero freq */ + +@@ -943,14 +1022,17 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ +- opt_lenb = (s->opt_len+3+7)>>3; +- static_lenb = (s->static_len+3+7)>>3; ++ opt_lenb = (s->opt_len + 3 + 7) >> 3; ++ static_lenb = (s->static_len + 3 + 7) >> 3; + + Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + s->sym_next / 3)); + +- if (static_lenb <= opt_lenb) opt_lenb = static_lenb; ++#ifndef FORCE_STATIC ++ if (static_lenb <= opt_lenb || s->strategy == Z_FIXED) ++#endif ++ opt_lenb = static_lenb; + + } else { + Assert(buf != (char*)0, "lost buf"); +@@ -960,7 +1042,7 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) + #ifdef FORCE_STORED + if (buf != (char*)0) { /* force stored block */ + #else +- if (stored_len+4 <= opt_lenb && buf != (char*)0) { ++ if (stored_len + 4 <= opt_lenb && buf != (char*)0) { + /* 4: two words for the lengths */ + #endif + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. +@@ -971,21 +1053,17 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) + */ + _tr_stored_block(s, buf, stored_len, last); + +-#ifdef FORCE_STATIC +- } else if (static_lenb >= 0) { /* force static trees */ +-#else +- } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { +-#endif +- send_bits(s, (STATIC_TREES<<1)+last, 3); ++ } else if (static_lenb == opt_lenb) { ++ send_bits(s, (STATIC_TREES<<1) + last, 3); + compress_block(s, (const ct_data *)static_ltree, + (const ct_data *)static_dtree); + #ifdef ZLIB_DEBUG + s->compressed_len += 3 + s->static_len; + #endif + } else { +- send_bits(s, (DYN_TREES<<1)+last, 3); +- send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, +- max_blindex+1); ++ send_bits(s, (DYN_TREES<<1) + last, 3); ++ send_all_trees(s, s->l_desc.max_code + 1, s->d_desc.max_code + 1, ++ max_blindex + 1); + compress_block(s, (const ct_data *)s->dyn_ltree, + (const ct_data *)s->dyn_dtree); + #ifdef ZLIB_DEBUG +@@ -1004,22 +1082,23 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) + s->compressed_len += 7; /* align on byte boundary */ + #endif + } +- Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, +- s->compressed_len-7*last)); ++ Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len >> 3, ++ s->compressed_len - 7*last)); + } + + /* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +-int ZLIB_INTERNAL _tr_tally (s, dist, lc) +- deflate_state *s; +- unsigned dist; /* distance of matched string */ +- unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +-{ +- s->sym_buf[s->sym_next++] = dist; +- s->sym_buf[s->sym_next++] = dist >> 8; +- s->sym_buf[s->sym_next++] = lc; ++int ZLIB_INTERNAL _tr_tally(deflate_state *s, unsigned dist, unsigned lc) { ++#ifdef LIT_MEM ++ s->d_buf[s->sym_next] = (ush)dist; ++ s->l_buf[s->sym_next++] = (uch)lc; ++#else ++ s->sym_buf[s->sym_next++] = (uch)dist; ++ s->sym_buf[s->sym_next++] = (uch)(dist >> 8); ++ s->sym_buf[s->sym_next++] = (uch)lc; ++#endif + if (dist == 0) { + /* lc is the unmatched char */ + s->dyn_ltree[lc].Freq++; +@@ -1031,152 +1110,8 @@ int ZLIB_INTERNAL _tr_tally (s, dist, lc) + (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + +- s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; ++ s->dyn_ltree[_length_code[lc] + LITERALS + 1].Freq++; + s->dyn_dtree[d_code(dist)].Freq++; + } + return (s->sym_next == s->sym_end); + } +- +-/* =========================================================================== +- * Send the block data compressed using the given Huffman trees +- */ +-local void compress_block(s, ltree, dtree) +- deflate_state *s; +- const ct_data *ltree; /* literal tree */ +- const ct_data *dtree; /* distance tree */ +-{ +- unsigned dist; /* distance of matched string */ +- int lc; /* match length or unmatched char (if dist == 0) */ +- unsigned sx = 0; /* running index in sym_buf */ +- unsigned code; /* the code to send */ +- int extra; /* number of extra bits to send */ +- +- if (s->sym_next != 0) do { +- dist = s->sym_buf[sx++] & 0xff; +- dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8; +- lc = s->sym_buf[sx++]; +- if (dist == 0) { +- send_code(s, lc, ltree); /* send a literal byte */ +- Tracecv(isgraph(lc), (stderr," '%c' ", lc)); +- } else { +- /* Here, lc is the match length - MIN_MATCH */ +- code = _length_code[lc]; +- send_code(s, code+LITERALS+1, ltree); /* send the length code */ +- extra = extra_lbits[code]; +- if (extra != 0) { +- lc -= base_length[code]; +- send_bits(s, lc, extra); /* send the extra length bits */ +- } +- dist--; /* dist is now the match distance - 1 */ +- code = d_code(dist); +- Assert (code < D_CODES, "bad d_code"); +- +- send_code(s, code, dtree); /* send the distance code */ +- extra = extra_dbits[code]; +- if (extra != 0) { +- dist -= (unsigned)base_dist[code]; +- send_bits(s, dist, extra); /* send the extra distance bits */ +- } +- } /* literal or match pair ? */ +- +- /* Check that the overlay between pending_buf and sym_buf is ok: */ +- Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow"); +- +- } while (sx < s->sym_next); +- +- send_code(s, END_BLOCK, ltree); +-} +- +-/* =========================================================================== +- * Check if the data type is TEXT or BINARY, using the following algorithm: +- * - TEXT if the two conditions below are satisfied: +- * a) There are no non-portable control characters belonging to the +- * "block list" (0..6, 14..25, 28..31). +- * b) There is at least one printable character belonging to the +- * "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). +- * - BINARY otherwise. +- * - The following partially-portable control characters form a +- * "gray list" that is ignored in this detection algorithm: +- * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). +- * IN assertion: the fields Freq of dyn_ltree are set. +- */ +-local int detect_data_type(s) +- deflate_state *s; +-{ +- /* block_mask is the bit mask of block-listed bytes +- * set bits 0..6, 14..25, and 28..31 +- * 0xf3ffc07f = binary 11110011111111111100000001111111 +- */ +- unsigned long block_mask = 0xf3ffc07fUL; +- int n; +- +- /* Check for non-textual ("block-listed") bytes. */ +- for (n = 0; n <= 31; n++, block_mask >>= 1) +- if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0)) +- return Z_BINARY; +- +- /* Check for textual ("allow-listed") bytes. */ +- if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 +- || s->dyn_ltree[13].Freq != 0) +- return Z_TEXT; +- for (n = 32; n < LITERALS; n++) +- if (s->dyn_ltree[n].Freq != 0) +- return Z_TEXT; +- +- /* There are no "block-listed" or "allow-listed" bytes: +- * this stream either is empty or has tolerated ("gray-listed") bytes only. +- */ +- return Z_BINARY; +-} +- +-/* =========================================================================== +- * Reverse the first len bits of a code, using straightforward code (a faster +- * method would use a table) +- * IN assertion: 1 <= len <= 15 +- */ +-local unsigned bi_reverse(code, len) +- unsigned code; /* the value to invert */ +- int len; /* its bit length */ +-{ +- register unsigned res = 0; +- do { +- res |= code & 1; +- code >>= 1, res <<= 1; +- } while (--len > 0); +- return res >> 1; +-} +- +-/* =========================================================================== +- * Flush the bit buffer, keeping at most 7 bits in it. +- */ +-local void bi_flush(s) +- deflate_state *s; +-{ +- if (s->bi_valid == 16) { +- put_short(s, s->bi_buf); +- s->bi_buf = 0; +- s->bi_valid = 0; +- } else if (s->bi_valid >= 8) { +- put_byte(s, (Byte)s->bi_buf); +- s->bi_buf >>= 8; +- s->bi_valid -= 8; +- } +-} +- +-/* =========================================================================== +- * Flush the bit buffer and align the output on a byte boundary +- */ +-local void bi_windup(s) +- deflate_state *s; +-{ +- if (s->bi_valid > 8) { +- put_short(s, s->bi_buf); +- } else if (s->bi_valid > 0) { +- put_byte(s, (Byte)s->bi_buf); +- } +- s->bi_buf = 0; +- s->bi_valid = 0; +-#ifdef ZLIB_DEBUG +- s->bits_sent = (s->bits_sent+7) & ~7; +-#endif +-} +diff --git a/src/zlib/uncompr.c b/src/zlib/uncompr.c +index f03a1a865..5e256663b 100644 +--- a/src/zlib/uncompr.c ++++ b/src/zlib/uncompr.c +@@ -24,12 +24,8 @@ + Z_DATA_ERROR if the input data was corrupted, including if the input data is + an incomplete zlib stream. + */ +-int ZEXPORT uncompress2 (dest, destLen, source, sourceLen) +- Bytef *dest; +- uLongf *destLen; +- const Bytef *source; +- uLong *sourceLen; +-{ ++int ZEXPORT uncompress2(Bytef *dest, uLongf *destLen, const Bytef *source, ++ uLong *sourceLen) { + z_stream stream; + int err; + const uInt max = (uInt)-1; +@@ -83,11 +79,7 @@ int ZEXPORT uncompress2 (dest, destLen, source, sourceLen) + err; + } + +-int ZEXPORT uncompress (dest, destLen, source, sourceLen) +- Bytef *dest; +- uLongf *destLen; +- const Bytef *source; +- uLong sourceLen; +-{ ++int ZEXPORT uncompress(Bytef *dest, uLongf *destLen, const Bytef *source, ++ uLong sourceLen) { + return uncompress2(dest, destLen, source, &sourceLen); + } +diff --git a/src/zlib/zconf.h b/src/zlib/zconf.h +index 5e1d68a00..62adc8d84 100644 +--- a/src/zlib/zconf.h ++++ b/src/zlib/zconf.h +@@ -1,5 +1,5 @@ + /* zconf.h -- configuration of the zlib compression library +- * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler ++ * Copyright (C) 1995-2024 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +@@ -38,6 +38,9 @@ + # define crc32 z_crc32 + # define crc32_combine z_crc32_combine + # define crc32_combine64 z_crc32_combine64 ++# define crc32_combine_gen z_crc32_combine_gen ++# define crc32_combine_gen64 z_crc32_combine_gen64 ++# define crc32_combine_op z_crc32_combine_op + # define crc32_z z_crc32_z + # define deflate z_deflate + # define deflateBound z_deflateBound +@@ -238,7 +241,11 @@ + #endif + + #ifdef Z_SOLO +- typedef unsigned long z_size_t; ++# ifdef _WIN64 ++ typedef unsigned long long z_size_t; ++# else ++ typedef unsigned long z_size_t; ++# endif + #else + # define z_longlong long long + # if defined(NO_SIZE_T) +@@ -293,14 +300,6 @@ + # endif + #endif + +-#ifndef Z_ARG /* function prototypes for stdarg */ +-# if defined(STDC) || defined(Z_HAVE_STDARG_H) +-# define Z_ARG(args) args +-# else +-# define Z_ARG(args) () +-# endif +-#endif +- + /* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have +@@ -349,6 +348,9 @@ + # ifdef FAR + # undef FAR + # endif ++# ifndef WIN32_LEAN_AND_MEAN ++# define WIN32_LEAN_AND_MEAN ++# endif + # include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +@@ -467,11 +469,18 @@ typedef uLong FAR uLongf; + # undef _LARGEFILE64_SOURCE + #endif + +-#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) +-# define Z_HAVE_UNISTD_H ++#ifndef Z_HAVE_UNISTD_H ++# ifdef __WATCOMC__ ++# define Z_HAVE_UNISTD_H ++# endif ++#endif ++#ifndef Z_HAVE_UNISTD_H ++# if defined(_LARGEFILE64_SOURCE) && !defined(_WIN32) ++# define Z_HAVE_UNISTD_H ++# endif + #endif + #ifndef Z_SOLO +-# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) ++# if defined(Z_HAVE_UNISTD_H) + # include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ + # ifdef VMS + # include /* for off_t */ +@@ -507,7 +516,7 @@ typedef uLong FAR uLongf; + #if !defined(_WIN32) && defined(Z_LARGE64) + # define z_off64_t off64_t + #else +-# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) ++# if defined(_WIN32) && !defined(__GNUC__) + # define z_off64_t __int64 + # else + # define z_off64_t z_off_t +diff --git a/src/zlib/zlib.h b/src/zlib/zlib.h +index 4a98e38bf..8d4b932ea 100644 +--- a/src/zlib/zlib.h ++++ b/src/zlib/zlib.h +@@ -1,7 +1,7 @@ + /* zlib.h -- interface of the 'zlib' general purpose compression library +- version 1.2.12, March 11th, 2022 ++ version 1.3.1, January 22nd, 2024 + +- Copyright (C) 1995-2022 Jean-loup Gailly and Mark Adler ++ Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages +@@ -37,11 +37,11 @@ + extern "C" { + #endif + +-#define ZLIB_VERSION "1.2.12" +-#define ZLIB_VERNUM 0x12c0 ++#define ZLIB_VERSION "1.3.1" ++#define ZLIB_VERNUM 0x1310 + #define ZLIB_VER_MAJOR 1 +-#define ZLIB_VER_MINOR 2 +-#define ZLIB_VER_REVISION 12 ++#define ZLIB_VER_MINOR 3 ++#define ZLIB_VER_REVISION 1 + #define ZLIB_VER_SUBREVISION 0 + + /* +@@ -78,8 +78,8 @@ extern "C" { + even in the case of corrupted input. + */ + +-typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +-typedef void (*free_func) OF((voidpf opaque, voidpf address)); ++typedef voidpf (*alloc_func)(voidpf opaque, uInt items, uInt size); ++typedef void (*free_func)(voidpf opaque, voidpf address); + + struct internal_state; + +@@ -217,7 +217,7 @@ typedef gz_header FAR *gz_headerp; + + /* basic functions */ + +-ZEXTERN const char * ZEXPORT zlibVersion OF((void)); ++ZEXTERN const char * ZEXPORT zlibVersion(void); + /* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is not + compatible with the zlib.h header file used by the application. This check +@@ -225,12 +225,12 @@ ZEXTERN const char * ZEXPORT zlibVersion OF((void)); + */ + + /* +-ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); ++ZEXTERN int ZEXPORT deflateInit(z_streamp strm, int level); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. If + zalloc and zfree are set to Z_NULL, deflateInit updates them to use default +- allocation functions. ++ allocation functions. total_in, total_out, adler, and msg are initialized. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at all +@@ -247,7 +247,7 @@ ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + */ + + +-ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); ++ZEXTERN int ZEXPORT deflate(z_streamp strm, int flush); + /* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce +@@ -276,7 +276,7 @@ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); + == 0), or after each call of deflate(). If deflate returns Z_OK and with + zero avail_out, it must be called again after making room in the output + buffer because there might be more output pending. See deflatePending(), +- which can be used if desired to determine whether or not there is more ouput ++ which can be used if desired to determine whether or not there is more output + in that case. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to +@@ -320,8 +320,8 @@ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that +- avail_out is greater than six to avoid repeated flush markers due to +- avail_out == 0 on return. ++ avail_out is greater than six when the flush marker begins, in order to avoid ++ repeated flush markers upon calling deflate() again when avail_out == 0. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there was +@@ -360,7 +360,7 @@ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); + */ + + +-ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); ++ZEXTERN int ZEXPORT deflateEnd(z_streamp strm); + /* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending +@@ -375,7 +375,7 @@ ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); + + + /* +-ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); ++ZEXTERN int ZEXPORT inflateInit(z_streamp strm); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by +@@ -383,7 +383,8 @@ ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + read or consumed. The allocation of a sliding window will be deferred to + the first call of inflate (if the decompression does not complete on the + first call). If zalloc and zfree are set to Z_NULL, inflateInit updates +- them to use default allocation functions. ++ them to use default allocation functions. total_in, total_out, adler, and ++ msg are initialized. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the +@@ -397,7 +398,7 @@ ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + */ + + +-ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); ++ZEXTERN int ZEXPORT inflate(z_streamp strm, int flush); + /* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce +@@ -517,7 +518,7 @@ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); + */ + + +-ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); ++ZEXTERN int ZEXPORT inflateEnd(z_streamp strm); + /* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending +@@ -535,12 +536,12 @@ ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); + */ + + /* +-ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, +- int level, +- int method, +- int windowBits, +- int memLevel, +- int strategy)); ++ZEXTERN int ZEXPORT deflateInit2(z_streamp strm, ++ int level, ++ int method, ++ int windowBits, ++ int memLevel, ++ int strategy); + + This is another version of deflateInit with more compression options. The + fields zalloc, zfree and opaque must be initialized before by the caller. +@@ -607,9 +608,9 @@ ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + compression: this will be done by deflate(). + */ + +-ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, +- const Bytef *dictionary, +- uInt dictLength)); ++ZEXTERN int ZEXPORT deflateSetDictionary(z_streamp strm, ++ const Bytef *dictionary, ++ uInt dictLength); + /* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. When using the zlib format, this +@@ -651,16 +652,16 @@ ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + not perform any compression: this will be done by deflate(). + */ + +-ZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm, +- Bytef *dictionary, +- uInt *dictLength)); ++ZEXTERN int ZEXPORT deflateGetDictionary(z_streamp strm, ++ Bytef *dictionary, ++ uInt *dictLength); + /* + Returns the sliding dictionary being maintained by deflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If deflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. +- Similary, if dictLength is Z_NULL, then it is not set. ++ Similarly, if dictLength is Z_NULL, then it is not set. + + deflateGetDictionary() may return a length less than the window size, even + when more than the window size in input has been provided. It may return up +@@ -673,8 +674,8 @@ ZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm, + stream state is inconsistent. + */ + +-ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, +- z_streamp source)); ++ZEXTERN int ZEXPORT deflateCopy(z_streamp dest, ++ z_streamp source); + /* + Sets the destination stream as a complete copy of the source stream. + +@@ -691,20 +692,20 @@ ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + destination. + */ + +-ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); ++ZEXTERN int ZEXPORT deflateReset(z_streamp strm); + /* + This function is equivalent to deflateEnd followed by deflateInit, but + does not free and reallocate the internal compression state. The stream + will leave the compression level and any other attributes that may have been +- set unchanged. ++ set unchanged. total_in, total_out, adler, and msg are initialized. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). + */ + +-ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, +- int level, +- int strategy)); ++ZEXTERN int ZEXPORT deflateParams(z_streamp strm, ++ int level, ++ int strategy); + /* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2(). This can be +@@ -729,7 +730,7 @@ ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + Then no more input data should be provided before the deflateParams() call. + If this is done, the old level and strategy will be applied to the data + compressed before deflateParams(), and the new level and strategy will be +- applied to the the data compressed after deflateParams(). ++ applied to the data compressed after deflateParams(). + + deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream + state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if +@@ -740,11 +741,11 @@ ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + retried with more output space. + */ + +-ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, +- int good_length, +- int max_lazy, +- int nice_length, +- int max_chain)); ++ZEXTERN int ZEXPORT deflateTune(z_streamp strm, ++ int good_length, ++ int max_lazy, ++ int nice_length, ++ int max_chain); + /* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for +@@ -757,8 +758,8 @@ ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +-ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, +- uLong sourceLen)); ++ZEXTERN uLong ZEXPORT deflateBound(z_streamp strm, ++ uLong sourceLen); + /* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() or +@@ -772,9 +773,9 @@ ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + than Z_FINISH or Z_NO_FLUSH are used. + */ + +-ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, +- unsigned *pending, +- int *bits)); ++ZEXTERN int ZEXPORT deflatePending(z_streamp strm, ++ unsigned *pending, ++ int *bits); + /* + deflatePending() returns the number of bytes and bits of output that have + been generated, but not yet provided in the available output. The bytes not +@@ -787,9 +788,9 @@ ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, + stream state was inconsistent. + */ + +-ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, +- int bits, +- int value)); ++ZEXTERN int ZEXPORT deflatePrime(z_streamp strm, ++ int bits, ++ int value); + /* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the bits +@@ -804,8 +805,8 @@ ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + source stream state was inconsistent. + */ + +-ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, +- gz_headerp head)); ++ZEXTERN int ZEXPORT deflateSetHeader(z_streamp strm, ++ gz_headerp head); + /* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called +@@ -821,16 +822,17 @@ ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, +- the time set to zero, and os set to 255, with no extra, name, or comment +- fields. The gzip header is returned to the default state by deflateReset(). ++ the time set to zero, and os set to the current operating system, with no ++ extra, name, or comment fields. The gzip header is returned to the default ++ state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. + */ + + /* +-ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, +- int windowBits)); ++ZEXTERN int ZEXPORT inflateInit2(z_streamp strm, ++ int windowBits); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized +@@ -883,9 +885,9 @@ ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + deferred until inflate() is called. + */ + +-ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, +- const Bytef *dictionary, +- uInt dictLength)); ++ZEXTERN int ZEXPORT inflateSetDictionary(z_streamp strm, ++ const Bytef *dictionary, ++ uInt dictLength); + /* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, +@@ -906,22 +908,22 @@ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + inflate(). + */ + +-ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm, +- Bytef *dictionary, +- uInt *dictLength)); ++ZEXTERN int ZEXPORT inflateGetDictionary(z_streamp strm, ++ Bytef *dictionary, ++ uInt *dictLength); + /* + Returns the sliding dictionary being maintained by inflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If inflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. +- Similary, if dictLength is Z_NULL, then it is not set. ++ Similarly, if dictLength is Z_NULL, then it is not set. + + inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. + */ + +-ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); ++ZEXTERN int ZEXPORT inflateSync(z_streamp strm); + /* + Skips invalid compressed data until a possible full flush point (see above + for the description of deflate with Z_FULL_FLUSH) can be found, or until all +@@ -934,14 +936,14 @@ ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); + inflateSync returns Z_OK if a possible full flush point has been found, + Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point + has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. +- In the success case, the application may save the current current value of +- total_in which indicates where valid compressed data was found. In the +- error case, the application may repeatedly call inflateSync, providing more +- input each time, until success or end of the input data. ++ In the success case, the application may save the current value of total_in ++ which indicates where valid compressed data was found. In the error case, ++ the application may repeatedly call inflateSync, providing more input each ++ time, until success or end of the input data. + */ + +-ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, +- z_streamp source)); ++ZEXTERN int ZEXPORT inflateCopy(z_streamp dest, ++ z_streamp source); + /* + Sets the destination stream as a complete copy of the source stream. + +@@ -956,18 +958,19 @@ ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + destination. + */ + +-ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); ++ZEXTERN int ZEXPORT inflateReset(z_streamp strm); + /* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate the internal decompression state. The + stream will keep attributes that may have been set by inflateInit2. ++ total_in, total_out, adler, and msg are initialized. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). + */ + +-ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, +- int windowBits)); ++ZEXTERN int ZEXPORT inflateReset2(z_streamp strm, ++ int windowBits); + /* + This function is the same as inflateReset, but it also permits changing + the wrap and window size requests. The windowBits parameter is interpreted +@@ -980,9 +983,9 @@ ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, + the windowBits parameter is invalid. + */ + +-ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, +- int bits, +- int value)); ++ZEXTERN int ZEXPORT inflatePrime(z_streamp strm, ++ int bits, ++ int value); + /* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the +@@ -1001,7 +1004,7 @@ ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, + stream state was inconsistent. + */ + +-ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); ++ZEXTERN long ZEXPORT inflateMark(z_streamp strm); + /* + This function returns two values, one in the lower 16 bits of the return + value, and the other in the remaining upper bits, obtained by shifting the +@@ -1029,8 +1032,8 @@ ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); + source stream state was inconsistent. + */ + +-ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, +- gz_headerp head)); ++ZEXTERN int ZEXPORT inflateGetHeader(z_streamp strm, ++ gz_headerp head); + /* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after +@@ -1070,8 +1073,8 @@ ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, + */ + + /* +-ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, +- unsigned char FAR *window)); ++ZEXTERN int ZEXPORT inflateBackInit(z_streamp strm, int windowBits, ++ unsigned char FAR *window); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized +@@ -1091,13 +1094,13 @@ ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + the version of the header file. + */ + +-typedef unsigned (*in_func) OF((void FAR *, +- z_const unsigned char FAR * FAR *)); +-typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); ++typedef unsigned (*in_func)(void FAR *, ++ z_const unsigned char FAR * FAR *); ++typedef int (*out_func)(void FAR *, unsigned char FAR *, unsigned); + +-ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, +- in_func in, void FAR *in_desc, +- out_func out, void FAR *out_desc)); ++ZEXTERN int ZEXPORT inflateBack(z_streamp strm, ++ in_func in, void FAR *in_desc, ++ out_func out, void FAR *out_desc); + /* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is potentially more efficient than +@@ -1165,7 +1168,7 @@ ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, + cannot return Z_OK. + */ + +-ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); ++ZEXTERN int ZEXPORT inflateBackEnd(z_streamp strm); + /* + All memory allocated by inflateBackInit() is freed. + +@@ -1173,7 +1176,7 @@ ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); + state was inconsistent. + */ + +-ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); ++ZEXTERN uLong ZEXPORT zlibCompileFlags(void); + /* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: +@@ -1226,8 +1229,8 @@ ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); + you need special options. + */ + +-ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, +- const Bytef *source, uLong sourceLen)); ++ZEXTERN int ZEXPORT compress(Bytef *dest, uLongf *destLen, ++ const Bytef *source, uLong sourceLen); + /* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size +@@ -1241,9 +1244,9 @@ ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + buffer. + */ + +-ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, +- const Bytef *source, uLong sourceLen, +- int level)); ++ZEXTERN int ZEXPORT compress2(Bytef *dest, uLongf *destLen, ++ const Bytef *source, uLong sourceLen, ++ int level); + /* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte +@@ -1257,15 +1260,15 @@ ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + Z_STREAM_ERROR if the level parameter is invalid. + */ + +-ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); ++ZEXTERN uLong ZEXPORT compressBound(uLong sourceLen); + /* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before a + compress() or compress2() call to allocate the destination buffer. + */ + +-ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, +- const Bytef *source, uLong sourceLen)); ++ZEXTERN int ZEXPORT uncompress(Bytef *dest, uLongf *destLen, ++ const Bytef *source, uLong sourceLen); + /* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size +@@ -1282,8 +1285,8 @@ ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + buffer with the uncompressed data up to that point. + */ + +-ZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest, uLongf *destLen, +- const Bytef *source, uLong *sourceLen)); ++ZEXTERN int ZEXPORT uncompress2(Bytef *dest, uLongf *destLen, ++ const Bytef *source, uLong *sourceLen); + /* + Same as uncompress, except that sourceLen is a pointer, where the + length of the source is *sourceLen. On return, *sourceLen is the number of +@@ -1302,7 +1305,7 @@ ZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest, uLongf *destLen, + typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ + + /* +-ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); ++ZEXTERN gzFile ZEXPORT gzopen(const char *path, const char *mode); + + Open the gzip (.gz) file at path for reading and decompressing, or + compressing and writing. The mode parameter is as in fopen ("rb" or "wb") +@@ -1339,7 +1342,7 @@ ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); + file could not be opened. + */ + +-ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); ++ZEXTERN gzFile ZEXPORT gzdopen(int fd, const char *mode); + /* + Associate a gzFile with the file descriptor fd. File descriptors are + obtained from calls like open, dup, creat, pipe or fileno (if the file has +@@ -1362,7 +1365,7 @@ ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); + will not detect if fd is invalid (unless fd is -1). + */ + +-ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); ++ZEXTERN int ZEXPORT gzbuffer(gzFile file, unsigned size); + /* + Set the internal buffer size used by this library's functions for file to + size. The default buffer size is 8192 bytes. This function must be called +@@ -1378,7 +1381,7 @@ ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); + too late. + */ + +-ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); ++ZEXTERN int ZEXPORT gzsetparams(gzFile file, int level, int strategy); + /* + Dynamically update the compression level and strategy for file. See the + description of deflateInit2 for the meaning of these parameters. Previously +@@ -1389,7 +1392,7 @@ ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); + or Z_MEM_ERROR if there is a memory allocation error. + */ + +-ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); ++ZEXTERN int ZEXPORT gzread(gzFile file, voidp buf, unsigned len); + /* + Read and decompress up to len uncompressed bytes from file into buf. If + the input file is not in gzip format, gzread copies the given number of +@@ -1419,8 +1422,8 @@ ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); + Z_STREAM_ERROR. + */ + +-ZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems, +- gzFile file)); ++ZEXTERN z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems, ++ gzFile file); + /* + Read and decompress up to nitems items of size size from file into buf, + otherwise operating as gzread() does. This duplicates the interface of +@@ -1437,22 +1440,22 @@ ZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems, + + In the event that the end of file is reached and only a partial item is + available at the end, i.e. the remaining uncompressed data length is not a +- multiple of size, then the final partial item is nevetheless read into buf ++ multiple of size, then the final partial item is nevertheless read into buf + and the end-of-file flag is set. The length of the partial item read is not + provided, but could be inferred from the result of gztell(). This behavior + is the same as the behavior of fread() implementations in common libraries, + but it prevents the direct use of gzfread() to read a concurrently written +- file, reseting and retrying on end-of-file, when size is not 1. ++ file, resetting and retrying on end-of-file, when size is not 1. + */ + +-ZEXTERN int ZEXPORT gzwrite OF((gzFile file, voidpc buf, unsigned len)); ++ZEXTERN int ZEXPORT gzwrite(gzFile file, voidpc buf, unsigned len); + /* + Compress and write the len uncompressed bytes at buf to file. gzwrite + returns the number of uncompressed bytes written or 0 in case of error. + */ + +-ZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size, +- z_size_t nitems, gzFile file)); ++ZEXTERN z_size_t ZEXPORT gzfwrite(voidpc buf, z_size_t size, ++ z_size_t nitems, gzFile file); + /* + Compress and write nitems items of size size from buf to file, duplicating + the interface of stdio's fwrite(), with size_t request and return types. If +@@ -1465,7 +1468,7 @@ ZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size, + is returned, and the error state is set to Z_STREAM_ERROR. + */ + +-ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); ++ZEXTERN int ZEXPORTVA gzprintf(gzFile file, const char *format, ...); + /* + Convert, format, compress, and write the arguments (...) to file under + control of the string format, as in fprintf. gzprintf returns the number of +@@ -1480,7 +1483,7 @@ ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); + This can be determined using zlibCompileFlags(). + */ + +-ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); ++ZEXTERN int ZEXPORT gzputs(gzFile file, const char *s); + /* + Compress and write the given null-terminated string s to file, excluding + the terminating null character. +@@ -1488,7 +1491,7 @@ ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); + gzputs returns the number of characters written, or -1 in case of error. + */ + +-ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); ++ZEXTERN char * ZEXPORT gzgets(gzFile file, char *buf, int len); + /* + Read and decompress bytes from file into buf, until len-1 characters are + read, or until a newline character is read and transferred to buf, or an +@@ -1502,13 +1505,13 @@ ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); + buf are indeterminate. + */ + +-ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); ++ZEXTERN int ZEXPORT gzputc(gzFile file, int c); + /* + Compress and write c, converted to an unsigned char, into file. gzputc + returns the value that was written, or -1 in case of error. + */ + +-ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); ++ZEXTERN int ZEXPORT gzgetc(gzFile file); + /* + Read and decompress one byte from file. gzgetc returns this byte or -1 + in case of end of file or error. This is implemented as a macro for speed. +@@ -1517,7 +1520,7 @@ ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); + points to has been clobbered or not. + */ + +-ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); ++ZEXTERN int ZEXPORT gzungetc(int c, gzFile file); + /* + Push c back onto the stream for file to be read as the first character on + the next read. At least one character of push-back is always allowed. +@@ -1529,7 +1532,7 @@ ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); + gzseek() or gzrewind(). + */ + +-ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); ++ZEXTERN int ZEXPORT gzflush(gzFile file, int flush); + /* + Flush all pending output to file. The parameter flush is as in the + deflate() function. The return value is the zlib error number (see function +@@ -1545,8 +1548,8 @@ ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); + */ + + /* +-ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, +- z_off_t offset, int whence)); ++ZEXTERN z_off_t ZEXPORT gzseek(gzFile file, ++ z_off_t offset, int whence); + + Set the starting position to offset relative to whence for the next gzread + or gzwrite on file. The offset represents a number of bytes in the +@@ -1564,7 +1567,7 @@ ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + would be before the current position. + */ + +-ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); ++ZEXTERN int ZEXPORT gzrewind(gzFile file); + /* + Rewind file. This function is supported only for reading. + +@@ -1572,7 +1575,7 @@ ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); + */ + + /* +-ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); ++ZEXTERN z_off_t ZEXPORT gztell(gzFile file); + + Return the starting position for the next gzread or gzwrite on file. + This position represents a number of bytes in the uncompressed data stream, +@@ -1583,7 +1586,7 @@ ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); + */ + + /* +-ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); ++ZEXTERN z_off_t ZEXPORT gzoffset(gzFile file); + + Return the current compressed (actual) read or write offset of file. This + offset includes the count of bytes that precede the gzip stream, for example +@@ -1592,7 +1595,7 @@ ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); + be used for a progress indicator. On error, gzoffset() returns -1. + */ + +-ZEXTERN int ZEXPORT gzeof OF((gzFile file)); ++ZEXTERN int ZEXPORT gzeof(gzFile file); + /* + Return true (1) if the end-of-file indicator for file has been set while + reading, false (0) otherwise. Note that the end-of-file indicator is set +@@ -1607,7 +1610,7 @@ ZEXTERN int ZEXPORT gzeof OF((gzFile file)); + has grown since the previous end of file was detected. + */ + +-ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); ++ZEXTERN int ZEXPORT gzdirect(gzFile file); + /* + Return true (1) if file is being copied directly while reading, or false + (0) if file is a gzip stream being decompressed. +@@ -1628,7 +1631,7 @@ ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); + gzip file reading and decompression, which may not be desired.) + */ + +-ZEXTERN int ZEXPORT gzclose OF((gzFile file)); ++ZEXTERN int ZEXPORT gzclose(gzFile file); + /* + Flush all pending output for file, if necessary, close file and + deallocate the (de)compression state. Note that once file is closed, you +@@ -1641,8 +1644,8 @@ ZEXTERN int ZEXPORT gzclose OF((gzFile file)); + last read ended in the middle of a gzip stream, or Z_OK on success. + */ + +-ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); +-ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); ++ZEXTERN int ZEXPORT gzclose_r(gzFile file); ++ZEXTERN int ZEXPORT gzclose_w(gzFile file); + /* + Same as gzclose(), but gzclose_r() is only for use when reading, and + gzclose_w() is only for use when writing or appending. The advantage to +@@ -1653,7 +1656,7 @@ ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); + zlib library. + */ + +-ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); ++ZEXTERN const char * ZEXPORT gzerror(gzFile file, int *errnum); + /* + Return the error message for the last error which occurred on file. + errnum is set to zlib error number. If an error occurred in the file system +@@ -1669,7 +1672,7 @@ ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); + functions above that do not distinguish those cases in their return values. + */ + +-ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); ++ZEXTERN void ZEXPORT gzclearerr(gzFile file); + /* + Clear the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip +@@ -1686,7 +1689,7 @@ ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); + library. + */ + +-ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); ++ZEXTERN uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len); + /* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. An Adler-32 value is in the range of a 32-bit +@@ -1706,15 +1709,15 @@ ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); + if (adler != original_adler) error(); + */ + +-ZEXTERN uLong ZEXPORT adler32_z OF((uLong adler, const Bytef *buf, +- z_size_t len)); ++ZEXTERN uLong ZEXPORT adler32_z(uLong adler, const Bytef *buf, ++ z_size_t len); + /* + Same as adler32(), but with a size_t length. + */ + + /* +-ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, +- z_off_t len2)); ++ZEXTERN uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, ++ z_off_t len2); + + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for +@@ -1724,7 +1727,7 @@ ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, + negative, the result has no meaning or utility. + */ + +-ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); ++ZEXTERN uLong ZEXPORT crc32(uLong crc, const Bytef *buf, uInt len); + /* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. A CRC-32 value is in the range of a 32-bit unsigned integer. +@@ -1742,30 +1745,30 @@ ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); + if (crc != original_crc) error(); + */ + +-ZEXTERN uLong ZEXPORT crc32_z OF((uLong crc, const Bytef *buf, +- z_size_t len)); ++ZEXTERN uLong ZEXPORT crc32_z(uLong crc, const Bytef *buf, ++ z_size_t len); + /* + Same as crc32(), but with a size_t length. + */ + + /* +-ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); ++ZEXTERN uLong ZEXPORT crc32_combine(uLong crc1, uLong crc2, z_off_t len2); + + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and +- len2. ++ len2. len2 must be non-negative. + */ + + /* +-ZEXTERN uLong ZEXPORT crc32_combine_gen OF((z_off_t len2)); ++ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t len2); + + Return the operator corresponding to length len2, to be used with +- crc32_combine_op(). ++ crc32_combine_op(). len2 must be non-negative. + */ + +-ZEXTERN uLong ZEXPORT crc32_combine_op OF((uLong crc1, uLong crc2, uLong op)); ++ZEXTERN uLong ZEXPORT crc32_combine_op(uLong crc1, uLong crc2, uLong op); + /* + Give the same result as crc32_combine(), using op in place of len2. op is + is generated from len2 by crc32_combine_gen(). This will be faster than +@@ -1778,20 +1781,20 @@ ZEXTERN uLong ZEXPORT crc32_combine_op OF((uLong crc1, uLong crc2, uLong op)); + /* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +-ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, +- const char *version, int stream_size)); +-ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, +- const char *version, int stream_size)); +-ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, +- int windowBits, int memLevel, +- int strategy, const char *version, +- int stream_size)); +-ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, +- const char *version, int stream_size)); +-ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, +- unsigned char FAR *window, +- const char *version, +- int stream_size)); ++ZEXTERN int ZEXPORT deflateInit_(z_streamp strm, int level, ++ const char *version, int stream_size); ++ZEXTERN int ZEXPORT inflateInit_(z_streamp strm, ++ const char *version, int stream_size); ++ZEXTERN int ZEXPORT deflateInit2_(z_streamp strm, int level, int method, ++ int windowBits, int memLevel, ++ int strategy, const char *version, ++ int stream_size); ++ZEXTERN int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, ++ const char *version, int stream_size); ++ZEXTERN int ZEXPORT inflateBackInit_(z_streamp strm, int windowBits, ++ unsigned char FAR *window, ++ const char *version, ++ int stream_size); + #ifdef Z_PREFIX_SET + # define z_deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +@@ -1836,7 +1839,7 @@ struct gzFile_s { + unsigned char *next; + z_off64_t pos; + }; +-ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ ++ZEXTERN int ZEXPORT gzgetc_(gzFile file); /* backward compatibility */ + #ifdef Z_PREFIX_SET + # undef z_gzgetc + # define z_gzgetc(g) \ +@@ -1853,13 +1856,13 @@ ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ + * without large file support, _LFS64_LARGEFILE must also be true + */ + #ifdef Z_LARGE64 +- ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); +- ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); +- ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); +- ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); +- ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); +- ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); +- ZEXTERN uLong ZEXPORT crc32_combine_gen64 OF((z_off64_t)); ++ ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *); ++ ZEXTERN z_off64_t ZEXPORT gzseek64(gzFile, z_off64_t, int); ++ ZEXTERN z_off64_t ZEXPORT gztell64(gzFile); ++ ZEXTERN z_off64_t ZEXPORT gzoffset64(gzFile); ++ ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off64_t); ++ ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off64_t); ++ ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off64_t); + #endif + + #if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) +@@ -1881,50 +1884,50 @@ ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ + # define crc32_combine_gen crc32_combine_gen64 + # endif + # ifndef Z_LARGE64 +- ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); +- ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); +- ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); +- ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); +- ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); +- ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +- ZEXTERN uLong ZEXPORT crc32_combine_gen64 OF((z_off_t)); ++ ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *); ++ ZEXTERN z_off_t ZEXPORT gzseek64(gzFile, z_off_t, int); ++ ZEXTERN z_off_t ZEXPORT gztell64(gzFile); ++ ZEXTERN z_off_t ZEXPORT gzoffset64(gzFile); ++ ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off_t); ++ ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off_t); ++ ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off_t); + # endif + #else +- ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); +- ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); +- ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); +- ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); +- ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); +- ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); +- ZEXTERN uLong ZEXPORT crc32_combine_gen OF((z_off_t)); ++ ZEXTERN gzFile ZEXPORT gzopen(const char *, const char *); ++ ZEXTERN z_off_t ZEXPORT gzseek(gzFile, z_off_t, int); ++ ZEXTERN z_off_t ZEXPORT gztell(gzFile); ++ ZEXTERN z_off_t ZEXPORT gzoffset(gzFile); ++ ZEXTERN uLong ZEXPORT adler32_combine(uLong, uLong, z_off_t); ++ ZEXTERN uLong ZEXPORT crc32_combine(uLong, uLong, z_off_t); ++ ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t); + #endif + + #else /* Z_SOLO */ + +- ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); +- ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); +- ZEXTERN uLong ZEXPORT crc32_combine_gen OF((z_off_t)); ++ ZEXTERN uLong ZEXPORT adler32_combine(uLong, uLong, z_off_t); ++ ZEXTERN uLong ZEXPORT crc32_combine(uLong, uLong, z_off_t); ++ ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t); + + #endif /* !Z_SOLO */ + + /* undocumented functions */ +-ZEXTERN const char * ZEXPORT zError OF((int)); +-ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); +-ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); +-ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); +-ZEXTERN int ZEXPORT inflateValidate OF((z_streamp, int)); +-ZEXTERN unsigned long ZEXPORT inflateCodesUsed OF ((z_streamp)); +-ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); +-ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); ++ZEXTERN const char * ZEXPORT zError(int); ++ZEXTERN int ZEXPORT inflateSyncPoint(z_streamp); ++ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table(void); ++ZEXTERN int ZEXPORT inflateUndermine(z_streamp, int); ++ZEXTERN int ZEXPORT inflateValidate(z_streamp, int); ++ZEXTERN unsigned long ZEXPORT inflateCodesUsed(z_streamp); ++ZEXTERN int ZEXPORT inflateResetKeep(z_streamp); ++ZEXTERN int ZEXPORT deflateResetKeep(z_streamp); + #if defined(_WIN32) && !defined(Z_SOLO) +-ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, +- const char *mode)); ++ZEXTERN gzFile ZEXPORT gzopen_w(const wchar_t *path, ++ const char *mode); + #endif + #if defined(STDC) || defined(Z_HAVE_STDARG_H) + # ifndef Z_SOLO +-ZEXTERN int ZEXPORTVA gzvprintf Z_ARG((gzFile file, +- const char *format, +- va_list va)); ++ZEXTERN int ZEXPORTVA gzvprintf(gzFile file, ++ const char *format, ++ va_list va); + # endif + #endif + +diff --git a/src/zlib/zutil.c b/src/zlib/zutil.c +index dcab28a0d..b1c5d2d3c 100644 +--- a/src/zlib/zutil.c ++++ b/src/zlib/zutil.c +@@ -24,13 +24,11 @@ z_const char * const z_errmsg[10] = { + }; + + +-const char * ZEXPORT zlibVersion() +-{ ++const char * ZEXPORT zlibVersion(void) { + return ZLIB_VERSION; + } + +-uLong ZEXPORT zlibCompileFlags() +-{ ++uLong ZEXPORT zlibCompileFlags(void) { + uLong flags; + + flags = 0; +@@ -61,9 +59,11 @@ uLong ZEXPORT zlibCompileFlags() + #ifdef ZLIB_DEBUG + flags += 1 << 8; + #endif ++ /* + #if defined(ASMV) || defined(ASMINF) + flags += 1 << 9; + #endif ++ */ + #ifdef ZLIB_WINAPI + flags += 1 << 10; + #endif +@@ -119,9 +119,7 @@ uLong ZEXPORT zlibCompileFlags() + # endif + int ZLIB_INTERNAL z_verbose = verbose; + +-void ZLIB_INTERNAL z_error (m) +- char *m; +-{ ++void ZLIB_INTERNAL z_error(char *m) { + fprintf(stderr, "%s\n", m); + exit(1); + } +@@ -130,9 +128,7 @@ void ZLIB_INTERNAL z_error (m) + /* exported to allow conversion of error code to string for compress() and + * uncompress() + */ +-const char * ZEXPORT zError(err) +- int err; +-{ ++const char * ZEXPORT zError(int err) { + return ERR_MSG(err); + } + +@@ -146,22 +142,14 @@ const char * ZEXPORT zError(err) + + #ifndef HAVE_MEMCPY + +-void ZLIB_INTERNAL zmemcpy(dest, source, len) +- Bytef* dest; +- const Bytef* source; +- uInt len; +-{ ++void ZLIB_INTERNAL zmemcpy(Bytef* dest, const Bytef* source, uInt len) { + if (len == 0) return; + do { + *dest++ = *source++; /* ??? to be unrolled */ + } while (--len != 0); + } + +-int ZLIB_INTERNAL zmemcmp(s1, s2, len) +- const Bytef* s1; +- const Bytef* s2; +- uInt len; +-{ ++int ZLIB_INTERNAL zmemcmp(const Bytef* s1, const Bytef* s2, uInt len) { + uInt j; + + for (j = 0; j < len; j++) { +@@ -170,10 +158,7 @@ int ZLIB_INTERNAL zmemcmp(s1, s2, len) + return 0; + } + +-void ZLIB_INTERNAL zmemzero(dest, len) +- Bytef* dest; +- uInt len; +-{ ++void ZLIB_INTERNAL zmemzero(Bytef* dest, uInt len) { + if (len == 0) return; + do { + *dest++ = 0; /* ??? to be unrolled */ +@@ -214,8 +199,7 @@ local ptr_table table[MAX_PTR]; + * a protected system like OS/2. Use Microsoft C instead. + */ + +-voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size) +-{ ++voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, unsigned size) { + voidpf buf; + ulg bsize = (ulg)items*size; + +@@ -240,8 +224,7 @@ voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size) + return buf; + } + +-void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +-{ ++void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) { + int n; + + (void)opaque; +@@ -277,14 +260,12 @@ void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) + # define _hfree hfree + #endif + +-voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size) +-{ ++voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, uInt items, uInt size) { + (void)opaque; + return _halloc((long)items, size); + } + +-void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +-{ ++void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) { + (void)opaque; + _hfree(ptr); + } +@@ -297,25 +278,18 @@ void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) + #ifndef MY_ZCALLOC /* Any system without a special alloc function */ + + #ifndef STDC +-extern voidp malloc OF((uInt size)); +-extern voidp calloc OF((uInt items, uInt size)); +-extern void free OF((voidpf ptr)); ++extern voidp malloc(uInt size); ++extern voidp calloc(uInt items, uInt size); ++extern void free(voidpf ptr); + #endif + +-voidpf ZLIB_INTERNAL zcalloc (opaque, items, size) +- voidpf opaque; +- unsigned items; +- unsigned size; +-{ ++voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, unsigned size) { + (void)opaque; + return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : + (voidpf)calloc(items, size); + } + +-void ZLIB_INTERNAL zcfree (opaque, ptr) +- voidpf opaque; +- voidpf ptr; +-{ ++void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) { + (void)opaque; + free(ptr); + } +diff --git a/src/zlib/zutil.h b/src/zlib/zutil.h +index d9a20ae1b..48dd7feba 100644 +--- a/src/zlib/zutil.h ++++ b/src/zlib/zutil.h +@@ -1,5 +1,5 @@ + /* zutil.h -- internal interface and configuration of the compression library +- * Copyright (C) 1995-2022 Jean-loup Gailly, Mark Adler ++ * Copyright (C) 1995-2024 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +@@ -56,7 +56,7 @@ typedef unsigned long ulg; + extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ + /* (size given to avoid silly warnings with Visual C++) */ + +-#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] ++#define ERR_MSG(err) z_errmsg[(err) < -6 || (err) > 2 ? 9 : 2 - (err)] + + #define ERR_RETURN(strm,err) \ + return (strm->msg = ERR_MSG(err), (err)) +@@ -137,17 +137,8 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ + # endif + #endif + +-#if defined(MACOS) || defined(TARGET_OS_MAC) ++#if defined(MACOS) + # define OS_CODE 7 +-# ifndef Z_SOLO +-# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +-# include /* for fdopen */ +-# else +-# ifndef fdopen +-# define fdopen(fd,mode) NULL /* No fdopen() */ +-# endif +-# endif +-# endif + #endif + + #ifdef __acorn +@@ -170,18 +161,6 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ + # define OS_CODE 19 + #endif + +-#if defined(_BEOS_) || defined(RISCOS) +-# define fdopen(fd,mode) NULL /* No fdopen() */ +-#endif +- +-#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX +-# if defined(_WIN32_WCE) +-# define fdopen(fd,mode) NULL /* No fdopen() */ +-# else +-# define fdopen(fd,type) _fdopen(fd,type) +-# endif +-#endif +- + #if defined(__BORLANDC__) && !defined(MSDOS) + #pragma warn -8004 + #pragma warn -8008 +@@ -191,8 +170,9 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ + /* provide prototypes for these when building zlib without LFS */ + #if !defined(_WIN32) && \ + (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0) +- ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); +- ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); ++ ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off_t); ++ ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off_t); ++ ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off_t); + #endif + + /* common defaults */ +@@ -231,16 +211,16 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ + # define zmemzero(dest, len) memset(dest, 0, len) + # endif + #else +- void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); +- int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); +- void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len)); ++ void ZLIB_INTERNAL zmemcpy(Bytef* dest, const Bytef* source, uInt len); ++ int ZLIB_INTERNAL zmemcmp(const Bytef* s1, const Bytef* s2, uInt len); ++ void ZLIB_INTERNAL zmemzero(Bytef* dest, uInt len); + #endif + + /* Diagnostic functions */ + #ifdef ZLIB_DEBUG + # include + extern int ZLIB_INTERNAL z_verbose; +- extern void ZLIB_INTERNAL z_error OF((char *m)); ++ extern void ZLIB_INTERNAL z_error(char *m); + # define Assert(cond,msg) {if(!(cond)) z_error(msg);} + # define Trace(x) {if (z_verbose>=0) fprintf x ;} + # define Tracev(x) {if (z_verbose>0) fprintf x ;} +@@ -257,9 +237,9 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ + #endif + + #ifndef Z_SOLO +- voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items, +- unsigned size)); +- void ZLIB_INTERNAL zcfree OF((voidpf opaque, voidpf ptr)); ++ voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, ++ unsigned size); ++ void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr); + #endif + + #define ZALLOC(strm, items, size) \ +-- +2.44.0 + diff --git a/0008-imp-Replaced-custom-XML-parsing-with-QXmlStreamReade.patch b/0008-imp-Replaced-custom-XML-parsing-with-QXmlStreamReade.patch new file mode 100644 index 0000000..64ec9cb --- /dev/null +++ b/0008-imp-Replaced-custom-XML-parsing-with-QXmlStreamReade.patch @@ -0,0 +1,1150 @@ +From 6c58d8d7867ce39a4eb34d94bcc54b9f6969ba10 Mon Sep 17 00:00:00 2001 +From: Julian Sikorski +Date: Fri, 8 Mar 2024 15:52:22 +0100 +Subject: [PATCH 08/10] imp: Replaced custom XML parsing with QXmlStreamReader. + (#42) + +* Refactored machinelist.{cpp,h} to use QXmlStreamReader. +* Refactored softwarelist.cpp to use QXmlStreamReader. +* Refactored deviceconfigurator.cpp to QXmlStreamReader. +* Refactored romalyzer.cpp to QXmlStreamReader. +* Refactored qmc2main.cpp to QXmlStreamReader. +--- + src/deviceconfigurator.cpp | 88 +++-- + src/machinelist.cpp | 639 ++++++++++++++++++------------------- + src/machinelist.h | 6 +- + src/qmc2main.cpp | 64 ++-- + src/romalyzer.cpp | 99 +++--- + src/softwarelist.cpp | 60 ++-- + 6 files changed, 466 insertions(+), 490 deletions(-) + +diff --git a/src/deviceconfigurator.cpp b/src/deviceconfigurator.cpp +index 6b06ebc4e..9b7b104a7 100644 +--- a/src/deviceconfigurator.cpp ++++ b/src/deviceconfigurator.cpp +@@ -2006,57 +2006,55 @@ QString DeviceTreeXmlHandler::getXmlData(const QString &machine) + + QString DeviceTreeXmlHandler::lookupDescription(const QString &machine) + { +- QStringList xmlLines(qmc2MachineList->xmlDb()->xml(machine).split('\n')); +- if ( xmlLines.count() > 1 ) { +- int index = 0; +- while ( index < xmlLines.count() && !xmlLines.at(index).startsWith("") ) +- index++; +- QString description(xmlLines.at(index)); +- description.remove("").remove(""); +- QTextDocument doc; +- doc.setHtml(description); +- return doc.toPlainText(); +- } else +- return QString(); ++ QXmlStreamReader xmlMachineEntry(qmc2MachineList->xmlDb()->xml(machine)); ++ if ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "machine" ) { ++ while ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "description" ) { ++ QString description(xmlMachineEntry.readElementText()); ++ QTextDocument doc; ++ doc.setHtml(description); ++ return doc.toPlainText(); ++ } else ++ xmlMachineEntry.skipCurrentElement(); ++ } ++ } ++ } ++ return QString(); + } + + QString DeviceTreeXmlHandler::lookupBiosOptions(const QString &machine, QStringList *bioses, QStringList *biosDescriptions) + { +- QStringList xmlLines(qmc2MachineList->xmlDb()->xml(machine).split('\n')); +- if ( xmlLines.count() > 1 ) { +- int index = 0; +- QString defaultOption; +- while ( index < xmlLines.count() ) { +- if ( xmlLines.at(index).startsWith("= 0 ) { +- startIndex += 6; +- int endIndex = xmlLines.at(index).indexOf("\"", startIndex); +- name = xmlLines.at(index).mid(startIndex, endIndex - startIndex); +- } +- startIndex = xmlLines.at(index).indexOf("description=\""); +- if ( startIndex >= 0 ) { +- startIndex += 13; +- int endIndex = xmlLines.at(index).indexOf("\"", startIndex); +- description = xmlLines.at(index).mid(startIndex, endIndex - startIndex); +- QTextDocument doc; +- doc.setHtml(description); +- description = doc.toPlainText(); +- } +- if ( !name.isEmpty() && !description.isEmpty() ) { +- bioses->append(name); +- biosDescriptions->append(description); +- if ( xmlLines.at(index).indexOf("default=\"yes\"") >= 0 ) +- defaultOption = name; +- } ++ QXmlStreamReader xmlMachineEntry(qmc2MachineList->xmlDb()->xml(machine)); ++ if ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "machine" ) { ++ QString defaultOption; ++ while ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "biosset" ) { ++ QString name; ++ QString description; ++ if ( xmlMachineEntry.attributes().hasAttribute("name") ) ++ name = xmlMachineEntry.attributes().value("name").toString(); ++ if ( xmlMachineEntry.attributes().hasAttribute("description") ) { ++ description = xmlMachineEntry.attributes().value("description").toString(); ++ QTextDocument doc; ++ doc.setHtml(description); ++ description = doc.toPlainText(); ++ } ++ if ( !name.isEmpty() && !description.isEmpty() ) { ++ bioses->append(name); ++ biosDescriptions->append(description); ++ if ( xmlMachineEntry.attributes().hasAttribute("default") && xmlMachineEntry.attributes().value("default").toString() == "yes" ) ++ defaultOption = name; ++ } ++ xmlMachineEntry.skipCurrentElement(); ++ } else ++ xmlMachineEntry.skipCurrentElement(); + } +- index++; ++ return defaultOption; + } +- return defaultOption; +- } else +- return QString(); ++ } ++ return QString(); + } + + bool FileChooserKeyEventFilter::eventFilter(QObject *obj, QEvent *event) +diff --git a/src/machinelist.cpp b/src/machinelist.cpp +index 4ccdc3c4b..7be2aa311 100644 +--- a/src/machinelist.cpp ++++ b/src/machinelist.cpp +@@ -892,14 +892,10 @@ void MachineList::verify(bool currentOnly) + verifyProc->start(command, args, QIODevice::ReadOnly | QIODevice::Text); + } + +-QString MachineList::value(QString element, QString attribute, bool translate) ++QString MachineList::value(QXmlStreamReader &element, QString attribute, bool translate) + { +- QString attributePattern(" " + attribute + "=\""); +- if ( element.contains(attributePattern) ) { +- QString valueString(element.remove(0, element.indexOf(attributePattern) + attributePattern.length())); +- valueString = valueString.remove(valueString.indexOf("\""), valueString.lastIndexOf(">")).replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'"); +- if ( valueString == ">" ) +- return QString(); ++ if ( element.attributes().hasAttribute(attribute) ) { ++ QString valueString(element.attributes().value(attribute).toString()); + if ( translate ) + return tr(valueString.toUtf8().constData()); + else +@@ -908,7 +904,7 @@ QString MachineList::value(QString element, QString attribute, bool translate) + return QString(); + } + +-void MachineList::insertAttributeItems(QTreeWidgetItem *parent, QString element, QStringList attributes, QStringList descriptions, bool translate) ++void MachineList::insertAttributeItems(QTreeWidgetItem *parent, QXmlStreamReader &element, QStringList attributes, QStringList descriptions, bool translate) + { + QList itemList; + for (int i = 0; i < attributes.count(); i++) { +@@ -923,7 +919,7 @@ void MachineList::insertAttributeItems(QTreeWidgetItem *parent, QString element, + parent->addChildren(itemList); + } + +-void MachineList::insertAttributeItems(QList *itemList, QString element, QStringList attributes, QStringList descriptions, bool translate) ++void MachineList::insertAttributeItems(QList *itemList, QXmlStreamReader &element, QStringList attributes, QStringList descriptions, bool translate) + { + for (int i = 0; i < attributes.count(); i++) { + QString valueString(value(element, attributes.at(i), translate)); +@@ -939,12 +935,7 @@ void MachineList::insertAttributeItems(QList *itemList, QStri + void MachineList::parseMachineDetail(QTreeWidgetItem *item) + { + QString machineName(item->text(QMC2_MACHINELIST_COLUMN_NAME)); +- QStringList xmlLines(xmlDb()->xml(machineName).split("\n", QString::SkipEmptyParts)); +- if ( xmlLines.count() < 2 ) { +- qmc2MainWindow->log(QMC2_LOG_FRONTEND, tr("WARNING: couldn't find machine information for '%1'").arg(machineName)); +- return; +- } +- int gamePos = 1; ++ QXmlStreamReader xmlMachineEntry(xmlDb()->xml(machineName)); + item->child(0)->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Updating")); + qmc2MainWindow->treeWidgetMachineList->viewport()->repaint(); + qApp->processEvents(); +@@ -955,259 +946,263 @@ void MachineList::parseMachineDetail(QTreeWidgetItem *item) + + attributes << "name" << "sourcefile" << "isbios" << "isdevice" << "runnable" << "cloneof" << "romof" << "sampleof"; + descriptions << tr("Name") << tr("Source file") << tr("Is BIOS?") << tr("Is device?") << tr("Runnable") << tr("Clone of") << tr("ROM of") << tr("Sample of"); +- element = xmlLines.at(gamePos - 1).simplified(); +- insertAttributeItems(&itemList, element, attributes, descriptions, true); +- QString endMark(""); +- +- while ( !xmlLines.at(gamePos).contains(endMark) ) { +- childItem = 0; +- element = xmlLines.at(gamePos).simplified(); +- if ( element.contains("") ) { +- content = element.remove("").remove(""); +- childItem = new QTreeWidgetItem(); +- childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Year")); +- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, content); +- } +- if ( element.contains("") ) { +- content = element.remove("").remove(""); +- content.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'"); +- childItem = new QTreeWidgetItem(); +- childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Manufacturer")); +- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, content); +- } +- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("ROM")); +- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name")); +- attributes.clear(); +- attributes << "bios" << "size" << "crc" << "sha1" << "merge" << "region" << "offset" << "status" << "optional"; +- descriptions.clear(); +- descriptions << tr("BIOS") << tr("Size") << tr("CRC") << tr("SHA-1") << tr("Merge") << tr("Region") << tr("Offset") << tr("Status") << tr("Optional"); +- insertAttributeItems(childItem, element, attributes, descriptions, true); +- } +- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Device reference")); +- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name")); +- } +- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Chip")); +- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name")); +- attributes.clear(); +- attributes << "tag" << "type" << "clock"; +- descriptions.clear(); +- descriptions << tr("Tag") << tr("Type") << tr("Clock"); +- insertAttributeItems(childItem, element, attributes, descriptions, true); +- } +- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Display")); +- attributes.clear(); +- attributes << "type" << "rotate" << "flipx" << "width" << "height" << "refresh" << "pixclock" << "htotal" << "hbend" << "hbstart" << "vtotal" << "vbend" << "vbstart"; +- descriptions.clear(); +- descriptions << tr("Type") << tr("Rotate") << tr("Flip-X") << tr("Width") << tr("Height") << tr("Refresh") << tr("Pixel clock") << tr("H-Total") << tr("H-Bend") << tr("HB-Start") << tr("V-Total") << tr("V-Bend") << tr("VB-Start"); +- insertAttributeItems(childItem, element, attributes, descriptions, true); +- } +- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Sound")); +- attributes.clear(); +- attributes << "channels"; +- descriptions.clear(); +- descriptions << tr("Channels"); +- insertAttributeItems(childItem, element, attributes, descriptions, true); +- } +- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Input")); +- attributes.clear(); +- attributes << "service" << "tilt" << "players" << "buttons" << "coins"; +- descriptions.clear(); +- descriptions << tr("Service") << tr("Tilt") << tr("Players") << tr("Buttons") << tr("Coins"); +- insertAttributeItems(childItem, element, attributes, descriptions, true); +- gamePos++; +- while ( xmlLines.at(gamePos).contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Control")); +- nextChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(subElement, "type", true)); +- attributes.clear(); +- attributes << "minimum" << "maximum" << "sensitivity" << "keydelta" << "reverse" << "player" << "buttons" << "ways"; +- descriptions.clear(); +- descriptions << tr("Minimum") << tr("Maximum") << tr("Sensitivity") << tr("Key Delta") << tr("Reverse") << tr("Player") << tr("Buttons") << tr("Ways"); +- insertAttributeItems(nextChildItem, subElement, attributes, descriptions, true); +- gamePos++; +- } +- } +- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("DIP switch")); +- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name", true)); +- gamePos++; +- while ( xmlLines.at(gamePos).contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("DIP value")); +- secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(subElement, "name", true)); +- attributes.clear(); +- attributes << "default"; +- descriptions.clear(); +- descriptions << tr("Default"); +- insertAttributeItems(secondChildItem, subElement, attributes, descriptions, true); +- gamePos++; +- } +- } +- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Configuration")); +- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name", true)); +- attributes.clear(); +- attributes << "tag" << "mask"; +- descriptions.clear(); +- descriptions << tr("Tag") << tr("Mask"); +- insertAttributeItems(childItem, element, attributes, descriptions, true); +- gamePos++; +- while ( xmlLines.at(gamePos).contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Setting")); +- secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(subElement, "name", true)); +- attributes.clear(); +- attributes << "value" << "default"; +- descriptions.clear(); +- descriptions << tr("Value") << tr("Default"); +- insertAttributeItems(secondChildItem, subElement, attributes, descriptions, true); +- gamePos++; +- } +- } +- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Driver")); +- attributes.clear(); +- attributes << "status" << "emulation" << "color" << "sound" << "graphic" << "cocktail" << "protection" << "savestate" << "palettesize"; +- descriptions.clear(); +- descriptions << tr("Status") << tr("Emulation") << tr("Color") << tr("Sound") << tr("Graphic") << tr("Cocktail") << tr("Protection") << tr("Save state") << tr("Palette size"); +- insertAttributeItems(childItem, element, attributes, descriptions, true); +- } +- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("BIOS set")); +- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name")); +- attributes.clear(); +- attributes << "description" << "default"; +- descriptions.clear(); +- descriptions << tr("Description") << tr("Default"); +- insertAttributeItems(childItem, element, attributes, descriptions, true); +- } +- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Sample")); +- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name")); +- } +- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Disk")); +- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name")); +- attributes.clear(); +- attributes << "md5" << "sha1" << "merge" << "region" << "index" << "status" << "optional"; +- descriptions.clear(); +- descriptions << tr("MD5") << tr("SHA-1") << tr("Merge") << tr("Region") << tr("Index") << tr("Status") << tr("Optional"); +- insertAttributeItems(childItem, element, attributes, descriptions, true); +- } +- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Adjuster")); +- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name")); +- attributes.clear(); +- attributes << "default"; +- descriptions.clear(); +- descriptions << tr("Default"); +- insertAttributeItems(childItem, element, attributes, descriptions, true); +- } +- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Software list")); +- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name")); +- attributes.clear(); +- attributes << "status"; +- descriptions.clear(); +- descriptions << tr("Status"); +- insertAttributeItems(childItem, element, attributes, descriptions, true); +- } +- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Category")); +- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name", true)); +- gamePos++; +- while ( xmlLines.at(gamePos).contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Item")); +- secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(subElement, "name", true)); +- attributes.clear(); +- attributes << "default"; +- descriptions.clear(); +- descriptions << tr("Default"); +- insertAttributeItems(secondChildItem, subElement, attributes, descriptions, true); +- gamePos++; +- } +- } +- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Device")); +- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "type", true)); +- attributes.clear(); +- attributes << "tag" << "mandatory" << "interface"; +- descriptions.clear(); +- descriptions << tr("Tag") << tr("Mandatory") << tr("Interface"); +- insertAttributeItems(childItem, element, attributes, descriptions, false); +- gamePos++; +- while ( xmlLines.at(gamePos).contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Instance")); +- secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(subElement, "name", false)); +- attributes.clear(); +- attributes << "briefname"; +- descriptions.clear(); +- descriptions << tr("Brief name"); +- insertAttributeItems(secondChildItem, element, attributes, descriptions, false); +- gamePos++; +- } +- while ( xmlLines.at(gamePos).contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Extension")); +- secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(subElement, "name", false)); +- gamePos++; +- } +- } +- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("RAM options")); +- while ( xmlLines.at(gamePos).contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Option")); +- int fromIndex = subElement.indexOf('>') + 1; +- int toIndex = subElement.indexOf('<', fromIndex); +- QString ramOptionValue(subElement.mid(fromIndex, toIndex - fromIndex)); +- secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, ramOptionValue); +- attributes.clear(); +- attributes << "default"; +- descriptions.clear(); +- descriptions << tr("Default"); +- insertAttributeItems(secondChildItem, subElement, attributes, descriptions, false); +- gamePos++; ++ ++ if ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "machine" ) { ++ insertAttributeItems(&itemList, xmlMachineEntry, attributes, descriptions, true); ++ while ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "year" ) { ++ content = xmlMachineEntry.readElementText(); ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Year")); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, content); ++ } else if ( xmlMachineEntry.name() =="manufacturer" ) { ++ content = xmlMachineEntry.readElementText(); ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Manufacturer")); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, content); ++ } else if ( xmlMachineEntry.name() == "rom" ) { ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("ROM")); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "name")); ++ attributes.clear(); ++ attributes << "bios" << "size" << "crc" << "sha1" << "merge" << "region" << "offset" << "status" << "optional"; ++ descriptions.clear(); ++ descriptions << tr("BIOS") << tr("Size") << tr("CRC") << tr("SHA-1") << tr("Merge") << tr("Region") << tr("Offset") << tr("Status") << tr("Optional"); ++ insertAttributeItems(childItem, xmlMachineEntry, attributes, descriptions, true); ++ xmlMachineEntry.skipCurrentElement(); ++ } else if ( xmlMachineEntry.name() == "device_ref" ) { ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Device reference")); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "name")); ++ xmlMachineEntry.skipCurrentElement(); ++ } else if ( xmlMachineEntry.name() == "chip") { ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Chip")); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "name")); ++ attributes.clear(); ++ attributes << "tag" << "type" << "clock"; ++ descriptions.clear(); ++ descriptions << tr("Tag") << tr("Type") << tr("Clock"); ++ insertAttributeItems(childItem, xmlMachineEntry, attributes, descriptions, true); ++ xmlMachineEntry.skipCurrentElement(); ++ } else if ( xmlMachineEntry.name() == "display" ) { ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Display")); ++ attributes.clear(); ++ attributes << "type" << "rotate" << "flipx" << "width" << "height" << "refresh" << "pixclock" << "htotal" << "hbend" << "hbstart" << "vtotal" << "vbend" << "vbstart"; ++ descriptions.clear(); ++ descriptions << tr("Type") << tr("Rotate") << tr("Flip-X") << tr("Width") << tr("Height") << tr("Refresh") << tr("Pixel clock") << tr("H-Total") << tr("H-Bend") << tr("HB-Start") << tr("V-Total") << tr("V-Bend") << tr("VB-Start"); ++ insertAttributeItems(childItem, xmlMachineEntry, attributes, descriptions, true); ++ xmlMachineEntry.skipCurrentElement(); ++ } else if ( xmlMachineEntry.name() == "sound" ) { ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Sound")); ++ attributes.clear(); ++ attributes << "channels"; ++ descriptions.clear(); ++ descriptions << tr("Channels"); ++ insertAttributeItems(childItem, xmlMachineEntry, attributes, descriptions, true); ++ xmlMachineEntry.skipCurrentElement(); ++ } else if ( xmlMachineEntry.name() == "input" ) { ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Input")); ++ attributes.clear(); ++ attributes << "service" << "tilt" << "players" << "buttons" << "coins"; ++ descriptions.clear(); ++ descriptions << tr("Service") << tr("Tilt") << tr("Players") << tr("Buttons") << tr("Coins"); ++ insertAttributeItems(childItem, xmlMachineEntry, attributes, descriptions, true); ++ while ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "control" ) { ++ QTreeWidgetItem *nextChildItem = new QTreeWidgetItem(childItem); ++ nextChildItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Control")); ++ nextChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "type", true)); ++ attributes.clear(); ++ attributes << "minimum" << "maximum" << "sensitivity" << "keydelta" << "reverse" << "player" << "buttons" << "ways"; ++ descriptions.clear(); ++ descriptions << tr("Minimum") << tr("Maximum") << tr("Sensitivity") << tr("Key Delta") << tr("Reverse") << tr("Player") << tr("Buttons") << tr("Ways"); ++ insertAttributeItems(nextChildItem, xmlMachineEntry, attributes, descriptions, true); ++ xmlMachineEntry.skipCurrentElement(); ++ } else ++ xmlMachineEntry.skipCurrentElement(); ++ } ++ } else if ( xmlMachineEntry.name() == "dipswitch") { ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("DIP switch")); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "name", true)); ++ while ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "dipvalue") { ++ QTreeWidgetItem *secondChildItem = new QTreeWidgetItem(childItem); ++ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("DIP value")); ++ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "name", true)); ++ attributes.clear(); ++ attributes << "default"; ++ descriptions.clear(); ++ descriptions << tr("Default"); ++ insertAttributeItems(secondChildItem, xmlMachineEntry, attributes, descriptions, true); ++ xmlMachineEntry.skipCurrentElement(); ++ } else ++ xmlMachineEntry.skipCurrentElement(); ++ } ++ } else if ( xmlMachineEntry.name() == "configuration" ) { ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Configuration")); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "name", true)); ++ attributes.clear(); ++ attributes << "tag" << "mask"; ++ descriptions.clear(); ++ descriptions << tr("Tag") << tr("Mask"); ++ insertAttributeItems(childItem, xmlMachineEntry, attributes, descriptions, true); ++ while ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "confsetting" ) { ++ QTreeWidgetItem *secondChildItem = new QTreeWidgetItem(childItem); ++ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Setting")); ++ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "name", true)); ++ attributes.clear(); ++ attributes << "value" << "default"; ++ descriptions.clear(); ++ descriptions << tr("Value") << tr("Default"); ++ insertAttributeItems(secondChildItem, xmlMachineEntry, attributes, descriptions, true); ++ xmlMachineEntry.skipCurrentElement(); ++ } else ++ xmlMachineEntry.skipCurrentElement(); ++ } ++ } else if ( xmlMachineEntry.name() == "driver" ) { ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Driver")); ++ attributes.clear(); ++ attributes << "status" << "emulation" << "color" << "sound" << "graphic" << "cocktail" << "protection" << "savestate" << "palettesize"; ++ descriptions.clear(); ++ descriptions << tr("Status") << tr("Emulation") << tr("Color") << tr("Sound") << tr("Graphic") << tr("Cocktail") << tr("Protection") << tr("Save state") << tr("Palette size"); ++ insertAttributeItems(childItem, xmlMachineEntry, attributes, descriptions, true); ++ xmlMachineEntry.skipCurrentElement(); ++ } else if ( xmlMachineEntry.name() == "biosset" ) { ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("BIOS set")); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "name")); ++ attributes.clear(); ++ attributes << "description" << "default"; ++ descriptions.clear(); ++ descriptions << tr("Description") << tr("Default"); ++ insertAttributeItems(childItem, xmlMachineEntry, attributes, descriptions, true); ++ xmlMachineEntry.skipCurrentElement(); ++ } else if ( xmlMachineEntry.name() == "sample" ) { ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Sample")); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "name")); ++ xmlMachineEntry.skipCurrentElement(); ++ } else if ( xmlMachineEntry.name() == "disk" ) { ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Disk")); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "name")); ++ attributes.clear(); ++ attributes << "md5" << "sha1" << "merge" << "region" << "index" << "status" << "optional"; ++ descriptions.clear(); ++ descriptions << tr("MD5") << tr("SHA-1") << tr("Merge") << tr("Region") << tr("Index") << tr("Status") << tr("Optional"); ++ insertAttributeItems(childItem, xmlMachineEntry, attributes, descriptions, true); ++ xmlMachineEntry.skipCurrentElement(); ++ } else if ( xmlMachineEntry.name() == "adjuster" ) { ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Adjuster")); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "name")); ++ attributes.clear(); ++ attributes << "default"; ++ descriptions.clear(); ++ descriptions << tr("Default"); ++ insertAttributeItems(childItem, xmlMachineEntry, attributes, descriptions, true); ++ xmlMachineEntry.skipCurrentElement(); ++ } else if ( xmlMachineEntry.name() == "softwarelist" ) { ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Software list")); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "name")); ++ attributes.clear(); ++ attributes << "status"; ++ descriptions.clear(); ++ descriptions << tr("Status"); ++ insertAttributeItems(childItem, xmlMachineEntry, attributes, descriptions, true); ++ xmlMachineEntry.skipCurrentElement(); ++ } else if ( xmlMachineEntry.name() == "category" ) { ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Category")); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "name", true)); ++ while ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "item" ) { ++ QTreeWidgetItem *secondChildItem = new QTreeWidgetItem(childItem); ++ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Item")); ++ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "name", true)); ++ attributes.clear(); ++ attributes << "default"; ++ descriptions.clear(); ++ descriptions << tr("Default"); ++ insertAttributeItems(secondChildItem, xmlMachineEntry, attributes, descriptions, true); ++ xmlMachineEntry.skipCurrentElement(); ++ } else ++ xmlMachineEntry.skipCurrentElement(); ++ } ++ } else if ( xmlMachineEntry.name() == "device" ) { ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Device")); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "type", true)); ++ attributes.clear(); ++ attributes << "tag" << "mandatory" << "interface"; ++ descriptions.clear(); ++ descriptions << tr("Tag") << tr("Mandatory") << tr("Interface"); ++ insertAttributeItems(childItem, xmlMachineEntry, attributes, descriptions, false); ++ while ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "instance" ) { ++ QTreeWidgetItem *secondChildItem = new QTreeWidgetItem(childItem); ++ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Instance")); ++ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "name", false)); ++ attributes.clear(); ++ attributes << "briefname"; ++ descriptions.clear(); ++ descriptions << tr("Brief name"); ++ insertAttributeItems(secondChildItem, xmlMachineEntry, attributes, descriptions, false); ++ xmlMachineEntry.skipCurrentElement(); ++ } else if ( xmlMachineEntry.name() == "extension" ) { ++ QTreeWidgetItem *secondChildItem = new QTreeWidgetItem(childItem); ++ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Extension")); ++ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(xmlMachineEntry, "name", false)); ++ xmlMachineEntry.skipCurrentElement(); ++ } else ++ xmlMachineEntry.skipCurrentElement(); ++ } ++ } else if ( xmlMachineEntry.name() == "ramoption") { ++ childItem = new QTreeWidgetItem(); ++ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("RAM options")); ++ QTreeWidgetItem *secondChildItem = new QTreeWidgetItem(childItem); ++ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Option")); ++ attributes.clear(); ++ attributes << "default"; ++ descriptions.clear(); ++ descriptions << tr("Default"); ++ insertAttributeItems(secondChildItem, xmlMachineEntry, attributes, descriptions, false); ++ QString ramOptionValue = xmlMachineEntry.readElementText(); ++ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, ramOptionValue); ++ while ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "ramoption" ) { ++ QTreeWidgetItem *anotherSecondChildItem = new QTreeWidgetItem(childItem); ++ anotherSecondChildItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Option")); ++ attributes.clear(); ++ attributes << "default"; ++ descriptions.clear(); ++ descriptions << tr("Default"); ++ insertAttributeItems(anotherSecondChildItem, xmlMachineEntry, attributes, descriptions, false); ++ QString ramOptionValue = xmlMachineEntry.readElementText(); ++ anotherSecondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, ramOptionValue); ++ } ++ } ++ } else ++ xmlMachineEntry.skipCurrentElement(); ++ if ( childItem ) ++ itemList.append(childItem); + } +- if ( xmlLines.at(gamePos).contains(endMark) ) +- gamePos--; ++ } else { ++ qmc2MainWindow->log(QMC2_LOG_FRONTEND, tr("WARNING: couldn't find machine information for '%1'").arg(machineName)); ++ return; + } +- gamePos++; +- if ( childItem ) +- itemList.append(childItem); + } ++ + qmc2MainWindow->treeWidgetMachineList->setUpdatesEnabled(false); + delete item->takeChild(0); + item->addChildren(itemList); +@@ -1548,26 +1543,21 @@ void MachineList::parse() + machineListDb()->beginTransaction(); + int pendingDbUpdates = 0; + for (qint64 rowCounter = 1; rowCounter <= xmlRowCount && !qmc2LoadingInterrupted; rowCounter++) { +- QStringList xmlLines(xmlDb()->xml(rowCounter).split(lineSplitChar, QString::SkipEmptyParts)); +- for (int lineCounter = 0; lineCounter < xmlLines.count() && !qmc2LoadingInterrupted; lineCounter++) { +- while ( lineCounter < xmlLines.count() && !xmlLines.at(lineCounter).contains("") ) +- lineCounter++; +- if ( !qmc2LoadingInterrupted && lineCounter < xmlLines.count() ) { +- QString machineElement(xmlLines.at(lineCounter - 1).simplified()); +- if ( !machineElement.contains(" name=\"") ) +- continue; +- bool isBIOS = value(machineElement, "isbios").compare("yes") == 0; +- bool isDev = value(machineElement, "isdevice").compare("yes") == 0; +- QString machineName(value(machineElement, "name")); ++ QXmlStreamReader xmlMachineEntry(xmlDb()->xml(rowCounter)); ++ if ( xmlMachineEntry.readNextStartElement() && !qmc2LoadingInterrupted ) { ++ if ( xmlMachineEntry.name() == "machine" ) { ++ bool isBIOS = value(xmlMachineEntry, "isbios").compare("yes") == 0; ++ bool isDev = value(xmlMachineEntry, "isdevice").compare("yes") == 0; ++ QString machineName(value(xmlMachineEntry, "name")); + if ( machineName.isEmpty() ) { +- qmc2MainWindow->log(QMC2_LOG_FRONTEND, tr("WARNING: name attribute empty on XML line %1 (set will be ignored!) -- please inform MAME developers and include the offending output from -listxml").arg(lineCounter + 2)); ++ qmc2MainWindow->log(QMC2_LOG_FRONTEND, tr("WARNING: name attribute empty on XML line %1 (set will be ignored!) -- please inform MAME developers and include the offending output from -listxml").arg(xmlMachineEntry.lineNumber())); + qApp->processEvents(); + continue; + } +- QString machineSource(value(machineElement, "sourcefile")); +- QString machineCloneOf(value(machineElement, "cloneof")); +- QString descriptionElement(xmlLines.at(lineCounter).simplified()); +- QString machineDescription(descriptionElement.remove("").remove("").replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'")); ++ QString machineSource(value(xmlMachineEntry, "sourcefile")); ++ QString machineCloneOf(value(xmlMachineEntry, "cloneof")); ++ QString descriptionElement; ++ QString machineDescription; + MachineListItem *machineItem = new MachineListItem(); + qmc2MachineListItemHash.insert(machineName, machineItem); + machineItem->setFlags(MachineListItem::defaultItemFlags); +@@ -1576,37 +1566,39 @@ void MachineList::parse() + hiddenItemHash.insert(machineItem, true); + // find year & manufacturer and determine ROM/CHD requirements + bool endMachine = false; +- int i = lineCounter; ++ + QString machineYear(trQuestionMark), machineManufacturer(trQuestionMark), machinePlayers(trQuestionMark), machineDrvStat(trQuestionMark); + bool yearFound = false, manufacturerFound = false, hasROMs = false, hasCHDs = false, playersFound = false, statusFound = false; +- QString endMark(""); +- while ( !endMachine ) { +- QString xmlLine(xmlLines.at(i)); +- if ( xmlLine.contains("") ) { +- machineYear = xmlLine.simplified().remove("").remove(""); ++ while ( xmlMachineEntry.readNextStartElement() && !endMachine ) { ++ if ( xmlMachineEntry.name() == "description" ) { ++ machineDescription = xmlMachineEntry.readElementText(); ++ } else if ( xmlMachineEntry.name() == "year" ) { ++ machineYear = xmlMachineEntry.readElementText(); + yearFound = true; +- } else if ( xmlLine.contains("") ) { +- machineManufacturer = xmlLine.simplified().remove("").remove("").replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'"); ++ } else if ( xmlMachineEntry.name() == "manufacturer" ) { ++ machineManufacturer = xmlMachineEntry.readElementText(); + manufacturerFound = true; +- } else if ( xmlLine.contains("= 0 ) { +- machinePlayers = xmlLine.mid(playersPos, xmlLine.indexOf("\"", playersPos) - playersPos); ++ xmlMachineEntry.skipCurrentElement(); ++ } else if ( xmlMachineEntry.name() == "input" ) { ++ if ( xmlMachineEntry.attributes().hasAttribute("players") ) { ++ machinePlayers = xmlMachineEntry.attributes().value("players").toString(); + playersFound = true; + } +- } else if ( xmlLine.contains("= 0 ) { +- machineDrvStat = xmlLine.mid(statusPos, xmlLine.indexOf("\"", statusPos) - statusPos); ++ xmlMachineEntry.skipCurrentElement(); ++ } else if ( xmlMachineEntry.name() == "driver" ) { ++ if ( xmlMachineEntry.attributes().hasAttribute("status") ) { ++ machineDrvStat = xmlMachineEntry.attributes().value("status").toString(); + statusFound = true; + } +- } +- endMachine = xmlLine.contains(endMark) || (yearFound && manufacturerFound && hasROMs && hasCHDs && playersFound && statusFound); +- i++; ++ xmlMachineEntry.skipCurrentElement(); ++ } else ++ xmlMachineEntry.skipCurrentElement(); ++ endMachine = yearFound && manufacturerFound && hasROMs && hasCHDs && playersFound && statusFound; + } + if ( machineCloneOf.isEmpty() ) { + if ( !hierarchyHash.contains(machineName) ) +@@ -2544,28 +2536,29 @@ void MachineList::verifyFinished(int exitCode, QProcess::ExitStatus exitStatus) + QTreeWidgetItem *versionItem = qmc2VersionItemHash.value(machineName); + // there are quite a number of sets in MAME that don't require any ROMs... many/most device-sets in particular + bool romRequired = true; +- int xmlCounter = 0; +- QStringList xmlLines(xmlDb()->xml(machineName).split("\n", QString::SkipEmptyParts)); +- if ( xmlLines.count() > 0 ) { +- int romCounter = 0; +- int chdCounter = 0; +- bool endFound = false; +- QString endMark = ""; +- while ( !endFound && xmlCounter < xmlLines.count() ) { +- if ( xmlLines.at(xmlCounter).contains("xml(machineName)); ++ if ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "machine" ) { ++ int romCounter = 0; ++ int chdCounter = 0; ++ bool endFound = false; ++ while ( xmlMachineEntry.readNextStartElement() && !endFound ) { ++ if ( xmlMachineEntry.name() == "rom" ) { ++ romCounter++; ++ endFound = true; ++ xmlMachineEntry.skipCurrentElement(); ++ } else if ( xmlMachineEntry.name() == "disk" ) { ++ chdCounter++; ++ endFound = true; ++ xmlMachineEntry.skipCurrentElement(); ++ } else ++ xmlMachineEntry.skipCurrentElement(); ++ } ++ if ( romCounter == 0 && chdCounter > 0 ) ++ romRequired = true; ++ else ++ romRequired = (romCounter > 0); + } +- if ( romCounter == 0 && chdCounter > 0 ) +- romRequired = true; +- else +- romRequired = (romCounter > 0); + } + if ( romItem && hierarchyItem ) { + if ( romStateCache.isOpen() ) { +diff --git a/src/machinelist.h b/src/machinelist.h +index 8a4eee1e0..944ee88d0 100644 +--- a/src/machinelist.h ++++ b/src/machinelist.h +@@ -132,11 +132,11 @@ class MachineList : public QObject + void verifyReadyReadStandardOutput(); + + // internal methods +- QString value(QString, QString, bool translate = false); ++ QString value(QXmlStreamReader &, QString, bool translate = false); + void parse(); + void parseMachineDetail(QTreeWidgetItem *); +- void insertAttributeItems(QTreeWidgetItem *, QString, QStringList, QStringList, bool translate = false); +- void insertAttributeItems(QList *itemList, QString element, QStringList attributes, QStringList descriptions, bool translate = false); ++ void insertAttributeItems(QTreeWidgetItem *, QXmlStreamReader &, QStringList, QStringList, bool translate = false); ++ void insertAttributeItems(QList *itemList, QXmlStreamReader &element, QStringList attributes, QStringList descriptions, bool translate = false); + void enableWidgets(bool enable = true); + void disableWidgets() { enableWidgets(false); } + void filter(bool initial = false); +diff --git a/src/qmc2main.cpp b/src/qmc2main.cpp +index ec16009b2..e24fe89d6 100644 +--- a/src/qmc2main.cpp ++++ b/src/qmc2main.cpp +@@ -4631,44 +4631,36 @@ QStringList &MainWindow::getXmlChoices(const QString &machineName, const QString + return xmlChoices; + if ( defaultChoice ) + defaultChoice->clear(); +- QStringList xmlLines(qmc2MachineList->xmlDb()->xml(machineName).split('\n', QString::SkipEmptyParts)); +- QString defaultYes("default=\"yes\""); +- QString defaultOne("default=\"1\""); +- int i = 0; +- while ( i < xmlLines.count() ) { +- QString xmlLine(xmlLines.at(i++).simplified()); +- int index = xmlLine.indexOf('<' + optionElement); +- if ( index >= 0 ) { +- if ( optionAttribute.isEmpty() ) { +- index = xmlLine.indexOf('>', index); +- if ( index >= 0 ) { +- xmlLine.remove(0, index + 1); +- bool isDefaultChoice = false; +- if ( defaultChoice && (xmlLine.indexOf(defaultYes) >= 0 || xmlLine.indexOf(defaultOne) >= 0 || defaultChoice->isEmpty()) ) +- isDefaultChoice = true; +- xmlLine.replace("', ""); +- QTextDocument doc; +- doc.setHtml(xmlLine); +- xmlLine = doc.toPlainText(); +- xmlChoices << xmlLine; +- if ( isDefaultChoice ) +- *defaultChoice = xmlLine; +- } +- } else { +- QString prefix(optionAttribute + "=\""); +- index = xmlLine.indexOf(prefix); +- if ( index >= 0 ) { +- xmlLine.remove(0, index + prefix.length()); +- index = xmlLine.indexOf('\"'); +- if ( index >= 0 ) { ++ QXmlStreamReader xmlMachineEntry(qmc2MachineList->xmlDb()->xml(machineName)); ++ QString defaultYes("yes"); ++ QString defaultOne("1"); ++ if ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "machine" ) { ++ while ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == optionElement ) { ++ if ( optionAttribute.isEmpty() ) { ++ bool isDefaultChoice = false; ++ if ( defaultChoice && (xmlMachineEntry.attributes().hasAttribute("default") && xmlMachineEntry.attributes().value("default").toString() == defaultYes || xmlMachineEntry.attributes().value("default").toString() == defaultOne || defaultChoice->isEmpty()) ) ++ isDefaultChoice = true; + QTextDocument doc; +- doc.setHtml(xmlLine.left(index)); +- QString choice = doc.toPlainText(); +- xmlChoices << choice; +- if ( defaultChoice && (xmlLine.indexOf(defaultYes) >= 0 || xmlLine.indexOf(defaultOne) >= 0 || defaultChoice->isEmpty()) ) +- *defaultChoice = choice; ++ doc.setHtml(xmlMachineEntry.readElementText()); ++ QString xmlLine = doc.toPlainText(); ++ xmlChoices << xmlLine; ++ if ( isDefaultChoice ) ++ *defaultChoice = xmlLine; ++ } else { ++ if ( xmlMachineEntry.attributes().hasAttribute(optionAttribute) ) { ++ QTextDocument doc; ++ doc.setHtml(xmlMachineEntry.attributes().value(optionAttribute).toString()); ++ QString choice = doc.toPlainText(); ++ xmlChoices << choice; ++ if ( defaultChoice && (xmlMachineEntry.attributes().hasAttribute("default") && xmlMachineEntry.attributes().value("default").toString() == defaultYes || xmlMachineEntry.attributes().value("default").toString() == defaultOne || defaultChoice->isEmpty()) ) ++ *defaultChoice = choice; ++ xmlMachineEntry.skipCurrentElement(); ++ } + } +- } ++ } else ++ xmlMachineEntry.skipCurrentElement(); + } + } + } +diff --git a/src/romalyzer.cpp b/src/romalyzer.cpp +index ddb5b0b38..902db6ed7 100644 +--- a/src/romalyzer.cpp ++++ b/src/romalyzer.cpp +@@ -2753,18 +2753,15 @@ void ROMAlyzer::on_pushButtonChecksumWizardSearch_clicked() + lineEditSets->setEnabled(false); + labelStatus->setText(tr("Check-sum search")); + +- QString hashStartString; +- int hashStartOffset; ++ QString hashAttribute; + switch ( comboBoxChecksumWizardHashType->currentIndex() ) { + case QMC2_ROMALYZER_CSF_HASHTYPE_CRC: +- hashStartString = "crc=\""; +- hashStartOffset = 5; ++ hashAttribute = "crc"; + break; + + default: + case QMC2_ROMALYZER_CSF_HASHTYPE_SHA1: +- hashStartString = "sha1=\""; +- hashStartOffset = 6; ++ hashAttribute = "sha1"; + break; + } + +@@ -2775,29 +2772,28 @@ void ROMAlyzer::on_pushButtonChecksumWizardSearch_clicked() + int progressCount = 0, updateCount = 0; + foreach (QString list, uniqueSoftwareLists) { + foreach (QString set, qmc2MainWindow->swlDb->uniqueSoftwareSets(list)) { +- QStringList xmlLines(qmc2MainWindow->swlDb->xml(list, set).split('\n', QString::SkipEmptyParts)); +- for (int i = 0; i < xmlLines.count(); i++) { +- QString xmlLine(xmlLines.at(i)); +- int hashIndex = xmlLine.indexOf(hashStartString); +- if ( hashIndex >= 0 ) { +- int hashPos = hashIndex + hashStartOffset; +- QString currentChecksum(xmlLine.mid(hashPos, xmlLine.indexOf('\"', hashPos) - hashPos).toLower()); +- if ( currentChecksum.compare(searchedChecksum) == 0 ) { +- int fileNamePos; +- QString fileType; +- if ( xmlLine.startsWith("setText(QMC2_ROMALYZER_CSF_COLUMN_ID, list + ":" + set); +- item->setText(QMC2_ROMALYZER_CSF_COLUMN_FILENAME, fileName.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'")); +- item->setText(QMC2_ROMALYZER_CSF_COLUMN_TYPE, fileType); +- item->setText(QMC2_ROMALYZER_CSF_COLUMN_STATUS, tr("unknown")); ++ QXmlStreamReader xmlMachineEntry(qmc2MainWindow->swlDb->xml(list, set)); ++ if ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "machine" ) { ++ while ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.attributes().hasAttribute(hashAttribute) ) { ++ QString currentChecksum(xmlMachineEntry.attributes().value(hashAttribute).toString().toLower()); ++ if ( currentChecksum.compare(searchedChecksum) == 0 ) { ++ QString fileType; ++ if ( xmlMachineEntry.name() == "disk" ) ++ fileType = tr("CHD"); ++ else ++ fileType = tr("ROM"); ++ QString fileName(xmlMachineEntry.attributes().value("name").toString()); ++ QTreeWidgetItem *item = new QTreeWidgetItem(treeWidgetChecksumWizardSearchResult); ++ item->setText(QMC2_ROMALYZER_CSF_COLUMN_ID, list + ":" + set); ++ item->setText(QMC2_ROMALYZER_CSF_COLUMN_FILENAME, fileName); ++ item->setText(QMC2_ROMALYZER_CSF_COLUMN_TYPE, fileType); ++ item->setText(QMC2_ROMALYZER_CSF_COLUMN_STATUS, tr("unknown")); ++ } ++ xmlMachineEntry.skipCurrentElement(); ++ } else ++ xmlMachineEntry.skipCurrentElement(); + } + } + } +@@ -2820,29 +2816,28 @@ void ROMAlyzer::on_pushButtonChecksumWizardSearch_clicked() + qApp->processEvents(); + } + QString currentMachine(qmc2MainWindow->treeWidgetMachineList->topLevelItem(i)->text(QMC2_MACHINELIST_COLUMN_NAME)); +- QStringList xmlLines(qmc2MachineList->xmlDb()->xml(currentMachine).split('\n', QString::SkipEmptyParts)); +- for (int j = 0; j < xmlLines.count(); j++) { +- QString xmlLine(xmlLines.at(j)); +- int hashIndex = xmlLine.indexOf(hashStartString); +- if ( hashIndex >= 0 ) { +- int hashPos = hashIndex + hashStartOffset; +- QString currentChecksum(xmlLine.mid(hashPos, xmlLine.indexOf('\"', hashPos) - hashPos).toLower()); +- if ( currentChecksum.compare(searchedChecksum) == 0 ) { +- int fileNamePos; +- QString fileType; +- if ( xmlLine.startsWith("setText(QMC2_ROMALYZER_CSF_COLUMN_ID, currentMachine); +- item->setText(QMC2_ROMALYZER_CSF_COLUMN_FILENAME, fileName.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'")); +- item->setText(QMC2_ROMALYZER_CSF_COLUMN_TYPE, fileType); +- item->setText(QMC2_ROMALYZER_CSF_COLUMN_STATUS, tr("unknown")); ++ QXmlStreamReader xmlMachineEntry(qmc2MachineList->xmlDb()->xml(currentMachine)); ++ if ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "machine" ) { ++ while ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.attributes().hasAttribute(hashAttribute) ) { ++ QString currentChecksum(xmlMachineEntry.attributes().value(hashAttribute).toString().toLower()); ++ if ( currentChecksum.compare(searchedChecksum) == 0 ) { ++ QString fileType; ++ if ( xmlMachineEntry.name() == "disk" ) ++ fileType = tr("CHD"); ++ else ++ fileType = tr("ROM"); ++ QString fileName(xmlMachineEntry.attributes().value("name").toString()); ++ QTreeWidgetItem *item = new QTreeWidgetItem(treeWidgetChecksumWizardSearchResult); ++ item->setText(QMC2_ROMALYZER_CSF_COLUMN_ID, currentMachine); ++ item->setText(QMC2_ROMALYZER_CSF_COLUMN_FILENAME, fileName); ++ item->setText(QMC2_ROMALYZER_CSF_COLUMN_TYPE, fileType); ++ item->setText(QMC2_ROMALYZER_CSF_COLUMN_STATUS, tr("unknown")); ++ } ++ xmlMachineEntry.skipCurrentElement(); ++ } else ++ xmlMachineEntry.skipCurrentElement(); + } + } + } +diff --git a/src/softwarelist.cpp b/src/softwarelist.cpp +index 99f806da4..13c1f0f55 100644 +--- a/src/softwarelist.cpp ++++ b/src/softwarelist.cpp +@@ -1012,6 +1012,7 @@ QString &SoftwareList::lookupMountDevice(QString device, QString deviceInterface + QStringList xmlLines(qmc2MachineList->xmlDb()->xml(systemName).split('\n', QString::SkipEmptyParts)); + QStringList *xmlData = &xmlLines; + QStringList dynamicXmlData; ++ QXmlStreamReader xmlMachineEntry(qmc2MachineList->xmlDb()->xml(systemName)); + if ( comboBoxDeviceConfiguration->currentIndex() > 0 ) { + qmc2Config->beginGroup(QMC2_EMULATOR_PREFIX + QString("Configuration/Devices/%1/%2").arg(systemName).arg(comboBoxDeviceConfiguration->currentText())); + QStringList instances(qmc2Config->value("Instances").toStringList()); +@@ -1047,37 +1048,34 @@ QString &SoftwareList::lookupMountDevice(QString device, QString deviceInterface + #endif + } + +- int i = 0; +- while ( i < xmlData->count() && !xmlData->at(i).contains("") ) { +- QString line(xmlData->at(i++).simplified()); +- if ( line.startsWith("= 0 ) { +- startIndex += 11; +- endIndex = line.indexOf("\"", startIndex); +- QStringList devInterfaces(line.mid(startIndex, endIndex - startIndex).split(',', QString::SkipEmptyParts)); +- line = xmlData->at(i++).simplified(); +- startIndex = line.indexOf("briefname=\""); +- if ( startIndex >= 0 ) { +- startIndex += 11; +- endIndex = line.indexOf("\"", startIndex); +- devName = line.mid(startIndex, endIndex - startIndex); +- } +- if ( !devName.isEmpty() ) +- foreach (QString devIf, devInterfaces) +- deviceInstanceHash[devIf] << devName; +- } else { +- line = xmlData->at(i++).simplified(); +- startIndex = line.indexOf("briefname=\""); +- if ( startIndex >= 0 ) { +- startIndex += 11; +- endIndex = line.indexOf("\"", startIndex); +- devName = line.mid(startIndex, endIndex - startIndex); +- } +- if ( !devName.isEmpty() ) +- deviceInstanceHash[devName] << devName; ++ if ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "machine" ) { ++ while ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "device" && xmlMachineEntry.attributes().hasAttribute("type") ) { ++ QString devName; ++ if ( xmlMachineEntry.attributes().hasAttribute("interface") ) { ++ QStringList devInterfaces(xmlMachineEntry.attributes().value("interface").toString().split(',', QString::SkipEmptyParts)); ++ while ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "instance" && xmlMachineEntry.attributes().hasAttribute("briefname") ) { ++ devName = xmlMachineEntry.attributes().value("briefname").toString(); ++ if ( !devName.isEmpty() ) ++ foreach (QString devIf, devInterfaces) ++ deviceInstanceHash[devIf] << devName; ++ } ++ xmlMachineEntry.skipCurrentElement(); ++ } ++ } else { ++ while ( xmlMachineEntry.readNextStartElement() ) { ++ if ( xmlMachineEntry.name() == "instance" && xmlMachineEntry.attributes().hasAttribute("briefname") ) { ++ devName = xmlMachineEntry.attributes().value("briefname").toString(); ++ if ( !devName.isEmpty() ) ++ deviceInstanceHash[devName] << devName; ++ } ++ xmlMachineEntry.skipCurrentElement(); ++ } ++ } ++ } else ++ xmlMachineEntry.skipCurrentElement(); + } + } + } +-- +2.44.0 + diff --git a/41.patch b/41.patch deleted file mode 100644 index 49b7c2d..0000000 --- a/41.patch +++ /dev/null @@ -1,29339 +0,0 @@ -From 96cfca3fecde5462d5d9105ba96cac68fbe22052 Mon Sep 17 00:00:00 2001 -From: Julian Sikorski -Date: Wed, 21 Feb 2024 22:00:11 +0100 -Subject: [PATCH 1/4] imp: updated bundled zlib to 1.3.1 - ---- - src/zlib/README.zlib | 19 +- - src/zlib/adler32.c | 32 +- - src/zlib/compress.c | 21 +- - src/zlib/crc32.c | 255 +++++--------- - src/zlib/deflate.c | 796 ++++++++++++++++++++----------------------- - src/zlib/deflate.h | 55 ++- - src/zlib/gzclose.c | 4 +- - src/zlib/gzguts.h | 31 +- - src/zlib/gzlib.c | 113 ++---- - src/zlib/gzread.c | 96 ++---- - src/zlib/gzwrite.c | 84 ++--- - src/zlib/infback.c | 47 +-- - src/zlib/inffast.c | 5 +- - src/zlib/inffast.h | 2 +- - src/zlib/inflate.c | 138 ++------ - src/zlib/inftrees.c | 17 +- - src/zlib/inftrees.h | 12 +- - src/zlib/trees.c | 645 ++++++++++++++++------------------- - src/zlib/uncompr.c | 16 +- - src/zlib/zconf.h | 37 +- - src/zlib/zlib.h | 401 +++++++++++----------- - src/zlib/zutil.c | 62 +--- - src/zlib/zutil.h | 46 +-- - 23 files changed, 1219 insertions(+), 1715 deletions(-) - -diff --git a/src/zlib/README.zlib b/src/zlib/README.zlib -index 024b79d3d..c5f917540 100644 ---- a/src/zlib/README.zlib -+++ b/src/zlib/README.zlib -@@ -1,6 +1,6 @@ - ZLIB DATA COMPRESSION LIBRARY - --zlib 1.2.12 is a general purpose data compression library. All the code is -+zlib 1.3.1 is a general purpose data compression library. All the code is - thread safe. The data format used by the zlib library is described by RFCs - (Request for Comments) 1950 to 1952 in the files - http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and -@@ -29,18 +29,17 @@ PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help. - - Mark Nelson wrote an article about zlib for the Jan. 1997 - issue of Dr. Dobb's Journal; a copy of the article is available at --http://marknelson.us/1997/01/01/zlib-engine/ . -+https://marknelson.us/posts/1997/01/01/zlib-engine.html . - --The changes made in version 1.2.12 are documented in the file ChangeLog. -+The changes made in version 1.3.1 are documented in the file ChangeLog. - - Unsupported third party contributions are provided in directory contrib/ . - --zlib is available in Java using the java.util.zip package, documented at --http://java.sun.com/developer/technicalArticles/Programming/compression/ . -+zlib is available in Java using the java.util.zip package. Follow the API -+Documentation link at: https://docs.oracle.com/search/?q=java.util.zip . - --A Perl interface to zlib written by Paul Marquess is available --at CPAN (Comprehensive Perl Archive Network) sites, including --http://search.cpan.org/~pmqs/IO-Compress-Zlib/ . -+A Perl interface to zlib and bzip2 written by Paul Marquess -+can be found at https://github.com/pmqs/IO-Compress . - - A Python interface to zlib written by A.M. Kuchling is - available in Python 1.5 and later versions, see -@@ -64,7 +63,7 @@ Notes for some targets: - - zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works - when compiled with cc. - --- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is -+- On Digital Unix 4.0D (formerly OSF/1) on AlphaServer, the cc option -std1 is - necessary to get gzprintf working correctly. This is done by configure. - - - zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with -@@ -84,7 +83,7 @@ Acknowledgments: - - Copyright notice: - -- (C) 1995-2022 Jean-loup Gailly and Mark Adler -+ (C) 1995-2024 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages -diff --git a/src/zlib/adler32.c b/src/zlib/adler32.c -index d0be4380a..04b81d29b 100644 ---- a/src/zlib/adler32.c -+++ b/src/zlib/adler32.c -@@ -7,8 +7,6 @@ - - #include "zutil.h" - --local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2)); -- - #define BASE 65521U /* largest prime smaller than 65536 */ - #define NMAX 5552 - /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ -@@ -60,11 +58,7 @@ local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2)); - #endif - - /* ========================================================================= */ --uLong ZEXPORT adler32_z(adler, buf, len) -- uLong adler; -- const Bytef *buf; -- z_size_t len; --{ -+uLong ZEXPORT adler32_z(uLong adler, const Bytef *buf, z_size_t len) { - unsigned long sum2; - unsigned n; - -@@ -131,20 +125,12 @@ uLong ZEXPORT adler32_z(adler, buf, len) - } - - /* ========================================================================= */ --uLong ZEXPORT adler32(adler, buf, len) -- uLong adler; -- const Bytef *buf; -- uInt len; --{ -+uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len) { - return adler32_z(adler, buf, len); - } - - /* ========================================================================= */ --local uLong adler32_combine_(adler1, adler2, len2) -- uLong adler1; -- uLong adler2; -- z_off64_t len2; --{ -+local uLong adler32_combine_(uLong adler1, uLong adler2, z_off64_t len2) { - unsigned long sum1; - unsigned long sum2; - unsigned rem; -@@ -169,18 +155,10 @@ local uLong adler32_combine_(adler1, adler2, len2) - } - - /* ========================================================================= */ --uLong ZEXPORT adler32_combine(adler1, adler2, len2) -- uLong adler1; -- uLong adler2; -- z_off_t len2; --{ -+uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2) { - return adler32_combine_(adler1, adler2, len2); - } - --uLong ZEXPORT adler32_combine64(adler1, adler2, len2) -- uLong adler1; -- uLong adler2; -- z_off64_t len2; --{ -+uLong ZEXPORT adler32_combine64(uLong adler1, uLong adler2, z_off64_t len2) { - return adler32_combine_(adler1, adler2, len2); - } -diff --git a/src/zlib/compress.c b/src/zlib/compress.c -index e2db404ab..f43bacf7a 100644 ---- a/src/zlib/compress.c -+++ b/src/zlib/compress.c -@@ -19,13 +19,8 @@ - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. - */ --int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) -- Bytef *dest; -- uLongf *destLen; -- const Bytef *source; -- uLong sourceLen; -- int level; --{ -+int ZEXPORT compress2(Bytef *dest, uLongf *destLen, const Bytef *source, -+ uLong sourceLen, int level) { - z_stream stream; - int err; - const uInt max = (uInt)-1; -@@ -65,12 +60,8 @@ int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) - - /* =========================================================================== - */ --int ZEXPORT compress (dest, destLen, source, sourceLen) -- Bytef *dest; -- uLongf *destLen; -- const Bytef *source; -- uLong sourceLen; --{ -+int ZEXPORT compress(Bytef *dest, uLongf *destLen, const Bytef *source, -+ uLong sourceLen) { - return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); - } - -@@ -78,9 +69,7 @@ int ZEXPORT compress (dest, destLen, source, sourceLen) - If the default memLevel or windowBits for deflateInit() is changed, then - this function needs to be updated. - */ --uLong ZEXPORT compressBound (sourceLen) -- uLong sourceLen; --{ -+uLong ZEXPORT compressBound(uLong sourceLen) { - return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + - (sourceLen >> 25) + 13; - } -diff --git a/src/zlib/crc32.c b/src/zlib/crc32.c -index a1bdce5c2..6c38f5c04 100644 ---- a/src/zlib/crc32.c -+++ b/src/zlib/crc32.c -@@ -98,10 +98,6 @@ - # endif - #endif - --/* Local functions. */ --local z_crc_t multmodp OF((z_crc_t a, z_crc_t b)); --local z_crc_t x2nmodp OF((z_off64_t n, unsigned k)); -- - /* If available, use the ARM processor CRC32 instruction. */ - #if defined(__aarch64__) && defined(__ARM_FEATURE_CRC32) && W == 8 - # define ARMCRC32 -@@ -114,9 +110,7 @@ local z_crc_t x2nmodp OF((z_off64_t n, unsigned k)); - instruction, if one is available. This assumes that word_t is either 32 bits - or 64 bits. - */ --local z_word_t byte_swap(word) -- z_word_t word; --{ -+local z_word_t byte_swap(z_word_t word) { - # if W == 8 - return - (word & 0xff00000000000000) >> 56 | -@@ -137,24 +131,77 @@ local z_word_t byte_swap(word) - } - #endif - -+#ifdef DYNAMIC_CRC_TABLE -+/* ========================================================================= -+ * Table of powers of x for combining CRC-32s, filled in by make_crc_table() -+ * below. -+ */ -+ local z_crc_t FAR x2n_table[32]; -+#else -+/* ========================================================================= -+ * Tables for byte-wise and braided CRC-32 calculations, and a table of powers -+ * of x for combining CRC-32s, all made by make_crc_table(). -+ */ -+# include "crc32.h" -+#endif -+ - /* CRC polynomial. */ - #define POLY 0xedb88320 /* p(x) reflected, with x^32 implied */ - --#ifdef DYNAMIC_CRC_TABLE -+/* -+ Return a(x) multiplied by b(x) modulo p(x), where p(x) is the CRC polynomial, -+ reflected. For speed, this requires that a not be zero. -+ */ -+local z_crc_t multmodp(z_crc_t a, z_crc_t b) { -+ z_crc_t m, p; -+ -+ m = (z_crc_t)1 << 31; -+ p = 0; -+ for (;;) { -+ if (a & m) { -+ p ^= b; -+ if ((a & (m - 1)) == 0) -+ break; -+ } -+ m >>= 1; -+ b = b & 1 ? (b >> 1) ^ POLY : b >> 1; -+ } -+ return p; -+} -+ -+/* -+ Return x^(n * 2^k) modulo p(x). Requires that x2n_table[] has been -+ initialized. -+ */ -+local z_crc_t x2nmodp(z_off64_t n, unsigned k) { -+ z_crc_t p; -+ -+ p = (z_crc_t)1 << 31; /* x^0 == 1 */ -+ while (n) { -+ if (n & 1) -+ p = multmodp(x2n_table[k & 31], p); -+ n >>= 1; -+ k++; -+ } -+ return p; -+} - -+#ifdef DYNAMIC_CRC_TABLE -+/* ========================================================================= -+ * Build the tables for byte-wise and braided CRC-32 calculations, and a table -+ * of powers of x for combining CRC-32s. -+ */ - local z_crc_t FAR crc_table[256]; --local z_crc_t FAR x2n_table[32]; --local void make_crc_table OF((void)); - #ifdef W - local z_word_t FAR crc_big_table[256]; - local z_crc_t FAR crc_braid_table[W][256]; - local z_word_t FAR crc_braid_big_table[W][256]; -- local void braid OF((z_crc_t [][256], z_word_t [][256], int, int)); -+ local void braid(z_crc_t [][256], z_word_t [][256], int, int); - #endif - #ifdef MAKECRCH -- local void write_table OF((FILE *, const z_crc_t FAR *, int)); -- local void write_table32hi OF((FILE *, const z_word_t FAR *, int)); -- local void write_table64 OF((FILE *, const z_word_t FAR *, int)); -+ local void write_table(FILE *, const z_crc_t FAR *, int); -+ local void write_table32hi(FILE *, const z_word_t FAR *, int); -+ local void write_table64(FILE *, const z_word_t FAR *, int); - #endif /* MAKECRCH */ - - /* -@@ -167,7 +214,6 @@ local void make_crc_table OF((void)); - - /* Definition of once functionality. */ - typedef struct once_s once_t; --local void once OF((once_t *, void (*)(void))); - - /* Check for the availability of atomics. */ - #if defined(__STDC__) && __STDC_VERSION__ >= 201112L && \ -@@ -187,10 +233,7 @@ struct once_s { - invoke once() at the same time. The state must be a once_t initialized with - ONCE_INIT. - */ --local void once(state, init) -- once_t *state; -- void (*init)(void); --{ -+local void once(once_t *state, void (*init)(void)) { - if (!atomic_load(&state->done)) { - if (atomic_flag_test_and_set(&state->begun)) - while (!atomic_load(&state->done)) -@@ -213,10 +256,7 @@ struct once_s { - - /* Test and set. Alas, not atomic, but tries to minimize the period of - vulnerability. */ --local int test_and_set OF((int volatile *)); --local int test_and_set(flag) -- int volatile *flag; --{ -+local int test_and_set(int volatile *flag) { - int was; - - was = *flag; -@@ -225,10 +265,7 @@ local int test_and_set(flag) - } - - /* Run the provided init() function once. This is not thread-safe. */ --local void once(state, init) -- once_t *state; -- void (*init)(void); --{ -+local void once(once_t *state, void (*init)(void)) { - if (!state->done) { - if (test_and_set(&state->begun)) - while (!state->done) -@@ -270,8 +307,7 @@ local once_t made = ONCE_INIT; - combinations of CRC register values and incoming bytes. - */ - --local void make_crc_table() --{ -+local void make_crc_table(void) { - unsigned i, j, n; - z_crc_t p; - -@@ -438,11 +474,7 @@ local void make_crc_table() - Write the 32-bit values in table[0..k-1] to out, five per line in - hexadecimal separated by commas. - */ --local void write_table(out, table, k) -- FILE *out; -- const z_crc_t FAR *table; -- int k; --{ -+local void write_table(FILE *out, const z_crc_t FAR *table, int k) { - int n; - - for (n = 0; n < k; n++) -@@ -455,11 +487,7 @@ local void write_table(out, table, k) - Write the high 32-bits of each value in table[0..k-1] to out, five per line - in hexadecimal separated by commas. - */ --local void write_table32hi(out, table, k) --FILE *out; --const z_word_t FAR *table; --int k; --{ -+local void write_table32hi(FILE *out, const z_word_t FAR *table, int k) { - int n; - - for (n = 0; n < k; n++) -@@ -475,11 +503,7 @@ int k; - bits. If not, then the type cast and format string can be adjusted - accordingly. - */ --local void write_table64(out, table, k) -- FILE *out; -- const z_word_t FAR *table; -- int k; --{ -+local void write_table64(FILE *out, const z_word_t FAR *table, int k) { - int n; - - for (n = 0; n < k; n++) -@@ -489,8 +513,7 @@ local void write_table64(out, table, k) - } - - /* Actually do the deed. */ --int main() --{ -+int main(void) { - make_crc_table(); - return 0; - } -@@ -502,12 +525,7 @@ int main() - Generate the little and big-endian braid tables for the given n and z_word_t - size w. Each array must have room for w blocks of 256 elements. - */ --local void braid(ltl, big, n, w) -- z_crc_t ltl[][256]; -- z_word_t big[][256]; -- int n; -- int w; --{ -+local void braid(z_crc_t ltl[][256], z_word_t big[][256], int n, int w) { - int k; - z_crc_t i, p, q; - for (k = 0; k < w; k++) { -@@ -522,69 +540,13 @@ local void braid(ltl, big, n, w) - } - #endif - --#else /* !DYNAMIC_CRC_TABLE */ --/* ======================================================================== -- * Tables for byte-wise and braided CRC-32 calculations, and a table of powers -- * of x for combining CRC-32s, all made by make_crc_table(). -- */ --#include "crc32.h" - #endif /* DYNAMIC_CRC_TABLE */ - --/* ======================================================================== -- * Routines used for CRC calculation. Some are also required for the table -- * generation above. -- */ -- --/* -- Return a(x) multiplied by b(x) modulo p(x), where p(x) is the CRC polynomial, -- reflected. For speed, this requires that a not be zero. -- */ --local z_crc_t multmodp(a, b) -- z_crc_t a; -- z_crc_t b; --{ -- z_crc_t m, p; -- -- m = (z_crc_t)1 << 31; -- p = 0; -- for (;;) { -- if (a & m) { -- p ^= b; -- if ((a & (m - 1)) == 0) -- break; -- } -- m >>= 1; -- b = b & 1 ? (b >> 1) ^ POLY : b >> 1; -- } -- return p; --} -- --/* -- Return x^(n * 2^k) modulo p(x). Requires that x2n_table[] has been -- initialized. -- */ --local z_crc_t x2nmodp(n, k) -- z_off64_t n; -- unsigned k; --{ -- z_crc_t p; -- -- p = (z_crc_t)1 << 31; /* x^0 == 1 */ -- while (n) { -- if (n & 1) -- p = multmodp(x2n_table[k & 31], p); -- n >>= 1; -- k++; -- } -- return p; --} -- - /* ========================================================================= - * This function can be used by asm versions of crc32(), and to force the - * generation of the CRC tables in a threaded application. - */ --const z_crc_t FAR * ZEXPORT get_crc_table() --{ -+const z_crc_t FAR * ZEXPORT get_crc_table(void) { - #ifdef DYNAMIC_CRC_TABLE - once(&made, make_crc_table); - #endif /* DYNAMIC_CRC_TABLE */ -@@ -610,11 +572,8 @@ const z_crc_t FAR * ZEXPORT get_crc_table() - #define Z_BATCH_ZEROS 0xa10d3d0c /* computed from Z_BATCH = 3990 */ - #define Z_BATCH_MIN 800 /* fewest words in a final batch */ - --unsigned long ZEXPORT crc32_z(crc, buf, len) -- unsigned long crc; -- const unsigned char FAR *buf; -- z_size_t len; --{ -+unsigned long ZEXPORT crc32_z(unsigned long crc, const unsigned char FAR *buf, -+ z_size_t len) { - z_crc_t val; - z_word_t crc1, crc2; - const z_word_t *word; -@@ -630,7 +589,7 @@ unsigned long ZEXPORT crc32_z(crc, buf, len) - #endif /* DYNAMIC_CRC_TABLE */ - - /* Pre-condition the CRC */ -- crc ^= 0xffffffff; -+ crc = (~crc) & 0xffffffff; - - /* Compute the CRC up to a word boundary. */ - while (len && ((z_size_t)buf & 7) != 0) { -@@ -645,8 +604,8 @@ unsigned long ZEXPORT crc32_z(crc, buf, len) - len &= 7; - - /* Do three interleaved CRCs to realize the throughput of one crc32x -- instruction per cycle. Each CRC is calcuated on Z_BATCH words. The three -- CRCs are combined into a single CRC after each set of batches. */ -+ instruction per cycle. Each CRC is calculated on Z_BATCH words. The -+ three CRCs are combined into a single CRC after each set of batches. */ - while (num >= 3 * Z_BATCH) { - crc1 = 0; - crc2 = 0; -@@ -714,18 +673,14 @@ unsigned long ZEXPORT crc32_z(crc, buf, len) - least-significant byte of the word as the first byte of data, without any pre - or post conditioning. This is used to combine the CRCs of each braid. - */ --local z_crc_t crc_word(data) -- z_word_t data; --{ -+local z_crc_t crc_word(z_word_t data) { - int k; - for (k = 0; k < W; k++) - data = (data >> 8) ^ crc_table[data & 0xff]; - return (z_crc_t)data; - } - --local z_word_t crc_word_big(data) -- z_word_t data; --{ -+local z_word_t crc_word_big(z_word_t data) { - int k; - for (k = 0; k < W; k++) - data = (data << 8) ^ -@@ -736,11 +691,8 @@ local z_word_t crc_word_big(data) - #endif - - /* ========================================================================= */ --unsigned long ZEXPORT crc32_z(crc, buf, len) -- unsigned long crc; -- const unsigned char FAR *buf; -- z_size_t len; --{ -+unsigned long ZEXPORT crc32_z(unsigned long crc, const unsigned char FAR *buf, -+ z_size_t len) { - /* Return initial CRC, if requested. */ - if (buf == Z_NULL) return 0; - -@@ -749,7 +701,7 @@ unsigned long ZEXPORT crc32_z(crc, buf, len) - #endif /* DYNAMIC_CRC_TABLE */ - - /* Pre-condition the CRC */ -- crc ^= 0xffffffff; -+ crc = (~crc) & 0xffffffff; - - #ifdef W - -@@ -772,8 +724,8 @@ unsigned long ZEXPORT crc32_z(crc, buf, len) - words = (z_word_t const *)buf; - - /* Do endian check at execution time instead of compile time, since ARM -- processors can change the endianess at execution time. If the -- compiler knows what the endianess will be, it can optimize out the -+ processors can change the endianness at execution time. If the -+ compiler knows what the endianness will be, it can optimize out the - check and the unused branch. */ - endian = 1; - if (*(unsigned char *)&endian) { -@@ -1060,39 +1012,26 @@ unsigned long ZEXPORT crc32_z(crc, buf, len) - #endif - - /* ========================================================================= */ --unsigned long ZEXPORT crc32(crc, buf, len) -- unsigned long crc; -- const unsigned char FAR *buf; -- uInt len; --{ -+unsigned long ZEXPORT crc32(unsigned long crc, const unsigned char FAR *buf, -+ uInt len) { - return crc32_z(crc, buf, len); - } - - /* ========================================================================= */ --uLong ZEXPORT crc32_combine64(crc1, crc2, len2) -- uLong crc1; -- uLong crc2; -- z_off64_t len2; --{ -+uLong ZEXPORT crc32_combine64(uLong crc1, uLong crc2, z_off64_t len2) { - #ifdef DYNAMIC_CRC_TABLE - once(&made, make_crc_table); - #endif /* DYNAMIC_CRC_TABLE */ -- return multmodp(x2nmodp(len2, 3), crc1) ^ crc2; -+ return multmodp(x2nmodp(len2, 3), crc1) ^ (crc2 & 0xffffffff); - } - - /* ========================================================================= */ --uLong ZEXPORT crc32_combine(crc1, crc2, len2) -- uLong crc1; -- uLong crc2; -- z_off_t len2; --{ -- return crc32_combine64(crc1, crc2, len2); -+uLong ZEXPORT crc32_combine(uLong crc1, uLong crc2, z_off_t len2) { -+ return crc32_combine64(crc1, crc2, (z_off64_t)len2); - } - - /* ========================================================================= */ --uLong ZEXPORT crc32_combine_gen64(len2) -- z_off64_t len2; --{ -+uLong ZEXPORT crc32_combine_gen64(z_off64_t len2) { - #ifdef DYNAMIC_CRC_TABLE - once(&made, make_crc_table); - #endif /* DYNAMIC_CRC_TABLE */ -@@ -1100,17 +1039,11 @@ uLong ZEXPORT crc32_combine_gen64(len2) - } - - /* ========================================================================= */ --uLong ZEXPORT crc32_combine_gen(len2) -- z_off_t len2; --{ -- return crc32_combine_gen64(len2); -+uLong ZEXPORT crc32_combine_gen(z_off_t len2) { -+ return crc32_combine_gen64((z_off64_t)len2); - } - - /* ========================================================================= */ --uLong crc32_combine_op(crc1, crc2, op) -- uLong crc1; -- uLong crc2; -- uLong op; --{ -- return multmodp(op, crc1) ^ crc2; -+uLong ZEXPORT crc32_combine_op(uLong crc1, uLong crc2, uLong op) { -+ return multmodp(op, crc1) ^ (crc2 & 0xffffffff); - } -diff --git a/src/zlib/deflate.c b/src/zlib/deflate.c -index 799fb93cc..012ea8148 100644 ---- a/src/zlib/deflate.c -+++ b/src/zlib/deflate.c -@@ -1,5 +1,5 @@ - /* deflate.c -- compress data using the deflation algorithm -- * Copyright (C) 1995-2022 Jean-loup Gailly and Mark Adler -+ * Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -@@ -52,7 +52,7 @@ - #include "deflate.h" - - const char deflate_copyright[] = -- " deflate 1.2.12 Copyright 1995-2022 Jean-loup Gailly and Mark Adler "; -+ " deflate 1.3.1 Copyright 1995-2024 Jean-loup Gailly and Mark Adler "; - /* - If you use the zlib library in a product, an acknowledgment is welcome - in the documentation of your product. If for some reason you cannot -@@ -60,9 +60,6 @@ const char deflate_copyright[] = - copyright string in the executable of your product. - */ - --/* =========================================================================== -- * Function prototypes. -- */ - typedef enum { - need_more, /* block not completed, need more input or more output */ - block_done, /* block flush performed */ -@@ -70,35 +67,16 @@ typedef enum { - finish_done /* finish done, accept no more input or output */ - } block_state; - --typedef block_state (*compress_func) OF((deflate_state *s, int flush)); -+typedef block_state (*compress_func)(deflate_state *s, int flush); - /* Compression function. Returns the block state after the call. */ - --local int deflateStateCheck OF((z_streamp strm)); --local void slide_hash OF((deflate_state *s)); --local void fill_window OF((deflate_state *s)); --local block_state deflate_stored OF((deflate_state *s, int flush)); --local block_state deflate_fast OF((deflate_state *s, int flush)); -+local block_state deflate_stored(deflate_state *s, int flush); -+local block_state deflate_fast(deflate_state *s, int flush); - #ifndef FASTEST --local block_state deflate_slow OF((deflate_state *s, int flush)); --#endif --local block_state deflate_rle OF((deflate_state *s, int flush)); --local block_state deflate_huff OF((deflate_state *s, int flush)); --local void lm_init OF((deflate_state *s)); --local void putShortMSB OF((deflate_state *s, uInt b)); --local void flush_pending OF((z_streamp strm)); --local unsigned read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); --#ifdef ASMV --# pragma message("Assembler code may have bugs -- use at your own risk") -- void match_init OF((void)); /* asm code initialization */ -- uInt longest_match OF((deflate_state *s, IPos cur_match)); --#else --local uInt longest_match OF((deflate_state *s, IPos cur_match)); --#endif -- --#ifdef ZLIB_DEBUG --local void check_match OF((deflate_state *s, IPos start, IPos match, -- int length)); -+local block_state deflate_slow(deflate_state *s, int flush); - #endif -+local block_state deflate_rle(deflate_state *s, int flush); -+local block_state deflate_huff(deflate_state *s, int flush); - - /* =========================================================================== - * Local data -@@ -160,7 +138,7 @@ local const config configuration_table[10] = { - * characters, so that a running hash key can be computed from the previous - * key instead of complete recalculation each time. - */ --#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) -+#define UPDATE_HASH(s,h,c) (h = (((h) << s->hash_shift) ^ (c)) & s->hash_mask) - - - /* =========================================================================== -@@ -191,9 +169,9 @@ local const config configuration_table[10] = { - */ - #define CLEAR_HASH(s) \ - do { \ -- s->head[s->hash_size-1] = NIL; \ -+ s->head[s->hash_size - 1] = NIL; \ - zmemzero((Bytef *)s->head, \ -- (unsigned)(s->hash_size-1)*sizeof(*s->head)); \ -+ (unsigned)(s->hash_size - 1)*sizeof(*s->head)); \ - } while (0) - - /* =========================================================================== -@@ -201,9 +179,12 @@ local const config configuration_table[10] = { - * bit values at the expense of memory usage). We slide even when level == 0 to - * keep the hash table consistent if we switch back to level > 0 later. - */ --local void slide_hash(s) -- deflate_state *s; --{ -+#if defined(__has_feature) -+# if __has_feature(memory_sanitizer) -+ __attribute__((no_sanitize("memory"))) -+# endif -+#endif -+local void slide_hash(deflate_state *s) { - unsigned n, m; - Posf *p; - uInt wsize = s->w_size; -@@ -227,30 +208,177 @@ local void slide_hash(s) - #endif - } - -+/* =========================================================================== -+ * Read a new buffer from the current input stream, update the adler32 -+ * and total number of bytes read. All deflate() input goes through -+ * this function so some applications may wish to modify it to avoid -+ * allocating a large strm->next_in buffer and copying from it. -+ * (See also flush_pending()). -+ */ -+local unsigned read_buf(z_streamp strm, Bytef *buf, unsigned size) { -+ unsigned len = strm->avail_in; -+ -+ if (len > size) len = size; -+ if (len == 0) return 0; -+ -+ strm->avail_in -= len; -+ -+ zmemcpy(buf, strm->next_in, len); -+ if (strm->state->wrap == 1) { -+ strm->adler = adler32(strm->adler, buf, len); -+ } -+#ifdef GZIP -+ else if (strm->state->wrap == 2) { -+ strm->adler = crc32(strm->adler, buf, len); -+ } -+#endif -+ strm->next_in += len; -+ strm->total_in += len; -+ -+ return len; -+} -+ -+/* =========================================================================== -+ * Fill the window when the lookahead becomes insufficient. -+ * Updates strstart and lookahead. -+ * -+ * IN assertion: lookahead < MIN_LOOKAHEAD -+ * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD -+ * At least one byte has been read, or avail_in == 0; reads are -+ * performed for at least two bytes (required for the zip translate_eol -+ * option -- not supported here). -+ */ -+local void fill_window(deflate_state *s) { -+ unsigned n; -+ unsigned more; /* Amount of free space at the end of the window. */ -+ uInt wsize = s->w_size; -+ -+ Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); -+ -+ do { -+ more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); -+ -+ /* Deal with !@#$% 64K limit: */ -+ if (sizeof(int) <= 2) { -+ if (more == 0 && s->strstart == 0 && s->lookahead == 0) { -+ more = wsize; -+ -+ } else if (more == (unsigned)(-1)) { -+ /* Very unlikely, but possible on 16 bit machine if -+ * strstart == 0 && lookahead == 1 (input done a byte at time) -+ */ -+ more--; -+ } -+ } -+ -+ /* If the window is almost full and there is insufficient lookahead, -+ * move the upper half to the lower one to make room in the upper half. -+ */ -+ if (s->strstart >= wsize + MAX_DIST(s)) { -+ -+ zmemcpy(s->window, s->window + wsize, (unsigned)wsize - more); -+ s->match_start -= wsize; -+ s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ -+ s->block_start -= (long) wsize; -+ if (s->insert > s->strstart) -+ s->insert = s->strstart; -+ slide_hash(s); -+ more += wsize; -+ } -+ if (s->strm->avail_in == 0) break; -+ -+ /* If there was no sliding: -+ * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && -+ * more == window_size - lookahead - strstart -+ * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) -+ * => more >= window_size - 2*WSIZE + 2 -+ * In the BIG_MEM or MMAP case (not yet supported), -+ * window_size == input_size + MIN_LOOKAHEAD && -+ * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. -+ * Otherwise, window_size == 2*WSIZE so more >= 2. -+ * If there was sliding, more >= WSIZE. So in all cases, more >= 2. -+ */ -+ Assert(more >= 2, "more < 2"); -+ -+ n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); -+ s->lookahead += n; -+ -+ /* Initialize the hash value now that we have some input: */ -+ if (s->lookahead + s->insert >= MIN_MATCH) { -+ uInt str = s->strstart - s->insert; -+ s->ins_h = s->window[str]; -+ UPDATE_HASH(s, s->ins_h, s->window[str + 1]); -+#if MIN_MATCH != 3 -+ Call UPDATE_HASH() MIN_MATCH-3 more times -+#endif -+ while (s->insert) { -+ UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); -+#ifndef FASTEST -+ s->prev[str & s->w_mask] = s->head[s->ins_h]; -+#endif -+ s->head[s->ins_h] = (Pos)str; -+ str++; -+ s->insert--; -+ if (s->lookahead + s->insert < MIN_MATCH) -+ break; -+ } -+ } -+ /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, -+ * but this is not important since only literal bytes will be emitted. -+ */ -+ -+ } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); -+ -+ /* If the WIN_INIT bytes after the end of the current data have never been -+ * written, then zero those bytes in order to avoid memory check reports of -+ * the use of uninitialized (or uninitialised as Julian writes) bytes by -+ * the longest match routines. Update the high water mark for the next -+ * time through here. WIN_INIT is set to MAX_MATCH since the longest match -+ * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. -+ */ -+ if (s->high_water < s->window_size) { -+ ulg curr = s->strstart + (ulg)(s->lookahead); -+ ulg init; -+ -+ if (s->high_water < curr) { -+ /* Previous high water mark below current data -- zero WIN_INIT -+ * bytes or up to end of window, whichever is less. -+ */ -+ init = s->window_size - curr; -+ if (init > WIN_INIT) -+ init = WIN_INIT; -+ zmemzero(s->window + curr, (unsigned)init); -+ s->high_water = curr + init; -+ } -+ else if (s->high_water < (ulg)curr + WIN_INIT) { -+ /* High water mark at or above current data, but below current data -+ * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up -+ * to end of window, whichever is less. -+ */ -+ init = (ulg)curr + WIN_INIT - s->high_water; -+ if (init > s->window_size - s->high_water) -+ init = s->window_size - s->high_water; -+ zmemzero(s->window + s->high_water, (unsigned)init); -+ s->high_water += init; -+ } -+ } -+ -+ Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, -+ "not enough room for search"); -+} -+ - /* ========================================================================= */ --int ZEXPORT deflateInit_(strm, level, version, stream_size) -- z_streamp strm; -- int level; -- const char *version; -- int stream_size; --{ -+int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, -+ int stream_size) { - return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, - Z_DEFAULT_STRATEGY, version, stream_size); - /* To do: ignore strm->next_in if we use it as window */ - } - - /* ========================================================================= */ --int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, -- version, stream_size) -- z_streamp strm; -- int level; -- int method; -- int windowBits; -- int memLevel; -- int strategy; -- const char *version; -- int stream_size; --{ -+int ZEXPORT deflateInit2_(z_streamp strm, int level, int method, -+ int windowBits, int memLevel, int strategy, -+ const char *version, int stream_size) { - deflate_state *s; - int wrap = 1; - static const char my_version[] = ZLIB_VERSION; -@@ -285,6 +413,8 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, - - if (windowBits < 0) { /* suppress zlib wrapper */ - wrap = 0; -+ if (windowBits < -15) -+ return Z_STREAM_ERROR; - windowBits = -windowBits; - } - #ifdef GZIP -@@ -314,7 +444,7 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, - s->hash_bits = (uInt)memLevel + 7; - s->hash_size = 1 << s->hash_bits; - s->hash_mask = s->hash_size - 1; -- s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); -+ s->hash_shift = ((s->hash_bits + MIN_MATCH-1) / MIN_MATCH); - - s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); - s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); -@@ -340,11 +470,11 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, - * sym_buf value to read moves forward three bytes. From that symbol, up to - * 31 bits are written to pending_buf. The closest the written pending_buf - * bits gets to the next sym_buf symbol to read is just before the last -- * code is written. At that time, 31*(n-2) bits have been written, just -- * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at -- * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1 -+ * code is written. At that time, 31*(n - 2) bits have been written, just -+ * after 24*(n - 2) bits have been consumed from sym_buf. sym_buf starts at -+ * 8*n bits into pending_buf. (Note that the symbol buffer fills when n - 1 - * symbols are written.) The closest the writing gets to what is unread is -- * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and -+ * then n + 14 bits. Here n is lit_bufsize, which is 16384 by default, and - * can range from 128 to 32768. - * - * Therefore, at a minimum, there are 142 bits of space between what is -@@ -363,7 +493,7 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, - * symbols from which it is being constructed. - */ - -- s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 4); -+ s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, LIT_BUFS); - s->pending_buf_size = (ulg)s->lit_bufsize * 4; - - if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || -@@ -373,8 +503,14 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, - deflateEnd (strm); - return Z_MEM_ERROR; - } -+#ifdef LIT_MEM -+ s->d_buf = (ushf *)(s->pending_buf + (s->lit_bufsize << 1)); -+ s->l_buf = s->pending_buf + (s->lit_bufsize << 2); -+ s->sym_end = s->lit_bufsize - 1; -+#else - s->sym_buf = s->pending_buf + s->lit_bufsize; - s->sym_end = (s->lit_bufsize - 1) * 3; -+#endif - /* We avoid equality with lit_bufsize*3 because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. -@@ -390,9 +526,7 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, - /* ========================================================================= - * Check for a valid deflate stream state. Return 0 if ok, 1 if not. - */ --local int deflateStateCheck (strm) -- z_streamp strm; --{ -+local int deflateStateCheck(z_streamp strm) { - deflate_state *s; - if (strm == Z_NULL || - strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) -@@ -413,11 +547,8 @@ local int deflateStateCheck (strm) - } - - /* ========================================================================= */ --int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) -- z_streamp strm; -- const Bytef *dictionary; -- uInt dictLength; --{ -+int ZEXPORT deflateSetDictionary(z_streamp strm, const Bytef *dictionary, -+ uInt dictLength) { - deflate_state *s; - uInt str, n; - int wrap; -@@ -482,11 +613,8 @@ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) - } - - /* ========================================================================= */ --int ZEXPORT deflateGetDictionary (strm, dictionary, dictLength) -- z_streamp strm; -- Bytef *dictionary; -- uInt *dictLength; --{ -+int ZEXPORT deflateGetDictionary(z_streamp strm, Bytef *dictionary, -+ uInt *dictLength) { - deflate_state *s; - uInt len; - -@@ -504,9 +632,7 @@ int ZEXPORT deflateGetDictionary (strm, dictionary, dictLength) - } - - /* ========================================================================= */ --int ZEXPORT deflateResetKeep (strm) -- z_streamp strm; --{ -+int ZEXPORT deflateResetKeep(z_streamp strm) { - deflate_state *s; - - if (deflateStateCheck(strm)) { -@@ -541,10 +667,32 @@ int ZEXPORT deflateResetKeep (strm) - return Z_OK; - } - -+/* =========================================================================== -+ * Initialize the "longest match" routines for a new zlib stream -+ */ -+local void lm_init(deflate_state *s) { -+ s->window_size = (ulg)2L*s->w_size; -+ -+ CLEAR_HASH(s); -+ -+ /* Set the default configuration parameters: -+ */ -+ s->max_lazy_match = configuration_table[s->level].max_lazy; -+ s->good_match = configuration_table[s->level].good_length; -+ s->nice_match = configuration_table[s->level].nice_length; -+ s->max_chain_length = configuration_table[s->level].max_chain; -+ -+ s->strstart = 0; -+ s->block_start = 0L; -+ s->lookahead = 0; -+ s->insert = 0; -+ s->match_length = s->prev_length = MIN_MATCH-1; -+ s->match_available = 0; -+ s->ins_h = 0; -+} -+ - /* ========================================================================= */ --int ZEXPORT deflateReset (strm) -- z_streamp strm; --{ -+int ZEXPORT deflateReset(z_streamp strm) { - int ret; - - ret = deflateResetKeep(strm); -@@ -554,10 +702,7 @@ int ZEXPORT deflateReset (strm) - } - - /* ========================================================================= */ --int ZEXPORT deflateSetHeader (strm, head) -- z_streamp strm; -- gz_headerp head; --{ -+int ZEXPORT deflateSetHeader(z_streamp strm, gz_headerp head) { - if (deflateStateCheck(strm) || strm->state->wrap != 2) - return Z_STREAM_ERROR; - strm->state->gzhead = head; -@@ -565,11 +710,7 @@ int ZEXPORT deflateSetHeader (strm, head) - } - - /* ========================================================================= */ --int ZEXPORT deflatePending (strm, pending, bits) -- unsigned *pending; -- int *bits; -- z_streamp strm; --{ -+int ZEXPORT deflatePending(z_streamp strm, unsigned *pending, int *bits) { - if (deflateStateCheck(strm)) return Z_STREAM_ERROR; - if (pending != Z_NULL) - *pending = strm->state->pending; -@@ -579,19 +720,21 @@ int ZEXPORT deflatePending (strm, pending, bits) - } - - /* ========================================================================= */ --int ZEXPORT deflatePrime (strm, bits, value) -- z_streamp strm; -- int bits; -- int value; --{ -+int ZEXPORT deflatePrime(z_streamp strm, int bits, int value) { - deflate_state *s; - int put; - - if (deflateStateCheck(strm)) return Z_STREAM_ERROR; - s = strm->state; -+#ifdef LIT_MEM -+ if (bits < 0 || bits > 16 || -+ (uchf *)s->d_buf < s->pending_out + ((Buf_size + 7) >> 3)) -+ return Z_BUF_ERROR; -+#else - if (bits < 0 || bits > 16 || - s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3)) - return Z_BUF_ERROR; -+#endif - do { - put = Buf_size - s->bi_valid; - if (put > bits) -@@ -606,11 +749,7 @@ int ZEXPORT deflatePrime (strm, bits, value) - } - - /* ========================================================================= */ --int ZEXPORT deflateParams(strm, level, strategy) -- z_streamp strm; -- int level; -- int strategy; --{ -+int ZEXPORT deflateParams(z_streamp strm, int level, int strategy) { - deflate_state *s; - compress_func func; - -@@ -655,13 +794,8 @@ int ZEXPORT deflateParams(strm, level, strategy) - } - - /* ========================================================================= */ --int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) -- z_streamp strm; -- int good_length; -- int max_lazy; -- int nice_length; -- int max_chain; --{ -+int ZEXPORT deflateTune(z_streamp strm, int good_length, int max_lazy, -+ int nice_length, int max_chain) { - deflate_state *s; - - if (deflateStateCheck(strm)) return Z_STREAM_ERROR; -@@ -674,36 +808,47 @@ int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) - } - - /* ========================================================================= -- * For the default windowBits of 15 and memLevel of 8, this function returns -- * a close to exact, as well as small, upper bound on the compressed size. -- * They are coded as constants here for a reason--if the #define's are -- * changed, then this function needs to be changed as well. The return -- * value for 15 and 8 only works for those exact settings. -+ * For the default windowBits of 15 and memLevel of 8, this function returns a -+ * close to exact, as well as small, upper bound on the compressed size. This -+ * is an expansion of ~0.03%, plus a small constant. -+ * -+ * For any setting other than those defaults for windowBits and memLevel, one -+ * of two worst case bounds is returned. This is at most an expansion of ~4% or -+ * ~13%, plus a small constant. - * -- * For any setting other than those defaults for windowBits and memLevel, -- * the value returned is a conservative worst case for the maximum expansion -- * resulting from using fixed blocks instead of stored blocks, which deflate -- * can emit on compressed data for some combinations of the parameters. -+ * Both the 0.03% and 4% derive from the overhead of stored blocks. The first -+ * one is for stored blocks of 16383 bytes (memLevel == 8), whereas the second -+ * is for stored blocks of 127 bytes (the worst case memLevel == 1). The -+ * expansion results from five bytes of header for each stored block. - * -- * This function could be more sophisticated to provide closer upper bounds for -- * every combination of windowBits and memLevel. But even the conservative -- * upper bound of about 14% expansion does not seem onerous for output buffer -- * allocation. -+ * The larger expansion of 13% results from a window size less than or equal to -+ * the symbols buffer size (windowBits <= memLevel + 7). In that case some of -+ * the data being compressed may have slid out of the sliding window, impeding -+ * a stored block from being emitted. Then the only choice is a fixed or -+ * dynamic block, where a fixed block limits the maximum expansion to 9 bits -+ * per 8-bit byte, plus 10 bits for every block. The smallest block size for -+ * which this can occur is 255 (memLevel == 2). -+ * -+ * Shifts are used to approximate divisions, for speed. - */ --uLong ZEXPORT deflateBound(strm, sourceLen) -- z_streamp strm; -- uLong sourceLen; --{ -+uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen) { - deflate_state *s; -- uLong complen, wraplen; -+ uLong fixedlen, storelen, wraplen; -+ -+ /* upper bound for fixed blocks with 9-bit literals and length 255 -+ (memLevel == 2, which is the lowest that may not use stored blocks) -- -+ ~13% overhead plus a small constant */ -+ fixedlen = sourceLen + (sourceLen >> 3) + (sourceLen >> 8) + -+ (sourceLen >> 9) + 4; - -- /* conservative upper bound for compressed data */ -- complen = sourceLen + -- ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5; -+ /* upper bound for stored blocks with length 127 (memLevel == 1) -- -+ ~4% overhead plus a small constant */ -+ storelen = sourceLen + (sourceLen >> 5) + (sourceLen >> 7) + -+ (sourceLen >> 11) + 7; - -- /* if can't get parameters, return conservative bound plus zlib wrapper */ -+ /* if can't get parameters, return larger bound plus a zlib wrapper */ - if (deflateStateCheck(strm)) -- return complen + 6; -+ return (fixedlen > storelen ? fixedlen : storelen) + 6; - - /* compute wrapper length */ - s = strm->state; -@@ -740,11 +885,13 @@ uLong ZEXPORT deflateBound(strm, sourceLen) - wraplen = 6; - } - -- /* if not default parameters, return conservative bound */ -+ /* if not default parameters, return one of the conservative bounds */ - if (s->w_bits != 15 || s->hash_bits != 8 + 7) -- return complen + wraplen; -+ return (s->w_bits <= s->hash_bits && s->level ? fixedlen : storelen) + -+ wraplen; - -- /* default settings: return tight bound for that case */ -+ /* default settings: return tight bound for that case -- ~0.03% overhead -+ plus a small constant */ - return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + - (sourceLen >> 25) + 13 - 6 + wraplen; - } -@@ -754,10 +901,7 @@ uLong ZEXPORT deflateBound(strm, sourceLen) - * IN assertion: the stream state is correct and there is enough room in - * pending_buf. - */ --local void putShortMSB (s, b) -- deflate_state *s; -- uInt b; --{ -+local void putShortMSB(deflate_state *s, uInt b) { - put_byte(s, (Byte)(b >> 8)); - put_byte(s, (Byte)(b & 0xff)); - } -@@ -768,9 +912,7 @@ local void putShortMSB (s, b) - * applications may wish to modify it to avoid allocating a large - * strm->next_out buffer and copying into it. (See also read_buf()). - */ --local void flush_pending(strm) -- z_streamp strm; --{ -+local void flush_pending(z_streamp strm) { - unsigned len; - deflate_state *s = strm->state; - -@@ -801,10 +943,7 @@ local void flush_pending(strm) - } while (0) - - /* ========================================================================= */ --int ZEXPORT deflate (strm, flush) -- z_streamp strm; -- int flush; --{ -+int ZEXPORT deflate(z_streamp strm, int flush) { - int old_flush; /* value of flush param for previous deflate call */ - deflate_state *s; - -@@ -856,7 +995,7 @@ int ZEXPORT deflate (strm, flush) - s->status = BUSY_STATE; - if (s->status == INIT_STATE) { - /* zlib header */ -- uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; -+ uInt header = (Z_DEFLATED + ((s->w_bits - 8) << 4)) << 8; - uInt level_flags; - - if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) -@@ -1116,9 +1255,7 @@ int ZEXPORT deflate (strm, flush) - } - - /* ========================================================================= */ --int ZEXPORT deflateEnd (strm) -- z_streamp strm; --{ -+int ZEXPORT deflateEnd(z_streamp strm) { - int status; - - if (deflateStateCheck(strm)) return Z_STREAM_ERROR; -@@ -1142,11 +1279,10 @@ int ZEXPORT deflateEnd (strm) - * To simplify the source, this is not supported for 16-bit MSDOS (which - * doesn't have enough memory anyway to duplicate compression states). - */ --int ZEXPORT deflateCopy (dest, source) -- z_streamp dest; -- z_streamp source; --{ -+int ZEXPORT deflateCopy(z_streamp dest, z_streamp source) { - #ifdef MAXSEG_64K -+ (void)dest; -+ (void)source; - return Z_STREAM_ERROR; - #else - deflate_state *ds; -@@ -1170,7 +1306,7 @@ int ZEXPORT deflateCopy (dest, source) - ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); - ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); - ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); -- ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, 4); -+ ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, LIT_BUFS); - - if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || - ds->pending_buf == Z_NULL) { -@@ -1181,10 +1317,15 @@ int ZEXPORT deflateCopy (dest, source) - zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); - zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos)); - zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos)); -- zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); -+ zmemcpy(ds->pending_buf, ss->pending_buf, ds->lit_bufsize * LIT_BUFS); - - ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); -+#ifdef LIT_MEM -+ ds->d_buf = (ushf *)(ds->pending_buf + (ds->lit_bufsize << 1)); -+ ds->l_buf = ds->pending_buf + (ds->lit_bufsize << 2); -+#else - ds->sym_buf = ds->pending_buf + ds->lit_bufsize; -+#endif - - ds->l_desc.dyn_tree = ds->dyn_ltree; - ds->d_desc.dyn_tree = ds->dyn_dtree; -@@ -1194,71 +1335,6 @@ int ZEXPORT deflateCopy (dest, source) - #endif /* MAXSEG_64K */ - } - --/* =========================================================================== -- * Read a new buffer from the current input stream, update the adler32 -- * and total number of bytes read. All deflate() input goes through -- * this function so some applications may wish to modify it to avoid -- * allocating a large strm->next_in buffer and copying from it. -- * (See also flush_pending()). -- */ --local unsigned read_buf(strm, buf, size) -- z_streamp strm; -- Bytef *buf; -- unsigned size; --{ -- unsigned len = strm->avail_in; -- -- if (len > size) len = size; -- if (len == 0) return 0; -- -- strm->avail_in -= len; -- -- zmemcpy(buf, strm->next_in, len); -- if (strm->state->wrap == 1) { -- strm->adler = adler32(strm->adler, buf, len); -- } --#ifdef GZIP -- else if (strm->state->wrap == 2) { -- strm->adler = crc32(strm->adler, buf, len); -- } --#endif -- strm->next_in += len; -- strm->total_in += len; -- -- return len; --} -- --/* =========================================================================== -- * Initialize the "longest match" routines for a new zlib stream -- */ --local void lm_init (s) -- deflate_state *s; --{ -- s->window_size = (ulg)2L*s->w_size; -- -- CLEAR_HASH(s); -- -- /* Set the default configuration parameters: -- */ -- s->max_lazy_match = configuration_table[s->level].max_lazy; -- s->good_match = configuration_table[s->level].good_length; -- s->nice_match = configuration_table[s->level].nice_length; -- s->max_chain_length = configuration_table[s->level].max_chain; -- -- s->strstart = 0; -- s->block_start = 0L; -- s->lookahead = 0; -- s->insert = 0; -- s->match_length = s->prev_length = MIN_MATCH-1; -- s->match_available = 0; -- s->ins_h = 0; --#ifndef FASTEST --#ifdef ASMV -- match_init(); /* initialize the asm code */ --#endif --#endif --} -- - #ifndef FASTEST - /* =========================================================================== - * Set match_start to the longest match starting at the given string and -@@ -1269,14 +1345,7 @@ local void lm_init (s) - * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 - * OUT assertion: the match length is not greater than s->lookahead. - */ --#ifndef ASMV --/* For 80x86 and 680x0, an optimized version will be provided in match.asm or -- * match.S. The code will be functionally equivalent. -- */ --local uInt longest_match(s, cur_match) -- deflate_state *s; -- IPos cur_match; /* current match */ --{ -+local uInt longest_match(deflate_state *s, IPos cur_match) { - unsigned chain_length = s->max_chain_length;/* max hash chain length */ - register Bytef *scan = s->window + s->strstart; /* current string */ - register Bytef *match; /* matched string */ -@@ -1297,10 +1366,10 @@ local uInt longest_match(s, cur_match) - */ - register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; - register ush scan_start = *(ushf*)scan; -- register ush scan_end = *(ushf*)(scan+best_len-1); -+ register ush scan_end = *(ushf*)(scan + best_len - 1); - #else - register Bytef *strend = s->window + s->strstart + MAX_MATCH; -- register Byte scan_end1 = scan[best_len-1]; -+ register Byte scan_end1 = scan[best_len - 1]; - register Byte scan_end = scan[best_len]; - #endif - -@@ -1318,7 +1387,8 @@ local uInt longest_match(s, cur_match) - */ - if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead; - -- Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); -+ Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, -+ "need lookahead"); - - do { - Assert(cur_match < s->strstart, "no future"); -@@ -1336,43 +1406,44 @@ local uInt longest_match(s, cur_match) - /* This code assumes sizeof(unsigned short) == 2. Do not use - * UNALIGNED_OK if your compiler uses a different size. - */ -- if (*(ushf*)(match+best_len-1) != scan_end || -+ if (*(ushf*)(match + best_len - 1) != scan_end || - *(ushf*)match != scan_start) continue; - - /* It is not necessary to compare scan[2] and match[2] since they are - * always equal when the other bytes match, given that the hash keys - * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at -- * strstart+3, +5, ... up to strstart+257. We check for insufficient -+ * strstart + 3, + 5, up to strstart + 257. We check for insufficient - * lookahead only every 4th comparison; the 128th check will be made -- * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is -+ * at strstart + 257. If MAX_MATCH-2 is not a multiple of 8, it is - * necessary to put more guard bytes at the end of the window, or - * to check more often for insufficient lookahead. - */ - Assert(scan[2] == match[2], "scan[2]?"); - scan++, match++; - do { -- } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && -- *(ushf*)(scan+=2) == *(ushf*)(match+=2) && -- *(ushf*)(scan+=2) == *(ushf*)(match+=2) && -- *(ushf*)(scan+=2) == *(ushf*)(match+=2) && -+ } while (*(ushf*)(scan += 2) == *(ushf*)(match += 2) && -+ *(ushf*)(scan += 2) == *(ushf*)(match += 2) && -+ *(ushf*)(scan += 2) == *(ushf*)(match += 2) && -+ *(ushf*)(scan += 2) == *(ushf*)(match += 2) && - scan < strend); - /* The funny "do {}" generates better code on most compilers */ - -- /* Here, scan <= window+strstart+257 */ -- Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); -+ /* Here, scan <= window + strstart + 257 */ -+ Assert(scan <= s->window + (unsigned)(s->window_size - 1), -+ "wild scan"); - if (*scan == *match) scan++; - -- len = (MAX_MATCH - 1) - (int)(strend-scan); -+ len = (MAX_MATCH - 1) - (int)(strend - scan); - scan = strend - (MAX_MATCH-1); - - #else /* UNALIGNED_OK */ - -- if (match[best_len] != scan_end || -- match[best_len-1] != scan_end1 || -- *match != *scan || -- *++match != scan[1]) continue; -+ if (match[best_len] != scan_end || -+ match[best_len - 1] != scan_end1 || -+ *match != *scan || -+ *++match != scan[1]) continue; - -- /* The check at best_len-1 can be removed because it will be made -+ /* The check at best_len - 1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that -@@ -1382,7 +1453,7 @@ local uInt longest_match(s, cur_match) - Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; -- * the 256th check will be made at strstart+258. -+ * the 256th check will be made at strstart + 258. - */ - do { - } while (*++scan == *++match && *++scan == *++match && -@@ -1391,7 +1462,8 @@ local uInt longest_match(s, cur_match) - *++scan == *++match && *++scan == *++match && - scan < strend); - -- Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); -+ Assert(scan <= s->window + (unsigned)(s->window_size - 1), -+ "wild scan"); - - len = MAX_MATCH - (int)(strend - scan); - scan = strend - MAX_MATCH; -@@ -1403,9 +1475,9 @@ local uInt longest_match(s, cur_match) - best_len = len; - if (len >= nice_match) break; - #ifdef UNALIGNED_OK -- scan_end = *(ushf*)(scan+best_len-1); -+ scan_end = *(ushf*)(scan + best_len - 1); - #else -- scan_end1 = scan[best_len-1]; -+ scan_end1 = scan[best_len - 1]; - scan_end = scan[best_len]; - #endif - } -@@ -1415,17 +1487,13 @@ local uInt longest_match(s, cur_match) - if ((uInt)best_len <= s->lookahead) return (uInt)best_len; - return s->lookahead; - } --#endif /* ASMV */ - - #else /* FASTEST */ - - /* --------------------------------------------------------------------------- - * Optimized version for FASTEST only - */ --local uInt longest_match(s, cur_match) -- deflate_state *s; -- IPos cur_match; /* current match */ --{ -+local uInt longest_match(deflate_state *s, IPos cur_match) { - register Bytef *scan = s->window + s->strstart; /* current string */ - register Bytef *match; /* matched string */ - register int len; /* length of current match */ -@@ -1436,7 +1504,8 @@ local uInt longest_match(s, cur_match) - */ - Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - -- Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); -+ Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, -+ "need lookahead"); - - Assert(cur_match < s->strstart, "no future"); - -@@ -1446,7 +1515,7 @@ local uInt longest_match(s, cur_match) - */ - if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; - -- /* The check at best_len-1 can be removed because it will be made -+ /* The check at best_len - 1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that -@@ -1456,7 +1525,7 @@ local uInt longest_match(s, cur_match) - Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; -- * the 256th check will be made at strstart+258. -+ * the 256th check will be made at strstart + 258. - */ - do { - } while (*++scan == *++match && *++scan == *++match && -@@ -1465,7 +1534,7 @@ local uInt longest_match(s, cur_match) - *++scan == *++match && *++scan == *++match && - scan < strend); - -- Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); -+ Assert(scan <= s->window + (unsigned)(s->window_size - 1), "wild scan"); - - len = MAX_MATCH - (int)(strend - scan); - -@@ -1485,23 +1554,27 @@ local uInt longest_match(s, cur_match) - /* =========================================================================== - * Check that the match at match_start is indeed a match. - */ --local void check_match(s, start, match, length) -- deflate_state *s; -- IPos start, match; -- int length; --{ -+local void check_match(deflate_state *s, IPos start, IPos match, int length) { - /* check that the match is indeed a match */ -- if (zmemcmp(s->window + match, -- s->window + start, length) != EQUAL) { -- fprintf(stderr, " start %u, match %u, length %d\n", -- start, match, length); -+ Bytef *back = s->window + (int)match, *here = s->window + start; -+ IPos len = length; -+ if (match == (IPos)-1) { -+ /* match starts one byte before the current window -- just compare the -+ subsequent length-1 bytes */ -+ back++; -+ here++; -+ len--; -+ } -+ if (zmemcmp(back, here, len) != EQUAL) { -+ fprintf(stderr, " start %u, match %d, length %d\n", -+ start, (int)match, length); - do { -- fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); -- } while (--length != 0); -+ fprintf(stderr, "(%02x %02x)", *back++, *here++); -+ } while (--len != 0); - z_error("invalid match"); - } - if (z_verbose > 1) { -- fprintf(stderr,"\\[%d,%d]", start-match, length); -+ fprintf(stderr,"\\[%d,%d]", start - match, length); - do { putc(s->window[start++], stderr); } while (--length != 0); - } - } -@@ -1509,137 +1582,6 @@ local void check_match(s, start, match, length) - # define check_match(s, start, match, length) - #endif /* ZLIB_DEBUG */ - --/* =========================================================================== -- * Fill the window when the lookahead becomes insufficient. -- * Updates strstart and lookahead. -- * -- * IN assertion: lookahead < MIN_LOOKAHEAD -- * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD -- * At least one byte has been read, or avail_in == 0; reads are -- * performed for at least two bytes (required for the zip translate_eol -- * option -- not supported here). -- */ --local void fill_window(s) -- deflate_state *s; --{ -- unsigned n; -- unsigned more; /* Amount of free space at the end of the window. */ -- uInt wsize = s->w_size; -- -- Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); -- -- do { -- more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); -- -- /* Deal with !@#$% 64K limit: */ -- if (sizeof(int) <= 2) { -- if (more == 0 && s->strstart == 0 && s->lookahead == 0) { -- more = wsize; -- -- } else if (more == (unsigned)(-1)) { -- /* Very unlikely, but possible on 16 bit machine if -- * strstart == 0 && lookahead == 1 (input done a byte at time) -- */ -- more--; -- } -- } -- -- /* If the window is almost full and there is insufficient lookahead, -- * move the upper half to the lower one to make room in the upper half. -- */ -- if (s->strstart >= wsize+MAX_DIST(s)) { -- -- zmemcpy(s->window, s->window+wsize, (unsigned)wsize - more); -- s->match_start -= wsize; -- s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ -- s->block_start -= (long) wsize; -- if (s->insert > s->strstart) -- s->insert = s->strstart; -- slide_hash(s); -- more += wsize; -- } -- if (s->strm->avail_in == 0) break; -- -- /* If there was no sliding: -- * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && -- * more == window_size - lookahead - strstart -- * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) -- * => more >= window_size - 2*WSIZE + 2 -- * In the BIG_MEM or MMAP case (not yet supported), -- * window_size == input_size + MIN_LOOKAHEAD && -- * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. -- * Otherwise, window_size == 2*WSIZE so more >= 2. -- * If there was sliding, more >= WSIZE. So in all cases, more >= 2. -- */ -- Assert(more >= 2, "more < 2"); -- -- n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); -- s->lookahead += n; -- -- /* Initialize the hash value now that we have some input: */ -- if (s->lookahead + s->insert >= MIN_MATCH) { -- uInt str = s->strstart - s->insert; -- s->ins_h = s->window[str]; -- UPDATE_HASH(s, s->ins_h, s->window[str + 1]); --#if MIN_MATCH != 3 -- Call UPDATE_HASH() MIN_MATCH-3 more times --#endif -- while (s->insert) { -- UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); --#ifndef FASTEST -- s->prev[str & s->w_mask] = s->head[s->ins_h]; --#endif -- s->head[s->ins_h] = (Pos)str; -- str++; -- s->insert--; -- if (s->lookahead + s->insert < MIN_MATCH) -- break; -- } -- } -- /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, -- * but this is not important since only literal bytes will be emitted. -- */ -- -- } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); -- -- /* If the WIN_INIT bytes after the end of the current data have never been -- * written, then zero those bytes in order to avoid memory check reports of -- * the use of uninitialized (or uninitialised as Julian writes) bytes by -- * the longest match routines. Update the high water mark for the next -- * time through here. WIN_INIT is set to MAX_MATCH since the longest match -- * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. -- */ -- if (s->high_water < s->window_size) { -- ulg curr = s->strstart + (ulg)(s->lookahead); -- ulg init; -- -- if (s->high_water < curr) { -- /* Previous high water mark below current data -- zero WIN_INIT -- * bytes or up to end of window, whichever is less. -- */ -- init = s->window_size - curr; -- if (init > WIN_INIT) -- init = WIN_INIT; -- zmemzero(s->window + curr, (unsigned)init); -- s->high_water = curr + init; -- } -- else if (s->high_water < (ulg)curr + WIN_INIT) { -- /* High water mark at or above current data, but below current data -- * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up -- * to end of window, whichever is less. -- */ -- init = (ulg)curr + WIN_INIT - s->high_water; -- if (init > s->window_size - s->high_water) -- init = s->window_size - s->high_water; -- zmemzero(s->window + s->high_water, (unsigned)init); -- s->high_water += init; -- } -- } -- -- Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, -- "not enough room for search"); --} -- - /* =========================================================================== - * Flush the current block, with given end-of-file flag. - * IN assertion: strstart is set to the end of the current match. -@@ -1680,12 +1622,9 @@ local void fill_window(s) - * - * deflate_stored() is written to minimize the number of times an input byte is - * copied. It is most efficient with large input and output buffers, which -- * maximizes the opportunites to have a single copy from next_in to next_out. -+ * maximizes the opportunities to have a single copy from next_in to next_out. - */ --local block_state deflate_stored(s, flush) -- deflate_state *s; -- int flush; --{ -+local block_state deflate_stored(deflate_state *s, int flush) { - /* Smallest worthy block size when not flushing or finishing. By default - * this is 32K. This can be as small as 507 bytes for memLevel == 1. For - * large input and output buffers, the stored block size will be larger. -@@ -1869,10 +1808,7 @@ local block_state deflate_stored(s, flush) - * new strings in the dictionary only for unmatched strings or for short - * matches. It is used only for the fast compression options. - */ --local block_state deflate_fast(s, flush) -- deflate_state *s; -- int flush; --{ -+local block_state deflate_fast(deflate_state *s, int flush) { - IPos hash_head; /* head of the hash chain */ - int bflush; /* set if current block must be flushed */ - -@@ -1890,7 +1826,7 @@ local block_state deflate_fast(s, flush) - if (s->lookahead == 0) break; /* flush the current block */ - } - -- /* Insert the string window[strstart .. strstart+2] in the -+ /* Insert the string window[strstart .. strstart + 2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = NIL; -@@ -1938,7 +1874,7 @@ local block_state deflate_fast(s, flush) - s->strstart += s->match_length; - s->match_length = 0; - s->ins_h = s->window[s->strstart]; -- UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); -+ UPDATE_HASH(s, s->ins_h, s->window[s->strstart + 1]); - #if MIN_MATCH != 3 - Call UPDATE_HASH() MIN_MATCH-3 more times - #endif -@@ -1949,7 +1885,7 @@ local block_state deflate_fast(s, flush) - } else { - /* No match, output a literal byte */ - Tracevv((stderr,"%c", s->window[s->strstart])); -- _tr_tally_lit (s, s->window[s->strstart], bflush); -+ _tr_tally_lit(s, s->window[s->strstart], bflush); - s->lookahead--; - s->strstart++; - } -@@ -1971,10 +1907,7 @@ local block_state deflate_fast(s, flush) - * evaluation for matches: a match is finally adopted only if there is - * no better match at the next window position. - */ --local block_state deflate_slow(s, flush) -- deflate_state *s; -- int flush; --{ -+local block_state deflate_slow(deflate_state *s, int flush) { - IPos hash_head; /* head of hash chain */ - int bflush; /* set if current block must be flushed */ - -@@ -1993,7 +1926,7 @@ local block_state deflate_slow(s, flush) - if (s->lookahead == 0) break; /* flush the current block */ - } - -- /* Insert the string window[strstart .. strstart+2] in the -+ /* Insert the string window[strstart .. strstart + 2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = NIL; -@@ -2035,17 +1968,17 @@ local block_state deflate_slow(s, flush) - uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; - /* Do not insert strings in hash table beyond this. */ - -- check_match(s, s->strstart-1, s->prev_match, s->prev_length); -+ check_match(s, s->strstart - 1, s->prev_match, s->prev_length); - -- _tr_tally_dist(s, s->strstart -1 - s->prev_match, -+ _tr_tally_dist(s, s->strstart - 1 - s->prev_match, - s->prev_length - MIN_MATCH, bflush); - - /* Insert in hash table all strings up to the end of the match. -- * strstart-1 and strstart are already inserted. If there is not -+ * strstart - 1 and strstart are already inserted. If there is not - * enough lookahead, the last two strings are not inserted in - * the hash table. - */ -- s->lookahead -= s->prev_length-1; -+ s->lookahead -= s->prev_length - 1; - s->prev_length -= 2; - do { - if (++s->strstart <= max_insert) { -@@ -2063,8 +1996,8 @@ local block_state deflate_slow(s, flush) - * single literal. If there was a match but the current match - * is longer, truncate the previous match to a single literal. - */ -- Tracevv((stderr,"%c", s->window[s->strstart-1])); -- _tr_tally_lit(s, s->window[s->strstart-1], bflush); -+ Tracevv((stderr,"%c", s->window[s->strstart - 1])); -+ _tr_tally_lit(s, s->window[s->strstart - 1], bflush); - if (bflush) { - FLUSH_BLOCK_ONLY(s, 0); - } -@@ -2082,8 +2015,8 @@ local block_state deflate_slow(s, flush) - } - Assert (flush != Z_NO_FLUSH, "no flush?"); - if (s->match_available) { -- Tracevv((stderr,"%c", s->window[s->strstart-1])); -- _tr_tally_lit(s, s->window[s->strstart-1], bflush); -+ Tracevv((stderr,"%c", s->window[s->strstart - 1])); -+ _tr_tally_lit(s, s->window[s->strstart - 1], bflush); - s->match_available = 0; - } - s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; -@@ -2102,10 +2035,7 @@ local block_state deflate_slow(s, flush) - * one. Do not maintain a hash table. (It will be regenerated if this run of - * deflate switches away from Z_RLE.) - */ --local block_state deflate_rle(s, flush) -- deflate_state *s; -- int flush; --{ -+local block_state deflate_rle(deflate_state *s, int flush) { - int bflush; /* set if current block must be flushed */ - uInt prev; /* byte at distance one to match */ - Bytef *scan, *strend; /* scan goes up to strend for length of run */ -@@ -2140,7 +2070,8 @@ local block_state deflate_rle(s, flush) - if (s->match_length > s->lookahead) - s->match_length = s->lookahead; - } -- Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); -+ Assert(scan <= s->window + (uInt)(s->window_size - 1), -+ "wild scan"); - } - - /* Emit match if have run of MIN_MATCH or longer, else emit literal */ -@@ -2155,7 +2086,7 @@ local block_state deflate_rle(s, flush) - } else { - /* No match, output a literal byte */ - Tracevv((stderr,"%c", s->window[s->strstart])); -- _tr_tally_lit (s, s->window[s->strstart], bflush); -+ _tr_tally_lit(s, s->window[s->strstart], bflush); - s->lookahead--; - s->strstart++; - } -@@ -2175,10 +2106,7 @@ local block_state deflate_rle(s, flush) - * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. - * (It will be regenerated if this run of deflate switches away from Huffman.) - */ --local block_state deflate_huff(s, flush) -- deflate_state *s; -- int flush; --{ -+local block_state deflate_huff(deflate_state *s, int flush) { - int bflush; /* set if current block must be flushed */ - - for (;;) { -@@ -2195,7 +2123,7 @@ local block_state deflate_huff(s, flush) - /* Output a literal byte */ - s->match_length = 0; - Tracevv((stderr,"%c", s->window[s->strstart])); -- _tr_tally_lit (s, s->window[s->strstart], bflush); -+ _tr_tally_lit(s, s->window[s->strstart], bflush); - s->lookahead--; - s->strstart++; - if (bflush) FLUSH_BLOCK(s, 0); -diff --git a/src/zlib/deflate.h b/src/zlib/deflate.h -index 17c226113..300c6ada6 100644 ---- a/src/zlib/deflate.h -+++ b/src/zlib/deflate.h -@@ -1,5 +1,5 @@ - /* deflate.h -- internal compression state -- * Copyright (C) 1995-2018 Jean-loup Gailly -+ * Copyright (C) 1995-2024 Jean-loup Gailly - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -@@ -23,6 +23,10 @@ - # define GZIP - #endif - -+/* define LIT_MEM to slightly increase the speed of deflate (order 1% to 2%) at -+ the cost of a larger memory footprint */ -+/* #define LIT_MEM */ -+ - /* =========================================================================== - * Internal compression state. - */ -@@ -217,7 +221,14 @@ typedef struct internal_state { - /* Depth of each subtree used as tie breaker for trees of equal frequency - */ - -+#ifdef LIT_MEM -+# define LIT_BUFS 5 -+ ushf *d_buf; /* buffer for distances */ -+ uchf *l_buf; /* buffer for literals/lengths */ -+#else -+# define LIT_BUFS 4 - uchf *sym_buf; /* buffer for distances and literals/lengths */ -+#endif - - uInt lit_bufsize; - /* Size of match buffer for literals/lengths. There are 4 reasons for -@@ -239,7 +250,7 @@ typedef struct internal_state { - * - I can't count above 4 - */ - -- uInt sym_next; /* running index in sym_buf */ -+ uInt sym_next; /* running index in symbol buffer */ - uInt sym_end; /* symbol table full when sym_next reaches this */ - - ulg opt_len; /* bit length of current block with optimal trees */ -@@ -291,14 +302,14 @@ typedef struct internal_state { - memory checker errors from longest match routines */ - - /* in trees.c */ --void ZLIB_INTERNAL _tr_init OF((deflate_state *s)); --int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); --void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf, -- ulg stored_len, int last)); --void ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s)); --void ZLIB_INTERNAL _tr_align OF((deflate_state *s)); --void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, -- ulg stored_len, int last)); -+void ZLIB_INTERNAL _tr_init(deflate_state *s); -+int ZLIB_INTERNAL _tr_tally(deflate_state *s, unsigned dist, unsigned lc); -+void ZLIB_INTERNAL _tr_flush_block(deflate_state *s, charf *buf, -+ ulg stored_len, int last); -+void ZLIB_INTERNAL _tr_flush_bits(deflate_state *s); -+void ZLIB_INTERNAL _tr_align(deflate_state *s); -+void ZLIB_INTERNAL _tr_stored_block(deflate_state *s, charf *buf, -+ ulg stored_len, int last); - - #define d_code(dist) \ - ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) -@@ -318,6 +329,25 @@ void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, - extern const uch ZLIB_INTERNAL _dist_code[]; - #endif - -+#ifdef LIT_MEM -+# define _tr_tally_lit(s, c, flush) \ -+ { uch cc = (c); \ -+ s->d_buf[s->sym_next] = 0; \ -+ s->l_buf[s->sym_next++] = cc; \ -+ s->dyn_ltree[cc].Freq++; \ -+ flush = (s->sym_next == s->sym_end); \ -+ } -+# define _tr_tally_dist(s, distance, length, flush) \ -+ { uch len = (uch)(length); \ -+ ush dist = (ush)(distance); \ -+ s->d_buf[s->sym_next] = dist; \ -+ s->l_buf[s->sym_next++] = len; \ -+ dist--; \ -+ s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ -+ s->dyn_dtree[d_code(dist)].Freq++; \ -+ flush = (s->sym_next == s->sym_end); \ -+ } -+#else - # define _tr_tally_lit(s, c, flush) \ - { uch cc = (c); \ - s->sym_buf[s->sym_next++] = 0; \ -@@ -329,14 +359,15 @@ void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, - # define _tr_tally_dist(s, distance, length, flush) \ - { uch len = (uch)(length); \ - ush dist = (ush)(distance); \ -- s->sym_buf[s->sym_next++] = dist; \ -- s->sym_buf[s->sym_next++] = dist >> 8; \ -+ s->sym_buf[s->sym_next++] = (uch)dist; \ -+ s->sym_buf[s->sym_next++] = (uch)(dist >> 8); \ - s->sym_buf[s->sym_next++] = len; \ - dist--; \ - s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ - s->dyn_dtree[d_code(dist)].Freq++; \ - flush = (s->sym_next == s->sym_end); \ - } -+#endif - #else - # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) - # define _tr_tally_dist(s, distance, length, flush) \ -diff --git a/src/zlib/gzclose.c b/src/zlib/gzclose.c -index caeb99a31..48d6a86f0 100644 ---- a/src/zlib/gzclose.c -+++ b/src/zlib/gzclose.c -@@ -8,9 +8,7 @@ - /* gzclose() is in a separate file so that it is linked in only if it is used. - That way the other gzclose functions can be used instead to avoid linking in - unneeded compression or decompression routines. */ --int ZEXPORT gzclose(file) -- gzFile file; --{ -+int ZEXPORT gzclose(gzFile file) { - #ifndef NO_GZCOMPRESS - gz_statep state; - -diff --git a/src/zlib/gzguts.h b/src/zlib/gzguts.h -index 57faf3716..eba72085b 100644 ---- a/src/zlib/gzguts.h -+++ b/src/zlib/gzguts.h -@@ -1,5 +1,5 @@ - /* gzguts.h -- zlib internal header definitions for gz* operations -- * Copyright (C) 2004-2019 Mark Adler -+ * Copyright (C) 2004-2024 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -@@ -7,9 +7,8 @@ - # ifndef _LARGEFILE_SOURCE - # define _LARGEFILE_SOURCE 1 - # endif --# ifdef _FILE_OFFSET_BITS --# undef _FILE_OFFSET_BITS --# endif -+# undef _FILE_OFFSET_BITS -+# undef _TIME_BITS - #endif - - #ifdef HAVE_HIDDEN -@@ -119,8 +118,8 @@ - - /* gz* functions always use library allocation functions */ - #ifndef STDC -- extern voidp malloc OF((uInt size)); -- extern void free OF((voidpf ptr)); -+ extern voidp malloc(uInt size); -+ extern void free(voidpf ptr); - #endif - - /* get errno and strerror definition */ -@@ -138,10 +137,10 @@ - - /* provide prototypes for these when building zlib without LFS */ - #if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0 -- ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); -- ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); -- ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); -- ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); -+ ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *); -+ ZEXTERN z_off64_t ZEXPORT gzseek64(gzFile, z_off64_t, int); -+ ZEXTERN z_off64_t ZEXPORT gztell64(gzFile); -+ ZEXTERN z_off64_t ZEXPORT gzoffset64(gzFile); - #endif - - /* default memLevel */ -@@ -203,17 +202,13 @@ typedef struct { - typedef gz_state FAR *gz_statep; - - /* shared functions */ --void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *)); -+void ZLIB_INTERNAL gz_error(gz_statep, int, const char *); - #if defined UNDER_CE --char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error)); -+char ZLIB_INTERNAL *gz_strwinerror(DWORD error); - #endif - - /* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t - value -- needed when comparing unsigned to z_off64_t, which is signed - (possible z_off64_t types off_t, off64_t, and long are all signed) */ --#ifdef INT_MAX --# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX) --#else --unsigned ZLIB_INTERNAL gz_intmax OF((void)); --# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax()) --#endif -+unsigned ZLIB_INTERNAL gz_intmax(void); -+#define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax()) -diff --git a/src/zlib/gzlib.c b/src/zlib/gzlib.c -index dddaf2687..983153cc8 100644 ---- a/src/zlib/gzlib.c -+++ b/src/zlib/gzlib.c -@@ -1,5 +1,5 @@ - /* gzlib.c -- zlib functions common to reading and writing gzip files -- * Copyright (C) 2004-2019 Mark Adler -+ * Copyright (C) 2004-2024 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -@@ -15,10 +15,6 @@ - #endif - #endif - --/* Local functions */ --local void gz_reset OF((gz_statep)); --local gzFile gz_open OF((const void *, int, const char *)); -- - #if defined UNDER_CE - - /* Map the Windows error number in ERROR to a locale-dependent error message -@@ -30,9 +26,7 @@ local gzFile gz_open OF((const void *, int, const char *)); - - The gz_strwinerror function does not change the current setting of - GetLastError. */ --char ZLIB_INTERNAL *gz_strwinerror (error) -- DWORD error; --{ -+char ZLIB_INTERNAL *gz_strwinerror(DWORD error) { - static char buf[1024]; - - wchar_t *msgbuf; -@@ -72,9 +66,7 @@ char ZLIB_INTERNAL *gz_strwinerror (error) - #endif /* UNDER_CE */ - - /* Reset gzip file state */ --local void gz_reset(state) -- gz_statep state; --{ -+local void gz_reset(gz_statep state) { - state->x.have = 0; /* no output data available */ - if (state->mode == GZ_READ) { /* for reading ... */ - state->eof = 0; /* not at end of file */ -@@ -90,11 +82,7 @@ local void gz_reset(state) - } - - /* Open a gzip file either by name or file descriptor. */ --local gzFile gz_open(path, fd, mode) -- const void *path; -- int fd; -- const char *mode; --{ -+local gzFile gz_open(const void *path, int fd, const char *mode) { - gz_statep state; - z_size_t len; - int oflag; -@@ -269,26 +257,17 @@ local gzFile gz_open(path, fd, mode) - } - - /* -- see zlib.h -- */ --gzFile ZEXPORT gzopen(path, mode) -- const char *path; -- const char *mode; --{ -+gzFile ZEXPORT gzopen(const char *path, const char *mode) { - return gz_open(path, -1, mode); - } - - /* -- see zlib.h -- */ --gzFile ZEXPORT gzopen64(path, mode) -- const char *path; -- const char *mode; --{ -+gzFile ZEXPORT gzopen64(const char *path, const char *mode) { - return gz_open(path, -1, mode); - } - - /* -- see zlib.h -- */ --gzFile ZEXPORT gzdopen(fd, mode) -- int fd; -- const char *mode; --{ -+gzFile ZEXPORT gzdopen(int fd, const char *mode) { - char *path; /* identifier for error messages */ - gzFile gz; - -@@ -306,19 +285,13 @@ gzFile ZEXPORT gzdopen(fd, mode) - - /* -- see zlib.h -- */ - #ifdef WIDECHAR --gzFile ZEXPORT gzopen_w(path, mode) -- const wchar_t *path; -- const char *mode; --{ -+gzFile ZEXPORT gzopen_w(const wchar_t *path, const char *mode) { - return gz_open(path, -2, mode); - } - #endif - - /* -- see zlib.h -- */ --int ZEXPORT gzbuffer(file, size) -- gzFile file; -- unsigned size; --{ -+int ZEXPORT gzbuffer(gzFile file, unsigned size) { - gz_statep state; - - /* get internal structure and check integrity */ -@@ -335,16 +308,14 @@ int ZEXPORT gzbuffer(file, size) - /* check and set requested size */ - if ((size << 1) < size) - return -1; /* need to be able to double it */ -- if (size < 2) -- size = 2; /* need two bytes to check magic header */ -+ if (size < 8) -+ size = 8; /* needed to behave well with flushing */ - state->want = size; - return 0; - } - - /* -- see zlib.h -- */ --int ZEXPORT gzrewind(file) -- gzFile file; --{ -+int ZEXPORT gzrewind(gzFile file) { - gz_statep state; - - /* get internal structure */ -@@ -365,11 +336,7 @@ int ZEXPORT gzrewind(file) - } - - /* -- see zlib.h -- */ --z_off64_t ZEXPORT gzseek64(file, offset, whence) -- gzFile file; -- z_off64_t offset; -- int whence; --{ -+z_off64_t ZEXPORT gzseek64(gzFile file, z_off64_t offset, int whence) { - unsigned n; - z_off64_t ret; - gz_statep state; -@@ -442,11 +409,7 @@ z_off64_t ZEXPORT gzseek64(file, offset, whence) - } - - /* -- see zlib.h -- */ --z_off_t ZEXPORT gzseek(file, offset, whence) -- gzFile file; -- z_off_t offset; -- int whence; --{ -+z_off_t ZEXPORT gzseek(gzFile file, z_off_t offset, int whence) { - z_off64_t ret; - - ret = gzseek64(file, (z_off64_t)offset, whence); -@@ -454,9 +417,7 @@ z_off_t ZEXPORT gzseek(file, offset, whence) - } - - /* -- see zlib.h -- */ --z_off64_t ZEXPORT gztell64(file) -- gzFile file; --{ -+z_off64_t ZEXPORT gztell64(gzFile file) { - gz_statep state; - - /* get internal structure and check integrity */ -@@ -471,9 +432,7 @@ z_off64_t ZEXPORT gztell64(file) - } - - /* -- see zlib.h -- */ --z_off_t ZEXPORT gztell(file) -- gzFile file; --{ -+z_off_t ZEXPORT gztell(gzFile file) { - z_off64_t ret; - - ret = gztell64(file); -@@ -481,9 +440,7 @@ z_off_t ZEXPORT gztell(file) - } - - /* -- see zlib.h -- */ --z_off64_t ZEXPORT gzoffset64(file) -- gzFile file; --{ -+z_off64_t ZEXPORT gzoffset64(gzFile file) { - z_off64_t offset; - gz_statep state; - -@@ -504,9 +461,7 @@ z_off64_t ZEXPORT gzoffset64(file) - } - - /* -- see zlib.h -- */ --z_off_t ZEXPORT gzoffset(file) -- gzFile file; --{ -+z_off_t ZEXPORT gzoffset(gzFile file) { - z_off64_t ret; - - ret = gzoffset64(file); -@@ -514,9 +469,7 @@ z_off_t ZEXPORT gzoffset(file) - } - - /* -- see zlib.h -- */ --int ZEXPORT gzeof(file) -- gzFile file; --{ -+int ZEXPORT gzeof(gzFile file) { - gz_statep state; - - /* get internal structure and check integrity */ -@@ -531,10 +484,7 @@ int ZEXPORT gzeof(file) - } - - /* -- see zlib.h -- */ --const char * ZEXPORT gzerror(file, errnum) -- gzFile file; -- int *errnum; --{ -+const char * ZEXPORT gzerror(gzFile file, int *errnum) { - gz_statep state; - - /* get internal structure and check integrity */ -@@ -552,9 +502,7 @@ const char * ZEXPORT gzerror(file, errnum) - } - - /* -- see zlib.h -- */ --void ZEXPORT gzclearerr(file) -- gzFile file; --{ -+void ZEXPORT gzclearerr(gzFile file) { - gz_statep state; - - /* get internal structure and check integrity */ -@@ -578,11 +526,7 @@ void ZEXPORT gzclearerr(file) - memory). Simply save the error message as a static string. If there is an - allocation failure constructing the error message, then convert the error to - out of memory. */ --void ZLIB_INTERNAL gz_error(state, err, msg) -- gz_statep state; -- int err; -- const char *msg; --{ -+void ZLIB_INTERNAL gz_error(gz_statep state, int err, const char *msg) { - /* free previously allocated message and clear */ - if (state->msg != NULL) { - if (state->err != Z_MEM_ERROR) -@@ -619,21 +563,20 @@ void ZLIB_INTERNAL gz_error(state, err, msg) - #endif - } - --#ifndef INT_MAX - /* portably return maximum value for an int (when limits.h presumed not - available) -- we need to do this to cover cases where 2's complement not - used, since C standard permits 1's complement and sign-bit representations, - otherwise we could just use ((unsigned)-1) >> 1 */ --unsigned ZLIB_INTERNAL gz_intmax() --{ -- unsigned p, q; -- -- p = 1; -+unsigned ZLIB_INTERNAL gz_intmax(void) { -+#ifdef INT_MAX -+ return INT_MAX; -+#else -+ unsigned p = 1, q; - do { - q = p; - p <<= 1; - p++; - } while (p > q); - return q >> 1; --} - #endif -+} -diff --git a/src/zlib/gzread.c b/src/zlib/gzread.c -index 884c9bfe4..4168cbc88 100644 ---- a/src/zlib/gzread.c -+++ b/src/zlib/gzread.c -@@ -5,25 +5,12 @@ - - #include "gzguts.h" - --/* Local functions */ --local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *)); --local int gz_avail OF((gz_statep)); --local int gz_look OF((gz_statep)); --local int gz_decomp OF((gz_statep)); --local int gz_fetch OF((gz_statep)); --local int gz_skip OF((gz_statep, z_off64_t)); --local z_size_t gz_read OF((gz_statep, voidp, z_size_t)); -- - /* Use read() to load a buffer -- return -1 on error, otherwise 0. Read from - state->fd, and update state->eof, state->err, and state->msg as appropriate. - This function needs to loop on read(), since read() is not guaranteed to - read the number of bytes requested, depending on the type of descriptor. */ --local int gz_load(state, buf, len, have) -- gz_statep state; -- unsigned char *buf; -- unsigned len; -- unsigned *have; --{ -+local int gz_load(gz_statep state, unsigned char *buf, unsigned len, -+ unsigned *have) { - int ret; - unsigned get, max = ((unsigned)-1 >> 2) + 1; - -@@ -53,9 +40,7 @@ local int gz_load(state, buf, len, have) - If strm->avail_in != 0, then the current data is moved to the beginning of - the input buffer, and then the remainder of the buffer is loaded with the - available data from the input file. */ --local int gz_avail(state) -- gz_statep state; --{ -+local int gz_avail(gz_statep state) { - unsigned got; - z_streamp strm = &(state->strm); - -@@ -88,9 +73,7 @@ local int gz_avail(state) - case, all further file reads will be directly to either the output buffer or - a user buffer. If decompressing, the inflate state will be initialized. - gz_look() will return 0 on success or -1 on failure. */ --local int gz_look(state) -- gz_statep state; --{ -+local int gz_look(gz_statep state) { - z_streamp strm = &(state->strm); - - /* allocate read buffers and inflate memory */ -@@ -157,11 +140,9 @@ local int gz_look(state) - the output buffer is larger than the input buffer, which also assures - space for gzungetc() */ - state->x.next = state->out; -- if (strm->avail_in) { -- memcpy(state->x.next, strm->next_in, strm->avail_in); -- state->x.have = strm->avail_in; -- strm->avail_in = 0; -- } -+ memcpy(state->x.next, strm->next_in, strm->avail_in); -+ state->x.have = strm->avail_in; -+ strm->avail_in = 0; - state->how = COPY; - state->direct = 1; - return 0; -@@ -172,9 +153,7 @@ local int gz_look(state) - data. If the gzip stream completes, state->how is reset to LOOK to look for - the next gzip stream or raw data, once state->x.have is depleted. Returns 0 - on success, -1 on failure. */ --local int gz_decomp(state) -- gz_statep state; --{ -+local int gz_decomp(gz_statep state) { - int ret = Z_OK; - unsigned had; - z_streamp strm = &(state->strm); -@@ -226,9 +205,7 @@ local int gz_decomp(state) - looked for to determine whether to copy or decompress. Returns -1 on error, - otherwise 0. gz_fetch() will leave state->how as COPY or GZIP unless the - end of the input file has been reached and all data has been processed. */ --local int gz_fetch(state) -- gz_statep state; --{ -+local int gz_fetch(gz_statep state) { - z_streamp strm = &(state->strm); - - do { -@@ -256,10 +233,7 @@ local int gz_fetch(state) - } - - /* Skip len uncompressed bytes of output. Return -1 on error, 0 on success. */ --local int gz_skip(state, len) -- gz_statep state; -- z_off64_t len; --{ -+local int gz_skip(gz_statep state, z_off64_t len) { - unsigned n; - - /* skip over len bytes or reach end-of-file, whichever comes first */ -@@ -291,11 +265,7 @@ local int gz_skip(state, len) - input. Return the number of bytes read. If zero is returned, either the - end of file was reached, or there was an error. state->err must be - consulted in that case to determine which. */ --local z_size_t gz_read(state, buf, len) -- gz_statep state; -- voidp buf; -- z_size_t len; --{ -+local z_size_t gz_read(gz_statep state, voidp buf, z_size_t len) { - z_size_t got; - unsigned n; - -@@ -372,11 +342,7 @@ local z_size_t gz_read(state, buf, len) - } - - /* -- see zlib.h -- */ --int ZEXPORT gzread(file, buf, len) -- gzFile file; -- voidp buf; -- unsigned len; --{ -+int ZEXPORT gzread(gzFile file, voidp buf, unsigned len) { - gz_statep state; - - /* get internal structure */ -@@ -408,12 +374,7 @@ int ZEXPORT gzread(file, buf, len) - } - - /* -- see zlib.h -- */ --z_size_t ZEXPORT gzfread(buf, size, nitems, file) -- voidp buf; -- z_size_t size; -- z_size_t nitems; -- gzFile file; --{ -+z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems, gzFile file) { - z_size_t len; - gz_statep state; - -@@ -444,9 +405,7 @@ z_size_t ZEXPORT gzfread(buf, size, nitems, file) - #else - # undef gzgetc - #endif --int ZEXPORT gzgetc(file) -- gzFile file; --{ -+int ZEXPORT gzgetc(gzFile file) { - unsigned char buf[1]; - gz_statep state; - -@@ -471,17 +430,12 @@ int ZEXPORT gzgetc(file) - return gz_read(state, buf, 1) < 1 ? -1 : buf[0]; - } - --int ZEXPORT gzgetc_(file) --gzFile file; --{ -+int ZEXPORT gzgetc_(gzFile file) { - return gzgetc(file); - } - - /* -- see zlib.h -- */ --int ZEXPORT gzungetc(c, file) -- int c; -- gzFile file; --{ -+int ZEXPORT gzungetc(int c, gzFile file) { - gz_statep state; - - /* get internal structure */ -@@ -489,6 +443,10 @@ int ZEXPORT gzungetc(c, file) - return -1; - state = (gz_statep)file; - -+ /* in case this was just opened, set up the input buffer */ -+ if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0) -+ (void)gz_look(state); -+ - /* check that we're reading and that there's no (serious) error */ - if (state->mode != GZ_READ || - (state->err != Z_OK && state->err != Z_BUF_ERROR)) -@@ -538,11 +496,7 @@ int ZEXPORT gzungetc(c, file) - } - - /* -- see zlib.h -- */ --char * ZEXPORT gzgets(file, buf, len) -- gzFile file; -- char *buf; -- int len; --{ -+char * ZEXPORT gzgets(gzFile file, char *buf, int len) { - unsigned left, n; - char *str; - unsigned char *eol; -@@ -602,9 +556,7 @@ char * ZEXPORT gzgets(file, buf, len) - } - - /* -- see zlib.h -- */ --int ZEXPORT gzdirect(file) -- gzFile file; --{ -+int ZEXPORT gzdirect(gzFile file) { - gz_statep state; - - /* get internal structure */ -@@ -622,9 +574,7 @@ int ZEXPORT gzdirect(file) - } - - /* -- see zlib.h -- */ --int ZEXPORT gzclose_r(file) -- gzFile file; --{ -+int ZEXPORT gzclose_r(gzFile file) { - int ret, err; - gz_statep state; - -diff --git a/src/zlib/gzwrite.c b/src/zlib/gzwrite.c -index a8ffc8f53..435b4621b 100644 ---- a/src/zlib/gzwrite.c -+++ b/src/zlib/gzwrite.c -@@ -5,18 +5,10 @@ - - #include "gzguts.h" - --/* Local functions */ --local int gz_init OF((gz_statep)); --local int gz_comp OF((gz_statep, int)); --local int gz_zero OF((gz_statep, z_off64_t)); --local z_size_t gz_write OF((gz_statep, voidpc, z_size_t)); -- - /* Initialize state for writing a gzip file. Mark initialization by setting - state->size to non-zero. Return -1 on a memory allocation failure, or 0 on - success. */ --local int gz_init(state) -- gz_statep state; --{ -+local int gz_init(gz_statep state) { - int ret; - z_streamp strm = &(state->strm); - -@@ -70,10 +62,7 @@ local int gz_init(state) - deflate() flush value. If flush is Z_FINISH, then the deflate() state is - reset to start a new gzip stream. If gz->direct is true, then simply write - to the output file without compressing, and ignore flush. */ --local int gz_comp(state, flush) -- gz_statep state; -- int flush; --{ -+local int gz_comp(gz_statep state, int flush) { - int ret, writ; - unsigned have, put, max = ((unsigned)-1 >> 2) + 1; - z_streamp strm = &(state->strm); -@@ -151,10 +140,7 @@ local int gz_comp(state, flush) - - /* Compress len zeros to output. Return -1 on a write error or memory - allocation failure by gz_comp(), or 0 on success. */ --local int gz_zero(state, len) -- gz_statep state; -- z_off64_t len; --{ -+local int gz_zero(gz_statep state, z_off64_t len) { - int first; - unsigned n; - z_streamp strm = &(state->strm); -@@ -184,11 +170,7 @@ local int gz_zero(state, len) - - /* Write len bytes from buf to file. Return the number of bytes written. If - the returned value is less than len, then there was an error. */ --local z_size_t gz_write(state, buf, len) -- gz_statep state; -- voidpc buf; -- z_size_t len; --{ -+local z_size_t gz_write(gz_statep state, voidpc buf, z_size_t len) { - z_size_t put = len; - - /* if len is zero, avoid unnecessary operations */ -@@ -252,11 +234,7 @@ local z_size_t gz_write(state, buf, len) - } - - /* -- see zlib.h -- */ --int ZEXPORT gzwrite(file, buf, len) -- gzFile file; -- voidpc buf; -- unsigned len; --{ -+int ZEXPORT gzwrite(gzFile file, voidpc buf, unsigned len) { - gz_statep state; - - /* get internal structure */ -@@ -280,12 +258,8 @@ int ZEXPORT gzwrite(file, buf, len) - } - - /* -- see zlib.h -- */ --z_size_t ZEXPORT gzfwrite(buf, size, nitems, file) -- voidpc buf; -- z_size_t size; -- z_size_t nitems; -- gzFile file; --{ -+z_size_t ZEXPORT gzfwrite(voidpc buf, z_size_t size, z_size_t nitems, -+ gzFile file) { - z_size_t len; - gz_statep state; - -@@ -310,10 +284,7 @@ z_size_t ZEXPORT gzfwrite(buf, size, nitems, file) - } - - /* -- see zlib.h -- */ --int ZEXPORT gzputc(file, c) -- gzFile file; -- int c; --{ -+int ZEXPORT gzputc(gzFile file, int c) { - unsigned have; - unsigned char buf[1]; - gz_statep state; -@@ -358,10 +329,7 @@ int ZEXPORT gzputc(file, c) - } - - /* -- see zlib.h -- */ --int ZEXPORT gzputs(file, s) -- gzFile file; -- const char *s; --{ -+int ZEXPORT gzputs(gzFile file, const char *s) { - z_size_t len, put; - gz_statep state; - -@@ -388,8 +356,7 @@ int ZEXPORT gzputs(file, s) - #include - - /* -- see zlib.h -- */ --int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) --{ -+int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) { - int len; - unsigned left; - char *next; -@@ -460,8 +427,7 @@ int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) - return len; - } - --int ZEXPORTVA gzprintf(gzFile file, const char *format, ...) --{ -+int ZEXPORTVA gzprintf(gzFile file, const char *format, ...) { - va_list va; - int ret; - -@@ -474,13 +440,10 @@ int ZEXPORTVA gzprintf(gzFile file, const char *format, ...) - #else /* !STDC && !Z_HAVE_STDARG_H */ - - /* -- see zlib.h -- */ --int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, -- a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) -- gzFile file; -- const char *format; -- int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, -- a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; --{ -+int ZEXPORTVA gzprintf(gzFile file, const char *format, int a1, int a2, int a3, -+ int a4, int a5, int a6, int a7, int a8, int a9, int a10, -+ int a11, int a12, int a13, int a14, int a15, int a16, -+ int a17, int a18, int a19, int a20) { - unsigned len, left; - char *next; - gz_statep state; -@@ -562,10 +525,7 @@ int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, - #endif - - /* -- see zlib.h -- */ --int ZEXPORT gzflush(file, flush) -- gzFile file; -- int flush; --{ -+int ZEXPORT gzflush(gzFile file, int flush) { - gz_statep state; - - /* get internal structure */ -@@ -594,11 +554,7 @@ int ZEXPORT gzflush(file, flush) - } - - /* -- see zlib.h -- */ --int ZEXPORT gzsetparams(file, level, strategy) -- gzFile file; -- int level; -- int strategy; --{ -+int ZEXPORT gzsetparams(gzFile file, int level, int strategy) { - gz_statep state; - z_streamp strm; - -@@ -609,7 +565,7 @@ int ZEXPORT gzsetparams(file, level, strategy) - strm = &(state->strm); - - /* check that we're writing and that there's no error */ -- if (state->mode != GZ_WRITE || state->err != Z_OK) -+ if (state->mode != GZ_WRITE || state->err != Z_OK || state->direct) - return Z_STREAM_ERROR; - - /* if no change is requested, then do nothing */ -@@ -636,9 +592,7 @@ int ZEXPORT gzsetparams(file, level, strategy) - } - - /* -- see zlib.h -- */ --int ZEXPORT gzclose_w(file) -- gzFile file; --{ -+int ZEXPORT gzclose_w(gzFile file) { - int ret = Z_OK; - gz_statep state; - -diff --git a/src/zlib/infback.c b/src/zlib/infback.c -index a390c58e8..e7b25b307 100644 ---- a/src/zlib/infback.c -+++ b/src/zlib/infback.c -@@ -15,9 +15,6 @@ - #include "inflate.h" - #include "inffast.h" - --/* function prototypes */ --local void fixedtables OF((struct inflate_state FAR *state)); -- - /* - strm provides memory allocation functions in zalloc and zfree, or - Z_NULL to use the library memory allocation functions. -@@ -25,13 +22,9 @@ local void fixedtables OF((struct inflate_state FAR *state)); - windowBits is in the range 8..15, and window is a user-supplied - window and output buffer that is 2**windowBits bytes. - */ --int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) --z_streamp strm; --int windowBits; --unsigned char FAR *window; --const char *version; --int stream_size; --{ -+int ZEXPORT inflateBackInit_(z_streamp strm, int windowBits, -+ unsigned char FAR *window, const char *version, -+ int stream_size) { - struct inflate_state FAR *state; - - if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || -@@ -66,6 +59,7 @@ int stream_size; - state->window = window; - state->wnext = 0; - state->whave = 0; -+ state->sane = 1; - return Z_OK; - } - -@@ -79,9 +73,7 @@ int stream_size; - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ --local void fixedtables(state) --struct inflate_state FAR *state; --{ -+local void fixedtables(struct inflate_state FAR *state) { - #ifdef BUILDFIXED - static int virgin = 1; - static code *lenfix, *distfix; -@@ -247,13 +239,8 @@ struct inflate_state FAR *state; - inflateBack() can also return Z_STREAM_ERROR if the input parameters - are not correct, i.e. strm is Z_NULL or the state was not initialized. - */ --int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) --z_streamp strm; --in_func in; --void FAR *in_desc; --out_func out; --void FAR *out_desc; --{ -+int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc, -+ out_func out, void FAR *out_desc) { - struct inflate_state FAR *state; - z_const unsigned char FAR *next; /* next input */ - unsigned char FAR *put; /* next output */ -@@ -605,33 +592,33 @@ void FAR *out_desc; - break; - - case DONE: -- /* inflate stream terminated properly -- write leftover output */ -+ /* inflate stream terminated properly */ - ret = Z_STREAM_END; -- if (left < state->wsize) { -- if (out(out_desc, state->window, state->wsize - left)) -- ret = Z_BUF_ERROR; -- } - goto inf_leave; - - case BAD: - ret = Z_DATA_ERROR; - goto inf_leave; - -- default: /* can't happen, but makes compilers happy */ -+ default: -+ /* can't happen, but makes compilers happy */ - ret = Z_STREAM_ERROR; - goto inf_leave; - } - -- /* Return unused input */ -+ /* Write leftover output and return unused input */ - inf_leave: -+ if (left < state->wsize) { -+ if (out(out_desc, state->window, state->wsize - left) && -+ ret == Z_STREAM_END) -+ ret = Z_BUF_ERROR; -+ } - strm->next_in = next; - strm->avail_in = have; - return ret; - } - --int ZEXPORT inflateBackEnd(strm) --z_streamp strm; --{ -+int ZEXPORT inflateBackEnd(z_streamp strm) { - if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) - return Z_STREAM_ERROR; - ZFREE(strm, strm->state); -diff --git a/src/zlib/inffast.c b/src/zlib/inffast.c -index 1fec7f363..9354676e7 100644 ---- a/src/zlib/inffast.c -+++ b/src/zlib/inffast.c -@@ -47,10 +47,7 @@ - requires strm->avail_out >= 258 for each loop to avoid checking for - output space. - */ --void ZLIB_INTERNAL inflate_fast(strm, start) --z_streamp strm; --unsigned start; /* inflate()'s starting value for strm->avail_out */ --{ -+void ZLIB_INTERNAL inflate_fast(z_streamp strm, unsigned start) { - struct inflate_state FAR *state; - z_const unsigned char FAR *in; /* local strm->next_in */ - z_const unsigned char FAR *last; /* have enough input while in < last */ -diff --git a/src/zlib/inffast.h b/src/zlib/inffast.h -index e5c1aa4ca..49c6d156c 100644 ---- a/src/zlib/inffast.h -+++ b/src/zlib/inffast.h -@@ -8,4 +8,4 @@ - subject to change. Applications should only use zlib.h. - */ - --void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start)); -+void ZLIB_INTERNAL inflate_fast(z_streamp strm, unsigned start); -diff --git a/src/zlib/inflate.c b/src/zlib/inflate.c -index 7be8c6366..94ecff015 100644 ---- a/src/zlib/inflate.c -+++ b/src/zlib/inflate.c -@@ -91,20 +91,7 @@ - # endif - #endif - --/* function prototypes */ --local int inflateStateCheck OF((z_streamp strm)); --local void fixedtables OF((struct inflate_state FAR *state)); --local int updatewindow OF((z_streamp strm, const unsigned char FAR *end, -- unsigned copy)); --#ifdef BUILDFIXED -- void makefixed OF((void)); --#endif --local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf, -- unsigned len)); -- --local int inflateStateCheck(strm) --z_streamp strm; --{ -+local int inflateStateCheck(z_streamp strm) { - struct inflate_state FAR *state; - if (strm == Z_NULL || - strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) -@@ -116,9 +103,7 @@ z_streamp strm; - return 0; - } - --int ZEXPORT inflateResetKeep(strm) --z_streamp strm; --{ -+int ZEXPORT inflateResetKeep(z_streamp strm) { - struct inflate_state FAR *state; - - if (inflateStateCheck(strm)) return Z_STREAM_ERROR; -@@ -142,9 +127,7 @@ z_streamp strm; - return Z_OK; - } - --int ZEXPORT inflateReset(strm) --z_streamp strm; --{ -+int ZEXPORT inflateReset(z_streamp strm) { - struct inflate_state FAR *state; - - if (inflateStateCheck(strm)) return Z_STREAM_ERROR; -@@ -155,10 +138,7 @@ z_streamp strm; - return inflateResetKeep(strm); - } - --int ZEXPORT inflateReset2(strm, windowBits) --z_streamp strm; --int windowBits; --{ -+int ZEXPORT inflateReset2(z_streamp strm, int windowBits) { - int wrap; - struct inflate_state FAR *state; - -@@ -168,6 +148,8 @@ int windowBits; - - /* extract wrap request from windowBits parameter */ - if (windowBits < 0) { -+ if (windowBits < -15) -+ return Z_STREAM_ERROR; - wrap = 0; - windowBits = -windowBits; - } -@@ -193,12 +175,8 @@ int windowBits; - return inflateReset(strm); - } - --int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) --z_streamp strm; --int windowBits; --const char *version; --int stream_size; --{ -+int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, -+ const char *version, int stream_size) { - int ret; - struct inflate_state FAR *state; - -@@ -237,22 +215,17 @@ int stream_size; - return ret; - } - --int ZEXPORT inflateInit_(strm, version, stream_size) --z_streamp strm; --const char *version; --int stream_size; --{ -+int ZEXPORT inflateInit_(z_streamp strm, const char *version, -+ int stream_size) { - return inflateInit2_(strm, DEF_WBITS, version, stream_size); - } - --int ZEXPORT inflatePrime(strm, bits, value) --z_streamp strm; --int bits; --int value; --{ -+int ZEXPORT inflatePrime(z_streamp strm, int bits, int value) { - struct inflate_state FAR *state; - - if (inflateStateCheck(strm)) return Z_STREAM_ERROR; -+ if (bits == 0) -+ return Z_OK; - state = (struct inflate_state FAR *)strm->state; - if (bits < 0) { - state->hold = 0; -@@ -276,9 +249,7 @@ int value; - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ --local void fixedtables(state) --struct inflate_state FAR *state; --{ -+local void fixedtables(struct inflate_state FAR *state) { - #ifdef BUILDFIXED - static int virgin = 1; - static code *lenfix, *distfix; -@@ -340,7 +311,7 @@ struct inflate_state FAR *state; - - a.out > inffixed.h - */ --void makefixed() -+void makefixed(void) - { - unsigned low, size; - struct inflate_state state; -@@ -394,11 +365,7 @@ void makefixed() - output will fall in the output data, making match copies simpler and faster. - The advantage may be dependent on the size of the processor's data caches. - */ --local int updatewindow(strm, end, copy) --z_streamp strm; --const Bytef *end; --unsigned copy; --{ -+local int updatewindow(z_streamp strm, const Bytef *end, unsigned copy) { - struct inflate_state FAR *state; - unsigned dist; - -@@ -620,10 +587,7 @@ unsigned copy; - will return Z_BUF_ERROR if it has not reached the end of the stream. - */ - --int ZEXPORT inflate(strm, flush) --z_streamp strm; --int flush; --{ -+int ZEXPORT inflate(z_streamp strm, int flush) { - struct inflate_state FAR *state; - z_const unsigned char FAR *next; /* next input */ - unsigned char FAR *put; /* next output */ -@@ -764,8 +728,9 @@ int flush; - if (copy > have) copy = have; - if (copy) { - if (state->head != Z_NULL && -- state->head->extra != Z_NULL) { -- len = state->head->extra_len - state->length; -+ state->head->extra != Z_NULL && -+ (len = state->head->extra_len - state->length) < -+ state->head->extra_max) { - zmemcpy(state->head->extra + len, next, - len + copy > state->head->extra_max ? - state->head->extra_max - len : copy); -@@ -1298,9 +1263,7 @@ int flush; - return ret; - } - --int ZEXPORT inflateEnd(strm) --z_streamp strm; --{ -+int ZEXPORT inflateEnd(z_streamp strm) { - struct inflate_state FAR *state; - if (inflateStateCheck(strm)) - return Z_STREAM_ERROR; -@@ -1312,11 +1275,8 @@ z_streamp strm; - return Z_OK; - } - --int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength) --z_streamp strm; --Bytef *dictionary; --uInt *dictLength; --{ -+int ZEXPORT inflateGetDictionary(z_streamp strm, Bytef *dictionary, -+ uInt *dictLength) { - struct inflate_state FAR *state; - - /* check state */ -@@ -1335,11 +1295,8 @@ uInt *dictLength; - return Z_OK; - } - --int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) --z_streamp strm; --const Bytef *dictionary; --uInt dictLength; --{ -+int ZEXPORT inflateSetDictionary(z_streamp strm, const Bytef *dictionary, -+ uInt dictLength) { - struct inflate_state FAR *state; - unsigned long dictid; - int ret; -@@ -1370,10 +1327,7 @@ uInt dictLength; - return Z_OK; - } - --int ZEXPORT inflateGetHeader(strm, head) --z_streamp strm; --gz_headerp head; --{ -+int ZEXPORT inflateGetHeader(z_streamp strm, gz_headerp head) { - struct inflate_state FAR *state; - - /* check state */ -@@ -1398,11 +1352,8 @@ gz_headerp head; - called again with more data and the *have state. *have is initialized to - zero for the first call. - */ --local unsigned syncsearch(have, buf, len) --unsigned FAR *have; --const unsigned char FAR *buf; --unsigned len; --{ -+local unsigned syncsearch(unsigned FAR *have, const unsigned char FAR *buf, -+ unsigned len) { - unsigned got; - unsigned next; - -@@ -1421,9 +1372,7 @@ unsigned len; - return next; - } - --int ZEXPORT inflateSync(strm) --z_streamp strm; --{ -+int ZEXPORT inflateSync(z_streamp strm) { - unsigned len; /* number of bytes to look at or looked at */ - int flags; /* temporary to save header status */ - unsigned long in, out; /* temporary to save total_in and total_out */ -@@ -1438,7 +1387,7 @@ z_streamp strm; - /* if first time, start search in bit buffer */ - if (state->mode != SYNC) { - state->mode = SYNC; -- state->hold <<= state->bits & 7; -+ state->hold >>= state->bits & 7; - state->bits -= state->bits & 7; - len = 0; - while (state->bits >= 8) { -@@ -1479,9 +1428,7 @@ z_streamp strm; - block. When decompressing, PPP checks that at the end of input packet, - inflate is waiting for these length bytes. - */ --int ZEXPORT inflateSyncPoint(strm) --z_streamp strm; --{ -+int ZEXPORT inflateSyncPoint(z_streamp strm) { - struct inflate_state FAR *state; - - if (inflateStateCheck(strm)) return Z_STREAM_ERROR; -@@ -1489,10 +1436,7 @@ z_streamp strm; - return state->mode == STORED && state->bits == 0; - } - --int ZEXPORT inflateCopy(dest, source) --z_streamp dest; --z_streamp source; --{ -+int ZEXPORT inflateCopy(z_streamp dest, z_streamp source) { - struct inflate_state FAR *state; - struct inflate_state FAR *copy; - unsigned char FAR *window; -@@ -1536,10 +1480,7 @@ z_streamp source; - return Z_OK; - } - --int ZEXPORT inflateUndermine(strm, subvert) --z_streamp strm; --int subvert; --{ -+int ZEXPORT inflateUndermine(z_streamp strm, int subvert) { - struct inflate_state FAR *state; - - if (inflateStateCheck(strm)) return Z_STREAM_ERROR; -@@ -1554,10 +1495,7 @@ int subvert; - #endif - } - --int ZEXPORT inflateValidate(strm, check) --z_streamp strm; --int check; --{ -+int ZEXPORT inflateValidate(z_streamp strm, int check) { - struct inflate_state FAR *state; - - if (inflateStateCheck(strm)) return Z_STREAM_ERROR; -@@ -1569,9 +1507,7 @@ int check; - return Z_OK; - } - --long ZEXPORT inflateMark(strm) --z_streamp strm; --{ -+long ZEXPORT inflateMark(z_streamp strm) { - struct inflate_state FAR *state; - - if (inflateStateCheck(strm)) -@@ -1582,9 +1518,7 @@ z_streamp strm; - (state->mode == MATCH ? state->was - state->length : 0)); - } - --unsigned long ZEXPORT inflateCodesUsed(strm) --z_streamp strm; --{ -+unsigned long ZEXPORT inflateCodesUsed(z_streamp strm) { - struct inflate_state FAR *state; - if (inflateStateCheck(strm)) return (unsigned long)-1; - state = (struct inflate_state FAR *)strm->state; -diff --git a/src/zlib/inftrees.c b/src/zlib/inftrees.c -index 09462a740..98cfe1644 100644 ---- a/src/zlib/inftrees.c -+++ b/src/zlib/inftrees.c -@@ -1,5 +1,5 @@ - /* inftrees.c -- generate Huffman trees for efficient decoding -- * Copyright (C) 1995-2022 Mark Adler -+ * Copyright (C) 1995-2024 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -@@ -9,7 +9,7 @@ - #define MAXBITS 15 - - const char inflate_copyright[] = -- " inflate 1.2.12 Copyright 1995-2022 Mark Adler "; -+ " inflate 1.3.1 Copyright 1995-2024 Mark Adler "; - /* - If you use the zlib library in a product, an acknowledgment is welcome - in the documentation of your product. If for some reason you cannot -@@ -29,14 +29,9 @@ const char inflate_copyright[] = - table index bits. It will differ if the request is greater than the - longest code or if it is less than the shortest code. - */ --int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work) --codetype type; --unsigned short FAR *lens; --unsigned codes; --code FAR * FAR *table; --unsigned FAR *bits; --unsigned short FAR *work; --{ -+int ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens, -+ unsigned codes, code FAR * FAR *table, -+ unsigned FAR *bits, unsigned short FAR *work) { - unsigned len; /* a code's length in bits */ - unsigned sym; /* index of code symbols */ - unsigned min, max; /* minimum and maximum code lengths */ -@@ -62,7 +57,7 @@ unsigned short FAR *work; - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; - static const unsigned short lext[31] = { /* Length codes 257..285 extra */ - 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, -- 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 199, 202}; -+ 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 203, 77}; - static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, -diff --git a/src/zlib/inftrees.h b/src/zlib/inftrees.h -index baa53a0b1..396f74b5d 100644 ---- a/src/zlib/inftrees.h -+++ b/src/zlib/inftrees.h -@@ -38,11 +38,11 @@ typedef struct { - /* Maximum size of the dynamic table. The maximum number of code structures is - 1444, which is the sum of 852 for literal/length codes and 592 for distance - codes. These values were found by exhaustive searches using the program -- examples/enough.c found in the zlib distribtution. The arguments to that -+ examples/enough.c found in the zlib distribution. The arguments to that - program are the number of symbols, the initial root table size, and the - maximum bit length of a code. "enough 286 9 15" for literal/length codes -- returns returns 852, and "enough 30 6 15" for distance codes returns 592. -- The initial root table size (9 or 6) is found in the fifth argument of the -+ returns 852, and "enough 30 6 15" for distance codes returns 592. The -+ initial root table size (9 or 6) is found in the fifth argument of the - inflate_table() calls in inflate.c and infback.c. If the root table size is - changed, then these maximum sizes would be need to be recalculated and - updated. */ -@@ -57,6 +57,6 @@ typedef enum { - DISTS - } codetype; - --int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens, -- unsigned codes, code FAR * FAR *table, -- unsigned FAR *bits, unsigned short FAR *work)); -+int ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens, -+ unsigned codes, code FAR * FAR *table, -+ unsigned FAR *bits, unsigned short FAR *work); -diff --git a/src/zlib/trees.c b/src/zlib/trees.c -index f73fd99c3..6a523ef34 100644 ---- a/src/zlib/trees.c -+++ b/src/zlib/trees.c -@@ -1,5 +1,5 @@ - /* trees.c -- output deflated data using Huffman coding -- * Copyright (C) 1995-2021 Jean-loup Gailly -+ * Copyright (C) 1995-2024 Jean-loup Gailly - * detect_data_type() function provided freely by Cosmin Truta, 2006 - * For conditions of distribution and use, see copyright notice in zlib.h - */ -@@ -122,39 +122,116 @@ struct static_tree_desc_s { - int max_length; /* max bit length for the codes */ - }; - --local const static_tree_desc static_l_desc = -+#ifdef NO_INIT_GLOBAL_POINTERS -+# define TCONST -+#else -+# define TCONST const -+#endif -+ -+local TCONST static_tree_desc static_l_desc = - {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; - --local const static_tree_desc static_d_desc = -+local TCONST static_tree_desc static_d_desc = - {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; - --local const static_tree_desc static_bl_desc = -+local TCONST static_tree_desc static_bl_desc = - {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; - - /* =========================================================================== -- * Local (static) routines in this file. -+ * Output a short LSB first on the stream. -+ * IN assertion: there is enough room in pendingBuf. -+ */ -+#define put_short(s, w) { \ -+ put_byte(s, (uch)((w) & 0xff)); \ -+ put_byte(s, (uch)((ush)(w) >> 8)); \ -+} -+ -+/* =========================================================================== -+ * Reverse the first len bits of a code, using straightforward code (a faster -+ * method would use a table) -+ * IN assertion: 1 <= len <= 15 -+ */ -+local unsigned bi_reverse(unsigned code, int len) { -+ register unsigned res = 0; -+ do { -+ res |= code & 1; -+ code >>= 1, res <<= 1; -+ } while (--len > 0); -+ return res >> 1; -+} -+ -+/* =========================================================================== -+ * Flush the bit buffer, keeping at most 7 bits in it. -+ */ -+local void bi_flush(deflate_state *s) { -+ if (s->bi_valid == 16) { -+ put_short(s, s->bi_buf); -+ s->bi_buf = 0; -+ s->bi_valid = 0; -+ } else if (s->bi_valid >= 8) { -+ put_byte(s, (Byte)s->bi_buf); -+ s->bi_buf >>= 8; -+ s->bi_valid -= 8; -+ } -+} -+ -+/* =========================================================================== -+ * Flush the bit buffer and align the output on a byte boundary -+ */ -+local void bi_windup(deflate_state *s) { -+ if (s->bi_valid > 8) { -+ put_short(s, s->bi_buf); -+ } else if (s->bi_valid > 0) { -+ put_byte(s, (Byte)s->bi_buf); -+ } -+ s->bi_buf = 0; -+ s->bi_valid = 0; -+#ifdef ZLIB_DEBUG -+ s->bits_sent = (s->bits_sent + 7) & ~7; -+#endif -+} -+ -+/* =========================================================================== -+ * Generate the codes for a given tree and bit counts (which need not be -+ * optimal). -+ * IN assertion: the array bl_count contains the bit length statistics for -+ * the given tree and the field len is set for all tree elements. -+ * OUT assertion: the field code is set for all tree elements of non -+ * zero code length. - */ -+local void gen_codes(ct_data *tree, int max_code, ushf *bl_count) { -+ ush next_code[MAX_BITS+1]; /* next code value for each bit length */ -+ unsigned code = 0; /* running code value */ -+ int bits; /* bit index */ -+ int n; /* code index */ - --local void tr_static_init OF((void)); --local void init_block OF((deflate_state *s)); --local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); --local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); --local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); --local void build_tree OF((deflate_state *s, tree_desc *desc)); --local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); --local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); --local int build_bl_tree OF((deflate_state *s)); --local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, -- int blcodes)); --local void compress_block OF((deflate_state *s, const ct_data *ltree, -- const ct_data *dtree)); --local int detect_data_type OF((deflate_state *s)); --local unsigned bi_reverse OF((unsigned code, int len)); --local void bi_windup OF((deflate_state *s)); --local void bi_flush OF((deflate_state *s)); -+ /* The distribution counts are first used to generate the code values -+ * without bit reversal. -+ */ -+ for (bits = 1; bits <= MAX_BITS; bits++) { -+ code = (code + bl_count[bits - 1]) << 1; -+ next_code[bits] = (ush)code; -+ } -+ /* Check that the bit counts in bl_count are consistent. The last code -+ * must be all ones. -+ */ -+ Assert (code + bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1, -+ "inconsistent bit counts"); -+ Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); -+ -+ for (n = 0; n <= max_code; n++) { -+ int len = tree[n].Len; -+ if (len == 0) continue; -+ /* Now reverse the bits */ -+ tree[n].Code = (ush)bi_reverse(next_code[len]++, len); -+ -+ Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", -+ n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len] - 1)); -+ } -+} - - #ifdef GEN_TREES_H --local void gen_trees_header OF((void)); -+local void gen_trees_header(void); - #endif - - #ifndef ZLIB_DEBUG -@@ -167,33 +244,18 @@ local void gen_trees_header OF((void)); - send_bits(s, tree[c].Code, tree[c].Len); } - #endif - --/* =========================================================================== -- * Output a short LSB first on the stream. -- * IN assertion: there is enough room in pendingBuf. -- */ --#define put_short(s, w) { \ -- put_byte(s, (uch)((w) & 0xff)); \ -- put_byte(s, (uch)((ush)(w) >> 8)); \ --} -- - /* =========================================================================== - * Send a value on a given number of bits. - * IN assertion: length <= 16 and value fits in length bits. - */ - #ifdef ZLIB_DEBUG --local void send_bits OF((deflate_state *s, int value, int length)); -- --local void send_bits(s, value, length) -- deflate_state *s; -- int value; /* value to send */ -- int length; /* number of bits */ --{ -+local void send_bits(deflate_state *s, int value, int length) { - Tracevv((stderr," l %2d v %4x ", length, value)); - Assert(length > 0 && length <= 15, "invalid length"); - s->bits_sent += (ulg)length; - - /* If not enough room in bi_buf, use (valid) bits from bi_buf and -- * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) -+ * (16 - bi_valid) bits from value, leaving (width - (16 - bi_valid)) - * unused bits in value. - */ - if (s->bi_valid > (int)Buf_size - length) { -@@ -229,8 +291,7 @@ local void send_bits(s, value, length) - /* =========================================================================== - * Initialize the various 'constant' tables. - */ --local void tr_static_init() --{ -+local void tr_static_init(void) { - #if defined(GEN_TREES_H) || !defined(STDC) - static int static_init_done = 0; - int n; /* iterates over tree elements */ -@@ -256,7 +317,7 @@ local void tr_static_init() - length = 0; - for (code = 0; code < LENGTH_CODES-1; code++) { - base_length[code] = length; -- for (n = 0; n < (1< dist code (0..29) */ - dist = 0; - for (code = 0 ; code < 16; code++) { - base_dist[code] = dist; -- for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ - for ( ; code < D_CODES; code++) { - base_dist[code] = dist << 7; -- for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { -+ for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { - _dist_code[256 + dist++] = (uch)code; - } - } -- Assert (dist == 256, "tr_static_init: 256+dist != 512"); -+ Assert (dist == 256, "tr_static_init: 256 + dist != 512"); - - /* Construct the codes of the static literal tree */ - for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; -@@ -312,7 +373,7 @@ local void tr_static_init() - } - - /* =========================================================================== -- * Genererate the file trees.h describing the static trees. -+ * Generate the file trees.h describing the static trees. - */ - #ifdef GEN_TREES_H - # ifndef ZLIB_DEBUG -@@ -321,10 +382,9 @@ local void tr_static_init() - - # define SEPARATOR(i, last, width) \ - ((i) == (last)? "\n};\n\n" : \ -- ((i) % (width) == (width)-1 ? ",\n" : ", ")) -+ ((i) % (width) == (width) - 1 ? ",\n" : ", ")) - --void gen_trees_header() --{ -+void gen_trees_header(void) { - FILE *header = fopen("trees.h", "w"); - int i; - -@@ -373,12 +433,26 @@ void gen_trees_header() - } - #endif /* GEN_TREES_H */ - -+/* =========================================================================== -+ * Initialize a new block. -+ */ -+local void init_block(deflate_state *s) { -+ int n; /* iterates over tree elements */ -+ -+ /* Initialize the trees. */ -+ for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; -+ for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; -+ for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; -+ -+ s->dyn_ltree[END_BLOCK].Freq = 1; -+ s->opt_len = s->static_len = 0L; -+ s->sym_next = s->matches = 0; -+} -+ - /* =========================================================================== - * Initialize the tree data structures for a new zlib stream. - */ --void ZLIB_INTERNAL _tr_init(s) -- deflate_state *s; --{ -+void ZLIB_INTERNAL _tr_init(deflate_state *s) { - tr_static_init(); - - s->l_desc.dyn_tree = s->dyn_ltree; -@@ -401,24 +475,6 @@ void ZLIB_INTERNAL _tr_init(s) - init_block(s); - } - --/* =========================================================================== -- * Initialize a new block. -- */ --local void init_block(s) -- deflate_state *s; --{ -- int n; /* iterates over tree elements */ -- -- /* Initialize the trees. */ -- for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; -- for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; -- for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; -- -- s->dyn_ltree[END_BLOCK].Freq = 1; -- s->opt_len = s->static_len = 0L; -- s->sym_next = s->matches = 0; --} -- - #define SMALLEST 1 - /* Index within the heap array of least frequent node in the Huffman tree */ - -@@ -448,17 +504,13 @@ local void init_block(s) - * when the heap property is re-established (each father smaller than its - * two sons). - */ --local void pqdownheap(s, tree, k) -- deflate_state *s; -- ct_data *tree; /* the tree to restore */ -- int k; /* node to move down */ --{ -+local void pqdownheap(deflate_state *s, ct_data *tree, int k) { - int v = s->heap[k]; - int j = k << 1; /* left son of k */ - while (j <= s->heap_len) { - /* Set j to the smallest of the two sons: */ - if (j < s->heap_len && -- smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { -+ smaller(tree, s->heap[j + 1], s->heap[j], s->depth)) { - j++; - } - /* Exit if v is smaller than both sons */ -@@ -483,10 +535,7 @@ local void pqdownheap(s, tree, k) - * The length opt_len is updated; static_len is also updated if stree is - * not null. - */ --local void gen_bitlen(s, desc) -- deflate_state *s; -- tree_desc *desc; /* the tree descriptor */ --{ -+local void gen_bitlen(deflate_state *s, tree_desc *desc) { - ct_data *tree = desc->dyn_tree; - int max_code = desc->max_code; - const ct_data *stree = desc->stat_desc->static_tree; -@@ -507,7 +556,7 @@ local void gen_bitlen(s, desc) - */ - tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ - -- for (h = s->heap_max+1; h < HEAP_SIZE; h++) { -+ for (h = s->heap_max + 1; h < HEAP_SIZE; h++) { - n = s->heap[h]; - bits = tree[tree[n].Dad].Len + 1; - if (bits > max_length) bits = max_length, overflow++; -@@ -518,7 +567,7 @@ local void gen_bitlen(s, desc) - - s->bl_count[bits]++; - xbits = 0; -- if (n >= base) xbits = extra[n-base]; -+ if (n >= base) xbits = extra[n - base]; - f = tree[n].Freq; - s->opt_len += (ulg)f * (unsigned)(bits + xbits); - if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits); -@@ -530,10 +579,10 @@ local void gen_bitlen(s, desc) - - /* Find the first bit length which could increase: */ - do { -- bits = max_length-1; -+ bits = max_length - 1; - while (s->bl_count[bits] == 0) bits--; -- s->bl_count[bits]--; /* move one leaf down the tree */ -- s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ -+ s->bl_count[bits]--; /* move one leaf down the tree */ -+ s->bl_count[bits + 1] += 2; /* move one overflow item as its brother */ - s->bl_count[max_length]--; - /* The brother of the overflow item also moves one step up, - * but this does not affect bl_count[max_length] -@@ -561,48 +610,9 @@ local void gen_bitlen(s, desc) - } - } - --/* =========================================================================== -- * Generate the codes for a given tree and bit counts (which need not be -- * optimal). -- * IN assertion: the array bl_count contains the bit length statistics for -- * the given tree and the field len is set for all tree elements. -- * OUT assertion: the field code is set for all tree elements of non -- * zero code length. -- */ --local void gen_codes (tree, max_code, bl_count) -- ct_data *tree; /* the tree to decorate */ -- int max_code; /* largest code with non zero frequency */ -- ushf *bl_count; /* number of codes at each bit length */ --{ -- ush next_code[MAX_BITS+1]; /* next code value for each bit length */ -- unsigned code = 0; /* running code value */ -- int bits; /* bit index */ -- int n; /* code index */ -- -- /* The distribution counts are first used to generate the code values -- * without bit reversal. -- */ -- for (bits = 1; bits <= MAX_BITS; bits++) { -- code = (code + bl_count[bits-1]) << 1; -- next_code[bits] = (ush)code; -- } -- /* Check that the bit counts in bl_count are consistent. The last code -- * must be all ones. -- */ -- Assert (code + bl_count[MAX_BITS]-1 == (1< -+#endif - - /* =========================================================================== - * Construct one Huffman tree and assigns the code bit strings and lengths. -@@ -612,10 +622,7 @@ local void gen_codes (tree, max_code, bl_count) - * and corresponding code. The length opt_len is updated; static_len is - * also updated if stree is not null. The field max_code is set. - */ --local void build_tree(s, desc) -- deflate_state *s; -- tree_desc *desc; /* the tree descriptor */ --{ -+local void build_tree(deflate_state *s, tree_desc *desc) { - ct_data *tree = desc->dyn_tree; - const ct_data *stree = desc->stat_desc->static_tree; - int elems = desc->stat_desc->elems; -@@ -624,7 +631,7 @@ local void build_tree(s, desc) - int node; /* new node being created */ - - /* Construct the initial heap, with least frequent element in -- * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. -+ * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n + 1]. - * heap[0] is not used. - */ - s->heap_len = 0, s->heap_max = HEAP_SIZE; -@@ -652,7 +659,7 @@ local void build_tree(s, desc) - } - desc->max_code = max_code; - -- /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, -+ /* The elements heap[heap_len/2 + 1 .. heap_len] are leaves of the tree, - * establish sub-heaps of increasing lengths: - */ - for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); -@@ -700,11 +707,7 @@ local void build_tree(s, desc) - * Scan a literal or distance tree to determine the frequencies of the codes - * in the bit length tree. - */ --local void scan_tree (s, tree, max_code) -- deflate_state *s; -- ct_data *tree; /* the tree to be scanned */ -- int max_code; /* and its largest code of non zero frequency */ --{ -+local void scan_tree(deflate_state *s, ct_data *tree, int max_code) { - int n; /* iterates over all tree elements */ - int prevlen = -1; /* last emitted length */ - int curlen; /* length of current code */ -@@ -714,10 +717,10 @@ local void scan_tree (s, tree, max_code) - int min_count = 4; /* min repeat count */ - - if (nextlen == 0) max_count = 138, min_count = 3; -- tree[max_code+1].Len = (ush)0xffff; /* guard */ -+ tree[max_code + 1].Len = (ush)0xffff; /* guard */ - - for (n = 0; n <= max_code; n++) { -- curlen = nextlen; nextlen = tree[n+1].Len; -+ curlen = nextlen; nextlen = tree[n + 1].Len; - if (++count < max_count && curlen == nextlen) { - continue; - } else if (count < min_count) { -@@ -745,11 +748,7 @@ local void scan_tree (s, tree, max_code) - * Send a literal or distance tree in compressed form, using the codes in - * bl_tree. - */ --local void send_tree (s, tree, max_code) -- deflate_state *s; -- ct_data *tree; /* the tree to be scanned */ -- int max_code; /* and its largest code of non zero frequency */ --{ -+local void send_tree(deflate_state *s, ct_data *tree, int max_code) { - int n; /* iterates over all tree elements */ - int prevlen = -1; /* last emitted length */ - int curlen; /* length of current code */ -@@ -758,11 +757,11 @@ local void send_tree (s, tree, max_code) - int max_count = 7; /* max repeat count */ - int min_count = 4; /* min repeat count */ - -- /* tree[max_code+1].Len = -1; */ /* guard already set */ -+ /* tree[max_code + 1].Len = -1; */ /* guard already set */ - if (nextlen == 0) max_count = 138, min_count = 3; - - for (n = 0; n <= max_code; n++) { -- curlen = nextlen; nextlen = tree[n+1].Len; -+ curlen = nextlen; nextlen = tree[n + 1].Len; - if (++count < max_count && curlen == nextlen) { - continue; - } else if (count < min_count) { -@@ -773,13 +772,13 @@ local void send_tree (s, tree, max_code) - send_code(s, curlen, s->bl_tree); count--; - } - Assert(count >= 3 && count <= 6, " 3_6?"); -- send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); -+ send_code(s, REP_3_6, s->bl_tree); send_bits(s, count - 3, 2); - - } else if (count <= 10) { -- send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); -+ send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count - 3, 3); - - } else { -- send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); -+ send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count - 11, 7); - } - count = 0; prevlen = curlen; - if (nextlen == 0) { -@@ -796,9 +795,7 @@ local void send_tree (s, tree, max_code) - * Construct the Huffman tree for the bit lengths and return the index in - * bl_order of the last bit length code to send. - */ --local int build_bl_tree(s) -- deflate_state *s; --{ -+local int build_bl_tree(deflate_state *s) { - int max_blindex; /* index of last bit length code of non zero freq */ - - /* Determine the bit length frequencies for literal and distance trees */ -@@ -807,8 +804,8 @@ local int build_bl_tree(s) - - /* Build the bit length tree: */ - build_tree(s, (tree_desc *)(&(s->bl_desc))); -- /* opt_len now includes the length of the tree representations, except -- * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. -+ /* opt_len now includes the length of the tree representations, except the -+ * lengths of the bit lengths codes and the 5 + 5 + 4 bits for the counts. - */ - - /* Determine the number of bit length codes to send. The pkzip format -@@ -819,7 +816,7 @@ local int build_bl_tree(s) - if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; - } - /* Update opt_len to include the bit length tree and counts */ -- s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4; -+ s->opt_len += 3*((ulg)max_blindex + 1) + 5 + 5 + 4; - Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", - s->opt_len, s->static_len)); - -@@ -831,42 +828,36 @@ local int build_bl_tree(s) - * lengths of the bit length codes, the literal tree and the distance tree. - * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. - */ --local void send_all_trees(s, lcodes, dcodes, blcodes) -- deflate_state *s; -- int lcodes, dcodes, blcodes; /* number of codes for each tree */ --{ -+local void send_all_trees(deflate_state *s, int lcodes, int dcodes, -+ int blcodes) { - int rank; /* index in bl_order */ - - Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); - Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, - "too many codes"); - Tracev((stderr, "\nbl counts: ")); -- send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ -- send_bits(s, dcodes-1, 5); -- send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ -+ send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ -+ send_bits(s, dcodes - 1, 5); -+ send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ - for (rank = 0; rank < blcodes; rank++) { - Tracev((stderr, "\nbl code %2d ", bl_order[rank])); - send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); - } - Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); - -- send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ -+ send_tree(s, (ct_data *)s->dyn_ltree, lcodes - 1); /* literal tree */ - Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); - -- send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ -+ send_tree(s, (ct_data *)s->dyn_dtree, dcodes - 1); /* distance tree */ - Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); - } - - /* =========================================================================== - * Send a stored block - */ --void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) -- deflate_state *s; -- charf *buf; /* input block */ -- ulg stored_len; /* length of input block */ -- int last; /* one if this is the last block for a file */ --{ -- send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */ -+void ZLIB_INTERNAL _tr_stored_block(deflate_state *s, charf *buf, -+ ulg stored_len, int last) { -+ send_bits(s, (STORED_BLOCK<<1) + last, 3); /* send block type */ - bi_windup(s); /* align on byte boundary */ - put_short(s, (ush)stored_len); - put_short(s, (ush)~stored_len); -@@ -877,16 +868,14 @@ void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) - s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; - s->compressed_len += (stored_len + 4) << 3; - s->bits_sent += 2*16; -- s->bits_sent += stored_len<<3; -+ s->bits_sent += stored_len << 3; - #endif - } - - /* =========================================================================== - * Flush the bits in the bit buffer to pending output (leaves at most 7 bits) - */ --void ZLIB_INTERNAL _tr_flush_bits(s) -- deflate_state *s; --{ -+void ZLIB_INTERNAL _tr_flush_bits(deflate_state *s) { - bi_flush(s); - } - -@@ -894,9 +883,7 @@ void ZLIB_INTERNAL _tr_flush_bits(s) - * Send one empty static block to give enough lookahead for inflate. - * This takes 10 bits, of which 7 may remain in the bit buffer. - */ --void ZLIB_INTERNAL _tr_align(s) -- deflate_state *s; --{ -+void ZLIB_INTERNAL _tr_align(deflate_state *s) { - send_bits(s, STATIC_TREES<<1, 3); - send_code(s, END_BLOCK, static_ltree); - #ifdef ZLIB_DEBUG -@@ -905,16 +892,108 @@ void ZLIB_INTERNAL _tr_align(s) - bi_flush(s); - } - -+/* =========================================================================== -+ * Send the block data compressed using the given Huffman trees -+ */ -+local void compress_block(deflate_state *s, const ct_data *ltree, -+ const ct_data *dtree) { -+ unsigned dist; /* distance of matched string */ -+ int lc; /* match length or unmatched char (if dist == 0) */ -+ unsigned sx = 0; /* running index in symbol buffers */ -+ unsigned code; /* the code to send */ -+ int extra; /* number of extra bits to send */ -+ -+ if (s->sym_next != 0) do { -+#ifdef LIT_MEM -+ dist = s->d_buf[sx]; -+ lc = s->l_buf[sx++]; -+#else -+ dist = s->sym_buf[sx++] & 0xff; -+ dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8; -+ lc = s->sym_buf[sx++]; -+#endif -+ if (dist == 0) { -+ send_code(s, lc, ltree); /* send a literal byte */ -+ Tracecv(isgraph(lc), (stderr," '%c' ", lc)); -+ } else { -+ /* Here, lc is the match length - MIN_MATCH */ -+ code = _length_code[lc]; -+ send_code(s, code + LITERALS + 1, ltree); /* send length code */ -+ extra = extra_lbits[code]; -+ if (extra != 0) { -+ lc -= base_length[code]; -+ send_bits(s, lc, extra); /* send the extra length bits */ -+ } -+ dist--; /* dist is now the match distance - 1 */ -+ code = d_code(dist); -+ Assert (code < D_CODES, "bad d_code"); -+ -+ send_code(s, code, dtree); /* send the distance code */ -+ extra = extra_dbits[code]; -+ if (extra != 0) { -+ dist -= (unsigned)base_dist[code]; -+ send_bits(s, dist, extra); /* send the extra distance bits */ -+ } -+ } /* literal or match pair ? */ -+ -+ /* Check for no overlay of pending_buf on needed symbols */ -+#ifdef LIT_MEM -+ Assert(s->pending < 2 * (s->lit_bufsize + sx), "pendingBuf overflow"); -+#else -+ Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow"); -+#endif -+ -+ } while (sx < s->sym_next); -+ -+ send_code(s, END_BLOCK, ltree); -+} -+ -+/* =========================================================================== -+ * Check if the data type is TEXT or BINARY, using the following algorithm: -+ * - TEXT if the two conditions below are satisfied: -+ * a) There are no non-portable control characters belonging to the -+ * "block list" (0..6, 14..25, 28..31). -+ * b) There is at least one printable character belonging to the -+ * "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). -+ * - BINARY otherwise. -+ * - The following partially-portable control characters form a -+ * "gray list" that is ignored in this detection algorithm: -+ * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). -+ * IN assertion: the fields Freq of dyn_ltree are set. -+ */ -+local int detect_data_type(deflate_state *s) { -+ /* block_mask is the bit mask of block-listed bytes -+ * set bits 0..6, 14..25, and 28..31 -+ * 0xf3ffc07f = binary 11110011111111111100000001111111 -+ */ -+ unsigned long block_mask = 0xf3ffc07fUL; -+ int n; -+ -+ /* Check for non-textual ("block-listed") bytes. */ -+ for (n = 0; n <= 31; n++, block_mask >>= 1) -+ if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0)) -+ return Z_BINARY; -+ -+ /* Check for textual ("allow-listed") bytes. */ -+ if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 -+ || s->dyn_ltree[13].Freq != 0) -+ return Z_TEXT; -+ for (n = 32; n < LITERALS; n++) -+ if (s->dyn_ltree[n].Freq != 0) -+ return Z_TEXT; -+ -+ /* There are no "block-listed" or "allow-listed" bytes: -+ * this stream either is empty or has tolerated ("gray-listed") bytes only. -+ */ -+ return Z_BINARY; -+} -+ - /* =========================================================================== - * Determine the best encoding for the current block: dynamic trees, static - * trees or store, and write out the encoded block. - */ --void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) -- deflate_state *s; -- charf *buf; /* input block, or NULL if too old */ -- ulg stored_len; /* length of input block */ -- int last; /* one if this is the last block for a file */ --{ -+void ZLIB_INTERNAL _tr_flush_block(deflate_state *s, charf *buf, -+ ulg stored_len, int last) { - ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ - int max_blindex = 0; /* index of last bit length code of non zero freq */ - -@@ -943,14 +1022,17 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) - max_blindex = build_bl_tree(s); - - /* Determine the best encoding. Compute the block lengths in bytes. */ -- opt_lenb = (s->opt_len+3+7)>>3; -- static_lenb = (s->static_len+3+7)>>3; -+ opt_lenb = (s->opt_len + 3 + 7) >> 3; -+ static_lenb = (s->static_len + 3 + 7) >> 3; - - Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", - opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - s->sym_next / 3)); - -- if (static_lenb <= opt_lenb) opt_lenb = static_lenb; -+#ifndef FORCE_STATIC -+ if (static_lenb <= opt_lenb || s->strategy == Z_FIXED) -+#endif -+ opt_lenb = static_lenb; - - } else { - Assert(buf != (char*)0, "lost buf"); -@@ -960,7 +1042,7 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) - #ifdef FORCE_STORED - if (buf != (char*)0) { /* force stored block */ - #else -- if (stored_len+4 <= opt_lenb && buf != (char*)0) { -+ if (stored_len + 4 <= opt_lenb && buf != (char*)0) { - /* 4: two words for the lengths */ - #endif - /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. -@@ -971,21 +1053,17 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) - */ - _tr_stored_block(s, buf, stored_len, last); - --#ifdef FORCE_STATIC -- } else if (static_lenb >= 0) { /* force static trees */ --#else -- } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { --#endif -- send_bits(s, (STATIC_TREES<<1)+last, 3); -+ } else if (static_lenb == opt_lenb) { -+ send_bits(s, (STATIC_TREES<<1) + last, 3); - compress_block(s, (const ct_data *)static_ltree, - (const ct_data *)static_dtree); - #ifdef ZLIB_DEBUG - s->compressed_len += 3 + s->static_len; - #endif - } else { -- send_bits(s, (DYN_TREES<<1)+last, 3); -- send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, -- max_blindex+1); -+ send_bits(s, (DYN_TREES<<1) + last, 3); -+ send_all_trees(s, s->l_desc.max_code + 1, s->d_desc.max_code + 1, -+ max_blindex + 1); - compress_block(s, (const ct_data *)s->dyn_ltree, - (const ct_data *)s->dyn_dtree); - #ifdef ZLIB_DEBUG -@@ -1004,22 +1082,23 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) - s->compressed_len += 7; /* align on byte boundary */ - #endif - } -- Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, -- s->compressed_len-7*last)); -+ Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len >> 3, -+ s->compressed_len - 7*last)); - } - - /* =========================================================================== - * Save the match info and tally the frequency counts. Return true if - * the current block must be flushed. - */ --int ZLIB_INTERNAL _tr_tally (s, dist, lc) -- deflate_state *s; -- unsigned dist; /* distance of matched string */ -- unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ --{ -- s->sym_buf[s->sym_next++] = dist; -- s->sym_buf[s->sym_next++] = dist >> 8; -- s->sym_buf[s->sym_next++] = lc; -+int ZLIB_INTERNAL _tr_tally(deflate_state *s, unsigned dist, unsigned lc) { -+#ifdef LIT_MEM -+ s->d_buf[s->sym_next] = (ush)dist; -+ s->l_buf[s->sym_next++] = (uch)lc; -+#else -+ s->sym_buf[s->sym_next++] = (uch)dist; -+ s->sym_buf[s->sym_next++] = (uch)(dist >> 8); -+ s->sym_buf[s->sym_next++] = (uch)lc; -+#endif - if (dist == 0) { - /* lc is the unmatched char */ - s->dyn_ltree[lc].Freq++; -@@ -1031,152 +1110,8 @@ int ZLIB_INTERNAL _tr_tally (s, dist, lc) - (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && - (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); - -- s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; -+ s->dyn_ltree[_length_code[lc] + LITERALS + 1].Freq++; - s->dyn_dtree[d_code(dist)].Freq++; - } - return (s->sym_next == s->sym_end); - } -- --/* =========================================================================== -- * Send the block data compressed using the given Huffman trees -- */ --local void compress_block(s, ltree, dtree) -- deflate_state *s; -- const ct_data *ltree; /* literal tree */ -- const ct_data *dtree; /* distance tree */ --{ -- unsigned dist; /* distance of matched string */ -- int lc; /* match length or unmatched char (if dist == 0) */ -- unsigned sx = 0; /* running index in sym_buf */ -- unsigned code; /* the code to send */ -- int extra; /* number of extra bits to send */ -- -- if (s->sym_next != 0) do { -- dist = s->sym_buf[sx++] & 0xff; -- dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8; -- lc = s->sym_buf[sx++]; -- if (dist == 0) { -- send_code(s, lc, ltree); /* send a literal byte */ -- Tracecv(isgraph(lc), (stderr," '%c' ", lc)); -- } else { -- /* Here, lc is the match length - MIN_MATCH */ -- code = _length_code[lc]; -- send_code(s, code+LITERALS+1, ltree); /* send the length code */ -- extra = extra_lbits[code]; -- if (extra != 0) { -- lc -= base_length[code]; -- send_bits(s, lc, extra); /* send the extra length bits */ -- } -- dist--; /* dist is now the match distance - 1 */ -- code = d_code(dist); -- Assert (code < D_CODES, "bad d_code"); -- -- send_code(s, code, dtree); /* send the distance code */ -- extra = extra_dbits[code]; -- if (extra != 0) { -- dist -= (unsigned)base_dist[code]; -- send_bits(s, dist, extra); /* send the extra distance bits */ -- } -- } /* literal or match pair ? */ -- -- /* Check that the overlay between pending_buf and sym_buf is ok: */ -- Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow"); -- -- } while (sx < s->sym_next); -- -- send_code(s, END_BLOCK, ltree); --} -- --/* =========================================================================== -- * Check if the data type is TEXT or BINARY, using the following algorithm: -- * - TEXT if the two conditions below are satisfied: -- * a) There are no non-portable control characters belonging to the -- * "block list" (0..6, 14..25, 28..31). -- * b) There is at least one printable character belonging to the -- * "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). -- * - BINARY otherwise. -- * - The following partially-portable control characters form a -- * "gray list" that is ignored in this detection algorithm: -- * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). -- * IN assertion: the fields Freq of dyn_ltree are set. -- */ --local int detect_data_type(s) -- deflate_state *s; --{ -- /* block_mask is the bit mask of block-listed bytes -- * set bits 0..6, 14..25, and 28..31 -- * 0xf3ffc07f = binary 11110011111111111100000001111111 -- */ -- unsigned long block_mask = 0xf3ffc07fUL; -- int n; -- -- /* Check for non-textual ("block-listed") bytes. */ -- for (n = 0; n <= 31; n++, block_mask >>= 1) -- if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0)) -- return Z_BINARY; -- -- /* Check for textual ("allow-listed") bytes. */ -- if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 -- || s->dyn_ltree[13].Freq != 0) -- return Z_TEXT; -- for (n = 32; n < LITERALS; n++) -- if (s->dyn_ltree[n].Freq != 0) -- return Z_TEXT; -- -- /* There are no "block-listed" or "allow-listed" bytes: -- * this stream either is empty or has tolerated ("gray-listed") bytes only. -- */ -- return Z_BINARY; --} -- --/* =========================================================================== -- * Reverse the first len bits of a code, using straightforward code (a faster -- * method would use a table) -- * IN assertion: 1 <= len <= 15 -- */ --local unsigned bi_reverse(code, len) -- unsigned code; /* the value to invert */ -- int len; /* its bit length */ --{ -- register unsigned res = 0; -- do { -- res |= code & 1; -- code >>= 1, res <<= 1; -- } while (--len > 0); -- return res >> 1; --} -- --/* =========================================================================== -- * Flush the bit buffer, keeping at most 7 bits in it. -- */ --local void bi_flush(s) -- deflate_state *s; --{ -- if (s->bi_valid == 16) { -- put_short(s, s->bi_buf); -- s->bi_buf = 0; -- s->bi_valid = 0; -- } else if (s->bi_valid >= 8) { -- put_byte(s, (Byte)s->bi_buf); -- s->bi_buf >>= 8; -- s->bi_valid -= 8; -- } --} -- --/* =========================================================================== -- * Flush the bit buffer and align the output on a byte boundary -- */ --local void bi_windup(s) -- deflate_state *s; --{ -- if (s->bi_valid > 8) { -- put_short(s, s->bi_buf); -- } else if (s->bi_valid > 0) { -- put_byte(s, (Byte)s->bi_buf); -- } -- s->bi_buf = 0; -- s->bi_valid = 0; --#ifdef ZLIB_DEBUG -- s->bits_sent = (s->bits_sent+7) & ~7; --#endif --} -diff --git a/src/zlib/uncompr.c b/src/zlib/uncompr.c -index f03a1a865..5e256663b 100644 ---- a/src/zlib/uncompr.c -+++ b/src/zlib/uncompr.c -@@ -24,12 +24,8 @@ - Z_DATA_ERROR if the input data was corrupted, including if the input data is - an incomplete zlib stream. - */ --int ZEXPORT uncompress2 (dest, destLen, source, sourceLen) -- Bytef *dest; -- uLongf *destLen; -- const Bytef *source; -- uLong *sourceLen; --{ -+int ZEXPORT uncompress2(Bytef *dest, uLongf *destLen, const Bytef *source, -+ uLong *sourceLen) { - z_stream stream; - int err; - const uInt max = (uInt)-1; -@@ -83,11 +79,7 @@ int ZEXPORT uncompress2 (dest, destLen, source, sourceLen) - err; - } - --int ZEXPORT uncompress (dest, destLen, source, sourceLen) -- Bytef *dest; -- uLongf *destLen; -- const Bytef *source; -- uLong sourceLen; --{ -+int ZEXPORT uncompress(Bytef *dest, uLongf *destLen, const Bytef *source, -+ uLong sourceLen) { - return uncompress2(dest, destLen, source, &sourceLen); - } -diff --git a/src/zlib/zconf.h b/src/zlib/zconf.h -index 5e1d68a00..62adc8d84 100644 ---- a/src/zlib/zconf.h -+++ b/src/zlib/zconf.h -@@ -1,5 +1,5 @@ - /* zconf.h -- configuration of the zlib compression library -- * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler -+ * Copyright (C) 1995-2024 Jean-loup Gailly, Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -@@ -38,6 +38,9 @@ - # define crc32 z_crc32 - # define crc32_combine z_crc32_combine - # define crc32_combine64 z_crc32_combine64 -+# define crc32_combine_gen z_crc32_combine_gen -+# define crc32_combine_gen64 z_crc32_combine_gen64 -+# define crc32_combine_op z_crc32_combine_op - # define crc32_z z_crc32_z - # define deflate z_deflate - # define deflateBound z_deflateBound -@@ -238,7 +241,11 @@ - #endif - - #ifdef Z_SOLO -- typedef unsigned long z_size_t; -+# ifdef _WIN64 -+ typedef unsigned long long z_size_t; -+# else -+ typedef unsigned long z_size_t; -+# endif - #else - # define z_longlong long long - # if defined(NO_SIZE_T) -@@ -293,14 +300,6 @@ - # endif - #endif - --#ifndef Z_ARG /* function prototypes for stdarg */ --# if defined(STDC) || defined(Z_HAVE_STDARG_H) --# define Z_ARG(args) args --# else --# define Z_ARG(args) () --# endif --#endif -- - /* The following definitions for FAR are needed only for MSDOS mixed - * model programming (small or medium model with some far allocations). - * This was tested only with MSC; for other MSDOS compilers you may have -@@ -349,6 +348,9 @@ - # ifdef FAR - # undef FAR - # endif -+# ifndef WIN32_LEAN_AND_MEAN -+# define WIN32_LEAN_AND_MEAN -+# endif - # include - /* No need for _export, use ZLIB.DEF instead. */ - /* For complete Windows compatibility, use WINAPI, not __stdcall. */ -@@ -467,11 +469,18 @@ typedef uLong FAR uLongf; - # undef _LARGEFILE64_SOURCE - #endif - --#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) --# define Z_HAVE_UNISTD_H -+#ifndef Z_HAVE_UNISTD_H -+# ifdef __WATCOMC__ -+# define Z_HAVE_UNISTD_H -+# endif -+#endif -+#ifndef Z_HAVE_UNISTD_H -+# if defined(_LARGEFILE64_SOURCE) && !defined(_WIN32) -+# define Z_HAVE_UNISTD_H -+# endif - #endif - #ifndef Z_SOLO --# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) -+# if defined(Z_HAVE_UNISTD_H) - # include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ - # ifdef VMS - # include /* for off_t */ -@@ -507,7 +516,7 @@ typedef uLong FAR uLongf; - #if !defined(_WIN32) && defined(Z_LARGE64) - # define z_off64_t off64_t - #else --# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) -+# if defined(_WIN32) && !defined(__GNUC__) - # define z_off64_t __int64 - # else - # define z_off64_t z_off_t -diff --git a/src/zlib/zlib.h b/src/zlib/zlib.h -index 4a98e38bf..8d4b932ea 100644 ---- a/src/zlib/zlib.h -+++ b/src/zlib/zlib.h -@@ -1,7 +1,7 @@ - /* zlib.h -- interface of the 'zlib' general purpose compression library -- version 1.2.12, March 11th, 2022 -+ version 1.3.1, January 22nd, 2024 - -- Copyright (C) 1995-2022 Jean-loup Gailly and Mark Adler -+ Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages -@@ -37,11 +37,11 @@ - extern "C" { - #endif - --#define ZLIB_VERSION "1.2.12" --#define ZLIB_VERNUM 0x12c0 -+#define ZLIB_VERSION "1.3.1" -+#define ZLIB_VERNUM 0x1310 - #define ZLIB_VER_MAJOR 1 --#define ZLIB_VER_MINOR 2 --#define ZLIB_VER_REVISION 12 -+#define ZLIB_VER_MINOR 3 -+#define ZLIB_VER_REVISION 1 - #define ZLIB_VER_SUBREVISION 0 - - /* -@@ -78,8 +78,8 @@ extern "C" { - even in the case of corrupted input. - */ - --typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); --typedef void (*free_func) OF((voidpf opaque, voidpf address)); -+typedef voidpf (*alloc_func)(voidpf opaque, uInt items, uInt size); -+typedef void (*free_func)(voidpf opaque, voidpf address); - - struct internal_state; - -@@ -217,7 +217,7 @@ typedef gz_header FAR *gz_headerp; - - /* basic functions */ - --ZEXTERN const char * ZEXPORT zlibVersion OF((void)); -+ZEXTERN const char * ZEXPORT zlibVersion(void); - /* The application can compare zlibVersion and ZLIB_VERSION for consistency. - If the first character differs, the library code actually used is not - compatible with the zlib.h header file used by the application. This check -@@ -225,12 +225,12 @@ ZEXTERN const char * ZEXPORT zlibVersion OF((void)); - */ - - /* --ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); -+ZEXTERN int ZEXPORT deflateInit(z_streamp strm, int level); - - Initializes the internal stream state for compression. The fields - zalloc, zfree and opaque must be initialized before by the caller. If - zalloc and zfree are set to Z_NULL, deflateInit updates them to use default -- allocation functions. -+ allocation functions. total_in, total_out, adler, and msg are initialized. - - The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: - 1 gives best speed, 9 gives best compression, 0 gives no compression at all -@@ -247,7 +247,7 @@ ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); - */ - - --ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); -+ZEXTERN int ZEXPORT deflate(z_streamp strm, int flush); - /* - deflate compresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce -@@ -276,7 +276,7 @@ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); - == 0), or after each call of deflate(). If deflate returns Z_OK and with - zero avail_out, it must be called again after making room in the output - buffer because there might be more output pending. See deflatePending(), -- which can be used if desired to determine whether or not there is more ouput -+ which can be used if desired to determine whether or not there is more output - in that case. - - Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to -@@ -320,8 +320,8 @@ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); - with the same value of the flush parameter and more output space (updated - avail_out), until the flush is complete (deflate returns with non-zero - avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that -- avail_out is greater than six to avoid repeated flush markers due to -- avail_out == 0 on return. -+ avail_out is greater than six when the flush marker begins, in order to avoid -+ repeated flush markers upon calling deflate() again when avail_out == 0. - - If the parameter flush is set to Z_FINISH, pending input is processed, - pending output is flushed and deflate returns with Z_STREAM_END if there was -@@ -360,7 +360,7 @@ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); - */ - - --ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); -+ZEXTERN int ZEXPORT deflateEnd(z_streamp strm); - /* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any pending -@@ -375,7 +375,7 @@ ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); - - - /* --ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); -+ZEXTERN int ZEXPORT inflateInit(z_streamp strm); - - Initializes the internal stream state for decompression. The fields - next_in, avail_in, zalloc, zfree and opaque must be initialized before by -@@ -383,7 +383,8 @@ ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); - read or consumed. The allocation of a sliding window will be deferred to - the first call of inflate (if the decompression does not complete on the - first call). If zalloc and zfree are set to Z_NULL, inflateInit updates -- them to use default allocation functions. -+ them to use default allocation functions. total_in, total_out, adler, and -+ msg are initialized. - - inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the -@@ -397,7 +398,7 @@ ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); - */ - - --ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); -+ZEXTERN int ZEXPORT inflate(z_streamp strm, int flush); - /* - inflate decompresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce -@@ -517,7 +518,7 @@ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); - */ - - --ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); -+ZEXTERN int ZEXPORT inflateEnd(z_streamp strm); - /* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any pending -@@ -535,12 +536,12 @@ ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); - */ - - /* --ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, -- int level, -- int method, -- int windowBits, -- int memLevel, -- int strategy)); -+ZEXTERN int ZEXPORT deflateInit2(z_streamp strm, -+ int level, -+ int method, -+ int windowBits, -+ int memLevel, -+ int strategy); - - This is another version of deflateInit with more compression options. The - fields zalloc, zfree and opaque must be initialized before by the caller. -@@ -607,9 +608,9 @@ ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, - compression: this will be done by deflate(). - */ - --ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, -- const Bytef *dictionary, -- uInt dictLength)); -+ZEXTERN int ZEXPORT deflateSetDictionary(z_streamp strm, -+ const Bytef *dictionary, -+ uInt dictLength); - /* - Initializes the compression dictionary from the given byte sequence - without producing any compressed output. When using the zlib format, this -@@ -651,16 +652,16 @@ ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, - not perform any compression: this will be done by deflate(). - */ - --ZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm, -- Bytef *dictionary, -- uInt *dictLength)); -+ZEXTERN int ZEXPORT deflateGetDictionary(z_streamp strm, -+ Bytef *dictionary, -+ uInt *dictLength); - /* - Returns the sliding dictionary being maintained by deflate. dictLength is - set to the number of bytes in the dictionary, and that many bytes are copied - to dictionary. dictionary must have enough space, where 32768 bytes is - always enough. If deflateGetDictionary() is called with dictionary equal to - Z_NULL, then only the dictionary length is returned, and nothing is copied. -- Similary, if dictLength is Z_NULL, then it is not set. -+ Similarly, if dictLength is Z_NULL, then it is not set. - - deflateGetDictionary() may return a length less than the window size, even - when more than the window size in input has been provided. It may return up -@@ -673,8 +674,8 @@ ZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm, - stream state is inconsistent. - */ - --ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, -- z_streamp source)); -+ZEXTERN int ZEXPORT deflateCopy(z_streamp dest, -+ z_streamp source); - /* - Sets the destination stream as a complete copy of the source stream. - -@@ -691,20 +692,20 @@ ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, - destination. - */ - --ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); -+ZEXTERN int ZEXPORT deflateReset(z_streamp strm); - /* - This function is equivalent to deflateEnd followed by deflateInit, but - does not free and reallocate the internal compression state. The stream - will leave the compression level and any other attributes that may have been -- set unchanged. -+ set unchanged. total_in, total_out, adler, and msg are initialized. - - deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL). - */ - --ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, -- int level, -- int strategy)); -+ZEXTERN int ZEXPORT deflateParams(z_streamp strm, -+ int level, -+ int strategy); - /* - Dynamically update the compression level and compression strategy. The - interpretation of level and strategy is as in deflateInit2(). This can be -@@ -729,7 +730,7 @@ ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, - Then no more input data should be provided before the deflateParams() call. - If this is done, the old level and strategy will be applied to the data - compressed before deflateParams(), and the new level and strategy will be -- applied to the the data compressed after deflateParams(). -+ applied to the data compressed after deflateParams(). - - deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream - state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if -@@ -740,11 +741,11 @@ ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, - retried with more output space. - */ - --ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, -- int good_length, -- int max_lazy, -- int nice_length, -- int max_chain)); -+ZEXTERN int ZEXPORT deflateTune(z_streamp strm, -+ int good_length, -+ int max_lazy, -+ int nice_length, -+ int max_chain); - /* - Fine tune deflate's internal compression parameters. This should only be - used by someone who understands the algorithm used by zlib's deflate for -@@ -757,8 +758,8 @@ ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, - returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. - */ - --ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, -- uLong sourceLen)); -+ZEXTERN uLong ZEXPORT deflateBound(z_streamp strm, -+ uLong sourceLen); - /* - deflateBound() returns an upper bound on the compressed size after - deflation of sourceLen bytes. It must be called after deflateInit() or -@@ -772,9 +773,9 @@ ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, - than Z_FINISH or Z_NO_FLUSH are used. - */ - --ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, -- unsigned *pending, -- int *bits)); -+ZEXTERN int ZEXPORT deflatePending(z_streamp strm, -+ unsigned *pending, -+ int *bits); - /* - deflatePending() returns the number of bytes and bits of output that have - been generated, but not yet provided in the available output. The bytes not -@@ -787,9 +788,9 @@ ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, - stream state was inconsistent. - */ - --ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, -- int bits, -- int value)); -+ZEXTERN int ZEXPORT deflatePrime(z_streamp strm, -+ int bits, -+ int value); - /* - deflatePrime() inserts bits in the deflate output stream. The intent - is that this function is used to start off the deflate output with the bits -@@ -804,8 +805,8 @@ ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, - source stream state was inconsistent. - */ - --ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, -- gz_headerp head)); -+ZEXTERN int ZEXPORT deflateSetHeader(z_streamp strm, -+ gz_headerp head); - /* - deflateSetHeader() provides gzip header information for when a gzip - stream is requested by deflateInit2(). deflateSetHeader() may be called -@@ -821,16 +822,17 @@ ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, - gzip file" and give up. - - If deflateSetHeader is not used, the default gzip header has text false, -- the time set to zero, and os set to 255, with no extra, name, or comment -- fields. The gzip header is returned to the default state by deflateReset(). -+ the time set to zero, and os set to the current operating system, with no -+ extra, name, or comment fields. The gzip header is returned to the default -+ state by deflateReset(). - - deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. - */ - - /* --ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, -- int windowBits)); -+ZEXTERN int ZEXPORT inflateInit2(z_streamp strm, -+ int windowBits); - - This is another version of inflateInit with an extra parameter. The - fields next_in, avail_in, zalloc, zfree and opaque must be initialized -@@ -883,9 +885,9 @@ ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, - deferred until inflate() is called. - */ - --ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, -- const Bytef *dictionary, -- uInt dictLength)); -+ZEXTERN int ZEXPORT inflateSetDictionary(z_streamp strm, -+ const Bytef *dictionary, -+ uInt dictLength); - /* - Initializes the decompression dictionary from the given uncompressed byte - sequence. This function must be called immediately after a call of inflate, -@@ -906,22 +908,22 @@ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, - inflate(). - */ - --ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm, -- Bytef *dictionary, -- uInt *dictLength)); -+ZEXTERN int ZEXPORT inflateGetDictionary(z_streamp strm, -+ Bytef *dictionary, -+ uInt *dictLength); - /* - Returns the sliding dictionary being maintained by inflate. dictLength is - set to the number of bytes in the dictionary, and that many bytes are copied - to dictionary. dictionary must have enough space, where 32768 bytes is - always enough. If inflateGetDictionary() is called with dictionary equal to - Z_NULL, then only the dictionary length is returned, and nothing is copied. -- Similary, if dictLength is Z_NULL, then it is not set. -+ Similarly, if dictLength is Z_NULL, then it is not set. - - inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the - stream state is inconsistent. - */ - --ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); -+ZEXTERN int ZEXPORT inflateSync(z_streamp strm); - /* - Skips invalid compressed data until a possible full flush point (see above - for the description of deflate with Z_FULL_FLUSH) can be found, or until all -@@ -934,14 +936,14 @@ ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); - inflateSync returns Z_OK if a possible full flush point has been found, - Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point - has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. -- In the success case, the application may save the current current value of -- total_in which indicates where valid compressed data was found. In the -- error case, the application may repeatedly call inflateSync, providing more -- input each time, until success or end of the input data. -+ In the success case, the application may save the current value of total_in -+ which indicates where valid compressed data was found. In the error case, -+ the application may repeatedly call inflateSync, providing more input each -+ time, until success or end of the input data. - */ - --ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, -- z_streamp source)); -+ZEXTERN int ZEXPORT inflateCopy(z_streamp dest, -+ z_streamp source); - /* - Sets the destination stream as a complete copy of the source stream. - -@@ -956,18 +958,19 @@ ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, - destination. - */ - --ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); -+ZEXTERN int ZEXPORT inflateReset(z_streamp strm); - /* - This function is equivalent to inflateEnd followed by inflateInit, - but does not free and reallocate the internal decompression state. The - stream will keep attributes that may have been set by inflateInit2. -+ total_in, total_out, adler, and msg are initialized. - - inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL). - */ - --ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, -- int windowBits)); -+ZEXTERN int ZEXPORT inflateReset2(z_streamp strm, -+ int windowBits); - /* - This function is the same as inflateReset, but it also permits changing - the wrap and window size requests. The windowBits parameter is interpreted -@@ -980,9 +983,9 @@ ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, - the windowBits parameter is invalid. - */ - --ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, -- int bits, -- int value)); -+ZEXTERN int ZEXPORT inflatePrime(z_streamp strm, -+ int bits, -+ int value); - /* - This function inserts bits in the inflate input stream. The intent is - that this function is used to start inflating at a bit position in the -@@ -1001,7 +1004,7 @@ ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, - stream state was inconsistent. - */ - --ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); -+ZEXTERN long ZEXPORT inflateMark(z_streamp strm); - /* - This function returns two values, one in the lower 16 bits of the return - value, and the other in the remaining upper bits, obtained by shifting the -@@ -1029,8 +1032,8 @@ ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); - source stream state was inconsistent. - */ - --ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, -- gz_headerp head)); -+ZEXTERN int ZEXPORT inflateGetHeader(z_streamp strm, -+ gz_headerp head); - /* - inflateGetHeader() requests that gzip header information be stored in the - provided gz_header structure. inflateGetHeader() may be called after -@@ -1070,8 +1073,8 @@ ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, - */ - - /* --ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, -- unsigned char FAR *window)); -+ZEXTERN int ZEXPORT inflateBackInit(z_streamp strm, int windowBits, -+ unsigned char FAR *window); - - Initialize the internal stream state for decompression using inflateBack() - calls. The fields zalloc, zfree and opaque in strm must be initialized -@@ -1091,13 +1094,13 @@ ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, - the version of the header file. - */ - --typedef unsigned (*in_func) OF((void FAR *, -- z_const unsigned char FAR * FAR *)); --typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); -+typedef unsigned (*in_func)(void FAR *, -+ z_const unsigned char FAR * FAR *); -+typedef int (*out_func)(void FAR *, unsigned char FAR *, unsigned); - --ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, -- in_func in, void FAR *in_desc, -- out_func out, void FAR *out_desc)); -+ZEXTERN int ZEXPORT inflateBack(z_streamp strm, -+ in_func in, void FAR *in_desc, -+ out_func out, void FAR *out_desc); - /* - inflateBack() does a raw inflate with a single call using a call-back - interface for input and output. This is potentially more efficient than -@@ -1165,7 +1168,7 @@ ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, - cannot return Z_OK. - */ - --ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); -+ZEXTERN int ZEXPORT inflateBackEnd(z_streamp strm); - /* - All memory allocated by inflateBackInit() is freed. - -@@ -1173,7 +1176,7 @@ ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); - state was inconsistent. - */ - --ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); -+ZEXTERN uLong ZEXPORT zlibCompileFlags(void); - /* Return flags indicating compile-time options. - - Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: -@@ -1226,8 +1229,8 @@ ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); - you need special options. - */ - --ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, -- const Bytef *source, uLong sourceLen)); -+ZEXTERN int ZEXPORT compress(Bytef *dest, uLongf *destLen, -+ const Bytef *source, uLong sourceLen); - /* - Compresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total size -@@ -1241,9 +1244,9 @@ ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, - buffer. - */ - --ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, -- const Bytef *source, uLong sourceLen, -- int level)); -+ZEXTERN int ZEXPORT compress2(Bytef *dest, uLongf *destLen, -+ const Bytef *source, uLong sourceLen, -+ int level); - /* - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte -@@ -1257,15 +1260,15 @@ ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, - Z_STREAM_ERROR if the level parameter is invalid. - */ - --ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); -+ZEXTERN uLong ZEXPORT compressBound(uLong sourceLen); - /* - compressBound() returns an upper bound on the compressed size after - compress() or compress2() on sourceLen bytes. It would be used before a - compress() or compress2() call to allocate the destination buffer. - */ - --ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, -- const Bytef *source, uLong sourceLen)); -+ZEXTERN int ZEXPORT uncompress(Bytef *dest, uLongf *destLen, -+ const Bytef *source, uLong sourceLen); - /* - Decompresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total size -@@ -1282,8 +1285,8 @@ ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, - buffer with the uncompressed data up to that point. - */ - --ZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest, uLongf *destLen, -- const Bytef *source, uLong *sourceLen)); -+ZEXTERN int ZEXPORT uncompress2(Bytef *dest, uLongf *destLen, -+ const Bytef *source, uLong *sourceLen); - /* - Same as uncompress, except that sourceLen is a pointer, where the - length of the source is *sourceLen. On return, *sourceLen is the number of -@@ -1302,7 +1305,7 @@ ZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest, uLongf *destLen, - typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ - - /* --ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); -+ZEXTERN gzFile ZEXPORT gzopen(const char *path, const char *mode); - - Open the gzip (.gz) file at path for reading and decompressing, or - compressing and writing. The mode parameter is as in fopen ("rb" or "wb") -@@ -1339,7 +1342,7 @@ ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); - file could not be opened. - */ - --ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); -+ZEXTERN gzFile ZEXPORT gzdopen(int fd, const char *mode); - /* - Associate a gzFile with the file descriptor fd. File descriptors are - obtained from calls like open, dup, creat, pipe or fileno (if the file has -@@ -1362,7 +1365,7 @@ ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); - will not detect if fd is invalid (unless fd is -1). - */ - --ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); -+ZEXTERN int ZEXPORT gzbuffer(gzFile file, unsigned size); - /* - Set the internal buffer size used by this library's functions for file to - size. The default buffer size is 8192 bytes. This function must be called -@@ -1378,7 +1381,7 @@ ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); - too late. - */ - --ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); -+ZEXTERN int ZEXPORT gzsetparams(gzFile file, int level, int strategy); - /* - Dynamically update the compression level and strategy for file. See the - description of deflateInit2 for the meaning of these parameters. Previously -@@ -1389,7 +1392,7 @@ ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); - or Z_MEM_ERROR if there is a memory allocation error. - */ - --ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); -+ZEXTERN int ZEXPORT gzread(gzFile file, voidp buf, unsigned len); - /* - Read and decompress up to len uncompressed bytes from file into buf. If - the input file is not in gzip format, gzread copies the given number of -@@ -1419,8 +1422,8 @@ ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); - Z_STREAM_ERROR. - */ - --ZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems, -- gzFile file)); -+ZEXTERN z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems, -+ gzFile file); - /* - Read and decompress up to nitems items of size size from file into buf, - otherwise operating as gzread() does. This duplicates the interface of -@@ -1437,22 +1440,22 @@ ZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems, - - In the event that the end of file is reached and only a partial item is - available at the end, i.e. the remaining uncompressed data length is not a -- multiple of size, then the final partial item is nevetheless read into buf -+ multiple of size, then the final partial item is nevertheless read into buf - and the end-of-file flag is set. The length of the partial item read is not - provided, but could be inferred from the result of gztell(). This behavior - is the same as the behavior of fread() implementations in common libraries, - but it prevents the direct use of gzfread() to read a concurrently written -- file, reseting and retrying on end-of-file, when size is not 1. -+ file, resetting and retrying on end-of-file, when size is not 1. - */ - --ZEXTERN int ZEXPORT gzwrite OF((gzFile file, voidpc buf, unsigned len)); -+ZEXTERN int ZEXPORT gzwrite(gzFile file, voidpc buf, unsigned len); - /* - Compress and write the len uncompressed bytes at buf to file. gzwrite - returns the number of uncompressed bytes written or 0 in case of error. - */ - --ZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size, -- z_size_t nitems, gzFile file)); -+ZEXTERN z_size_t ZEXPORT gzfwrite(voidpc buf, z_size_t size, -+ z_size_t nitems, gzFile file); - /* - Compress and write nitems items of size size from buf to file, duplicating - the interface of stdio's fwrite(), with size_t request and return types. If -@@ -1465,7 +1468,7 @@ ZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size, - is returned, and the error state is set to Z_STREAM_ERROR. - */ - --ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); -+ZEXTERN int ZEXPORTVA gzprintf(gzFile file, const char *format, ...); - /* - Convert, format, compress, and write the arguments (...) to file under - control of the string format, as in fprintf. gzprintf returns the number of -@@ -1480,7 +1483,7 @@ ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); - This can be determined using zlibCompileFlags(). - */ - --ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); -+ZEXTERN int ZEXPORT gzputs(gzFile file, const char *s); - /* - Compress and write the given null-terminated string s to file, excluding - the terminating null character. -@@ -1488,7 +1491,7 @@ ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); - gzputs returns the number of characters written, or -1 in case of error. - */ - --ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); -+ZEXTERN char * ZEXPORT gzgets(gzFile file, char *buf, int len); - /* - Read and decompress bytes from file into buf, until len-1 characters are - read, or until a newline character is read and transferred to buf, or an -@@ -1502,13 +1505,13 @@ ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); - buf are indeterminate. - */ - --ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); -+ZEXTERN int ZEXPORT gzputc(gzFile file, int c); - /* - Compress and write c, converted to an unsigned char, into file. gzputc - returns the value that was written, or -1 in case of error. - */ - --ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); -+ZEXTERN int ZEXPORT gzgetc(gzFile file); - /* - Read and decompress one byte from file. gzgetc returns this byte or -1 - in case of end of file or error. This is implemented as a macro for speed. -@@ -1517,7 +1520,7 @@ ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); - points to has been clobbered or not. - */ - --ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); -+ZEXTERN int ZEXPORT gzungetc(int c, gzFile file); - /* - Push c back onto the stream for file to be read as the first character on - the next read. At least one character of push-back is always allowed. -@@ -1529,7 +1532,7 @@ ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); - gzseek() or gzrewind(). - */ - --ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); -+ZEXTERN int ZEXPORT gzflush(gzFile file, int flush); - /* - Flush all pending output to file. The parameter flush is as in the - deflate() function. The return value is the zlib error number (see function -@@ -1545,8 +1548,8 @@ ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); - */ - - /* --ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, -- z_off_t offset, int whence)); -+ZEXTERN z_off_t ZEXPORT gzseek(gzFile file, -+ z_off_t offset, int whence); - - Set the starting position to offset relative to whence for the next gzread - or gzwrite on file. The offset represents a number of bytes in the -@@ -1564,7 +1567,7 @@ ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, - would be before the current position. - */ - --ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); -+ZEXTERN int ZEXPORT gzrewind(gzFile file); - /* - Rewind file. This function is supported only for reading. - -@@ -1572,7 +1575,7 @@ ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); - */ - - /* --ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); -+ZEXTERN z_off_t ZEXPORT gztell(gzFile file); - - Return the starting position for the next gzread or gzwrite on file. - This position represents a number of bytes in the uncompressed data stream, -@@ -1583,7 +1586,7 @@ ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); - */ - - /* --ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); -+ZEXTERN z_off_t ZEXPORT gzoffset(gzFile file); - - Return the current compressed (actual) read or write offset of file. This - offset includes the count of bytes that precede the gzip stream, for example -@@ -1592,7 +1595,7 @@ ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); - be used for a progress indicator. On error, gzoffset() returns -1. - */ - --ZEXTERN int ZEXPORT gzeof OF((gzFile file)); -+ZEXTERN int ZEXPORT gzeof(gzFile file); - /* - Return true (1) if the end-of-file indicator for file has been set while - reading, false (0) otherwise. Note that the end-of-file indicator is set -@@ -1607,7 +1610,7 @@ ZEXTERN int ZEXPORT gzeof OF((gzFile file)); - has grown since the previous end of file was detected. - */ - --ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); -+ZEXTERN int ZEXPORT gzdirect(gzFile file); - /* - Return true (1) if file is being copied directly while reading, or false - (0) if file is a gzip stream being decompressed. -@@ -1628,7 +1631,7 @@ ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); - gzip file reading and decompression, which may not be desired.) - */ - --ZEXTERN int ZEXPORT gzclose OF((gzFile file)); -+ZEXTERN int ZEXPORT gzclose(gzFile file); - /* - Flush all pending output for file, if necessary, close file and - deallocate the (de)compression state. Note that once file is closed, you -@@ -1641,8 +1644,8 @@ ZEXTERN int ZEXPORT gzclose OF((gzFile file)); - last read ended in the middle of a gzip stream, or Z_OK on success. - */ - --ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); --ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); -+ZEXTERN int ZEXPORT gzclose_r(gzFile file); -+ZEXTERN int ZEXPORT gzclose_w(gzFile file); - /* - Same as gzclose(), but gzclose_r() is only for use when reading, and - gzclose_w() is only for use when writing or appending. The advantage to -@@ -1653,7 +1656,7 @@ ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); - zlib library. - */ - --ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); -+ZEXTERN const char * ZEXPORT gzerror(gzFile file, int *errnum); - /* - Return the error message for the last error which occurred on file. - errnum is set to zlib error number. If an error occurred in the file system -@@ -1669,7 +1672,7 @@ ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); - functions above that do not distinguish those cases in their return values. - */ - --ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); -+ZEXTERN void ZEXPORT gzclearerr(gzFile file); - /* - Clear the error and end-of-file flags for file. This is analogous to the - clearerr() function in stdio. This is useful for continuing to read a gzip -@@ -1686,7 +1689,7 @@ ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); - library. - */ - --ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); -+ZEXTERN uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len); - /* - Update a running Adler-32 checksum with the bytes buf[0..len-1] and - return the updated checksum. An Adler-32 value is in the range of a 32-bit -@@ -1706,15 +1709,15 @@ ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); - if (adler != original_adler) error(); - */ - --ZEXTERN uLong ZEXPORT adler32_z OF((uLong adler, const Bytef *buf, -- z_size_t len)); -+ZEXTERN uLong ZEXPORT adler32_z(uLong adler, const Bytef *buf, -+ z_size_t len); - /* - Same as adler32(), but with a size_t length. - */ - - /* --ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, -- z_off_t len2)); -+ZEXTERN uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, -+ z_off_t len2); - - Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 - and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for -@@ -1724,7 +1727,7 @@ ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, - negative, the result has no meaning or utility. - */ - --ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); -+ZEXTERN uLong ZEXPORT crc32(uLong crc, const Bytef *buf, uInt len); - /* - Update a running CRC-32 with the bytes buf[0..len-1] and return the - updated CRC-32. A CRC-32 value is in the range of a 32-bit unsigned integer. -@@ -1742,30 +1745,30 @@ ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); - if (crc != original_crc) error(); - */ - --ZEXTERN uLong ZEXPORT crc32_z OF((uLong crc, const Bytef *buf, -- z_size_t len)); -+ZEXTERN uLong ZEXPORT crc32_z(uLong crc, const Bytef *buf, -+ z_size_t len); - /* - Same as crc32(), but with a size_t length. - */ - - /* --ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); -+ZEXTERN uLong ZEXPORT crc32_combine(uLong crc1, uLong crc2, z_off_t len2); - - Combine two CRC-32 check values into one. For two sequences of bytes, - seq1 and seq2 with lengths len1 and len2, CRC-32 check values were - calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 - check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and -- len2. -+ len2. len2 must be non-negative. - */ - - /* --ZEXTERN uLong ZEXPORT crc32_combine_gen OF((z_off_t len2)); -+ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t len2); - - Return the operator corresponding to length len2, to be used with -- crc32_combine_op(). -+ crc32_combine_op(). len2 must be non-negative. - */ - --ZEXTERN uLong ZEXPORT crc32_combine_op OF((uLong crc1, uLong crc2, uLong op)); -+ZEXTERN uLong ZEXPORT crc32_combine_op(uLong crc1, uLong crc2, uLong op); - /* - Give the same result as crc32_combine(), using op in place of len2. op is - is generated from len2 by crc32_combine_gen(). This will be faster than -@@ -1778,20 +1781,20 @@ ZEXTERN uLong ZEXPORT crc32_combine_op OF((uLong crc1, uLong crc2, uLong op)); - /* deflateInit and inflateInit are macros to allow checking the zlib version - * and the compiler's view of z_stream: - */ --ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, -- const char *version, int stream_size)); --ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, -- const char *version, int stream_size)); --ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, -- int windowBits, int memLevel, -- int strategy, const char *version, -- int stream_size)); --ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, -- const char *version, int stream_size)); --ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, -- unsigned char FAR *window, -- const char *version, -- int stream_size)); -+ZEXTERN int ZEXPORT deflateInit_(z_streamp strm, int level, -+ const char *version, int stream_size); -+ZEXTERN int ZEXPORT inflateInit_(z_streamp strm, -+ const char *version, int stream_size); -+ZEXTERN int ZEXPORT deflateInit2_(z_streamp strm, int level, int method, -+ int windowBits, int memLevel, -+ int strategy, const char *version, -+ int stream_size); -+ZEXTERN int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, -+ const char *version, int stream_size); -+ZEXTERN int ZEXPORT inflateBackInit_(z_streamp strm, int windowBits, -+ unsigned char FAR *window, -+ const char *version, -+ int stream_size); - #ifdef Z_PREFIX_SET - # define z_deflateInit(strm, level) \ - deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) -@@ -1836,7 +1839,7 @@ struct gzFile_s { - unsigned char *next; - z_off64_t pos; - }; --ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ -+ZEXTERN int ZEXPORT gzgetc_(gzFile file); /* backward compatibility */ - #ifdef Z_PREFIX_SET - # undef z_gzgetc - # define z_gzgetc(g) \ -@@ -1853,13 +1856,13 @@ ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ - * without large file support, _LFS64_LARGEFILE must also be true - */ - #ifdef Z_LARGE64 -- ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); -- ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); -- ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); -- ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); -- ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); -- ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); -- ZEXTERN uLong ZEXPORT crc32_combine_gen64 OF((z_off64_t)); -+ ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *); -+ ZEXTERN z_off64_t ZEXPORT gzseek64(gzFile, z_off64_t, int); -+ ZEXTERN z_off64_t ZEXPORT gztell64(gzFile); -+ ZEXTERN z_off64_t ZEXPORT gzoffset64(gzFile); -+ ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off64_t); -+ ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off64_t); -+ ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off64_t); - #endif - - #if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) -@@ -1881,50 +1884,50 @@ ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ - # define crc32_combine_gen crc32_combine_gen64 - # endif - # ifndef Z_LARGE64 -- ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); -- ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); -- ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); -- ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); -- ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); -- ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); -- ZEXTERN uLong ZEXPORT crc32_combine_gen64 OF((z_off_t)); -+ ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *); -+ ZEXTERN z_off_t ZEXPORT gzseek64(gzFile, z_off_t, int); -+ ZEXTERN z_off_t ZEXPORT gztell64(gzFile); -+ ZEXTERN z_off_t ZEXPORT gzoffset64(gzFile); -+ ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off_t); -+ ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off_t); -+ ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off_t); - # endif - #else -- ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); -- ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); -- ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); -- ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); -- ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); -- ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); -- ZEXTERN uLong ZEXPORT crc32_combine_gen OF((z_off_t)); -+ ZEXTERN gzFile ZEXPORT gzopen(const char *, const char *); -+ ZEXTERN z_off_t ZEXPORT gzseek(gzFile, z_off_t, int); -+ ZEXTERN z_off_t ZEXPORT gztell(gzFile); -+ ZEXTERN z_off_t ZEXPORT gzoffset(gzFile); -+ ZEXTERN uLong ZEXPORT adler32_combine(uLong, uLong, z_off_t); -+ ZEXTERN uLong ZEXPORT crc32_combine(uLong, uLong, z_off_t); -+ ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t); - #endif - - #else /* Z_SOLO */ - -- ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); -- ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); -- ZEXTERN uLong ZEXPORT crc32_combine_gen OF((z_off_t)); -+ ZEXTERN uLong ZEXPORT adler32_combine(uLong, uLong, z_off_t); -+ ZEXTERN uLong ZEXPORT crc32_combine(uLong, uLong, z_off_t); -+ ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t); - - #endif /* !Z_SOLO */ - - /* undocumented functions */ --ZEXTERN const char * ZEXPORT zError OF((int)); --ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); --ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); --ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); --ZEXTERN int ZEXPORT inflateValidate OF((z_streamp, int)); --ZEXTERN unsigned long ZEXPORT inflateCodesUsed OF ((z_streamp)); --ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); --ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); -+ZEXTERN const char * ZEXPORT zError(int); -+ZEXTERN int ZEXPORT inflateSyncPoint(z_streamp); -+ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table(void); -+ZEXTERN int ZEXPORT inflateUndermine(z_streamp, int); -+ZEXTERN int ZEXPORT inflateValidate(z_streamp, int); -+ZEXTERN unsigned long ZEXPORT inflateCodesUsed(z_streamp); -+ZEXTERN int ZEXPORT inflateResetKeep(z_streamp); -+ZEXTERN int ZEXPORT deflateResetKeep(z_streamp); - #if defined(_WIN32) && !defined(Z_SOLO) --ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, -- const char *mode)); -+ZEXTERN gzFile ZEXPORT gzopen_w(const wchar_t *path, -+ const char *mode); - #endif - #if defined(STDC) || defined(Z_HAVE_STDARG_H) - # ifndef Z_SOLO --ZEXTERN int ZEXPORTVA gzvprintf Z_ARG((gzFile file, -- const char *format, -- va_list va)); -+ZEXTERN int ZEXPORTVA gzvprintf(gzFile file, -+ const char *format, -+ va_list va); - # endif - #endif - -diff --git a/src/zlib/zutil.c b/src/zlib/zutil.c -index dcab28a0d..b1c5d2d3c 100644 ---- a/src/zlib/zutil.c -+++ b/src/zlib/zutil.c -@@ -24,13 +24,11 @@ z_const char * const z_errmsg[10] = { - }; - - --const char * ZEXPORT zlibVersion() --{ -+const char * ZEXPORT zlibVersion(void) { - return ZLIB_VERSION; - } - --uLong ZEXPORT zlibCompileFlags() --{ -+uLong ZEXPORT zlibCompileFlags(void) { - uLong flags; - - flags = 0; -@@ -61,9 +59,11 @@ uLong ZEXPORT zlibCompileFlags() - #ifdef ZLIB_DEBUG - flags += 1 << 8; - #endif -+ /* - #if defined(ASMV) || defined(ASMINF) - flags += 1 << 9; - #endif -+ */ - #ifdef ZLIB_WINAPI - flags += 1 << 10; - #endif -@@ -119,9 +119,7 @@ uLong ZEXPORT zlibCompileFlags() - # endif - int ZLIB_INTERNAL z_verbose = verbose; - --void ZLIB_INTERNAL z_error (m) -- char *m; --{ -+void ZLIB_INTERNAL z_error(char *m) { - fprintf(stderr, "%s\n", m); - exit(1); - } -@@ -130,9 +128,7 @@ void ZLIB_INTERNAL z_error (m) - /* exported to allow conversion of error code to string for compress() and - * uncompress() - */ --const char * ZEXPORT zError(err) -- int err; --{ -+const char * ZEXPORT zError(int err) { - return ERR_MSG(err); - } - -@@ -146,22 +142,14 @@ const char * ZEXPORT zError(err) - - #ifndef HAVE_MEMCPY - --void ZLIB_INTERNAL zmemcpy(dest, source, len) -- Bytef* dest; -- const Bytef* source; -- uInt len; --{ -+void ZLIB_INTERNAL zmemcpy(Bytef* dest, const Bytef* source, uInt len) { - if (len == 0) return; - do { - *dest++ = *source++; /* ??? to be unrolled */ - } while (--len != 0); - } - --int ZLIB_INTERNAL zmemcmp(s1, s2, len) -- const Bytef* s1; -- const Bytef* s2; -- uInt len; --{ -+int ZLIB_INTERNAL zmemcmp(const Bytef* s1, const Bytef* s2, uInt len) { - uInt j; - - for (j = 0; j < len; j++) { -@@ -170,10 +158,7 @@ int ZLIB_INTERNAL zmemcmp(s1, s2, len) - return 0; - } - --void ZLIB_INTERNAL zmemzero(dest, len) -- Bytef* dest; -- uInt len; --{ -+void ZLIB_INTERNAL zmemzero(Bytef* dest, uInt len) { - if (len == 0) return; - do { - *dest++ = 0; /* ??? to be unrolled */ -@@ -214,8 +199,7 @@ local ptr_table table[MAX_PTR]; - * a protected system like OS/2. Use Microsoft C instead. - */ - --voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size) --{ -+voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, unsigned size) { - voidpf buf; - ulg bsize = (ulg)items*size; - -@@ -240,8 +224,7 @@ voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size) - return buf; - } - --void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) --{ -+void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) { - int n; - - (void)opaque; -@@ -277,14 +260,12 @@ void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) - # define _hfree hfree - #endif - --voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size) --{ -+voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, uInt items, uInt size) { - (void)opaque; - return _halloc((long)items, size); - } - --void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) --{ -+void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) { - (void)opaque; - _hfree(ptr); - } -@@ -297,25 +278,18 @@ void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) - #ifndef MY_ZCALLOC /* Any system without a special alloc function */ - - #ifndef STDC --extern voidp malloc OF((uInt size)); --extern voidp calloc OF((uInt items, uInt size)); --extern void free OF((voidpf ptr)); -+extern voidp malloc(uInt size); -+extern voidp calloc(uInt items, uInt size); -+extern void free(voidpf ptr); - #endif - --voidpf ZLIB_INTERNAL zcalloc (opaque, items, size) -- voidpf opaque; -- unsigned items; -- unsigned size; --{ -+voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, unsigned size) { - (void)opaque; - return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : - (voidpf)calloc(items, size); - } - --void ZLIB_INTERNAL zcfree (opaque, ptr) -- voidpf opaque; -- voidpf ptr; --{ -+void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) { - (void)opaque; - free(ptr); - } -diff --git a/src/zlib/zutil.h b/src/zlib/zutil.h -index d9a20ae1b..48dd7feba 100644 ---- a/src/zlib/zutil.h -+++ b/src/zlib/zutil.h -@@ -1,5 +1,5 @@ - /* zutil.h -- internal interface and configuration of the compression library -- * Copyright (C) 1995-2022 Jean-loup Gailly, Mark Adler -+ * Copyright (C) 1995-2024 Jean-loup Gailly, Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -@@ -56,7 +56,7 @@ typedef unsigned long ulg; - extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ - /* (size given to avoid silly warnings with Visual C++) */ - --#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] -+#define ERR_MSG(err) z_errmsg[(err) < -6 || (err) > 2 ? 9 : 2 - (err)] - - #define ERR_RETURN(strm,err) \ - return (strm->msg = ERR_MSG(err), (err)) -@@ -137,17 +137,8 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ - # endif - #endif - --#if defined(MACOS) || defined(TARGET_OS_MAC) -+#if defined(MACOS) - # define OS_CODE 7 --# ifndef Z_SOLO --# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os --# include /* for fdopen */ --# else --# ifndef fdopen --# define fdopen(fd,mode) NULL /* No fdopen() */ --# endif --# endif --# endif - #endif - - #ifdef __acorn -@@ -170,18 +161,6 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ - # define OS_CODE 19 - #endif - --#if defined(_BEOS_) || defined(RISCOS) --# define fdopen(fd,mode) NULL /* No fdopen() */ --#endif -- --#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX --# if defined(_WIN32_WCE) --# define fdopen(fd,mode) NULL /* No fdopen() */ --# else --# define fdopen(fd,type) _fdopen(fd,type) --# endif --#endif -- - #if defined(__BORLANDC__) && !defined(MSDOS) - #pragma warn -8004 - #pragma warn -8008 -@@ -191,8 +170,9 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ - /* provide prototypes for these when building zlib without LFS */ - #if !defined(_WIN32) && \ - (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0) -- ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); -- ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); -+ ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off_t); -+ ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off_t); -+ ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off_t); - #endif - - /* common defaults */ -@@ -231,16 +211,16 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ - # define zmemzero(dest, len) memset(dest, 0, len) - # endif - #else -- void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); -- int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); -- void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len)); -+ void ZLIB_INTERNAL zmemcpy(Bytef* dest, const Bytef* source, uInt len); -+ int ZLIB_INTERNAL zmemcmp(const Bytef* s1, const Bytef* s2, uInt len); -+ void ZLIB_INTERNAL zmemzero(Bytef* dest, uInt len); - #endif - - /* Diagnostic functions */ - #ifdef ZLIB_DEBUG - # include - extern int ZLIB_INTERNAL z_verbose; -- extern void ZLIB_INTERNAL z_error OF((char *m)); -+ extern void ZLIB_INTERNAL z_error(char *m); - # define Assert(cond,msg) {if(!(cond)) z_error(msg);} - # define Trace(x) {if (z_verbose>=0) fprintf x ;} - # define Tracev(x) {if (z_verbose>0) fprintf x ;} -@@ -257,9 +237,9 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ - #endif - - #ifndef Z_SOLO -- voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items, -- unsigned size)); -- void ZLIB_INTERNAL zcfree OF((voidpf opaque, voidpf ptr)); -+ voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, -+ unsigned size); -+ void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr); - #endif - - #define ZALLOC(strm, items, size) \ - -From f60071745897c8769d34d4c513b06eb3e3af0425 Mon Sep 17 00:00:00 2001 -From: Julian Sikorski -Date: Wed, 21 Feb 2024 22:12:26 +0100 -Subject: [PATCH 2/4] imp: updated bundled LZMA SDK to 23.01 - ---- - qmc2.pro | 2 +- - src/lzma/7z.h | 12 +- - src/lzma/7zAlloc.c | 69 ++-- - src/lzma/7zAlloc.h | 6 +- - src/lzma/7zArcIn.c | 405 ++++++++++----------- - src/lzma/7zBuf.h | 6 +- - src/lzma/7zCrc.c | 130 ++++--- - src/lzma/7zCrc.h | 14 +- - src/lzma/7zCrcOpt.c | 16 +- - src/lzma/7zDec.c | 172 +++++---- - src/lzma/7zFile.c | 33 +- - src/lzma/7zFile.h | 9 +- - src/lzma/7zStream.c | 67 ++-- - src/lzma/7zTypes.h | 274 +++++++++------ - src/lzma/7zVersion.h | 10 +- - src/lzma/7zWindows.h | 101 ++++++ - src/lzma/Aes.c | 108 +++--- - src/lzma/Aes.h | 36 +- - src/lzma/AesOpt.c | 348 ++++++++++-------- - src/lzma/Alloc.c | 192 ++++++---- - src/lzma/Alloc.h | 19 +- - src/lzma/Bcj2.c | 319 +++++++++-------- - src/lzma/Bcj2.h | 270 +++++++++++--- - src/lzma/Bcj2Enc.c | 559 +++++++++++++++++++---------- - src/lzma/Bra.c | 496 ++++++++++++++++++-------- - src/lzma/Bra.h | 115 +++--- - src/lzma/Bra86.c | 221 +++++++++--- - src/lzma/BraIA64.c | 57 +-- - src/lzma/Compiler.h | 162 +++++++-- - src/lzma/CpuArch.c | 795 ++++++++++++++++++++++++++++++------------ - src/lzma/CpuArch.h | 233 +++++++++---- - src/lzma/Delta.h | 6 +- - src/lzma/DllSecur.c | 127 +++---- - src/lzma/DllSecur.h | 6 +- - src/lzma/LzFind.c | 519 +++++++++++++++------------ - src/lzma/LzFind.h | 53 ++- - src/lzma/LzFindMt.c | 70 ++-- - src/lzma/LzFindMt.h | 10 +- - src/lzma/LzFindOpt.c | 14 +- - src/lzma/LzHash.h | 8 +- - src/lzma/Lzma2Dec.c | 12 +- - src/lzma/Lzma2Dec.h | 15 +- - src/lzma/Lzma2DecMt.c | 155 ++++---- - src/lzma/Lzma2DecMt.h | 20 +- - src/lzma/Lzma2Enc.c | 174 ++++----- - src/lzma/Lzma2Enc.h | 20 +- - src/lzma/Lzma86.h | 6 +- - src/lzma/Lzma86Dec.c | 7 +- - src/lzma/Lzma86Enc.c | 7 +- - src/lzma/LzmaDec.c | 190 +++++----- - src/lzma/LzmaDec.h | 17 +- - src/lzma/LzmaEnc.c | 389 ++++++++++----------- - src/lzma/LzmaEnc.h | 23 +- - src/lzma/LzmaLib.c | 8 +- - src/lzma/LzmaLib.h | 12 +- - src/lzma/MtCoder.c | 104 +++--- - src/lzma/MtCoder.h | 50 +-- - src/lzma/MtDec.c | 101 ++---- - src/lzma/MtDec.h | 34 +- - src/lzma/Ppmd.h | 12 +- - src/lzma/Ppmd7.c | 186 +++++----- - src/lzma/Ppmd7.h | 10 +- - src/lzma/Ppmd7Dec.c | 57 +-- - src/lzma/Ppmd7Enc.c | 87 +++-- - src/lzma/Precomp.h | 6 +- - src/lzma/RotateDefs.h | 28 +- - src/lzma/Sha256.c | 150 ++++---- - src/lzma/Sha256.h | 12 +- - src/lzma/Sha256Opt.c | 129 ++++--- - src/lzma/Sort.h | 6 +- - src/lzma/Threads.c | 86 +++-- - src/lzma/Threads.h | 50 +-- - src/lzma/Xz.c | 4 +- - src/lzma/Xz.h | 56 ++- - src/lzma/XzCrc64.c | 32 +- - src/lzma/XzCrc64.h | 12 +- - src/lzma/XzCrc64Opt.c | 28 +- - src/lzma/XzDec.c | 300 +++++++++------- - src/lzma/XzEnc.c | 270 +++++++------- - src/lzma/XzEnc.h | 23 +- - src/lzma/XzIn.c | 75 ++-- - src/lzma/lzma-sdk.txt | 2 +- - src/sevenzipfile.cpp | 2 +- - 83 files changed, 5514 insertions(+), 3522 deletions(-) - create mode 100644 src/lzma/7zWindows.h - -diff --git a/qmc2.pro b/qmc2.pro -index 90bd30a45..9891fedee 100644 ---- a/qmc2.pro -+++ b/qmc2.pro -@@ -303,7 +303,7 @@ TRANSLATIONS += data/lng/qmc2_de.ts \ - data/lng/qmc2_us.ts - RESOURCES += qmc2.qrc - QMAKE_MAKEFILE = Makefile.qmake --DEFINES += _7ZIP_PPMD_SUPPORT _7ZIP_ST -+DEFINES += Z7_PPMD_SUPPORT Z7_ST - - contains(DEFINES, QMC2_LIBARCHIVE_ENABLED) { - SOURCES += src/archivefile.cpp -diff --git a/src/lzma/7z.h b/src/lzma/7z.h -index 304f75ffc..9e27c0152 100644 ---- a/src/lzma/7z.h -+++ b/src/lzma/7z.h -@@ -1,8 +1,8 @@ - /* 7z.h -- 7z interface --2018-07-02 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - --#ifndef __7Z_H --#define __7Z_H -+#ifndef ZIP7_INC_7Z_H -+#define ZIP7_INC_7Z_H - - #include "7zTypes.h" - -@@ -98,7 +98,7 @@ typedef struct - UInt64 SzAr_GetFolderUnpackSize(const CSzAr *p, UInt32 folderIndex); - - SRes SzAr_DecodeFolder(const CSzAr *p, UInt32 folderIndex, -- ILookInStream *stream, UInt64 startPos, -+ ILookInStreamPtr stream, UInt64 startPos, - Byte *outBuffer, size_t outSize, - ISzAllocPtr allocMain); - -@@ -174,7 +174,7 @@ UInt16 *SzArEx_GetFullNameUtf16_Back(const CSzArEx *p, size_t fileIndex, UInt16 - - SRes SzArEx_Extract( - const CSzArEx *db, -- ILookInStream *inStream, -+ ILookInStreamPtr inStream, - UInt32 fileIndex, /* index of file */ - UInt32 *blockIndex, /* index of solid block */ - Byte **outBuffer, /* pointer to pointer to output buffer (allocated with allocMain) */ -@@ -196,7 +196,7 @@ SZ_ERROR_INPUT_EOF - SZ_ERROR_FAIL - */ - --SRes SzArEx_Open(CSzArEx *p, ILookInStream *inStream, -+SRes SzArEx_Open(CSzArEx *p, ILookInStreamPtr inStream, - ISzAllocPtr allocMain, ISzAllocPtr allocTemp); - - EXTERN_C_END -diff --git a/src/lzma/7zAlloc.c b/src/lzma/7zAlloc.c -index c924a529f..2f0659af6 100644 ---- a/src/lzma/7zAlloc.c -+++ b/src/lzma/7zAlloc.c -@@ -1,5 +1,5 @@ --/* 7zAlloc.c -- Allocation functions --2017-04-03 : Igor Pavlov : Public domain */ -+/* 7zAlloc.c -- Allocation functions for 7z processing -+2023-03-04 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -7,74 +7,83 @@ - - #include "7zAlloc.h" - --/* #define _SZ_ALLOC_DEBUG */ --/* use _SZ_ALLOC_DEBUG to debug alloc/free operations */ -+/* #define SZ_ALLOC_DEBUG */ -+/* use SZ_ALLOC_DEBUG to debug alloc/free operations */ - --#ifdef _SZ_ALLOC_DEBUG -+#ifdef SZ_ALLOC_DEBUG - -+/* - #ifdef _WIN32 --#include -+#include "7zWindows.h" - #endif -+*/ - - #include --int g_allocCount = 0; --int g_allocCountTemp = 0; -+static int g_allocCount = 0; -+static int g_allocCountTemp = 0; - -+static void Print_Alloc(const char *s, size_t size, int *counter) -+{ -+ const unsigned size2 = (unsigned)size; -+ fprintf(stderr, "\n%s count = %10d : %10u bytes; ", s, *counter, size2); -+ (*counter)++; -+} -+static void Print_Free(const char *s, int *counter) -+{ -+ (*counter)--; -+ fprintf(stderr, "\n%s count = %10d", s, *counter); -+} - #endif - - void *SzAlloc(ISzAllocPtr p, size_t size) - { -- UNUSED_VAR(p); -+ UNUSED_VAR(p) - if (size == 0) - return 0; -- #ifdef _SZ_ALLOC_DEBUG -- fprintf(stderr, "\nAlloc %10u bytes; count = %10d", (unsigned)size, g_allocCount); -- g_allocCount++; -+ #ifdef SZ_ALLOC_DEBUG -+ Print_Alloc("Alloc", size, &g_allocCount); - #endif - return malloc(size); - } - - void SzFree(ISzAllocPtr p, void *address) - { -- UNUSED_VAR(p); -- #ifdef _SZ_ALLOC_DEBUG -- if (address != 0) -- { -- g_allocCount--; -- fprintf(stderr, "\nFree; count = %10d", g_allocCount); -- } -+ UNUSED_VAR(p) -+ #ifdef SZ_ALLOC_DEBUG -+ if (address) -+ Print_Free("Free ", &g_allocCount); - #endif - free(address); - } - - void *SzAllocTemp(ISzAllocPtr p, size_t size) - { -- UNUSED_VAR(p); -+ UNUSED_VAR(p) - if (size == 0) - return 0; -- #ifdef _SZ_ALLOC_DEBUG -- fprintf(stderr, "\nAlloc_temp %10u bytes; count = %10d", (unsigned)size, g_allocCountTemp); -- g_allocCountTemp++; -+ #ifdef SZ_ALLOC_DEBUG -+ Print_Alloc("Alloc_temp", size, &g_allocCountTemp); -+ /* - #ifdef _WIN32 - return HeapAlloc(GetProcessHeap(), 0, size); - #endif -+ */ - #endif - return malloc(size); - } - - void SzFreeTemp(ISzAllocPtr p, void *address) - { -- UNUSED_VAR(p); -- #ifdef _SZ_ALLOC_DEBUG -- if (address != 0) -- { -- g_allocCountTemp--; -- fprintf(stderr, "\nFree_temp; count = %10d", g_allocCountTemp); -- } -+ UNUSED_VAR(p) -+ #ifdef SZ_ALLOC_DEBUG -+ if (address) -+ Print_Free("Free_temp ", &g_allocCountTemp); -+ /* - #ifdef _WIN32 - HeapFree(GetProcessHeap(), 0, address); - return; - #endif -+ */ - #endif - free(address); - } -diff --git a/src/lzma/7zAlloc.h b/src/lzma/7zAlloc.h -index 44778f9b2..b2b8b0cdd 100644 ---- a/src/lzma/7zAlloc.h -+++ b/src/lzma/7zAlloc.h -@@ -1,8 +1,8 @@ - /* 7zAlloc.h -- Allocation functions --2017-04-03 : Igor Pavlov : Public domain */ -+2023-03-04 : Igor Pavlov : Public domain */ - --#ifndef __7Z_ALLOC_H --#define __7Z_ALLOC_H -+#ifndef ZIP7_INC_7Z_ALLOC_H -+#define ZIP7_INC_7Z_ALLOC_H - - #include "7zTypes.h" - -diff --git a/src/lzma/7zArcIn.c b/src/lzma/7zArcIn.c -index c2405bdef..14b77551e 100644 ---- a/src/lzma/7zArcIn.c -+++ b/src/lzma/7zArcIn.c -@@ -1,5 +1,5 @@ - /* 7zArcIn.c -- 7z Input functions --2021-02-09 : Igor Pavlov : Public domain */ -+2023-05-11 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -10,10 +10,11 @@ - #include "7zCrc.h" - #include "CpuArch.h" - --#define MY_ALLOC(T, p, size, alloc) { \ -- if ((p = (T *)ISzAlloc_Alloc(alloc, (size) * sizeof(T))) == NULL) return SZ_ERROR_MEM; } -+#define MY_ALLOC(T, p, size, alloc) \ -+ { if ((p = (T *)ISzAlloc_Alloc(alloc, (size) * sizeof(T))) == NULL) return SZ_ERROR_MEM; } - --#define MY_ALLOC_ZE(T, p, size, alloc) { if ((size) == 0) p = NULL; else MY_ALLOC(T, p, size, alloc) } -+#define MY_ALLOC_ZE(T, p, size, alloc) \ -+ { if ((size) == 0) p = NULL; else MY_ALLOC(T, p, size, alloc) } - - #define MY_ALLOC_AND_CPY(to, size, from, alloc) \ - { MY_ALLOC(Byte, to, size, alloc); memcpy(to, from, size); } -@@ -58,7 +59,7 @@ enum EIdEnum - - const Byte k7zSignature[k7zSignatureSize] = {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C}; - --#define SzBitUi32s_Init(p) { (p)->Defs = NULL; (p)->Vals = NULL; } -+#define SzBitUi32s_INIT(p) { (p)->Defs = NULL; (p)->Vals = NULL; } - - static SRes SzBitUi32s_Alloc(CSzBitUi32s *p, size_t num, ISzAllocPtr alloc) - { -@@ -69,8 +70,8 @@ static SRes SzBitUi32s_Alloc(CSzBitUi32s *p, size_t num, ISzAllocPtr alloc) - } - else - { -- MY_ALLOC(Byte, p->Defs, (num + 7) >> 3, alloc); -- MY_ALLOC(UInt32, p->Vals, num, alloc); -+ MY_ALLOC(Byte, p->Defs, (num + 7) >> 3, alloc) -+ MY_ALLOC(UInt32, p->Vals, num, alloc) - } - return SZ_OK; - } -@@ -81,7 +82,7 @@ static void SzBitUi32s_Free(CSzBitUi32s *p, ISzAllocPtr alloc) - ISzAlloc_Free(alloc, p->Vals); p->Vals = NULL; - } - --#define SzBitUi64s_Init(p) { (p)->Defs = NULL; (p)->Vals = NULL; } -+#define SzBitUi64s_INIT(p) { (p)->Defs = NULL; (p)->Vals = NULL; } - - static void SzBitUi64s_Free(CSzBitUi64s *p, ISzAllocPtr alloc) - { -@@ -96,7 +97,7 @@ static void SzAr_Init(CSzAr *p) - p->NumFolders = 0; - - p->PackPositions = NULL; -- SzBitUi32s_Init(&p->FolderCRCs); -+ SzBitUi32s_INIT(&p->FolderCRCs) - - p->FoCodersOffsets = NULL; - p->FoStartPackStreamIndex = NULL; -@@ -142,11 +143,11 @@ void SzArEx_Init(CSzArEx *p) - p->FileNameOffsets = NULL; - p->FileNames = NULL; - -- SzBitUi32s_Init(&p->CRCs); -- SzBitUi32s_Init(&p->Attribs); -- // SzBitUi32s_Init(&p->Parents); -- SzBitUi64s_Init(&p->MTime); -- SzBitUi64s_Init(&p->CTime); -+ SzBitUi32s_INIT(&p->CRCs) -+ SzBitUi32s_INIT(&p->Attribs) -+ // SzBitUi32s_INIT(&p->Parents) -+ SzBitUi64s_INIT(&p->MTime) -+ SzBitUi64s_INIT(&p->CTime) - } - - void SzArEx_Free(CSzArEx *p, ISzAllocPtr alloc) -@@ -180,11 +181,20 @@ static int TestSignatureCandidate(const Byte *testBytes) - return 1; - } - --#define SzData_Clear(p) { (p)->Data = NULL; (p)->Size = 0; } -+#define SzData_CLEAR(p) { (p)->Data = NULL; (p)->Size = 0; } -+ -+#define SZ_READ_BYTE_SD_NOCHECK(_sd_, dest) \ -+ (_sd_)->Size--; dest = *(_sd_)->Data++; -+ -+#define SZ_READ_BYTE_SD(_sd_, dest) \ -+ if ((_sd_)->Size == 0) return SZ_ERROR_ARCHIVE; \ -+ SZ_READ_BYTE_SD_NOCHECK(_sd_, dest) - --#define SZ_READ_BYTE_SD(_sd_, dest) if ((_sd_)->Size == 0) return SZ_ERROR_ARCHIVE; (_sd_)->Size--; dest = *(_sd_)->Data++; - #define SZ_READ_BYTE(dest) SZ_READ_BYTE_SD(sd, dest) --#define SZ_READ_BYTE_2(dest) if (sd.Size == 0) return SZ_ERROR_ARCHIVE; sd.Size--; dest = *sd.Data++; -+ -+#define SZ_READ_BYTE_2(dest) \ -+ if (sd.Size == 0) return SZ_ERROR_ARCHIVE; \ -+ sd.Size--; dest = *sd.Data++; - - #define SKIP_DATA(sd, size) { sd->Size -= (size_t)(size); sd->Data += (size_t)(size); } - #define SKIP_DATA2(sd, size) { sd.Size -= (size_t)(size); sd.Data += (size_t)(size); } -@@ -192,25 +202,25 @@ static int TestSignatureCandidate(const Byte *testBytes) - #define SZ_READ_32(dest) if (sd.Size < 4) return SZ_ERROR_ARCHIVE; \ - dest = GetUi32(sd.Data); SKIP_DATA2(sd, 4); - --static MY_NO_INLINE SRes ReadNumber(CSzData *sd, UInt64 *value) -+static Z7_NO_INLINE SRes ReadNumber(CSzData *sd, UInt64 *value) - { - Byte firstByte, mask; - unsigned i; - UInt32 v; - -- SZ_READ_BYTE(firstByte); -+ SZ_READ_BYTE(firstByte) - if ((firstByte & 0x80) == 0) - { - *value = firstByte; - return SZ_OK; - } -- SZ_READ_BYTE(v); -+ SZ_READ_BYTE(v) - if ((firstByte & 0x40) == 0) - { - *value = (((UInt32)firstByte & 0x3F) << 8) | v; - return SZ_OK; - } -- SZ_READ_BYTE(mask); -+ SZ_READ_BYTE(mask) - *value = v | ((UInt32)mask << 8); - mask = 0x20; - for (i = 2; i < 8; i++) -@@ -218,11 +228,11 @@ static MY_NO_INLINE SRes ReadNumber(CSzData *sd, UInt64 *value) - Byte b; - if ((firstByte & mask) == 0) - { -- UInt64 highPart = (unsigned)firstByte & (unsigned)(mask - 1); -+ const UInt64 highPart = (unsigned)firstByte & (unsigned)(mask - 1); - *value |= (highPart << (8 * i)); - return SZ_OK; - } -- SZ_READ_BYTE(b); -+ SZ_READ_BYTE(b) - *value |= ((UInt64)b << (8 * i)); - mask >>= 1; - } -@@ -230,7 +240,7 @@ static MY_NO_INLINE SRes ReadNumber(CSzData *sd, UInt64 *value) - } - - --static MY_NO_INLINE SRes SzReadNumber32(CSzData *sd, UInt32 *value) -+static Z7_NO_INLINE SRes SzReadNumber32(CSzData *sd, UInt32 *value) - { - Byte firstByte; - UInt64 value64; -@@ -244,7 +254,7 @@ static MY_NO_INLINE SRes SzReadNumber32(CSzData *sd, UInt32 *value) - sd->Size--; - return SZ_OK; - } -- RINOK(ReadNumber(sd, &value64)); -+ RINOK(ReadNumber(sd, &value64)) - if (value64 >= (UInt32)0x80000000 - 1) - return SZ_ERROR_UNSUPPORTED; - if (value64 >= ((UInt64)(1) << ((sizeof(size_t) - 1) * 8 + 4))) -@@ -258,10 +268,10 @@ static MY_NO_INLINE SRes SzReadNumber32(CSzData *sd, UInt32 *value) - static SRes SkipData(CSzData *sd) - { - UInt64 size; -- RINOK(ReadNumber(sd, &size)); -+ RINOK(ReadNumber(sd, &size)) - if (size > sd->Size) - return SZ_ERROR_ARCHIVE; -- SKIP_DATA(sd, size); -+ SKIP_DATA(sd, size) - return SZ_OK; - } - -@@ -270,22 +280,22 @@ static SRes WaitId(CSzData *sd, UInt32 id) - for (;;) - { - UInt64 type; -- RINOK(ReadID(sd, &type)); -+ RINOK(ReadID(sd, &type)) - if (type == id) - return SZ_OK; - if (type == k7zIdEnd) - return SZ_ERROR_ARCHIVE; -- RINOK(SkipData(sd)); -+ RINOK(SkipData(sd)) - } - } - - static SRes RememberBitVector(CSzData *sd, UInt32 numItems, const Byte **v) - { -- UInt32 numBytes = (numItems + 7) >> 3; -+ const UInt32 numBytes = (numItems + 7) >> 3; - if (numBytes > sd->Size) - return SZ_ERROR_ARCHIVE; - *v = sd->Data; -- SKIP_DATA(sd, numBytes); -+ SKIP_DATA(sd, numBytes) - return SZ_OK; - } - -@@ -307,48 +317,48 @@ static UInt32 CountDefinedBits(const Byte *bits, UInt32 numItems) - return sum; - } - --static MY_NO_INLINE SRes ReadBitVector(CSzData *sd, UInt32 numItems, Byte **v, ISzAllocPtr alloc) -+static Z7_NO_INLINE SRes ReadBitVector(CSzData *sd, UInt32 numItems, Byte **v, ISzAllocPtr alloc) - { - Byte allAreDefined; - Byte *v2; -- UInt32 numBytes = (numItems + 7) >> 3; -+ const UInt32 numBytes = (numItems + 7) >> 3; - *v = NULL; -- SZ_READ_BYTE(allAreDefined); -+ SZ_READ_BYTE(allAreDefined) - if (numBytes == 0) - return SZ_OK; - if (allAreDefined == 0) - { - if (numBytes > sd->Size) - return SZ_ERROR_ARCHIVE; -- MY_ALLOC_AND_CPY(*v, numBytes, sd->Data, alloc); -- SKIP_DATA(sd, numBytes); -+ MY_ALLOC_AND_CPY(*v, numBytes, sd->Data, alloc) -+ SKIP_DATA(sd, numBytes) - return SZ_OK; - } -- MY_ALLOC(Byte, *v, numBytes, alloc); -+ MY_ALLOC(Byte, *v, numBytes, alloc) - v2 = *v; - memset(v2, 0xFF, (size_t)numBytes); - { -- unsigned numBits = (unsigned)numItems & 7; -+ const unsigned numBits = (unsigned)numItems & 7; - if (numBits != 0) - v2[(size_t)numBytes - 1] = (Byte)((((UInt32)1 << numBits) - 1) << (8 - numBits)); - } - return SZ_OK; - } - --static MY_NO_INLINE SRes ReadUi32s(CSzData *sd2, UInt32 numItems, CSzBitUi32s *crcs, ISzAllocPtr alloc) -+static Z7_NO_INLINE SRes ReadUi32s(CSzData *sd2, UInt32 numItems, CSzBitUi32s *crcs, ISzAllocPtr alloc) - { - UInt32 i; - CSzData sd; - UInt32 *vals; - const Byte *defs; -- MY_ALLOC_ZE(UInt32, crcs->Vals, numItems, alloc); -+ MY_ALLOC_ZE(UInt32, crcs->Vals, numItems, alloc) - sd = *sd2; - defs = crcs->Defs; - vals = crcs->Vals; - for (i = 0; i < numItems; i++) - if (SzBitArray_Check(defs, i)) - { -- SZ_READ_32(vals[i]); -+ SZ_READ_32(vals[i]) - } - else - vals[i] = 0; -@@ -359,7 +369,7 @@ static MY_NO_INLINE SRes ReadUi32s(CSzData *sd2, UInt32 numItems, CSzBitUi32s *c - static SRes ReadBitUi32s(CSzData *sd, UInt32 numItems, CSzBitUi32s *crcs, ISzAllocPtr alloc) - { - SzBitUi32s_Free(crcs, alloc); -- RINOK(ReadBitVector(sd, numItems, &crcs->Defs, alloc)); -+ RINOK(ReadBitVector(sd, numItems, &crcs->Defs, alloc)) - return ReadUi32s(sd, numItems, crcs, alloc); - } - -@@ -367,36 +377,36 @@ static SRes SkipBitUi32s(CSzData *sd, UInt32 numItems) - { - Byte allAreDefined; - UInt32 numDefined = numItems; -- SZ_READ_BYTE(allAreDefined); -+ SZ_READ_BYTE(allAreDefined) - if (!allAreDefined) - { -- size_t numBytes = (numItems + 7) >> 3; -+ const size_t numBytes = (numItems + 7) >> 3; - if (numBytes > sd->Size) - return SZ_ERROR_ARCHIVE; - numDefined = CountDefinedBits(sd->Data, numItems); -- SKIP_DATA(sd, numBytes); -+ SKIP_DATA(sd, numBytes) - } - if (numDefined > (sd->Size >> 2)) - return SZ_ERROR_ARCHIVE; -- SKIP_DATA(sd, (size_t)numDefined * 4); -+ SKIP_DATA(sd, (size_t)numDefined * 4) - return SZ_OK; - } - - static SRes ReadPackInfo(CSzAr *p, CSzData *sd, ISzAllocPtr alloc) - { -- RINOK(SzReadNumber32(sd, &p->NumPackStreams)); -+ RINOK(SzReadNumber32(sd, &p->NumPackStreams)) - -- RINOK(WaitId(sd, k7zIdSize)); -- MY_ALLOC(UInt64, p->PackPositions, (size_t)p->NumPackStreams + 1, alloc); -+ RINOK(WaitId(sd, k7zIdSize)) -+ MY_ALLOC(UInt64, p->PackPositions, (size_t)p->NumPackStreams + 1, alloc) - { - UInt64 sum = 0; - UInt32 i; -- UInt32 numPackStreams = p->NumPackStreams; -+ const UInt32 numPackStreams = p->NumPackStreams; - for (i = 0; i < numPackStreams; i++) - { - UInt64 packSize; - p->PackPositions[i] = sum; -- RINOK(ReadNumber(sd, &packSize)); -+ RINOK(ReadNumber(sd, &packSize)) - sum += packSize; - if (sum < packSize) - return SZ_ERROR_ARCHIVE; -@@ -407,16 +417,16 @@ static SRes ReadPackInfo(CSzAr *p, CSzData *sd, ISzAllocPtr alloc) - for (;;) - { - UInt64 type; -- RINOK(ReadID(sd, &type)); -+ RINOK(ReadID(sd, &type)) - if (type == k7zIdEnd) - return SZ_OK; - if (type == k7zIdCRC) - { - /* CRC of packed streams is unused now */ -- RINOK(SkipBitUi32s(sd, p->NumPackStreams)); -+ RINOK(SkipBitUi32s(sd, p->NumPackStreams)) - continue; - } -- RINOK(SkipData(sd)); -+ RINOK(SkipData(sd)) - } - } - -@@ -442,7 +452,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) - f->NumPackStreams = 0; - f->UnpackStream = 0; - -- RINOK(SzReadNumber32(sd, &numCoders)); -+ RINOK(SzReadNumber32(sd, &numCoders)) - if (numCoders == 0 || numCoders > SZ_NUM_CODERS_IN_FOLDER_MAX) - return SZ_ERROR_UNSUPPORTED; - -@@ -453,7 +463,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) - unsigned idSize, j; - UInt64 id; - -- SZ_READ_BYTE(mainByte); -+ SZ_READ_BYTE(mainByte) - if ((mainByte & 0xC0) != 0) - return SZ_ERROR_UNSUPPORTED; - -@@ -481,12 +491,12 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) - { - UInt32 numStreams; - -- RINOK(SzReadNumber32(sd, &numStreams)); -+ RINOK(SzReadNumber32(sd, &numStreams)) - if (numStreams > k_NumCodersStreams_in_Folder_MAX) - return SZ_ERROR_UNSUPPORTED; - coder->NumStreams = (Byte)numStreams; - -- RINOK(SzReadNumber32(sd, &numStreams)); -+ RINOK(SzReadNumber32(sd, &numStreams)) - if (numStreams != 1) - return SZ_ERROR_UNSUPPORTED; - } -@@ -499,7 +509,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) - if ((mainByte & 0x20) != 0) - { - UInt32 propsSize = 0; -- RINOK(SzReadNumber32(sd, &propsSize)); -+ RINOK(SzReadNumber32(sd, &propsSize)) - if (propsSize > sd->Size) - return SZ_ERROR_ARCHIVE; - if (propsSize >= 0x80) -@@ -549,12 +559,12 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) - { - CSzBond *bp = f->Bonds + i; - -- RINOK(SzReadNumber32(sd, &bp->InIndex)); -+ RINOK(SzReadNumber32(sd, &bp->InIndex)) - if (bp->InIndex >= numInStreams || streamUsed[bp->InIndex]) - return SZ_ERROR_ARCHIVE; - streamUsed[bp->InIndex] = True7z; - -- RINOK(SzReadNumber32(sd, &bp->OutIndex)); -+ RINOK(SzReadNumber32(sd, &bp->OutIndex)) - if (bp->OutIndex >= numCoders || coderUsed[bp->OutIndex]) - return SZ_ERROR_ARCHIVE; - coderUsed[bp->OutIndex] = True7z; -@@ -584,7 +594,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) - for (i = 0; i < numPackStreams; i++) - { - UInt32 index; -- RINOK(SzReadNumber32(sd, &index)); -+ RINOK(SzReadNumber32(sd, &index)) - if (index >= numInStreams || streamUsed[index]) - return SZ_ERROR_ARCHIVE; - streamUsed[index] = True7z; -@@ -598,7 +608,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) - } - - --static MY_NO_INLINE SRes SkipNumbers(CSzData *sd2, UInt32 num) -+static Z7_NO_INLINE SRes SkipNumbers(CSzData *sd2, UInt32 num) - { - CSzData sd; - sd = *sd2; -@@ -606,7 +616,7 @@ static MY_NO_INLINE SRes SkipNumbers(CSzData *sd2, UInt32 num) - { - Byte firstByte, mask; - unsigned i; -- SZ_READ_BYTE_2(firstByte); -+ SZ_READ_BYTE_2(firstByte) - if ((firstByte & 0x80) == 0) - continue; - if ((firstByte & 0x40) == 0) -@@ -622,7 +632,7 @@ static MY_NO_INLINE SRes SkipNumbers(CSzData *sd2, UInt32 num) - mask >>= 1; - if (i > sd.Size) - return SZ_ERROR_ARCHIVE; -- SKIP_DATA2(sd, i); -+ SKIP_DATA2(sd, i) - } - *sd2 = sd; - return SZ_OK; -@@ -645,30 +655,30 @@ static SRes ReadUnpackInfo(CSzAr *p, - const Byte *startBufPtr; - Byte external; - -- RINOK(WaitId(sd2, k7zIdFolder)); -+ RINOK(WaitId(sd2, k7zIdFolder)) - -- RINOK(SzReadNumber32(sd2, &numFolders)); -+ RINOK(SzReadNumber32(sd2, &numFolders)) - if (numFolders > numFoldersMax) - return SZ_ERROR_UNSUPPORTED; - p->NumFolders = numFolders; - -- SZ_READ_BYTE_SD(sd2, external); -+ SZ_READ_BYTE_SD(sd2, external) - if (external == 0) - sd = *sd2; - else - { - UInt32 index; -- RINOK(SzReadNumber32(sd2, &index)); -+ RINOK(SzReadNumber32(sd2, &index)) - if (index >= numTempBufs) - return SZ_ERROR_ARCHIVE; - sd.Data = tempBufs[index].data; - sd.Size = tempBufs[index].size; - } - -- MY_ALLOC(size_t, p->FoCodersOffsets, (size_t)numFolders + 1, alloc); -- MY_ALLOC(UInt32, p->FoStartPackStreamIndex, (size_t)numFolders + 1, alloc); -- MY_ALLOC(UInt32, p->FoToCoderUnpackSizes, (size_t)numFolders + 1, alloc); -- MY_ALLOC_ZE(Byte, p->FoToMainUnpackSizeIndex, (size_t)numFolders, alloc); -+ MY_ALLOC(size_t, p->FoCodersOffsets, (size_t)numFolders + 1, alloc) -+ MY_ALLOC(UInt32, p->FoStartPackStreamIndex, (size_t)numFolders + 1, alloc) -+ MY_ALLOC(UInt32, p->FoToCoderUnpackSizes, (size_t)numFolders + 1, alloc) -+ MY_ALLOC_ZE(Byte, p->FoToMainUnpackSizeIndex, (size_t)numFolders, alloc) - - startBufPtr = sd.Data; - -@@ -681,7 +691,7 @@ static SRes ReadUnpackInfo(CSzAr *p, - - p->FoCodersOffsets[fo] = (size_t)(sd.Data - startBufPtr); - -- RINOK(SzReadNumber32(&sd, &numCoders)); -+ RINOK(SzReadNumber32(&sd, &numCoders)) - if (numCoders == 0 || numCoders > k_Scan_NumCoders_MAX) - return SZ_ERROR_UNSUPPORTED; - -@@ -691,7 +701,7 @@ static SRes ReadUnpackInfo(CSzAr *p, - unsigned idSize; - UInt32 coderInStreams; - -- SZ_READ_BYTE_2(mainByte); -+ SZ_READ_BYTE_2(mainByte) - if ((mainByte & 0xC0) != 0) - return SZ_ERROR_UNSUPPORTED; - idSize = (mainByte & 0xF); -@@ -699,15 +709,15 @@ static SRes ReadUnpackInfo(CSzAr *p, - return SZ_ERROR_UNSUPPORTED; - if (idSize > sd.Size) - return SZ_ERROR_ARCHIVE; -- SKIP_DATA2(sd, idSize); -+ SKIP_DATA2(sd, idSize) - - coderInStreams = 1; - - if ((mainByte & 0x10) != 0) - { - UInt32 coderOutStreams; -- RINOK(SzReadNumber32(&sd, &coderInStreams)); -- RINOK(SzReadNumber32(&sd, &coderOutStreams)); -+ RINOK(SzReadNumber32(&sd, &coderInStreams)) -+ RINOK(SzReadNumber32(&sd, &coderOutStreams)) - if (coderInStreams > k_Scan_NumCodersStreams_in_Folder_MAX || coderOutStreams != 1) - return SZ_ERROR_UNSUPPORTED; - } -@@ -717,10 +727,10 @@ static SRes ReadUnpackInfo(CSzAr *p, - if ((mainByte & 0x20) != 0) - { - UInt32 propsSize; -- RINOK(SzReadNumber32(&sd, &propsSize)); -+ RINOK(SzReadNumber32(&sd, &propsSize)) - if (propsSize > sd.Size) - return SZ_ERROR_ARCHIVE; -- SKIP_DATA2(sd, propsSize); -+ SKIP_DATA2(sd, propsSize) - } - } - -@@ -734,7 +744,7 @@ static SRes ReadUnpackInfo(CSzAr *p, - Byte coderUsed[k_Scan_NumCoders_MAX]; - - UInt32 i; -- UInt32 numBonds = numCoders - 1; -+ const UInt32 numBonds = numCoders - 1; - if (numInStreams < numBonds) - return SZ_ERROR_ARCHIVE; - -@@ -750,12 +760,12 @@ static SRes ReadUnpackInfo(CSzAr *p, - { - UInt32 index; - -- RINOK(SzReadNumber32(&sd, &index)); -+ RINOK(SzReadNumber32(&sd, &index)) - if (index >= numInStreams || streamUsed[index]) - return SZ_ERROR_ARCHIVE; - streamUsed[index] = True7z; - -- RINOK(SzReadNumber32(&sd, &index)); -+ RINOK(SzReadNumber32(&sd, &index)) - if (index >= numCoders || coderUsed[index]) - return SZ_ERROR_ARCHIVE; - coderUsed[index] = True7z; -@@ -767,7 +777,7 @@ static SRes ReadUnpackInfo(CSzAr *p, - for (i = 0; i < numPackStreams; i++) - { - UInt32 index; -- RINOK(SzReadNumber32(&sd, &index)); -+ RINOK(SzReadNumber32(&sd, &index)) - if (index >= numInStreams || streamUsed[index]) - return SZ_ERROR_ARCHIVE; - streamUsed[index] = True7z; -@@ -802,7 +812,7 @@ static SRes ReadUnpackInfo(CSzAr *p, - const size_t dataSize = (size_t)(sd.Data - startBufPtr); - p->FoStartPackStreamIndex[fo] = packStreamIndex; - p->FoCodersOffsets[fo] = dataSize; -- MY_ALLOC_ZE_AND_CPY(p->CodersData, dataSize, startBufPtr, alloc); -+ MY_ALLOC_ZE_AND_CPY(p->CodersData, dataSize, startBufPtr, alloc) - } - - if (external != 0) -@@ -812,21 +822,21 @@ static SRes ReadUnpackInfo(CSzAr *p, - sd = *sd2; - } - -- RINOK(WaitId(&sd, k7zIdCodersUnpackSize)); -+ RINOK(WaitId(&sd, k7zIdCodersUnpackSize)) - -- MY_ALLOC_ZE(UInt64, p->CoderUnpackSizes, (size_t)numCodersOutStreams, alloc); -+ MY_ALLOC_ZE(UInt64, p->CoderUnpackSizes, (size_t)numCodersOutStreams, alloc) - { - UInt32 i; - for (i = 0; i < numCodersOutStreams; i++) - { -- RINOK(ReadNumber(&sd, p->CoderUnpackSizes + i)); -+ RINOK(ReadNumber(&sd, p->CoderUnpackSizes + i)) - } - } - - for (;;) - { - UInt64 type; -- RINOK(ReadID(&sd, &type)); -+ RINOK(ReadID(&sd, &type)) - if (type == k7zIdEnd) - { - *sd2 = sd; -@@ -834,10 +844,10 @@ static SRes ReadUnpackInfo(CSzAr *p, - } - if (type == k7zIdCRC) - { -- RINOK(ReadBitUi32s(&sd, numFolders, &p->FolderCRCs, alloc)); -+ RINOK(ReadBitUi32s(&sd, numFolders, &p->FolderCRCs, alloc)) - continue; - } -- RINOK(SkipData(&sd)); -+ RINOK(SkipData(&sd)) - } - } - -@@ -862,13 +872,13 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi) - { - UInt64 type = 0; - UInt32 numSubDigests = 0; -- UInt32 numFolders = p->NumFolders; -+ const UInt32 numFolders = p->NumFolders; - UInt32 numUnpackStreams = numFolders; - UInt32 numUnpackSizesInData = 0; - - for (;;) - { -- RINOK(ReadID(sd, &type)); -+ RINOK(ReadID(sd, &type)) - if (type == k7zIdNumUnpackStream) - { - UInt32 i; -@@ -878,7 +888,7 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi) - for (i = 0; i < numFolders; i++) - { - UInt32 numStreams; -- RINOK(SzReadNumber32(sd, &numStreams)); -+ RINOK(SzReadNumber32(sd, &numStreams)) - if (numUnpackStreams > numUnpackStreams + numStreams) - return SZ_ERROR_UNSUPPORTED; - numUnpackStreams += numStreams; -@@ -892,7 +902,7 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi) - } - if (type == k7zIdCRC || type == k7zIdSize || type == k7zIdEnd) - break; -- RINOK(SkipData(sd)); -+ RINOK(SkipData(sd)) - } - - if (!ssi->sdNumSubStreams.Data) -@@ -908,9 +918,9 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi) - if (type == k7zIdSize) - { - ssi->sdSizes.Data = sd->Data; -- RINOK(SkipNumbers(sd, numUnpackSizesInData)); -+ RINOK(SkipNumbers(sd, numUnpackSizesInData)) - ssi->sdSizes.Size = (size_t)(sd->Data - ssi->sdSizes.Data); -- RINOK(ReadID(sd, &type)); -+ RINOK(ReadID(sd, &type)) - } - - for (;;) -@@ -920,14 +930,14 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi) - if (type == k7zIdCRC) - { - ssi->sdCRCs.Data = sd->Data; -- RINOK(SkipBitUi32s(sd, numSubDigests)); -+ RINOK(SkipBitUi32s(sd, numSubDigests)) - ssi->sdCRCs.Size = (size_t)(sd->Data - ssi->sdCRCs.Data); - } - else - { -- RINOK(SkipData(sd)); -+ RINOK(SkipData(sd)) - } -- RINOK(ReadID(sd, &type)); -+ RINOK(ReadID(sd, &type)) - } - } - -@@ -940,31 +950,31 @@ static SRes SzReadStreamsInfo(CSzAr *p, - { - UInt64 type; - -- SzData_Clear(&ssi->sdSizes); -- SzData_Clear(&ssi->sdCRCs); -- SzData_Clear(&ssi->sdNumSubStreams); -+ SzData_CLEAR(&ssi->sdSizes) -+ SzData_CLEAR(&ssi->sdCRCs) -+ SzData_CLEAR(&ssi->sdNumSubStreams) - - *dataOffset = 0; -- RINOK(ReadID(sd, &type)); -+ RINOK(ReadID(sd, &type)) - if (type == k7zIdPackInfo) - { -- RINOK(ReadNumber(sd, dataOffset)); -+ RINOK(ReadNumber(sd, dataOffset)) - if (*dataOffset > p->RangeLimit) - return SZ_ERROR_ARCHIVE; -- RINOK(ReadPackInfo(p, sd, alloc)); -+ RINOK(ReadPackInfo(p, sd, alloc)) - if (p->PackPositions[p->NumPackStreams] > p->RangeLimit - *dataOffset) - return SZ_ERROR_ARCHIVE; -- RINOK(ReadID(sd, &type)); -+ RINOK(ReadID(sd, &type)) - } - if (type == k7zIdUnpackInfo) - { -- RINOK(ReadUnpackInfo(p, sd, numFoldersMax, tempBufs, numTempBufs, alloc)); -- RINOK(ReadID(sd, &type)); -+ RINOK(ReadUnpackInfo(p, sd, numFoldersMax, tempBufs, numTempBufs, alloc)) -+ RINOK(ReadID(sd, &type)) - } - if (type == k7zIdSubStreamsInfo) - { -- RINOK(ReadSubStreamsInfo(p, sd, ssi)); -- RINOK(ReadID(sd, &type)); -+ RINOK(ReadSubStreamsInfo(p, sd, ssi)) -+ RINOK(ReadID(sd, &type)) - } - else - { -@@ -976,7 +986,7 @@ static SRes SzReadStreamsInfo(CSzAr *p, - } - - static SRes SzReadAndDecodePackedStreams( -- ILookInStream *inStream, -+ ILookInStreamPtr inStream, - CSzData *sd, - CBuf *tempBufs, - UInt32 numFoldersMax, -@@ -988,7 +998,7 @@ static SRes SzReadAndDecodePackedStreams( - UInt32 fo; - CSubStreamInfo ssi; - -- RINOK(SzReadStreamsInfo(p, sd, numFoldersMax, NULL, 0, &dataStartPos, &ssi, allocTemp)); -+ RINOK(SzReadStreamsInfo(p, sd, numFoldersMax, NULL, 0, &dataStartPos, &ssi, allocTemp)) - - dataStartPos += baseOffset; - if (p->NumFolders == 0) -@@ -1000,7 +1010,7 @@ static SRes SzReadAndDecodePackedStreams( - for (fo = 0; fo < p->NumFolders; fo++) - { - CBuf *tempBuf = tempBufs + fo; -- UInt64 unpackSize = SzAr_GetFolderUnpackSize(p, fo); -+ const UInt64 unpackSize = SzAr_GetFolderUnpackSize(p, fo); - if ((size_t)unpackSize != unpackSize) - return SZ_ERROR_MEM; - if (!Buf_Create(tempBuf, (size_t)unpackSize, allocTemp)) -@@ -1010,8 +1020,8 @@ static SRes SzReadAndDecodePackedStreams( - for (fo = 0; fo < p->NumFolders; fo++) - { - const CBuf *tempBuf = tempBufs + fo; -- RINOK(LookInStream_SeekTo(inStream, dataStartPos)); -- RINOK(SzAr_DecodeFolder(p, fo, inStream, dataStartPos, tempBuf->data, tempBuf->size, allocTemp)); -+ RINOK(LookInStream_SeekTo(inStream, dataStartPos)) -+ RINOK(SzAr_DecodeFolder(p, fo, inStream, dataStartPos, tempBuf->data, tempBuf->size, allocTemp)) - } - - return SZ_OK; -@@ -1046,7 +1056,7 @@ static SRes SzReadFileNames(const Byte *data, size_t size, UInt32 numFiles, size - return (pos == size) ? SZ_OK : SZ_ERROR_ARCHIVE; - } - --static MY_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num, -+static Z7_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num, - CSzData *sd2, - const CBuf *tempBufs, UInt32 numTempBufs, - ISzAllocPtr alloc) -@@ -1057,22 +1067,22 @@ static MY_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num, - Byte *defs; - Byte external; - -- RINOK(ReadBitVector(sd2, num, &p->Defs, alloc)); -+ RINOK(ReadBitVector(sd2, num, &p->Defs, alloc)) - -- SZ_READ_BYTE_SD(sd2, external); -+ SZ_READ_BYTE_SD(sd2, external) - if (external == 0) - sd = *sd2; - else - { - UInt32 index; -- RINOK(SzReadNumber32(sd2, &index)); -+ RINOK(SzReadNumber32(sd2, &index)) - if (index >= numTempBufs) - return SZ_ERROR_ARCHIVE; - sd.Data = tempBufs[index].data; - sd.Size = tempBufs[index].size; - } - -- MY_ALLOC_ZE(CNtfsFileTime, p->Vals, num, alloc); -+ MY_ALLOC_ZE(CNtfsFileTime, p->Vals, num, alloc) - vals = p->Vals; - defs = p->Defs; - for (i = 0; i < num; i++) -@@ -1082,7 +1092,7 @@ static MY_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num, - return SZ_ERROR_ARCHIVE; - vals[i].Low = GetUi32(sd.Data); - vals[i].High = GetUi32(sd.Data + 4); -- SKIP_DATA2(sd, 8); -+ SKIP_DATA2(sd, 8) - } - else - vals[i].High = vals[i].Low = 0; -@@ -1100,7 +1110,7 @@ static MY_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num, - static SRes SzReadHeader2( - CSzArEx *p, /* allocMain */ - CSzData *sd, -- ILookInStream *inStream, -+ ILookInStreamPtr inStream, - CBuf *tempBufs, UInt32 *numTempBufs, - ISzAllocPtr allocMain, - ISzAllocPtr allocTemp -@@ -1111,26 +1121,26 @@ static SRes SzReadHeader2( - { - UInt64 type; - -- SzData_Clear(&ssi.sdSizes); -- SzData_Clear(&ssi.sdCRCs); -- SzData_Clear(&ssi.sdNumSubStreams); -+ SzData_CLEAR(&ssi.sdSizes) -+ SzData_CLEAR(&ssi.sdCRCs) -+ SzData_CLEAR(&ssi.sdNumSubStreams) - - ssi.NumSubDigests = 0; - ssi.NumTotalSubStreams = 0; - -- RINOK(ReadID(sd, &type)); -+ RINOK(ReadID(sd, &type)) - - if (type == k7zIdArchiveProperties) - { - for (;;) - { - UInt64 type2; -- RINOK(ReadID(sd, &type2)); -+ RINOK(ReadID(sd, &type2)) - if (type2 == k7zIdEnd) - break; -- RINOK(SkipData(sd)); -+ RINOK(SkipData(sd)) - } -- RINOK(ReadID(sd, &type)); -+ RINOK(ReadID(sd, &type)) - } - - if (type == k7zIdAdditionalStreamsInfo) -@@ -1148,15 +1158,15 @@ static SRes SzReadHeader2( - - if (res != SZ_OK) - return res; -- RINOK(ReadID(sd, &type)); -+ RINOK(ReadID(sd, &type)) - } - - if (type == k7zIdMainStreamsInfo) - { - RINOK(SzReadStreamsInfo(&p->db, sd, (UInt32)1 << 30, tempBufs, *numTempBufs, -- &p->dataPos, &ssi, allocMain)); -+ &p->dataPos, &ssi, allocMain)) - p->dataPos += p->startPosAfterHeader; -- RINOK(ReadID(sd, &type)); -+ RINOK(ReadID(sd, &type)) - } - - if (type == k7zIdEnd) -@@ -1174,23 +1184,23 @@ static SRes SzReadHeader2( - const Byte *emptyStreams = NULL; - const Byte *emptyFiles = NULL; - -- RINOK(SzReadNumber32(sd, &numFiles)); -+ RINOK(SzReadNumber32(sd, &numFiles)) - p->NumFiles = numFiles; - - for (;;) - { - UInt64 type; - UInt64 size; -- RINOK(ReadID(sd, &type)); -+ RINOK(ReadID(sd, &type)) - if (type == k7zIdEnd) - break; -- RINOK(ReadNumber(sd, &size)); -+ RINOK(ReadNumber(sd, &size)) - if (size > sd->Size) - return SZ_ERROR_ARCHIVE; - - if (type >= ((UInt32)1 << 8)) - { -- SKIP_DATA(sd, size); -+ SKIP_DATA(sd, size) - } - else switch ((unsigned)type) - { -@@ -1200,7 +1210,7 @@ static SRes SzReadHeader2( - const Byte *namesData; - Byte external; - -- SZ_READ_BYTE(external); -+ SZ_READ_BYTE(external) - if (external == 0) - { - namesSize = (size_t)size - 1; -@@ -1209,7 +1219,7 @@ static SRes SzReadHeader2( - else - { - UInt32 index; -- RINOK(SzReadNumber32(sd, &index)); -+ RINOK(SzReadNumber32(sd, &index)) - if (index >= *numTempBufs) - return SZ_ERROR_ARCHIVE; - namesData = (tempBufs)[index].data; -@@ -1218,25 +1228,25 @@ static SRes SzReadHeader2( - - if ((namesSize & 1) != 0) - return SZ_ERROR_ARCHIVE; -- MY_ALLOC(size_t, p->FileNameOffsets, numFiles + 1, allocMain); -- MY_ALLOC_ZE_AND_CPY(p->FileNames, namesSize, namesData, allocMain); -+ MY_ALLOC(size_t, p->FileNameOffsets, numFiles + 1, allocMain) -+ MY_ALLOC_ZE_AND_CPY(p->FileNames, namesSize, namesData, allocMain) - RINOK(SzReadFileNames(p->FileNames, namesSize, numFiles, p->FileNameOffsets)) - if (external == 0) - { -- SKIP_DATA(sd, namesSize); -+ SKIP_DATA(sd, namesSize) - } - break; - } - case k7zIdEmptyStream: - { -- RINOK(RememberBitVector(sd, numFiles, &emptyStreams)); -+ RINOK(RememberBitVector(sd, numFiles, &emptyStreams)) - numEmptyStreams = CountDefinedBits(emptyStreams, numFiles); - emptyFiles = NULL; - break; - } - case k7zIdEmptyFile: - { -- RINOK(RememberBitVector(sd, numEmptyStreams, &emptyFiles)); -+ RINOK(RememberBitVector(sd, numEmptyStreams, &emptyFiles)) - break; - } - case k7zIdWinAttrib: -@@ -1245,22 +1255,22 @@ static SRes SzReadHeader2( - CSzData sdSwitch; - CSzData *sdPtr; - SzBitUi32s_Free(&p->Attribs, allocMain); -- RINOK(ReadBitVector(sd, numFiles, &p->Attribs.Defs, allocMain)); -+ RINOK(ReadBitVector(sd, numFiles, &p->Attribs.Defs, allocMain)) - -- SZ_READ_BYTE(external); -+ SZ_READ_BYTE(external) - if (external == 0) - sdPtr = sd; - else - { - UInt32 index; -- RINOK(SzReadNumber32(sd, &index)); -+ RINOK(SzReadNumber32(sd, &index)) - if (index >= *numTempBufs) - return SZ_ERROR_ARCHIVE; - sdSwitch.Data = (tempBufs)[index].data; - sdSwitch.Size = (tempBufs)[index].size; - sdPtr = &sdSwitch; - } -- RINOK(ReadUi32s(sdPtr, numFiles, &p->Attribs, allocMain)); -+ RINOK(ReadUi32s(sdPtr, numFiles, &p->Attribs, allocMain)) - break; - } - /* -@@ -1273,11 +1283,11 @@ static SRes SzReadHeader2( - break; - } - */ -- case k7zIdMTime: RINOK(ReadTime(&p->MTime, numFiles, sd, tempBufs, *numTempBufs, allocMain)); break; -- case k7zIdCTime: RINOK(ReadTime(&p->CTime, numFiles, sd, tempBufs, *numTempBufs, allocMain)); break; -+ case k7zIdMTime: RINOK(ReadTime(&p->MTime, numFiles, sd, tempBufs, *numTempBufs, allocMain)) break; -+ case k7zIdCTime: RINOK(ReadTime(&p->CTime, numFiles, sd, tempBufs, *numTempBufs, allocMain)) break; - default: - { -- SKIP_DATA(sd, size); -+ SKIP_DATA(sd, size) - } - } - } -@@ -1288,10 +1298,10 @@ static SRes SzReadHeader2( - for (;;) - { - UInt64 type; -- RINOK(ReadID(sd, &type)); -+ RINOK(ReadID(sd, &type)) - if (type == k7zIdEnd) - break; -- RINOK(SkipData(sd)); -+ RINOK(SkipData(sd)) - } - - { -@@ -1303,40 +1313,37 @@ static SRes SzReadHeader2( - UInt64 unpackPos = 0; - const Byte *digestsDefs = NULL; - const Byte *digestsVals = NULL; -- UInt32 digestsValsIndex = 0; -- UInt32 digestIndex; -- Byte allDigestsDefined = 0; -+ UInt32 digestIndex = 0; - Byte isDirMask = 0; - Byte crcMask = 0; - Byte mask = 0x80; - -- MY_ALLOC(UInt32, p->FolderToFile, p->db.NumFolders + 1, allocMain); -- MY_ALLOC_ZE(UInt32, p->FileToFolder, p->NumFiles, allocMain); -- MY_ALLOC(UInt64, p->UnpackPositions, p->NumFiles + 1, allocMain); -- MY_ALLOC_ZE(Byte, p->IsDirs, (p->NumFiles + 7) >> 3, allocMain); -+ MY_ALLOC(UInt32, p->FolderToFile, p->db.NumFolders + 1, allocMain) -+ MY_ALLOC_ZE(UInt32, p->FileToFolder, p->NumFiles, allocMain) -+ MY_ALLOC(UInt64, p->UnpackPositions, p->NumFiles + 1, allocMain) -+ MY_ALLOC_ZE(Byte, p->IsDirs, (p->NumFiles + 7) >> 3, allocMain) - -- RINOK(SzBitUi32s_Alloc(&p->CRCs, p->NumFiles, allocMain)); -+ RINOK(SzBitUi32s_Alloc(&p->CRCs, p->NumFiles, allocMain)) - - if (ssi.sdCRCs.Size != 0) - { -- SZ_READ_BYTE_SD(&ssi.sdCRCs, allDigestsDefined); -+ Byte allDigestsDefined = 0; -+ SZ_READ_BYTE_SD_NOCHECK(&ssi.sdCRCs, allDigestsDefined) - if (allDigestsDefined) - digestsVals = ssi.sdCRCs.Data; - else - { -- size_t numBytes = (ssi.NumSubDigests + 7) >> 3; -+ const size_t numBytes = (ssi.NumSubDigests + 7) >> 3; - digestsDefs = ssi.sdCRCs.Data; - digestsVals = digestsDefs + numBytes; - } - } - -- digestIndex = 0; -- - for (i = 0; i < numFiles; i++, mask >>= 1) - { - if (mask == 0) - { -- UInt32 byteIndex = (i - 1) >> 3; -+ const UInt32 byteIndex = (i - 1) >> 3; - p->IsDirs[byteIndex] = isDirMask; - p->CRCs.Defs[byteIndex] = crcMask; - isDirMask = 0; -@@ -1374,18 +1381,17 @@ static SRes SzReadHeader2( - numSubStreams = 1; - if (ssi.sdNumSubStreams.Data) - { -- RINOK(SzReadNumber32(&ssi.sdNumSubStreams, &numSubStreams)); -+ RINOK(SzReadNumber32(&ssi.sdNumSubStreams, &numSubStreams)) - } - remSubStreams = numSubStreams; - if (numSubStreams != 0) - break; - { -- UInt64 folderUnpackSize = SzAr_GetFolderUnpackSize(&p->db, folderIndex); -+ const UInt64 folderUnpackSize = SzAr_GetFolderUnpackSize(&p->db, folderIndex); - unpackPos += folderUnpackSize; - if (unpackPos < folderUnpackSize) - return SZ_ERROR_ARCHIVE; - } -- - folderIndex++; - } - } -@@ -1397,47 +1403,44 @@ static SRes SzReadHeader2( - - if (--remSubStreams == 0) - { -- UInt64 folderUnpackSize = SzAr_GetFolderUnpackSize(&p->db, folderIndex); -- UInt64 startFolderUnpackPos = p->UnpackPositions[p->FolderToFile[folderIndex]]; -+ const UInt64 folderUnpackSize = SzAr_GetFolderUnpackSize(&p->db, folderIndex); -+ const UInt64 startFolderUnpackPos = p->UnpackPositions[p->FolderToFile[folderIndex]]; - if (folderUnpackSize < unpackPos - startFolderUnpackPos) - return SZ_ERROR_ARCHIVE; - unpackPos = startFolderUnpackPos + folderUnpackSize; - if (unpackPos < folderUnpackSize) - return SZ_ERROR_ARCHIVE; - -- if (numSubStreams == 1 && SzBitWithVals_Check(&p->db.FolderCRCs, i)) -+ if (numSubStreams == 1 && SzBitWithVals_Check(&p->db.FolderCRCs, folderIndex)) - { - p->CRCs.Vals[i] = p->db.FolderCRCs.Vals[folderIndex]; - crcMask |= mask; - } -- else if (allDigestsDefined || (digestsDefs && SzBitArray_Check(digestsDefs, digestIndex))) -- { -- p->CRCs.Vals[i] = GetUi32(digestsVals + (size_t)digestsValsIndex * 4); -- digestsValsIndex++; -- crcMask |= mask; -- } -- - folderIndex++; - } - else - { - UInt64 v; -- RINOK(ReadNumber(&ssi.sdSizes, &v)); -+ RINOK(ReadNumber(&ssi.sdSizes, &v)) - unpackPos += v; - if (unpackPos < v) - return SZ_ERROR_ARCHIVE; -- if (allDigestsDefined || (digestsDefs && SzBitArray_Check(digestsDefs, digestIndex))) -+ } -+ if ((crcMask & mask) == 0 && digestsVals) -+ { -+ if (!digestsDefs || SzBitArray_Check(digestsDefs, digestIndex)) - { -- p->CRCs.Vals[i] = GetUi32(digestsVals + (size_t)digestsValsIndex * 4); -- digestsValsIndex++; -+ p->CRCs.Vals[i] = GetUi32(digestsVals); -+ digestsVals += 4; - crcMask |= mask; - } -+ digestIndex++; - } - } - - if (mask != 0x80) - { -- UInt32 byteIndex = (i - 1) >> 3; -+ const UInt32 byteIndex = (i - 1) >> 3; - p->IsDirs[byteIndex] = isDirMask; - p->CRCs.Defs[byteIndex] = crcMask; - } -@@ -1454,7 +1457,7 @@ static SRes SzReadHeader2( - break; - if (!ssi.sdNumSubStreams.Data) - return SZ_ERROR_ARCHIVE; -- RINOK(SzReadNumber32(&ssi.sdNumSubStreams, &numSubStreams)); -+ RINOK(SzReadNumber32(&ssi.sdNumSubStreams, &numSubStreams)) - if (numSubStreams != 0) - return SZ_ERROR_ARCHIVE; - /* -@@ -1479,7 +1482,7 @@ static SRes SzReadHeader2( - static SRes SzReadHeader( - CSzArEx *p, - CSzData *sd, -- ILookInStream *inStream, -+ ILookInStreamPtr inStream, - ISzAllocPtr allocMain, - ISzAllocPtr allocTemp) - { -@@ -1498,7 +1501,7 @@ static SRes SzReadHeader( - for (i = 0; i < NUM_ADDITIONAL_STREAMS_MAX; i++) - Buf_Free(tempBufs + i, allocTemp); - -- RINOK(res); -+ RINOK(res) - - if (sd->Size != 0) - return SZ_ERROR_FAIL; -@@ -1508,7 +1511,7 @@ static SRes SzReadHeader( - - static SRes SzArEx_Open2( - CSzArEx *p, -- ILookInStream *inStream, -+ ILookInStreamPtr inStream, - ISzAllocPtr allocMain, - ISzAllocPtr allocTemp) - { -@@ -1521,9 +1524,9 @@ static SRes SzArEx_Open2( - SRes res; - - startArcPos = 0; -- RINOK(ILookInStream_Seek(inStream, &startArcPos, SZ_SEEK_CUR)); -+ RINOK(ILookInStream_Seek(inStream, &startArcPos, SZ_SEEK_CUR)) - -- RINOK(LookInStream_Read2(inStream, header, k7zStartHeaderSize, SZ_ERROR_NO_ARCHIVE)); -+ RINOK(LookInStream_Read2(inStream, header, k7zStartHeaderSize, SZ_ERROR_NO_ARCHIVE)) - - if (!TestSignatureCandidate(header)) - return SZ_ERROR_NO_ARCHIVE; -@@ -1552,14 +1555,14 @@ static SRes SzArEx_Open2( - - { - Int64 pos = 0; -- RINOK(ILookInStream_Seek(inStream, &pos, SZ_SEEK_END)); -+ RINOK(ILookInStream_Seek(inStream, &pos, SZ_SEEK_END)) - if ((UInt64)pos < (UInt64)startArcPos + nextHeaderOffset || - (UInt64)pos < (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset || - (UInt64)pos < (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset + nextHeaderSize) - return SZ_ERROR_INPUT_EOF; - } - -- RINOK(LookInStream_SeekTo(inStream, (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset)); -+ RINOK(LookInStream_SeekTo(inStream, (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset)) - - if (!Buf_Create(&buf, nextHeaderSizeT, allocTemp)) - return SZ_ERROR_MEM; -@@ -1634,10 +1637,10 @@ static SRes SzArEx_Open2( - } - - --SRes SzArEx_Open(CSzArEx *p, ILookInStream *inStream, -+SRes SzArEx_Open(CSzArEx *p, ILookInStreamPtr inStream, - ISzAllocPtr allocMain, ISzAllocPtr allocTemp) - { -- SRes res = SzArEx_Open2(p, inStream, allocMain, allocTemp); -+ const SRes res = SzArEx_Open2(p, inStream, allocMain, allocTemp); - if (res != SZ_OK) - SzArEx_Free(p, allocMain); - return res; -@@ -1646,7 +1649,7 @@ SRes SzArEx_Open(CSzArEx *p, ILookInStream *inStream, - - SRes SzArEx_Extract( - const CSzArEx *p, -- ILookInStream *inStream, -+ ILookInStreamPtr inStream, - UInt32 fileIndex, - UInt32 *blockIndex, - Byte **tempBuf, -@@ -1656,7 +1659,7 @@ SRes SzArEx_Extract( - ISzAllocPtr allocMain, - ISzAllocPtr allocTemp) - { -- UInt32 folderIndex = p->FileToFolder[fileIndex]; -+ const UInt32 folderIndex = p->FileToFolder[fileIndex]; - SRes res = SZ_OK; - - *offset = 0; -@@ -1673,13 +1676,13 @@ SRes SzArEx_Extract( - - if (*tempBuf == NULL || *blockIndex != folderIndex) - { -- UInt64 unpackSizeSpec = SzAr_GetFolderUnpackSize(&p->db, folderIndex); -+ const UInt64 unpackSizeSpec = SzAr_GetFolderUnpackSize(&p->db, folderIndex); - /* - UInt64 unpackSizeSpec = - p->UnpackPositions[p->FolderToFile[(size_t)folderIndex + 1]] - - p->UnpackPositions[p->FolderToFile[folderIndex]]; - */ -- size_t unpackSize = (size_t)unpackSizeSpec; -+ const size_t unpackSize = (size_t)unpackSizeSpec; - - if (unpackSize != unpackSizeSpec) - return SZ_ERROR_MEM; -@@ -1707,7 +1710,7 @@ SRes SzArEx_Extract( - - if (res == SZ_OK) - { -- UInt64 unpackPos = p->UnpackPositions[fileIndex]; -+ const UInt64 unpackPos = p->UnpackPositions[fileIndex]; - *offset = (size_t)(unpackPos - p->UnpackPositions[p->FolderToFile[folderIndex]]); - *outSizeProcessed = (size_t)(p->UnpackPositions[(size_t)fileIndex + 1] - unpackPos); - if (*offset + *outSizeProcessed > *outBufferSize) -@@ -1723,8 +1726,8 @@ SRes SzArEx_Extract( - - size_t SzArEx_GetFileNameUtf16(const CSzArEx *p, size_t fileIndex, UInt16 *dest) - { -- size_t offs = p->FileNameOffsets[fileIndex]; -- size_t len = p->FileNameOffsets[fileIndex + 1] - offs; -+ const size_t offs = p->FileNameOffsets[fileIndex]; -+ const size_t len = p->FileNameOffsets[fileIndex + 1] - offs; - if (dest != 0) - { - size_t i; -diff --git a/src/lzma/7zBuf.h b/src/lzma/7zBuf.h -index 81d1b5b64..c0ba8a7b6 100644 ---- a/src/lzma/7zBuf.h -+++ b/src/lzma/7zBuf.h -@@ -1,8 +1,8 @@ - /* 7zBuf.h -- Byte Buffer --2017-04-03 : Igor Pavlov : Public domain */ -+2023-03-04 : Igor Pavlov : Public domain */ - --#ifndef __7Z_BUF_H --#define __7Z_BUF_H -+#ifndef ZIP7_INC_7Z_BUF_H -+#define ZIP7_INC_7Z_BUF_H - - #include "7zTypes.h" - -diff --git a/src/lzma/7zCrc.c b/src/lzma/7zCrc.c -index f186324dd..c995a8be4 100644 ---- a/src/lzma/7zCrc.c -+++ b/src/lzma/7zCrc.c -@@ -1,5 +1,5 @@ --/* 7zCrc.c -- CRC32 init --2021-04-01 : Igor Pavlov : Public domain */ -+/* 7zCrc.c -- CRC32 calculation and init -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -13,22 +13,20 @@ - #else - #define CRC_NUM_TABLES 9 - -- #define CRC_UINT32_SWAP(v) ((v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | (v << 24)) -- -- UInt32 MY_FAST_CALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table); -- UInt32 MY_FAST_CALL CrcUpdateT1_BeT8(UInt32 v, const void *data, size_t size, const UInt32 *table); -+ UInt32 Z7_FASTCALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table); -+ UInt32 Z7_FASTCALL CrcUpdateT1_BeT8(UInt32 v, const void *data, size_t size, const UInt32 *table); - #endif - - #ifndef MY_CPU_BE -- UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table); -- UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table); -+ UInt32 Z7_FASTCALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table); -+ UInt32 Z7_FASTCALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table); - #endif - --typedef UInt32 (MY_FAST_CALL *CRC_FUNC)(UInt32 v, const void *data, size_t size, const UInt32 *table); -- -+/* - extern - CRC_FUNC g_CrcUpdateT4; - CRC_FUNC g_CrcUpdateT4; -+*/ - extern - CRC_FUNC g_CrcUpdateT8; - CRC_FUNC g_CrcUpdateT8; -@@ -44,20 +42,22 @@ CRC_FUNC g_CrcUpdate; - - UInt32 g_CrcTable[256 * CRC_NUM_TABLES]; - --UInt32 MY_FAST_CALL CrcUpdate(UInt32 v, const void *data, size_t size) -+UInt32 Z7_FASTCALL CrcUpdate(UInt32 v, const void *data, size_t size) - { - return g_CrcUpdate(v, data, size, g_CrcTable); - } - --UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size) -+UInt32 Z7_FASTCALL CrcCalc(const void *data, size_t size) - { - return g_CrcUpdate(CRC_INIT_VAL, data, size, g_CrcTable) ^ CRC_INIT_VAL; - } - -+#if CRC_NUM_TABLES < 4 \ -+ || (CRC_NUM_TABLES == 4 && defined(MY_CPU_BE)) \ -+ || (!defined(MY_CPU_LE) && !defined(MY_CPU_BE)) - #define CRC_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) -- --UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table); --UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table) -+UInt32 Z7_FASTCALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table); -+UInt32 Z7_FASTCALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table) - { - const Byte *p = (const Byte *)data; - const Byte *pEnd = p + size; -@@ -65,7 +65,7 @@ UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const U - v = CRC_UPDATE_BYTE_2(v, *p); - return v; - } -- -+#endif - - /* ---------- hardware CRC ---------- */ - -@@ -78,16 +78,29 @@ UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const U - #if defined(_MSC_VER) - #if defined(MY_CPU_ARM64) - #if (_MSC_VER >= 1910) -+ #ifndef __clang__ - #define USE_ARM64_CRC -+ #include -+ #endif - #endif - #endif - #elif (defined(__clang__) && (__clang_major__ >= 3)) \ - || (defined(__GNUC__) && (__GNUC__ > 4)) - #if !defined(__ARM_FEATURE_CRC32) - #define __ARM_FEATURE_CRC32 1 -- #if (!defined(__clang__) || (__clang_major__ > 3)) // fix these numbers -+ #if defined(__clang__) -+ #if defined(MY_CPU_ARM64) -+ #define ATTRIB_CRC __attribute__((__target__("crc"))) -+ #else -+ #define ATTRIB_CRC __attribute__((__target__("armv8-a,crc"))) -+ #endif -+ #else -+ #if defined(MY_CPU_ARM64) -+ #define ATTRIB_CRC __attribute__((__target__("+crc"))) -+ #else - #define ATTRIB_CRC __attribute__((__target__("arch=armv8-a+crc"))) - #endif -+ #endif - #endif - #if defined(__ARM_FEATURE_CRC32) - #define USE_ARM64_CRC -@@ -105,7 +118,7 @@ UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const U - - #pragma message("ARM64 CRC emulation") - --MY_FORCE_INLINE -+Z7_FORCE_INLINE - UInt32 __crc32b(UInt32 v, UInt32 data) - { - const UInt32 *table = g_CrcTable; -@@ -113,7 +126,7 @@ UInt32 __crc32b(UInt32 v, UInt32 data) - return v; - } - --MY_FORCE_INLINE -+Z7_FORCE_INLINE - UInt32 __crc32w(UInt32 v, UInt32 data) - { - const UInt32 *table = g_CrcTable; -@@ -124,7 +137,7 @@ UInt32 __crc32w(UInt32 v, UInt32 data) - return v; - } - --MY_FORCE_INLINE -+Z7_FORCE_INLINE - UInt32 __crc32d(UInt32 v, UInt64 data) - { - const UInt32 *table = g_CrcTable; -@@ -156,9 +169,9 @@ UInt32 __crc32d(UInt32 v, UInt64 data) - // #pragma message("USE ARM HW CRC") - - ATTRIB_CRC --UInt32 MY_FAST_CALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, const UInt32 *table); -+UInt32 Z7_FASTCALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, const UInt32 *table); - ATTRIB_CRC --UInt32 MY_FAST_CALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, const UInt32 *table) -+UInt32 Z7_FASTCALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, const UInt32 *table) - { - const Byte *p = (const Byte *)data; - UNUSED_VAR(table); -@@ -188,9 +201,9 @@ UInt32 MY_FAST_CALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, cons - } - - ATTRIB_CRC --UInt32 MY_FAST_CALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, const UInt32 *table); -+UInt32 Z7_FASTCALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, const UInt32 *table); - ATTRIB_CRC --UInt32 MY_FAST_CALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, const UInt32 *table) -+UInt32 Z7_FASTCALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, const UInt32 *table) - { - const Byte *p = (const Byte *)data; - UNUSED_VAR(table); -@@ -219,6 +232,9 @@ UInt32 MY_FAST_CALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, cons - return v; - } - -+#undef T0_32_UNROLL_BYTES -+#undef T0_64_UNROLL_BYTES -+ - #endif // defined(USE_ARM64_CRC) || defined(USE_CRC_EMU) - - #endif // MY_CPU_LE -@@ -226,7 +242,7 @@ UInt32 MY_FAST_CALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, cons - - - --void MY_FAST_CALL CrcGenerateTable() -+void Z7_FASTCALL CrcGenerateTable(void) - { - UInt32 i; - for (i = 0; i < 256; i++) -@@ -239,64 +255,62 @@ void MY_FAST_CALL CrcGenerateTable() - } - for (i = 256; i < 256 * CRC_NUM_TABLES; i++) - { -- UInt32 r = g_CrcTable[(size_t)i - 256]; -+ const UInt32 r = g_CrcTable[(size_t)i - 256]; - g_CrcTable[i] = g_CrcTable[r & 0xFF] ^ (r >> 8); - } - - #if CRC_NUM_TABLES < 4 -- -- g_CrcUpdate = CrcUpdateT1; -- -- #else -- -- #ifdef MY_CPU_LE -- -- g_CrcUpdateT4 = CrcUpdateT4; -- g_CrcUpdate = CrcUpdateT4; -- -- #if CRC_NUM_TABLES >= 8 -+ g_CrcUpdate = CrcUpdateT1; -+ #elif defined(MY_CPU_LE) -+ // g_CrcUpdateT4 = CrcUpdateT4; -+ #if CRC_NUM_TABLES < 8 -+ g_CrcUpdate = CrcUpdateT4; -+ #else // CRC_NUM_TABLES >= 8 - g_CrcUpdateT8 = CrcUpdateT8; -- -+ /* - #ifdef MY_CPU_X86_OR_AMD64 - if (!CPU_Is_InOrder()) - #endif -- g_CrcUpdate = CrcUpdateT8; -+ */ -+ g_CrcUpdate = CrcUpdateT8; - #endif -- - #else - { -- #ifndef MY_CPU_BE -+ #ifndef MY_CPU_BE - UInt32 k = 0x01020304; - const Byte *p = (const Byte *)&k; - if (p[0] == 4 && p[1] == 3) - { -- g_CrcUpdateT4 = CrcUpdateT4; -- g_CrcUpdate = CrcUpdateT4; -- #if CRC_NUM_TABLES >= 8 -- g_CrcUpdateT8 = CrcUpdateT8; -- g_CrcUpdate = CrcUpdateT8; -+ #if CRC_NUM_TABLES < 8 -+ // g_CrcUpdateT4 = CrcUpdateT4; -+ g_CrcUpdate = CrcUpdateT4; -+ #else // CRC_NUM_TABLES >= 8 -+ g_CrcUpdateT8 = CrcUpdateT8; -+ g_CrcUpdate = CrcUpdateT8; - #endif - } - else if (p[0] != 1 || p[1] != 2) - g_CrcUpdate = CrcUpdateT1; - else -- #endif -+ #endif // MY_CPU_BE - { - for (i = 256 * CRC_NUM_TABLES - 1; i >= 256; i--) - { -- UInt32 x = g_CrcTable[(size_t)i - 256]; -- g_CrcTable[i] = CRC_UINT32_SWAP(x); -+ const UInt32 x = g_CrcTable[(size_t)i - 256]; -+ g_CrcTable[i] = Z7_BSWAP32(x); - } -- g_CrcUpdateT4 = CrcUpdateT1_BeT4; -- g_CrcUpdate = CrcUpdateT1_BeT4; -- #if CRC_NUM_TABLES >= 8 -- g_CrcUpdateT8 = CrcUpdateT1_BeT8; -- g_CrcUpdate = CrcUpdateT1_BeT8; -+ #if CRC_NUM_TABLES <= 4 -+ g_CrcUpdate = CrcUpdateT1; -+ #elif CRC_NUM_TABLES <= 8 -+ // g_CrcUpdateT4 = CrcUpdateT1_BeT4; -+ g_CrcUpdate = CrcUpdateT1_BeT4; -+ #else // CRC_NUM_TABLES > 8 -+ g_CrcUpdateT8 = CrcUpdateT1_BeT8; -+ g_CrcUpdate = CrcUpdateT1_BeT8; - #endif - } - } -- #endif -- #endif -+ #endif // CRC_NUM_TABLES < 4 - - #ifdef MY_CPU_LE - #ifdef USE_ARM64_CRC -@@ -320,3 +334,7 @@ void MY_FAST_CALL CrcGenerateTable() - #endif - #endif - } -+ -+#undef kCrcPoly -+#undef CRC64_NUM_TABLES -+#undef CRC_UPDATE_BYTE_2 -diff --git a/src/lzma/7zCrc.h b/src/lzma/7zCrc.h -index 8fd579587..4afaeae4a 100644 ---- a/src/lzma/7zCrc.h -+++ b/src/lzma/7zCrc.h -@@ -1,8 +1,8 @@ - /* 7zCrc.h -- CRC32 calculation --2013-01-18 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - --#ifndef __7Z_CRC_H --#define __7Z_CRC_H -+#ifndef ZIP7_INC_7Z_CRC_H -+#define ZIP7_INC_7Z_CRC_H - - #include "7zTypes.h" - -@@ -11,14 +11,16 @@ EXTERN_C_BEGIN - extern UInt32 g_CrcTable[]; - - /* Call CrcGenerateTable one time before other CRC functions */ --void MY_FAST_CALL CrcGenerateTable(void); -+void Z7_FASTCALL CrcGenerateTable(void); - - #define CRC_INIT_VAL 0xFFFFFFFF - #define CRC_GET_DIGEST(crc) ((crc) ^ CRC_INIT_VAL) - #define CRC_UPDATE_BYTE(crc, b) (g_CrcTable[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) - --UInt32 MY_FAST_CALL CrcUpdate(UInt32 crc, const void *data, size_t size); --UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size); -+UInt32 Z7_FASTCALL CrcUpdate(UInt32 crc, const void *data, size_t size); -+UInt32 Z7_FASTCALL CrcCalc(const void *data, size_t size); -+ -+typedef UInt32 (Z7_FASTCALL *CRC_FUNC)(UInt32 v, const void *data, size_t size, const UInt32 *table); - - EXTERN_C_END - -diff --git a/src/lzma/7zCrcOpt.c b/src/lzma/7zCrcOpt.c -index 69fad9ca2..9c649290d 100644 ---- a/src/lzma/7zCrcOpt.c -+++ b/src/lzma/7zCrcOpt.c -@@ -1,5 +1,5 @@ - /* 7zCrcOpt.c -- CRC32 calculation --2021-02-09 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -9,8 +9,8 @@ - - #define CRC_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) - --UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table); --UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table) -+UInt32 Z7_FASTCALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table); -+UInt32 Z7_FASTCALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table) - { - const Byte *p = (const Byte *)data; - for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++) -@@ -29,8 +29,8 @@ UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const U - return v; - } - --UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table); --UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table) -+UInt32 Z7_FASTCALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table); -+UInt32 Z7_FASTCALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table) - { - const Byte *p = (const Byte *)data; - for (; size > 0 && ((unsigned)(ptrdiff_t)p & 7) != 0; size--, p++) -@@ -61,11 +61,11 @@ UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const U - - #ifndef MY_CPU_LE - --#define CRC_UINT32_SWAP(v) ((v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | (v << 24)) -+#define CRC_UINT32_SWAP(v) Z7_BSWAP32(v) - - #define CRC_UPDATE_BYTE_2_BE(crc, b) (table[(((crc) >> 24) ^ (b))] ^ ((crc) << 8)) - --UInt32 MY_FAST_CALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table) -+UInt32 Z7_FASTCALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table) - { - const Byte *p = (const Byte *)data; - table += 0x100; -@@ -86,7 +86,7 @@ UInt32 MY_FAST_CALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, co - return CRC_UINT32_SWAP(v); - } - --UInt32 MY_FAST_CALL CrcUpdateT1_BeT8(UInt32 v, const void *data, size_t size, const UInt32 *table) -+UInt32 Z7_FASTCALL CrcUpdateT1_BeT8(UInt32 v, const void *data, size_t size, const UInt32 *table) - { - const Byte *p = (const Byte *)data; - table += 0x100; -diff --git a/src/lzma/7zDec.c b/src/lzma/7zDec.c -index 94b676f89..380391c59 100644 ---- a/src/lzma/7zDec.c -+++ b/src/lzma/7zDec.c -@@ -1,11 +1,11 @@ - /* 7zDec.c -- Decoding from 7z folder --2021-02-09 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - - #include - --/* #define _7ZIP_PPMD_SUPPPORT */ -+/* #define Z7_PPMD_SUPPORT */ - - #include "7z.h" - #include "7zCrc.h" -@@ -16,27 +16,49 @@ - #include "Delta.h" - #include "LzmaDec.h" - #include "Lzma2Dec.h" --#ifdef _7ZIP_PPMD_SUPPPORT -+#ifdef Z7_PPMD_SUPPORT - #include "Ppmd7.h" - #endif - - #define k_Copy 0 --#ifndef _7Z_NO_METHOD_LZMA2 -+#ifndef Z7_NO_METHOD_LZMA2 - #define k_LZMA2 0x21 - #endif - #define k_LZMA 0x30101 - #define k_BCJ2 0x303011B --#ifndef _7Z_NO_METHODS_FILTERS -+ -+#if !defined(Z7_NO_METHODS_FILTERS) -+#define Z7_USE_BRANCH_FILTER -+#endif -+ -+#if !defined(Z7_NO_METHODS_FILTERS) || \ -+ defined(Z7_USE_NATIVE_BRANCH_FILTER) && defined(MY_CPU_ARM64) -+#define Z7_USE_FILTER_ARM64 -+#ifndef Z7_USE_BRANCH_FILTER -+#define Z7_USE_BRANCH_FILTER -+#endif -+#define k_ARM64 0xa -+#endif -+ -+#if !defined(Z7_NO_METHODS_FILTERS) || \ -+ defined(Z7_USE_NATIVE_BRANCH_FILTER) && defined(MY_CPU_ARMT) -+#define Z7_USE_FILTER_ARMT -+#ifndef Z7_USE_BRANCH_FILTER -+#define Z7_USE_BRANCH_FILTER -+#endif -+#define k_ARMT 0x3030701 -+#endif -+ -+#ifndef Z7_NO_METHODS_FILTERS - #define k_Delta 3 - #define k_BCJ 0x3030103 - #define k_PPC 0x3030205 - #define k_IA64 0x3030401 - #define k_ARM 0x3030501 --#define k_ARMT 0x3030701 - #define k_SPARC 0x3030805 - #endif - --#ifdef _7ZIP_PPMD_SUPPPORT -+#ifdef Z7_PPMD_SUPPORT - - #define k_PPMD 0x30401 - -@@ -49,12 +71,12 @@ typedef struct - UInt64 processed; - BoolInt extra; - SRes res; -- const ILookInStream *inStream; -+ ILookInStreamPtr inStream; - } CByteInToLook; - --static Byte ReadByte(const IByteIn *pp) -+static Byte ReadByte(IByteInPtr pp) - { -- CByteInToLook *p = CONTAINER_FROM_VTBL(pp, CByteInToLook, vt); -+ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CByteInToLook) - if (p->cur != p->end) - return *p->cur++; - if (p->res == SZ_OK) -@@ -67,13 +89,13 @@ static Byte ReadByte(const IByteIn *pp) - p->cur = p->begin; - p->end = p->begin + size; - if (size != 0) -- return *p->cur++;; -+ return *p->cur++; - } - p->extra = True7z; - return 0; - } - --static SRes SzDecodePpmd(const Byte *props, unsigned propsSize, UInt64 inSize, const ILookInStream *inStream, -+static SRes SzDecodePpmd(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStreamPtr inStream, - Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain) - { - CPpmd7 ppmd; -@@ -138,14 +160,14 @@ static SRes SzDecodePpmd(const Byte *props, unsigned propsSize, UInt64 inSize, c - #endif - - --static SRes SzDecodeLzma(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStream *inStream, -+static SRes SzDecodeLzma(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStreamPtr inStream, - Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain) - { - CLzmaDec state; - SRes res = SZ_OK; - -- LzmaDec_Construct(&state); -- RINOK(LzmaDec_AllocateProbs(&state, props, propsSize, allocMain)); -+ LzmaDec_CONSTRUCT(&state) -+ RINOK(LzmaDec_AllocateProbs(&state, props, propsSize, allocMain)) - state.dic = outBuffer; - state.dicBufSize = outSize; - LzmaDec_Init(&state); -@@ -196,18 +218,18 @@ static SRes SzDecodeLzma(const Byte *props, unsigned propsSize, UInt64 inSize, I - } - - --#ifndef _7Z_NO_METHOD_LZMA2 -+#ifndef Z7_NO_METHOD_LZMA2 - --static SRes SzDecodeLzma2(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStream *inStream, -+static SRes SzDecodeLzma2(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStreamPtr inStream, - Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain) - { - CLzma2Dec state; - SRes res = SZ_OK; - -- Lzma2Dec_Construct(&state); -+ Lzma2Dec_CONSTRUCT(&state) - if (propsSize != 1) - return SZ_ERROR_DATA; -- RINOK(Lzma2Dec_AllocateProbs(&state, props[0], allocMain)); -+ RINOK(Lzma2Dec_AllocateProbs(&state, props[0], allocMain)) - state.decoder.dic = outBuffer; - state.decoder.dicBufSize = outSize; - Lzma2Dec_Init(&state); -@@ -257,7 +279,7 @@ static SRes SzDecodeLzma2(const Byte *props, unsigned propsSize, UInt64 inSize, - #endif - - --static SRes SzDecodeCopy(UInt64 inSize, ILookInStream *inStream, Byte *outBuffer) -+static SRes SzDecodeCopy(UInt64 inSize, ILookInStreamPtr inStream, Byte *outBuffer) - { - while (inSize > 0) - { -@@ -265,13 +287,13 @@ static SRes SzDecodeCopy(UInt64 inSize, ILookInStream *inStream, Byte *outBuffer - size_t curSize = (1 << 18); - if (curSize > inSize) - curSize = (size_t)inSize; -- RINOK(ILookInStream_Look(inStream, &inBuf, &curSize)); -+ RINOK(ILookInStream_Look(inStream, &inBuf, &curSize)) - if (curSize == 0) - return SZ_ERROR_INPUT_EOF; - memcpy(outBuffer, inBuf, curSize); - outBuffer += curSize; - inSize -= curSize; -- RINOK(ILookInStream_Skip(inStream, curSize)); -+ RINOK(ILookInStream_Skip(inStream, curSize)) - } - return SZ_OK; - } -@@ -282,12 +304,12 @@ static BoolInt IS_MAIN_METHOD(UInt32 m) - { - case k_Copy: - case k_LZMA: -- #ifndef _7Z_NO_METHOD_LZMA2 -+ #ifndef Z7_NO_METHOD_LZMA2 - case k_LZMA2: -- #endif -- #ifdef _7ZIP_PPMD_SUPPPORT -+ #endif -+ #ifdef Z7_PPMD_SUPPORT - case k_PPMD: -- #endif -+ #endif - return True7z; - } - return False7z; -@@ -317,7 +339,7 @@ static SRes CheckSupportedFolder(const CSzFolder *f) - } - - -- #ifndef _7Z_NO_METHODS_FILTERS -+ #if defined(Z7_USE_BRANCH_FILTER) - - if (f->NumCoders == 2) - { -@@ -333,13 +355,20 @@ static SRes CheckSupportedFolder(const CSzFolder *f) - return SZ_ERROR_UNSUPPORTED; - switch ((UInt32)c->MethodID) - { -+ #if !defined(Z7_NO_METHODS_FILTERS) - case k_Delta: - case k_BCJ: - case k_PPC: - case k_IA64: - case k_SPARC: - case k_ARM: -+ #endif -+ #ifdef Z7_USE_FILTER_ARM64 -+ case k_ARM64: -+ #endif -+ #ifdef Z7_USE_FILTER_ARMT - case k_ARMT: -+ #endif - break; - default: - return SZ_ERROR_UNSUPPORTED; -@@ -372,15 +401,16 @@ static SRes CheckSupportedFolder(const CSzFolder *f) - return SZ_ERROR_UNSUPPORTED; - } - --#ifndef _7Z_NO_METHODS_FILTERS --#define CASE_BRA_CONV(isa) case k_ ## isa: isa ## _Convert(outBuffer, outSize, 0, 0); break; --#endif -+ -+ -+ -+ - - static SRes SzFolder_Decode2(const CSzFolder *folder, - const Byte *propsData, - const UInt64 *unpackSizes, - const UInt64 *packPositions, -- ILookInStream *inStream, UInt64 startPos, -+ ILookInStreamPtr inStream, UInt64 startPos, - Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain, - Byte *tempBuf[]) - { -@@ -389,7 +419,7 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, - SizeT tempSize3 = 0; - Byte *tempBuf3 = 0; - -- RINOK(CheckSupportedFolder(folder)); -+ RINOK(CheckSupportedFolder(folder)) - - for (ci = 0; ci < folder->NumCoders; ci++) - { -@@ -404,8 +434,8 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, - SizeT outSizeCur = outSize; - if (folder->NumCoders == 4) - { -- UInt32 indices[] = { 3, 2, 0 }; -- UInt64 unpackSize = unpackSizes[ci]; -+ const UInt32 indices[] = { 3, 2, 0 }; -+ const UInt64 unpackSize = unpackSizes[ci]; - si = indices[ci]; - if (ci < 2) - { -@@ -431,37 +461,37 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, - } - offset = packPositions[si]; - inSize = packPositions[(size_t)si + 1] - offset; -- RINOK(LookInStream_SeekTo(inStream, startPos + offset)); -+ RINOK(LookInStream_SeekTo(inStream, startPos + offset)) - - if (coder->MethodID == k_Copy) - { - if (inSize != outSizeCur) /* check it */ - return SZ_ERROR_DATA; -- RINOK(SzDecodeCopy(inSize, inStream, outBufCur)); -+ RINOK(SzDecodeCopy(inSize, inStream, outBufCur)) - } - else if (coder->MethodID == k_LZMA) - { -- RINOK(SzDecodeLzma(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)); -+ RINOK(SzDecodeLzma(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)) - } -- #ifndef _7Z_NO_METHOD_LZMA2 -+ #ifndef Z7_NO_METHOD_LZMA2 - else if (coder->MethodID == k_LZMA2) - { -- RINOK(SzDecodeLzma2(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)); -+ RINOK(SzDecodeLzma2(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)) - } -- #endif -- #ifdef _7ZIP_PPMD_SUPPPORT -+ #endif -+ #ifdef Z7_PPMD_SUPPORT - else if (coder->MethodID == k_PPMD) - { -- RINOK(SzDecodePpmd(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)); -+ RINOK(SzDecodePpmd(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)) - } -- #endif -+ #endif - else - return SZ_ERROR_UNSUPPORTED; - } - else if (coder->MethodID == k_BCJ2) - { -- UInt64 offset = packPositions[1]; -- UInt64 s3Size = packPositions[2] - offset; -+ const UInt64 offset = packPositions[1]; -+ const UInt64 s3Size = packPositions[2] - offset; - - if (ci != 3) - return SZ_ERROR_UNSUPPORTED; -@@ -473,8 +503,8 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, - if (!tempBuf[2] && tempSizes[2] != 0) - return SZ_ERROR_MEM; - -- RINOK(LookInStream_SeekTo(inStream, startPos + offset)); -- RINOK(SzDecodeCopy(s3Size, inStream, tempBuf[2])); -+ RINOK(LookInStream_SeekTo(inStream, startPos + offset)) -+ RINOK(SzDecodeCopy(s3Size, inStream, tempBuf[2])) - - if ((tempSizes[0] & 3) != 0 || - (tempSizes[1] & 3) != 0 || -@@ -493,26 +523,22 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, - p.destLim = outBuffer + outSize; - - Bcj2Dec_Init(&p); -- RINOK(Bcj2Dec_Decode(&p)); -+ RINOK(Bcj2Dec_Decode(&p)) - - { - unsigned i; - for (i = 0; i < 4; i++) - if (p.bufs[i] != p.lims[i]) - return SZ_ERROR_DATA; -- -- if (!Bcj2Dec_IsFinished(&p)) -- return SZ_ERROR_DATA; -- -- if (p.dest != p.destLim -- || p.state != BCJ2_STREAM_MAIN) -+ if (p.dest != p.destLim || !Bcj2Dec_IsMaybeFinished(&p)) - return SZ_ERROR_DATA; - } - } - } -- #ifndef _7Z_NO_METHODS_FILTERS -+ #if defined(Z7_USE_BRANCH_FILTER) - else if (ci == 1) - { -+ #if !defined(Z7_NO_METHODS_FILTERS) - if (coder->MethodID == k_Delta) - { - if (coder->PropsSize != 1) -@@ -522,31 +548,53 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, - Delta_Init(state); - Delta_Decode(state, (unsigned)(propsData[coder->PropsOffset]) + 1, outBuffer, outSize); - } -+ continue; - } -- else -+ #endif -+ -+ #ifdef Z7_USE_FILTER_ARM64 -+ if (coder->MethodID == k_ARM64) -+ { -+ UInt32 pc = 0; -+ if (coder->PropsSize == 4) -+ pc = GetUi32(propsData + coder->PropsOffset); -+ else if (coder->PropsSize != 0) -+ return SZ_ERROR_UNSUPPORTED; -+ z7_BranchConv_ARM64_Dec(outBuffer, outSize, pc); -+ continue; -+ } -+ #endif -+ -+ #if !defined(Z7_NO_METHODS_FILTERS) || defined(Z7_USE_FILTER_ARMT) - { - if (coder->PropsSize != 0) - return SZ_ERROR_UNSUPPORTED; -+ #define CASE_BRA_CONV(isa) case k_ ## isa: Z7_BRANCH_CONV_DEC(isa)(outBuffer, outSize, 0); break; // pc = 0; - switch (coder->MethodID) - { -+ #if !defined(Z7_NO_METHODS_FILTERS) - case k_BCJ: - { -- UInt32 state; -- x86_Convert_Init(state); -- x86_Convert(outBuffer, outSize, 0, &state, 0); -+ UInt32 state = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL; -+ z7_BranchConvSt_X86_Dec(outBuffer, outSize, 0, &state); // pc = 0 - break; - } - CASE_BRA_CONV(PPC) - CASE_BRA_CONV(IA64) - CASE_BRA_CONV(SPARC) - CASE_BRA_CONV(ARM) -+ #endif -+ #if !defined(Z7_NO_METHODS_FILTERS) || defined(Z7_USE_FILTER_ARMT) - CASE_BRA_CONV(ARMT) -+ #endif - default: - return SZ_ERROR_UNSUPPORTED; - } -+ continue; - } -- } -- #endif -+ #endif -+ } // (c == 1) -+ #endif - else - return SZ_ERROR_UNSUPPORTED; - } -@@ -556,7 +604,7 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, - - - SRes SzAr_DecodeFolder(const CSzAr *p, UInt32 folderIndex, -- ILookInStream *inStream, UInt64 startPos, -+ ILookInStreamPtr inStream, UInt64 startPos, - Byte *outBuffer, size_t outSize, - ISzAllocPtr allocMain) - { -diff --git a/src/lzma/7zFile.c b/src/lzma/7zFile.c -index 13d2efa47..ba5daa133 100644 ---- a/src/lzma/7zFile.c -+++ b/src/lzma/7zFile.c -@@ -1,5 +1,5 @@ - /* 7zFile.c -- File IO --2021-04-29 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -268,7 +268,7 @@ WRes File_Write(CSzFile *p, const void *data, size_t *size) - return errno; - if (processed == 0) - break; -- data = (void *)((Byte *)data + (size_t)processed); -+ data = (const void *)((const Byte *)data + (size_t)processed); - originalSize -= (size_t)processed; - *size += (size_t)processed; - } -@@ -287,7 +287,8 @@ WRes File_Seek(CSzFile *p, Int64 *pos, ESzSeek origin) - DWORD moveMethod; - UInt32 low = (UInt32)*pos; - LONG high = (LONG)((UInt64)*pos >> 16 >> 16); /* for case when UInt64 is 32-bit only */ -- switch (origin) -+ // (int) to eliminate clang warning -+ switch ((int)origin) - { - case SZ_SEEK_SET: moveMethod = FILE_BEGIN; break; - case SZ_SEEK_CUR: moveMethod = FILE_CURRENT; break; -@@ -308,7 +309,7 @@ WRes File_Seek(CSzFile *p, Int64 *pos, ESzSeek origin) - - int moveMethod; // = origin; - -- switch (origin) -+ switch ((int)origin) - { - case SZ_SEEK_SET: moveMethod = SEEK_SET; break; - case SZ_SEEK_CUR: moveMethod = SEEK_CUR; break; -@@ -387,10 +388,10 @@ WRes File_GetLength(CSzFile *p, UInt64 *length) - - /* ---------- FileSeqInStream ---------- */ - --static SRes FileSeqInStream_Read(const ISeqInStream *pp, void *buf, size_t *size) -+static SRes FileSeqInStream_Read(ISeqInStreamPtr pp, void *buf, size_t *size) - { -- CFileSeqInStream *p = CONTAINER_FROM_VTBL(pp, CFileSeqInStream, vt); -- WRes wres = File_Read(&p->file, buf, size); -+ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CFileSeqInStream) -+ const WRes wres = File_Read(&p->file, buf, size); - p->wres = wres; - return (wres == 0) ? SZ_OK : SZ_ERROR_READ; - } -@@ -403,18 +404,18 @@ void FileSeqInStream_CreateVTable(CFileSeqInStream *p) - - /* ---------- FileInStream ---------- */ - --static SRes FileInStream_Read(const ISeekInStream *pp, void *buf, size_t *size) -+static SRes FileInStream_Read(ISeekInStreamPtr pp, void *buf, size_t *size) - { -- CFileInStream *p = CONTAINER_FROM_VTBL(pp, CFileInStream, vt); -- WRes wres = File_Read(&p->file, buf, size); -+ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CFileInStream) -+ const WRes wres = File_Read(&p->file, buf, size); - p->wres = wres; - return (wres == 0) ? SZ_OK : SZ_ERROR_READ; - } - --static SRes FileInStream_Seek(const ISeekInStream *pp, Int64 *pos, ESzSeek origin) -+static SRes FileInStream_Seek(ISeekInStreamPtr pp, Int64 *pos, ESzSeek origin) - { -- CFileInStream *p = CONTAINER_FROM_VTBL(pp, CFileInStream, vt); -- WRes wres = File_Seek(&p->file, pos, origin); -+ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CFileInStream) -+ const WRes wres = File_Seek(&p->file, pos, origin); - p->wres = wres; - return (wres == 0) ? SZ_OK : SZ_ERROR_READ; - } -@@ -428,10 +429,10 @@ void FileInStream_CreateVTable(CFileInStream *p) - - /* ---------- FileOutStream ---------- */ - --static size_t FileOutStream_Write(const ISeqOutStream *pp, const void *data, size_t size) -+static size_t FileOutStream_Write(ISeqOutStreamPtr pp, const void *data, size_t size) - { -- CFileOutStream *p = CONTAINER_FROM_VTBL(pp, CFileOutStream, vt); -- WRes wres = File_Write(&p->file, data, &size); -+ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CFileOutStream) -+ const WRes wres = File_Write(&p->file, data, &size); - p->wres = wres; - return size; - } -diff --git a/src/lzma/7zFile.h b/src/lzma/7zFile.h -index 788abb6b9..f5069cd9e 100644 ---- a/src/lzma/7zFile.h -+++ b/src/lzma/7zFile.h -@@ -1,8 +1,8 @@ - /* 7zFile.h -- File IO --2021-02-15 : Igor Pavlov : Public domain */ -+2023-03-05 : Igor Pavlov : Public domain */ - --#ifndef __7Z_FILE_H --#define __7Z_FILE_H -+#ifndef ZIP7_INC_FILE_H -+#define ZIP7_INC_FILE_H - - #ifdef _WIN32 - #define USE_WINDOWS_FILE -@@ -10,7 +10,8 @@ - #endif - - #ifdef USE_WINDOWS_FILE --#include -+#include "7zWindows.h" -+ - #else - // note: USE_FOPEN mode is limited to 32-bit file size - // #define USE_FOPEN -diff --git a/src/lzma/7zStream.c b/src/lzma/7zStream.c -index 28a14604f..74e75b65a 100644 ---- a/src/lzma/7zStream.c -+++ b/src/lzma/7zStream.c -@@ -1,5 +1,5 @@ - /* 7zStream.c -- 7z Stream functions --2021-02-09 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -7,12 +7,33 @@ - - #include "7zTypes.h" - --SRes SeqInStream_Read2(const ISeqInStream *stream, void *buf, size_t size, SRes errorType) -+ -+SRes SeqInStream_ReadMax(ISeqInStreamPtr stream, void *buf, size_t *processedSize) -+{ -+ size_t size = *processedSize; -+ *processedSize = 0; -+ while (size != 0) -+ { -+ size_t cur = size; -+ const SRes res = ISeqInStream_Read(stream, buf, &cur); -+ *processedSize += cur; -+ buf = (void *)((Byte *)buf + cur); -+ size -= cur; -+ if (res != SZ_OK) -+ return res; -+ if (cur == 0) -+ return SZ_OK; -+ } -+ return SZ_OK; -+} -+ -+/* -+SRes SeqInStream_Read2(ISeqInStreamPtr stream, void *buf, size_t size, SRes errorType) - { - while (size != 0) - { - size_t processed = size; -- RINOK(ISeqInStream_Read(stream, buf, &processed)); -+ RINOK(ISeqInStream_Read(stream, buf, &processed)) - if (processed == 0) - return errorType; - buf = (void *)((Byte *)buf + processed); -@@ -21,42 +42,44 @@ SRes SeqInStream_Read2(const ISeqInStream *stream, void *buf, size_t size, SRes - return SZ_OK; - } - --SRes SeqInStream_Read(const ISeqInStream *stream, void *buf, size_t size) -+SRes SeqInStream_Read(ISeqInStreamPtr stream, void *buf, size_t size) - { - return SeqInStream_Read2(stream, buf, size, SZ_ERROR_INPUT_EOF); - } -+*/ -+ - --SRes SeqInStream_ReadByte(const ISeqInStream *stream, Byte *buf) -+SRes SeqInStream_ReadByte(ISeqInStreamPtr stream, Byte *buf) - { - size_t processed = 1; -- RINOK(ISeqInStream_Read(stream, buf, &processed)); -+ RINOK(ISeqInStream_Read(stream, buf, &processed)) - return (processed == 1) ? SZ_OK : SZ_ERROR_INPUT_EOF; - } - - - --SRes LookInStream_SeekTo(const ILookInStream *stream, UInt64 offset) -+SRes LookInStream_SeekTo(ILookInStreamPtr stream, UInt64 offset) - { - Int64 t = (Int64)offset; - return ILookInStream_Seek(stream, &t, SZ_SEEK_SET); - } - --SRes LookInStream_LookRead(const ILookInStream *stream, void *buf, size_t *size) -+SRes LookInStream_LookRead(ILookInStreamPtr stream, void *buf, size_t *size) - { - const void *lookBuf; - if (*size == 0) - return SZ_OK; -- RINOK(ILookInStream_Look(stream, &lookBuf, size)); -+ RINOK(ILookInStream_Look(stream, &lookBuf, size)) - memcpy(buf, lookBuf, *size); - return ILookInStream_Skip(stream, *size); - } - --SRes LookInStream_Read2(const ILookInStream *stream, void *buf, size_t size, SRes errorType) -+SRes LookInStream_Read2(ILookInStreamPtr stream, void *buf, size_t size, SRes errorType) - { - while (size != 0) - { - size_t processed = size; -- RINOK(ILookInStream_Read(stream, buf, &processed)); -+ RINOK(ILookInStream_Read(stream, buf, &processed)) - if (processed == 0) - return errorType; - buf = (void *)((Byte *)buf + processed); -@@ -65,16 +88,16 @@ SRes LookInStream_Read2(const ILookInStream *stream, void *buf, size_t size, SRe - return SZ_OK; - } - --SRes LookInStream_Read(const ILookInStream *stream, void *buf, size_t size) -+SRes LookInStream_Read(ILookInStreamPtr stream, void *buf, size_t size) - { - return LookInStream_Read2(stream, buf, size, SZ_ERROR_INPUT_EOF); - } - - - --#define GET_LookToRead2 CLookToRead2 *p = CONTAINER_FROM_VTBL(pp, CLookToRead2, vt); -+#define GET_LookToRead2 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CLookToRead2) - --static SRes LookToRead2_Look_Lookahead(const ILookInStream *pp, const void **buf, size_t *size) -+static SRes LookToRead2_Look_Lookahead(ILookInStreamPtr pp, const void **buf, size_t *size) - { - SRes res = SZ_OK; - GET_LookToRead2 -@@ -93,7 +116,7 @@ static SRes LookToRead2_Look_Lookahead(const ILookInStream *pp, const void **buf - return res; - } - --static SRes LookToRead2_Look_Exact(const ILookInStream *pp, const void **buf, size_t *size) -+static SRes LookToRead2_Look_Exact(ILookInStreamPtr pp, const void **buf, size_t *size) - { - SRes res = SZ_OK; - GET_LookToRead2 -@@ -113,14 +136,14 @@ static SRes LookToRead2_Look_Exact(const ILookInStream *pp, const void **buf, si - return res; - } - --static SRes LookToRead2_Skip(const ILookInStream *pp, size_t offset) -+static SRes LookToRead2_Skip(ILookInStreamPtr pp, size_t offset) - { - GET_LookToRead2 - p->pos += offset; - return SZ_OK; - } - --static SRes LookToRead2_Read(const ILookInStream *pp, void *buf, size_t *size) -+static SRes LookToRead2_Read(ILookInStreamPtr pp, void *buf, size_t *size) - { - GET_LookToRead2 - size_t rem = p->size - p->pos; -@@ -134,7 +157,7 @@ static SRes LookToRead2_Read(const ILookInStream *pp, void *buf, size_t *size) - return SZ_OK; - } - --static SRes LookToRead2_Seek(const ILookInStream *pp, Int64 *pos, ESzSeek origin) -+static SRes LookToRead2_Seek(ILookInStreamPtr pp, Int64 *pos, ESzSeek origin) - { - GET_LookToRead2 - p->pos = p->size = 0; -@@ -153,9 +176,9 @@ void LookToRead2_CreateVTable(CLookToRead2 *p, int lookahead) - - - --static SRes SecToLook_Read(const ISeqInStream *pp, void *buf, size_t *size) -+static SRes SecToLook_Read(ISeqInStreamPtr pp, void *buf, size_t *size) - { -- CSecToLook *p = CONTAINER_FROM_VTBL(pp, CSecToLook, vt); -+ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSecToLook) - return LookInStream_LookRead(p->realStream, buf, size); - } - -@@ -164,9 +187,9 @@ void SecToLook_CreateVTable(CSecToLook *p) - p->vt.Read = SecToLook_Read; - } - --static SRes SecToRead_Read(const ISeqInStream *pp, void *buf, size_t *size) -+static SRes SecToRead_Read(ISeqInStreamPtr pp, void *buf, size_t *size) - { -- CSecToRead *p = CONTAINER_FROM_VTBL(pp, CSecToRead, vt); -+ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSecToRead) - return ILookInStream_Read(p->realStream, buf, size); - } - -diff --git a/src/lzma/7zTypes.h b/src/lzma/7zTypes.h -index 49291ce2a..e16175049 100644 ---- a/src/lzma/7zTypes.h -+++ b/src/lzma/7zTypes.h -@@ -1,8 +1,8 @@ - /* 7zTypes.h -- Basic types --2021-12-25 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - --#ifndef __7Z_TYPES_H --#define __7Z_TYPES_H -+#ifndef ZIP7_7Z_TYPES_H -+#define ZIP7_7Z_TYPES_H - - #ifdef _WIN32 - /* #include */ -@@ -52,6 +52,11 @@ typedef int SRes; - #define MY_ALIGN(n) - #endif - #else -+ /* -+ // C11/C++11: -+ #include -+ #define MY_ALIGN(n) alignas(n) -+ */ - #define MY_ALIGN(n) __attribute__ ((aligned(n))) - #endif - -@@ -62,7 +67,7 @@ typedef int SRes; - typedef unsigned WRes; - #define MY_SRes_HRESULT_FROM_WRes(x) HRESULT_FROM_WIN32(x) - --// #define MY_HRES_ERROR__INTERNAL_ERROR MY_SRes_HRESULT_FROM_WRes(ERROR_INTERNAL_ERROR) -+// #define MY_HRES_ERROR_INTERNAL_ERROR MY_SRes_HRESULT_FROM_WRes(ERROR_INTERNAL_ERROR) - - #else // _WIN32 - -@@ -70,13 +75,13 @@ typedef unsigned WRes; - typedef int WRes; - - // (FACILITY_ERRNO = 0x800) is 7zip's FACILITY constant to represent (errno) errors in HRESULT --#define MY__FACILITY_ERRNO 0x800 --#define MY__FACILITY_WIN32 7 --#define MY__FACILITY__WRes MY__FACILITY_ERRNO -+#define MY_FACILITY_ERRNO 0x800 -+#define MY_FACILITY_WIN32 7 -+#define MY_FACILITY_WRes MY_FACILITY_ERRNO - - #define MY_HRESULT_FROM_errno_CONST_ERROR(x) ((HRESULT)( \ - ( (HRESULT)(x) & 0x0000FFFF) \ -- | (MY__FACILITY__WRes << 16) \ -+ | (MY_FACILITY_WRes << 16) \ - | (HRESULT)0x80000000 )) - - #define MY_SRes_HRESULT_FROM_WRes(x) \ -@@ -120,23 +125,19 @@ typedef int WRes; - #define ERROR_INVALID_REPARSE_DATA ((HRESULT)0x80071128L) - #define ERROR_REPARSE_TAG_INVALID ((HRESULT)0x80071129L) - --// if (MY__FACILITY__WRes != FACILITY_WIN32), -+// if (MY_FACILITY_WRes != FACILITY_WIN32), - // we use FACILITY_WIN32 for COM errors: - #define E_OUTOFMEMORY ((HRESULT)0x8007000EL) - #define E_INVALIDARG ((HRESULT)0x80070057L) --#define MY__E_ERROR_NEGATIVE_SEEK ((HRESULT)0x80070083L) -+#define MY_E_ERROR_NEGATIVE_SEEK ((HRESULT)0x80070083L) - - /* - // we can use FACILITY_ERRNO for some COM errors, that have errno equivalents: - #define E_OUTOFMEMORY MY_HRESULT_FROM_errno_CONST_ERROR(ENOMEM) - #define E_INVALIDARG MY_HRESULT_FROM_errno_CONST_ERROR(EINVAL) --#define MY__E_ERROR_NEGATIVE_SEEK MY_HRESULT_FROM_errno_CONST_ERROR(EINVAL) -+#define MY_E_ERROR_NEGATIVE_SEEK MY_HRESULT_FROM_errno_CONST_ERROR(EINVAL) - */ - --// gcc / clang : (sizeof(long) == sizeof(void*)) in 32/64 bits --typedef long INT_PTR; --typedef unsigned long UINT_PTR; -- - #define TEXT(quote) quote - - #define FILE_ATTRIBUTE_READONLY 0x0001 -@@ -160,18 +161,18 @@ typedef unsigned long UINT_PTR; - - - #ifndef RINOK --#define RINOK(x) { int __result__ = (x); if (__result__ != 0) return __result__; } -+#define RINOK(x) { const int _result_ = (x); if (_result_ != 0) return _result_; } - #endif - - #ifndef RINOK_WRes --#define RINOK_WRes(x) { WRes __result__ = (x); if (__result__ != 0) return __result__; } -+#define RINOK_WRes(x) { const WRes _result_ = (x); if (_result_ != 0) return _result_; } - #endif - - typedef unsigned char Byte; - typedef short Int16; - typedef unsigned short UInt16; - --#ifdef _LZMA_UINT32_IS_ULONG -+#ifdef Z7_DECL_Int32_AS_long - typedef long Int32; - typedef unsigned long UInt32; - #else -@@ -210,37 +211,51 @@ typedef size_t SIZE_T; - #endif // _WIN32 - - --#define MY_HRES_ERROR__INTERNAL_ERROR ((HRESULT)0x8007054FL) -- -+#define MY_HRES_ERROR_INTERNAL_ERROR ((HRESULT)0x8007054FL) - --#ifdef _SZ_NO_INT_64 - --/* define _SZ_NO_INT_64, if your compiler doesn't support 64-bit integers. -- NOTES: Some code will work incorrectly in that case! */ -+#ifdef Z7_DECL_Int64_AS_long - - typedef long Int64; - typedef unsigned long UInt64; - - #else - --#if defined(_MSC_VER) || defined(__BORLANDC__) -+#if (defined(_MSC_VER) || defined(__BORLANDC__)) && !defined(__clang__) - typedef __int64 Int64; - typedef unsigned __int64 UInt64; --#define UINT64_CONST(n) n -+#else -+#if defined(__clang__) || defined(__GNUC__) -+#include -+typedef int64_t Int64; -+typedef uint64_t UInt64; - #else - typedef long long int Int64; - typedef unsigned long long int UInt64; --#define UINT64_CONST(n) n ## ULL -+// #define UINT64_CONST(n) n ## ULL -+#endif - #endif - - #endif - --#ifdef _LZMA_NO_SYSTEM_SIZE_T --typedef UInt32 SizeT; -+#define UINT64_CONST(n) n -+ -+ -+#ifdef Z7_DECL_SizeT_AS_unsigned_int -+typedef unsigned int SizeT; - #else - typedef size_t SizeT; - #endif - -+/* -+#if (defined(_MSC_VER) && _MSC_VER <= 1200) -+typedef size_t MY_uintptr_t; -+#else -+#include -+typedef uintptr_t MY_uintptr_t; -+#endif -+*/ -+ - typedef int BoolInt; - /* typedef BoolInt Bool; */ - #define True7z 1 -@@ -248,23 +263,23 @@ typedef int BoolInt; - - - #ifdef _WIN32 --#define MY_STD_CALL __stdcall -+#define Z7_STDCALL __stdcall - #else --#define MY_STD_CALL -+#define Z7_STDCALL - #endif - - #ifdef _MSC_VER - - #if _MSC_VER >= 1300 --#define MY_NO_INLINE __declspec(noinline) -+#define Z7_NO_INLINE __declspec(noinline) - #else --#define MY_NO_INLINE -+#define Z7_NO_INLINE - #endif - --#define MY_FORCE_INLINE __forceinline -+#define Z7_FORCE_INLINE __forceinline - --#define MY_CDECL __cdecl --#define MY_FAST_CALL __fastcall -+#define Z7_CDECL __cdecl -+#define Z7_FASTCALL __fastcall - - #else // _MSC_VER - -@@ -272,27 +287,25 @@ typedef int BoolInt; - || (defined(__clang__) && (__clang_major__ >= 4)) \ - || defined(__INTEL_COMPILER) \ - || defined(__xlC__) --#define MY_NO_INLINE __attribute__((noinline)) --// #define MY_FORCE_INLINE __attribute__((always_inline)) inline -+#define Z7_NO_INLINE __attribute__((noinline)) -+#define Z7_FORCE_INLINE __attribute__((always_inline)) inline - #else --#define MY_NO_INLINE -+#define Z7_NO_INLINE -+#define Z7_FORCE_INLINE - #endif - --#define MY_FORCE_INLINE -- -- --#define MY_CDECL -+#define Z7_CDECL - - #if defined(_M_IX86) \ - || defined(__i386__) --// #define MY_FAST_CALL __attribute__((fastcall)) --// #define MY_FAST_CALL __attribute__((cdecl)) --#define MY_FAST_CALL -+// #define Z7_FASTCALL __attribute__((fastcall)) -+// #define Z7_FASTCALL __attribute__((cdecl)) -+#define Z7_FASTCALL - #elif defined(MY_CPU_AMD64) --// #define MY_FAST_CALL __attribute__((ms_abi)) --#define MY_FAST_CALL -+// #define Z7_FASTCALL __attribute__((ms_abi)) -+#define Z7_FASTCALL - #else --#define MY_FAST_CALL -+#define Z7_FASTCALL - #endif - - #endif // _MSC_VER -@@ -300,41 +313,49 @@ typedef int BoolInt; - - /* The following interfaces use first parameter as pointer to structure */ - --typedef struct IByteIn IByteIn; --struct IByteIn -+// #define Z7_C_IFACE_CONST_QUAL -+#define Z7_C_IFACE_CONST_QUAL const -+ -+#define Z7_C_IFACE_DECL(a) \ -+ struct a ## _; \ -+ typedef Z7_C_IFACE_CONST_QUAL struct a ## _ * a ## Ptr; \ -+ typedef struct a ## _ a; \ -+ struct a ## _ -+ -+ -+Z7_C_IFACE_DECL (IByteIn) - { -- Byte (*Read)(const IByteIn *p); /* reads one byte, returns 0 in case of EOF or error */ -+ Byte (*Read)(IByteInPtr p); /* reads one byte, returns 0 in case of EOF or error */ - }; - #define IByteIn_Read(p) (p)->Read(p) - - --typedef struct IByteOut IByteOut; --struct IByteOut -+Z7_C_IFACE_DECL (IByteOut) - { -- void (*Write)(const IByteOut *p, Byte b); -+ void (*Write)(IByteOutPtr p, Byte b); - }; - #define IByteOut_Write(p, b) (p)->Write(p, b) - - --typedef struct ISeqInStream ISeqInStream; --struct ISeqInStream -+Z7_C_IFACE_DECL (ISeqInStream) - { -- SRes (*Read)(const ISeqInStream *p, void *buf, size_t *size); -+ SRes (*Read)(ISeqInStreamPtr p, void *buf, size_t *size); - /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. - (output(*size) < input(*size)) is allowed */ - }; - #define ISeqInStream_Read(p, buf, size) (p)->Read(p, buf, size) - -+/* try to read as much as avail in stream and limited by (*processedSize) */ -+SRes SeqInStream_ReadMax(ISeqInStreamPtr stream, void *buf, size_t *processedSize); - /* it can return SZ_ERROR_INPUT_EOF */ --SRes SeqInStream_Read(const ISeqInStream *stream, void *buf, size_t size); --SRes SeqInStream_Read2(const ISeqInStream *stream, void *buf, size_t size, SRes errorType); --SRes SeqInStream_ReadByte(const ISeqInStream *stream, Byte *buf); -+// SRes SeqInStream_Read(ISeqInStreamPtr stream, void *buf, size_t size); -+// SRes SeqInStream_Read2(ISeqInStreamPtr stream, void *buf, size_t size, SRes errorType); -+SRes SeqInStream_ReadByte(ISeqInStreamPtr stream, Byte *buf); - - --typedef struct ISeqOutStream ISeqOutStream; --struct ISeqOutStream -+Z7_C_IFACE_DECL (ISeqOutStream) - { -- size_t (*Write)(const ISeqOutStream *p, const void *buf, size_t size); -+ size_t (*Write)(ISeqOutStreamPtr p, const void *buf, size_t size); - /* Returns: result - the number of actually written bytes. - (result < size) means error */ - }; -@@ -348,29 +369,26 @@ typedef enum - } ESzSeek; - - --typedef struct ISeekInStream ISeekInStream; --struct ISeekInStream -+Z7_C_IFACE_DECL (ISeekInStream) - { -- SRes (*Read)(const ISeekInStream *p, void *buf, size_t *size); /* same as ISeqInStream::Read */ -- SRes (*Seek)(const ISeekInStream *p, Int64 *pos, ESzSeek origin); -+ SRes (*Read)(ISeekInStreamPtr p, void *buf, size_t *size); /* same as ISeqInStream::Read */ -+ SRes (*Seek)(ISeekInStreamPtr p, Int64 *pos, ESzSeek origin); - }; - #define ISeekInStream_Read(p, buf, size) (p)->Read(p, buf, size) - #define ISeekInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin) - - --typedef struct ILookInStream ILookInStream; --struct ILookInStream -+Z7_C_IFACE_DECL (ILookInStream) - { -- SRes (*Look)(const ILookInStream *p, const void **buf, size_t *size); -+ SRes (*Look)(ILookInStreamPtr p, const void **buf, size_t *size); - /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. - (output(*size) > input(*size)) is not allowed - (output(*size) < input(*size)) is allowed */ -- SRes (*Skip)(const ILookInStream *p, size_t offset); -+ SRes (*Skip)(ILookInStreamPtr p, size_t offset); - /* offset must be <= output(*size) of Look */ -- -- SRes (*Read)(const ILookInStream *p, void *buf, size_t *size); -+ SRes (*Read)(ILookInStreamPtr p, void *buf, size_t *size); - /* reads directly (without buffer). It's same as ISeqInStream::Read */ -- SRes (*Seek)(const ILookInStream *p, Int64 *pos, ESzSeek origin); -+ SRes (*Seek)(ILookInStreamPtr p, Int64 *pos, ESzSeek origin); - }; - - #define ILookInStream_Look(p, buf, size) (p)->Look(p, buf, size) -@@ -379,19 +397,18 @@ struct ILookInStream - #define ILookInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin) - - --SRes LookInStream_LookRead(const ILookInStream *stream, void *buf, size_t *size); --SRes LookInStream_SeekTo(const ILookInStream *stream, UInt64 offset); -+SRes LookInStream_LookRead(ILookInStreamPtr stream, void *buf, size_t *size); -+SRes LookInStream_SeekTo(ILookInStreamPtr stream, UInt64 offset); - - /* reads via ILookInStream::Read */ --SRes LookInStream_Read2(const ILookInStream *stream, void *buf, size_t size, SRes errorType); --SRes LookInStream_Read(const ILookInStream *stream, void *buf, size_t size); -- -+SRes LookInStream_Read2(ILookInStreamPtr stream, void *buf, size_t size, SRes errorType); -+SRes LookInStream_Read(ILookInStreamPtr stream, void *buf, size_t size); - - - typedef struct - { - ILookInStream vt; -- const ISeekInStream *realStream; -+ ISeekInStreamPtr realStream; - - size_t pos; - size_t size; /* it's data size */ -@@ -403,13 +420,13 @@ typedef struct - - void LookToRead2_CreateVTable(CLookToRead2 *p, int lookahead); - --#define LookToRead2_Init(p) { (p)->pos = (p)->size = 0; } -+#define LookToRead2_INIT(p) { (p)->pos = (p)->size = 0; } - - - typedef struct - { - ISeqInStream vt; -- const ILookInStream *realStream; -+ ILookInStreamPtr realStream; - } CSecToLook; - - void SecToLook_CreateVTable(CSecToLook *p); -@@ -419,20 +436,19 @@ void SecToLook_CreateVTable(CSecToLook *p); - typedef struct - { - ISeqInStream vt; -- const ILookInStream *realStream; -+ ILookInStreamPtr realStream; - } CSecToRead; - - void SecToRead_CreateVTable(CSecToRead *p); - - --typedef struct ICompressProgress ICompressProgress; -- --struct ICompressProgress -+Z7_C_IFACE_DECL (ICompressProgress) - { -- SRes (*Progress)(const ICompressProgress *p, UInt64 inSize, UInt64 outSize); -+ SRes (*Progress)(ICompressProgressPtr p, UInt64 inSize, UInt64 outSize); - /* Returns: result. (result != SZ_OK) means break. - Value (UInt64)(Int64)-1 for size means unknown value. */ - }; -+ - #define ICompressProgress_Progress(p, inSize, outSize) (p)->Progress(p, inSize, outSize) - - -@@ -470,13 +486,13 @@ struct ISzAlloc - - - --#ifndef MY_container_of -+#ifndef Z7_container_of - - /* --#define MY_container_of(ptr, type, m) container_of(ptr, type, m) --#define MY_container_of(ptr, type, m) CONTAINING_RECORD(ptr, type, m) --#define MY_container_of(ptr, type, m) ((type *)((char *)(ptr) - offsetof(type, m))) --#define MY_container_of(ptr, type, m) (&((type *)0)->m == (ptr), ((type *)(((char *)(ptr)) - MY_offsetof(type, m)))) -+#define Z7_container_of(ptr, type, m) container_of(ptr, type, m) -+#define Z7_container_of(ptr, type, m) CONTAINING_RECORD(ptr, type, m) -+#define Z7_container_of(ptr, type, m) ((type *)((char *)(ptr) - offsetof(type, m))) -+#define Z7_container_of(ptr, type, m) (&((type *)0)->m == (ptr), ((type *)(((char *)(ptr)) - MY_offsetof(type, m)))) - */ - - /* -@@ -485,24 +501,64 @@ struct ISzAlloc - GCC 4.8.1 : classes with non-public variable members" - */ - --#define MY_container_of(ptr, type, m) ((type *)(void *)((char *)(void *)(1 ? (ptr) : &((type *)0)->m) - MY_offsetof(type, m))) -+#define Z7_container_of(ptr, type, m) \ -+ ((type *)(void *)((char *)(void *) \ -+ (1 ? (ptr) : &((type *)NULL)->m) - MY_offsetof(type, m))) - --#endif -- --#define CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) ((type *)(void *)(ptr)) -+#define Z7_container_of_CONST(ptr, type, m) \ -+ ((const type *)(const void *)((const char *)(const void *) \ -+ (1 ? (ptr) : &((type *)NULL)->m) - MY_offsetof(type, m))) - - /* --#define CONTAINER_FROM_VTBL(ptr, type, m) CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) -+#define Z7_container_of_NON_CONST_FROM_CONST(ptr, type, m) \ -+ ((type *)(void *)(const void *)((const char *)(const void *) \ -+ (1 ? (ptr) : &((type *)NULL)->m) - MY_offsetof(type, m))) - */ --#define CONTAINER_FROM_VTBL(ptr, type, m) MY_container_of(ptr, type, m) - --#define CONTAINER_FROM_VTBL_CLS(ptr, type, m) CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) -+#endif -+ -+#define Z7_CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) ((type *)(void *)(ptr)) -+ -+// #define Z7_CONTAINER_FROM_VTBL(ptr, type, m) Z7_CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) -+#define Z7_CONTAINER_FROM_VTBL(ptr, type, m) Z7_container_of(ptr, type, m) -+// #define Z7_CONTAINER_FROM_VTBL(ptr, type, m) Z7_container_of_NON_CONST_FROM_CONST(ptr, type, m) -+ -+#define Z7_CONTAINER_FROM_VTBL_CONST(ptr, type, m) Z7_container_of_CONST(ptr, type, m) -+ -+#define Z7_CONTAINER_FROM_VTBL_CLS(ptr, type, m) Z7_CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) - /* --#define CONTAINER_FROM_VTBL_CLS(ptr, type, m) CONTAINER_FROM_VTBL(ptr, type, m) -+#define Z7_CONTAINER_FROM_VTBL_CLS(ptr, type, m) Z7_CONTAINER_FROM_VTBL(ptr, type, m) - */ -+#if defined (__clang__) || defined(__GNUC__) -+#define Z7_DIAGNOSCTIC_IGNORE_BEGIN_CAST_QUAL \ -+ _Pragma("GCC diagnostic push") \ -+ _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") -+#define Z7_DIAGNOSCTIC_IGNORE_END_CAST_QUAL \ -+ _Pragma("GCC diagnostic pop") -+#else -+#define Z7_DIAGNOSCTIC_IGNORE_BEGIN_CAST_QUAL -+#define Z7_DIAGNOSCTIC_IGNORE_END_CAST_QUAL -+#endif -+ -+#define Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR(ptr, type, m, p) \ -+ Z7_DIAGNOSCTIC_IGNORE_BEGIN_CAST_QUAL \ -+ type *p = Z7_CONTAINER_FROM_VTBL(ptr, type, m); \ -+ Z7_DIAGNOSCTIC_IGNORE_END_CAST_QUAL -+ -+#define Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(type) \ -+ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR(pp, type, vt, p) - - --#define MY_memset_0_ARRAY(a) memset((a), 0, sizeof(a)) -+// #define ZIP7_DECLARE_HANDLE(name) typedef void *name; -+#define Z7_DECLARE_HANDLE(name) struct name##_dummy{int unused;}; typedef struct name##_dummy *name; -+ -+ -+#define Z7_memset_0_ARRAY(a) memset((a), 0, sizeof(a)) -+ -+#ifndef Z7_ARRAY_SIZE -+#define Z7_ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) -+#endif -+ - - #ifdef _WIN32 - -@@ -520,6 +576,22 @@ struct ISzAlloc - - #endif - -+#define k_PropVar_TimePrec_0 0 -+#define k_PropVar_TimePrec_Unix 1 -+#define k_PropVar_TimePrec_DOS 2 -+#define k_PropVar_TimePrec_HighPrec 3 -+#define k_PropVar_TimePrec_Base 16 -+#define k_PropVar_TimePrec_100ns (k_PropVar_TimePrec_Base + 7) -+#define k_PropVar_TimePrec_1ns (k_PropVar_TimePrec_Base + 9) -+ - EXTERN_C_END - - #endif -+ -+/* -+#ifndef Z7_ST -+#ifdef _7ZIP_ST -+#define Z7_ST -+#endif -+#endif -+*/ -diff --git a/src/lzma/7zVersion.h b/src/lzma/7zVersion.h -index e9363d37b..754923961 100644 ---- a/src/lzma/7zVersion.h -+++ b/src/lzma/7zVersion.h -@@ -1,7 +1,7 @@ --#define MY_VER_MAJOR 21 --#define MY_VER_MINOR 07 -+#define MY_VER_MAJOR 23 -+#define MY_VER_MINOR 01 - #define MY_VER_BUILD 0 --#define MY_VERSION_NUMBERS "21.07" -+#define MY_VERSION_NUMBERS "23.01" - #define MY_VERSION MY_VERSION_NUMBERS - - #ifdef MY_CPU_NAME -@@ -10,12 +10,12 @@ - #define MY_VERSION_CPU MY_VERSION - #endif - --#define MY_DATE "2021-12-26" -+#define MY_DATE "2023-06-20" - #undef MY_COPYRIGHT - #undef MY_VERSION_COPYRIGHT_DATE - #define MY_AUTHOR_NAME "Igor Pavlov" - #define MY_COPYRIGHT_PD "Igor Pavlov : Public domain" --#define MY_COPYRIGHT_CR "Copyright (c) 1999-2021 Igor Pavlov" -+#define MY_COPYRIGHT_CR "Copyright (c) 1999-2023 Igor Pavlov" - - #ifdef USE_COPYRIGHT_CR - #define MY_COPYRIGHT MY_COPYRIGHT_CR -diff --git a/src/lzma/7zWindows.h b/src/lzma/7zWindows.h -new file mode 100644 -index 000000000..42c6db8bf ---- /dev/null -+++ b/src/lzma/7zWindows.h -@@ -0,0 +1,101 @@ -+/* 7zWindows.h -- StdAfx -+2023-04-02 : Igor Pavlov : Public domain */ -+ -+#ifndef ZIP7_INC_7Z_WINDOWS_H -+#define ZIP7_INC_7Z_WINDOWS_H -+ -+#ifdef _WIN32 -+ -+#if defined(__clang__) -+# pragma clang diagnostic push -+#endif -+ -+#if defined(_MSC_VER) -+ -+#pragma warning(push) -+#pragma warning(disable : 4668) // '_WIN32_WINNT' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' -+ -+#if _MSC_VER == 1900 -+// for old kit10 versions -+// #pragma warning(disable : 4255) // winuser.h(13979): warning C4255: 'GetThreadDpiAwarenessContext': -+#endif -+// win10 Windows Kit: -+#endif // _MSC_VER -+ -+#if defined(_MSC_VER) && _MSC_VER <= 1200 && !defined(_WIN64) -+// for msvc6 without sdk2003 -+#define RPC_NO_WINDOWS_H -+#endif -+ -+#if defined(__MINGW32__) || defined(__MINGW64__) -+// #if defined(__GNUC__) && !defined(__clang__) -+#include -+#else -+#include -+#endif -+// #include -+// #include -+ -+// but if precompiled with clang-cl then we need -+// #include -+#if defined(_MSC_VER) -+#pragma warning(pop) -+#endif -+ -+#if defined(__clang__) -+# pragma clang diagnostic pop -+#endif -+ -+#if defined(_MSC_VER) && _MSC_VER <= 1200 && !defined(_WIN64) -+#ifndef _W64 -+ -+typedef long LONG_PTR, *PLONG_PTR; -+typedef unsigned long ULONG_PTR, *PULONG_PTR; -+typedef ULONG_PTR DWORD_PTR, *PDWORD_PTR; -+ -+#define Z7_OLD_WIN_SDK -+#endif // _W64 -+#endif // _MSC_VER == 1200 -+ -+#ifdef Z7_OLD_WIN_SDK -+ -+#ifndef INVALID_FILE_ATTRIBUTES -+#define INVALID_FILE_ATTRIBUTES ((DWORD)-1) -+#endif -+#ifndef INVALID_SET_FILE_POINTER -+#define INVALID_SET_FILE_POINTER ((DWORD)-1) -+#endif -+#ifndef FILE_SPECIAL_ACCESS -+#define FILE_SPECIAL_ACCESS (FILE_ANY_ACCESS) -+#endif -+ -+// ShlObj.h: -+// #define BIF_NEWDIALOGSTYLE 0x0040 -+ -+#pragma warning(disable : 4201) -+// #pragma warning(disable : 4115) -+ -+#undef VARIANT_TRUE -+#define VARIANT_TRUE ((VARIANT_BOOL)-1) -+#endif -+ -+#endif // Z7_OLD_WIN_SDK -+ -+#ifdef UNDER_CE -+#undef VARIANT_TRUE -+#define VARIANT_TRUE ((VARIANT_BOOL)-1) -+#endif -+ -+ -+#if defined(_MSC_VER) -+#if _MSC_VER >= 1400 && _MSC_VER <= 1600 -+ // BaseTsd.h(148) : 'HandleToULong' : unreferenced inline function has been removed -+ // string.h -+ // #pragma warning(disable : 4514) -+#endif -+#endif -+ -+ -+/* #include "7zTypes.h" */ -+ -+#endif -diff --git a/src/lzma/Aes.c b/src/lzma/Aes.c -index 27e32e622..bcaafab11 100644 ---- a/src/lzma/Aes.c -+++ b/src/lzma/Aes.c -@@ -1,5 +1,5 @@ - /* Aes.c -- AES encryption / decryption --2021-05-13 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -7,7 +7,7 @@ - #include "Aes.h" - - AES_CODE_FUNC g_AesCbc_Decode; --#ifndef _SFX -+#ifndef Z7_SFX - AES_CODE_FUNC g_AesCbc_Encode; - AES_CODE_FUNC g_AesCtr_Code; - UInt32 g_Aes_SupportedFunctions_Flags; -@@ -51,7 +51,7 @@ static Byte InvS[256]; - #define DD(x) (D + (x << 8)) - - --// #define _SHOW_AES_STATUS -+// #define Z7_SHOW_AES_STATUS - - #ifdef MY_CPU_X86_OR_AMD64 - #define USE_HW_AES -@@ -72,11 +72,11 @@ static Byte InvS[256]; - #endif - - #ifdef USE_HW_AES --#ifdef _SHOW_AES_STATUS -+#ifdef Z7_SHOW_AES_STATUS - #include --#define _PRF(x) x -+#define PRF(x) x - #else --#define _PRF(x) -+#define PRF(x) - #endif - #endif - -@@ -90,23 +90,23 @@ void AesGenTables(void) - for (i = 0; i < 256; i++) - { - { -- UInt32 a1 = Sbox[i]; -- UInt32 a2 = xtime(a1); -- UInt32 a3 = a2 ^ a1; -+ const UInt32 a1 = Sbox[i]; -+ const UInt32 a2 = xtime(a1); -+ const UInt32 a3 = a2 ^ a1; - TT(0)[i] = Ui32(a2, a1, a1, a3); - TT(1)[i] = Ui32(a3, a2, a1, a1); - TT(2)[i] = Ui32(a1, a3, a2, a1); - TT(3)[i] = Ui32(a1, a1, a3, a2); - } - { -- UInt32 a1 = InvS[i]; -- UInt32 a2 = xtime(a1); -- UInt32 a4 = xtime(a2); -- UInt32 a8 = xtime(a4); -- UInt32 a9 = a8 ^ a1; -- UInt32 aB = a8 ^ a2 ^ a1; -- UInt32 aD = a8 ^ a4 ^ a1; -- UInt32 aE = a8 ^ a4 ^ a2; -+ const UInt32 a1 = InvS[i]; -+ const UInt32 a2 = xtime(a1); -+ const UInt32 a4 = xtime(a2); -+ const UInt32 a8 = xtime(a4); -+ const UInt32 a9 = a8 ^ a1; -+ const UInt32 aB = a8 ^ a2 ^ a1; -+ const UInt32 aD = a8 ^ a4 ^ a1; -+ const UInt32 aE = a8 ^ a4 ^ a2; - DD(0)[i] = Ui32(aE, a9, aD, aB); - DD(1)[i] = Ui32(aB, aE, a9, aD); - DD(2)[i] = Ui32(aD, aB, aE, a9); -@@ -116,7 +116,7 @@ void AesGenTables(void) - - { - AES_CODE_FUNC d = AesCbc_Decode; -- #ifndef _SFX -+ #ifndef Z7_SFX - AES_CODE_FUNC e = AesCbc_Encode; - AES_CODE_FUNC c = AesCtr_Code; - UInt32 flags = 0; -@@ -126,10 +126,10 @@ void AesGenTables(void) - if (CPU_IsSupported_AES()) - { - // #pragma message ("AES HW") -- _PRF(printf("\n===AES HW\n")); -+ PRF(printf("\n===AES HW\n")); - d = AesCbc_Decode_HW; - -- #ifndef _SFX -+ #ifndef Z7_SFX - e = AesCbc_Encode_HW; - c = AesCtr_Code_HW; - flags = k_Aes_SupportedFunctions_HW; -@@ -138,9 +138,9 @@ void AesGenTables(void) - #ifdef MY_CPU_X86_OR_AMD64 - if (CPU_IsSupported_VAES_AVX2()) - { -- _PRF(printf("\n===vaes avx2\n")); -+ PRF(printf("\n===vaes avx2\n")); - d = AesCbc_Decode_HW_256; -- #ifndef _SFX -+ #ifndef Z7_SFX - c = AesCtr_Code_HW_256; - flags |= k_Aes_SupportedFunctions_HW_256; - #endif -@@ -150,7 +150,7 @@ void AesGenTables(void) - #endif - - g_AesCbc_Decode = d; -- #ifndef _SFX -+ #ifndef Z7_SFX - g_AesCbc_Encode = e; - g_AesCtr_Code = c; - g_Aes_SupportedFunctions_Flags = flags; -@@ -194,7 +194,7 @@ void AesGenTables(void) - #define FD(i, x) InvS[gb(x, m[(i - x) & 3])] - #define FD4(i) dest[i] = Ui32(FD(i, 0), FD(i, 1), FD(i, 2), FD(i, 3)) ^ w[i]; - --void MY_FAST_CALL Aes_SetKey_Enc(UInt32 *w, const Byte *key, unsigned keySize) -+void Z7_FASTCALL Aes_SetKey_Enc(UInt32 *w, const Byte *key, unsigned keySize) - { - unsigned i, m; - const UInt32 *wLim; -@@ -230,7 +230,7 @@ void MY_FAST_CALL Aes_SetKey_Enc(UInt32 *w, const Byte *key, unsigned keySize) - while (++w != wLim); - } - --void MY_FAST_CALL Aes_SetKey_Dec(UInt32 *w, const Byte *key, unsigned keySize) -+void Z7_FASTCALL Aes_SetKey_Dec(UInt32 *w, const Byte *key, unsigned keySize) - { - unsigned i, num; - Aes_SetKey_Enc(w, key, keySize); -@@ -251,7 +251,7 @@ void MY_FAST_CALL Aes_SetKey_Dec(UInt32 *w, const Byte *key, unsigned keySize) - src and dest are pointers to 4 UInt32 words. - src and dest can point to same block */ - --// MY_FORCE_INLINE -+// Z7_FORCE_INLINE - static void Aes_Encode(const UInt32 *w, UInt32 *dest, const UInt32 *src) - { - UInt32 s[4]; -@@ -265,17 +265,20 @@ static void Aes_Encode(const UInt32 *w, UInt32 *dest, const UInt32 *src) - w += 4; - for (;;) - { -- HT16(m, s, 0); -+ HT16(m, s, 0) - if (--numRounds2 == 0) - break; -- HT16(s, m, 4); -+ HT16(s, m, 4) - w += 8; - } - w += 4; -- FT4(0); FT4(1); FT4(2); FT4(3); -+ FT4(0) -+ FT4(1) -+ FT4(2) -+ FT4(3) - } - --MY_FORCE_INLINE -+Z7_FORCE_INLINE - static void Aes_Decode(const UInt32 *w, UInt32 *dest, const UInt32 *src) - { - UInt32 s[4]; -@@ -289,12 +292,15 @@ static void Aes_Decode(const UInt32 *w, UInt32 *dest, const UInt32 *src) - for (;;) - { - w -= 8; -- HD16(m, s, 4); -+ HD16(m, s, 4) - if (--numRounds2 == 0) - break; -- HD16(s, m, 0); -+ HD16(s, m, 0) - } -- FD4(0); FD4(1); FD4(2); FD4(3); -+ FD4(0) -+ FD4(1) -+ FD4(2) -+ FD4(3) - } - - void AesCbc_Init(UInt32 *p, const Byte *iv) -@@ -304,7 +310,7 @@ void AesCbc_Init(UInt32 *p, const Byte *iv) - p[i] = GetUi32(iv + i * 4); - } - --void MY_FAST_CALL AesCbc_Encode(UInt32 *p, Byte *data, size_t numBlocks) -+void Z7_FASTCALL AesCbc_Encode(UInt32 *p, Byte *data, size_t numBlocks) - { - for (; numBlocks != 0; numBlocks--, data += AES_BLOCK_SIZE) - { -@@ -315,14 +321,14 @@ void MY_FAST_CALL AesCbc_Encode(UInt32 *p, Byte *data, size_t numBlocks) - - Aes_Encode(p + 4, p, p); - -- SetUi32(data, p[0]); -- SetUi32(data + 4, p[1]); -- SetUi32(data + 8, p[2]); -- SetUi32(data + 12, p[3]); -+ SetUi32(data, p[0]) -+ SetUi32(data + 4, p[1]) -+ SetUi32(data + 8, p[2]) -+ SetUi32(data + 12, p[3]) - } - } - --void MY_FAST_CALL AesCbc_Decode(UInt32 *p, Byte *data, size_t numBlocks) -+void Z7_FASTCALL AesCbc_Decode(UInt32 *p, Byte *data, size_t numBlocks) - { - UInt32 in[4], out[4]; - for (; numBlocks != 0; numBlocks--, data += AES_BLOCK_SIZE) -@@ -334,10 +340,10 @@ void MY_FAST_CALL AesCbc_Decode(UInt32 *p, Byte *data, size_t numBlocks) - - Aes_Decode(p + 4, out, in); - -- SetUi32(data, p[0] ^ out[0]); -- SetUi32(data + 4, p[1] ^ out[1]); -- SetUi32(data + 8, p[2] ^ out[2]); -- SetUi32(data + 12, p[3] ^ out[3]); -+ SetUi32(data, p[0] ^ out[0]) -+ SetUi32(data + 4, p[1] ^ out[1]) -+ SetUi32(data + 8, p[2] ^ out[2]) -+ SetUi32(data + 12, p[3] ^ out[3]) - - p[0] = in[0]; - p[1] = in[1]; -@@ -346,7 +352,7 @@ void MY_FAST_CALL AesCbc_Decode(UInt32 *p, Byte *data, size_t numBlocks) - } - } - --void MY_FAST_CALL AesCtr_Code(UInt32 *p, Byte *data, size_t numBlocks) -+void Z7_FASTCALL AesCtr_Code(UInt32 *p, Byte *data, size_t numBlocks) - { - for (; numBlocks != 0; numBlocks--) - { -@@ -360,7 +366,7 @@ void MY_FAST_CALL AesCtr_Code(UInt32 *p, Byte *data, size_t numBlocks) - - for (i = 0; i < 4; i++, data += 4) - { -- UInt32 t = temp[i]; -+ const UInt32 t = temp[i]; - - #ifdef MY_CPU_LE_UNALIGN - *((UInt32 *)(void *)data) ^= t; -@@ -373,3 +379,15 @@ void MY_FAST_CALL AesCtr_Code(UInt32 *p, Byte *data, size_t numBlocks) - } - } - } -+ -+#undef xtime -+#undef Ui32 -+#undef gb0 -+#undef gb1 -+#undef gb2 -+#undef gb3 -+#undef gb -+#undef TT -+#undef DD -+#undef USE_HW_AES -+#undef PRF -diff --git a/src/lzma/Aes.h b/src/lzma/Aes.h -index 2aa225642..7f0182ac0 100644 ---- a/src/lzma/Aes.h -+++ b/src/lzma/Aes.h -@@ -1,8 +1,8 @@ - /* Aes.h -- AES encryption / decryption --2018-04-28 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - --#ifndef __AES_H --#define __AES_H -+#ifndef ZIP7_INC_AES_H -+#define ZIP7_INC_AES_H - - #include "7zTypes.h" - -@@ -20,19 +20,19 @@ void AesGenTables(void); - - /* aes - 16-byte aligned pointer to keyMode+roundKeys sequence */ - /* keySize = 16 or 24 or 32 (bytes) */ --typedef void (MY_FAST_CALL *AES_SET_KEY_FUNC)(UInt32 *aes, const Byte *key, unsigned keySize); --void MY_FAST_CALL Aes_SetKey_Enc(UInt32 *aes, const Byte *key, unsigned keySize); --void MY_FAST_CALL Aes_SetKey_Dec(UInt32 *aes, const Byte *key, unsigned keySize); -+typedef void (Z7_FASTCALL *AES_SET_KEY_FUNC)(UInt32 *aes, const Byte *key, unsigned keySize); -+void Z7_FASTCALL Aes_SetKey_Enc(UInt32 *aes, const Byte *key, unsigned keySize); -+void Z7_FASTCALL Aes_SetKey_Dec(UInt32 *aes, const Byte *key, unsigned keySize); - - /* ivAes - 16-byte aligned pointer to iv+keyMode+roundKeys sequence: UInt32[AES_NUM_IVMRK_WORDS] */ - void AesCbc_Init(UInt32 *ivAes, const Byte *iv); /* iv size is AES_BLOCK_SIZE */ - - /* data - 16-byte aligned pointer to data */ - /* numBlocks - the number of 16-byte blocks in data array */ --typedef void (MY_FAST_CALL *AES_CODE_FUNC)(UInt32 *ivAes, Byte *data, size_t numBlocks); -+typedef void (Z7_FASTCALL *AES_CODE_FUNC)(UInt32 *ivAes, Byte *data, size_t numBlocks); - - extern AES_CODE_FUNC g_AesCbc_Decode; --#ifndef _SFX -+#ifndef Z7_SFX - extern AES_CODE_FUNC g_AesCbc_Encode; - extern AES_CODE_FUNC g_AesCtr_Code; - #define k_Aes_SupportedFunctions_HW (1 << 2) -@@ -41,19 +41,19 @@ extern UInt32 g_Aes_SupportedFunctions_Flags; - #endif - - --#define DECLARE__AES_CODE_FUNC(funcName) \ -- void MY_FAST_CALL funcName(UInt32 *ivAes, Byte *data, size_t numBlocks); -+#define Z7_DECLARE_AES_CODE_FUNC(funcName) \ -+ void Z7_FASTCALL funcName(UInt32 *ivAes, Byte *data, size_t numBlocks); - --DECLARE__AES_CODE_FUNC (AesCbc_Encode) --DECLARE__AES_CODE_FUNC (AesCbc_Decode) --DECLARE__AES_CODE_FUNC (AesCtr_Code) -+Z7_DECLARE_AES_CODE_FUNC (AesCbc_Encode) -+Z7_DECLARE_AES_CODE_FUNC (AesCbc_Decode) -+Z7_DECLARE_AES_CODE_FUNC (AesCtr_Code) - --DECLARE__AES_CODE_FUNC (AesCbc_Encode_HW) --DECLARE__AES_CODE_FUNC (AesCbc_Decode_HW) --DECLARE__AES_CODE_FUNC (AesCtr_Code_HW) -+Z7_DECLARE_AES_CODE_FUNC (AesCbc_Encode_HW) -+Z7_DECLARE_AES_CODE_FUNC (AesCbc_Decode_HW) -+Z7_DECLARE_AES_CODE_FUNC (AesCtr_Code_HW) - --DECLARE__AES_CODE_FUNC (AesCbc_Decode_HW_256) --DECLARE__AES_CODE_FUNC (AesCtr_Code_HW_256) -+Z7_DECLARE_AES_CODE_FUNC (AesCbc_Decode_HW_256) -+Z7_DECLARE_AES_CODE_FUNC (AesCtr_Code_HW_256) - - EXTERN_C_END - -diff --git a/src/lzma/AesOpt.c b/src/lzma/AesOpt.c -index 8be8ff69d..cfa6413f4 100644 ---- a/src/lzma/AesOpt.c -+++ b/src/lzma/AesOpt.c -@@ -1,39 +1,33 @@ - /* AesOpt.c -- AES optimized code for x86 AES hardware instructions --2021-04-01 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -+#include "Aes.h" - #include "CpuArch.h" - - #ifdef MY_CPU_X86_OR_AMD64 - -- #if defined(__clang__) -- #if __clang_major__ > 3 || (__clang_major__ == 3 && __clang_minor__ >= 8) -- #define USE_INTEL_AES -- #define ATTRIB_AES __attribute__((__target__("aes"))) -- #if (__clang_major__ >= 8) -- #define USE_INTEL_VAES -- #define ATTRIB_VAES __attribute__((__target__("aes,vaes,avx2"))) -- #endif -- #endif -- #elif defined(__GNUC__) -- #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4) -- #define USE_INTEL_AES -- #ifndef __AES__ -- #define ATTRIB_AES __attribute__((__target__("aes"))) -- #endif -- #if (__GNUC__ >= 8) -- #define USE_INTEL_VAES -- #define ATTRIB_VAES __attribute__((__target__("aes,vaes,avx2"))) -- #endif -- #endif -- #elif defined(__INTEL_COMPILER) -+ #if defined(__INTEL_COMPILER) - #if (__INTEL_COMPILER >= 1110) - #define USE_INTEL_AES - #if (__INTEL_COMPILER >= 1900) - #define USE_INTEL_VAES - #endif - #endif -+ #elif defined(__clang__) && (__clang_major__ > 3 || __clang_major__ == 3 && __clang_minor__ >= 8) \ -+ || defined(__GNUC__) && (__GNUC__ > 4 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4) -+ #define USE_INTEL_AES -+ #if !defined(__AES__) -+ #define ATTRIB_AES __attribute__((__target__("aes"))) -+ #endif -+ #if defined(__clang__) && (__clang_major__ >= 8) \ -+ || defined(__GNUC__) && (__GNUC__ >= 8) -+ #define USE_INTEL_VAES -+ #if !defined(__AES__) || !defined(__VAES__) || !defined(__AVX__) || !defined(__AVX2__) -+ #define ATTRIB_VAES __attribute__((__target__("aes,vaes,avx,avx2"))) -+ #endif -+ #endif - #elif defined(_MSC_VER) - #if (_MSC_VER > 1500) || (_MSC_FULL_VER >= 150030729) - #define USE_INTEL_AES -@@ -56,12 +50,15 @@ - #include - - #ifndef USE_INTEL_VAES --#define AES_TYPE_keys __m128i --#define AES_TYPE_data __m128i -+#define AES_TYPE_keys UInt32 -+#define AES_TYPE_data Byte -+// #define AES_TYPE_keys __m128i -+// #define AES_TYPE_data __m128i - #endif - - #define AES_FUNC_START(name) \ -- void MY_FAST_CALL name(__m128i *p, __m128i *data, size_t numBlocks) -+ void Z7_FASTCALL name(UInt32 *ivAes, Byte *data8, size_t numBlocks) -+ // void Z7_FASTCALL name(__m128i *p, __m128i *data, size_t numBlocks) - - #define AES_FUNC_START2(name) \ - AES_FUNC_START (name); \ -@@ -69,14 +66,16 @@ ATTRIB_AES \ - AES_FUNC_START (name) - - #define MM_OP(op, dest, src) dest = op(dest, src); --#define MM_OP_m(op, src) MM_OP(op, m, src); -+#define MM_OP_m(op, src) MM_OP(op, m, src) - --#define MM_XOR( dest, src) MM_OP(_mm_xor_si128, dest, src); --#define AVX_XOR(dest, src) MM_OP(_mm256_xor_si256, dest, src); -+#define MM_XOR( dest, src) MM_OP(_mm_xor_si128, dest, src) -+#define AVX_XOR(dest, src) MM_OP(_mm256_xor_si256, dest, src) - - - AES_FUNC_START2 (AesCbc_Encode_HW) - { -+ __m128i *p = (__m128i *)(void *)ivAes; -+ __m128i *data = (__m128i *)(void *)data8; - __m128i m = *p; - const __m128i k0 = p[2]; - const __m128i k1 = p[3]; -@@ -86,17 +85,17 @@ AES_FUNC_START2 (AesCbc_Encode_HW) - UInt32 r = numRounds2; - const __m128i *w = p + 4; - __m128i temp = *data; -- MM_XOR (temp, k0); -- MM_XOR (m, temp); -- MM_OP_m (_mm_aesenc_si128, k1); -+ MM_XOR (temp, k0) -+ MM_XOR (m, temp) -+ MM_OP_m (_mm_aesenc_si128, k1) - do - { -- MM_OP_m (_mm_aesenc_si128, w[0]); -- MM_OP_m (_mm_aesenc_si128, w[1]); -+ MM_OP_m (_mm_aesenc_si128, w[0]) -+ MM_OP_m (_mm_aesenc_si128, w[1]) - w += 2; - } - while (--r); -- MM_OP_m (_mm_aesenclast_si128, w[0]); -+ MM_OP_m (_mm_aesenclast_si128, w[0]) - *data = m; - } - *p = m; -@@ -104,14 +103,14 @@ AES_FUNC_START2 (AesCbc_Encode_HW) - - - #define WOP_1(op) --#define WOP_2(op) WOP_1 (op) op (m1, 1); --#define WOP_3(op) WOP_2 (op) op (m2, 2); --#define WOP_4(op) WOP_3 (op) op (m3, 3); -+#define WOP_2(op) WOP_1 (op) op (m1, 1) -+#define WOP_3(op) WOP_2 (op) op (m2, 2) -+#define WOP_4(op) WOP_3 (op) op (m3, 3) - #ifdef MY_CPU_AMD64 --#define WOP_5(op) WOP_4 (op) op (m4, 4); --#define WOP_6(op) WOP_5 (op) op (m5, 5); --#define WOP_7(op) WOP_6 (op) op (m6, 6); --#define WOP_8(op) WOP_7 (op) op (m7, 7); -+#define WOP_5(op) WOP_4 (op) op (m4, 4) -+#define WOP_6(op) WOP_5 (op) op (m5, 5) -+#define WOP_7(op) WOP_6 (op) op (m6, 6) -+#define WOP_8(op) WOP_7 (op) op (m7, 7) - #endif - /* - #define WOP_9(op) WOP_8 (op) op (m8, 8); -@@ -130,20 +129,20 @@ AES_FUNC_START2 (AesCbc_Encode_HW) - #define WOP_M1 WOP_4 - #endif - --#define WOP(op) op (m0, 0); WOP_M1(op) -+#define WOP(op) op (m0, 0) WOP_M1(op) - - --#define DECLARE_VAR(reg, ii) __m128i reg -+#define DECLARE_VAR(reg, ii) __m128i reg; - #define LOAD_data( reg, ii) reg = data[ii]; - #define STORE_data( reg, ii) data[ii] = reg; - #if (NUM_WAYS > 1) --#define XOR_data_M1(reg, ii) MM_XOR (reg, data[ii- 1]); -+#define XOR_data_M1(reg, ii) MM_XOR (reg, data[ii- 1]) - #endif - --#define AVX__DECLARE_VAR(reg, ii) __m256i reg --#define AVX__LOAD_data( reg, ii) reg = ((const __m256i *)(const void *)data)[ii]; --#define AVX__STORE_data( reg, ii) ((__m256i *)(void *)data)[ii] = reg; --#define AVX__XOR_data_M1(reg, ii) AVX_XOR (reg, (((const __m256i *)(const void *)(data - 1))[ii])); -+#define AVX_DECLARE_VAR(reg, ii) __m256i reg; -+#define AVX_LOAD_data( reg, ii) reg = ((const __m256i *)(const void *)data)[ii]; -+#define AVX_STORE_data( reg, ii) ((__m256i *)(void *)data)[ii] = reg; -+#define AVX_XOR_data_M1(reg, ii) AVX_XOR (reg, (((const __m256i *)(const void *)(data - 1))[ii])) - - #define MM_OP_key(op, reg) MM_OP(op, reg, key); - -@@ -154,23 +153,23 @@ AES_FUNC_START2 (AesCbc_Encode_HW) - #define AES_XOR( reg, ii) MM_OP_key (_mm_xor_si128, reg) - - --#define AVX__AES_DEC( reg, ii) MM_OP_key (_mm256_aesdec_epi128, reg) --#define AVX__AES_DEC_LAST( reg, ii) MM_OP_key (_mm256_aesdeclast_epi128, reg) --#define AVX__AES_ENC( reg, ii) MM_OP_key (_mm256_aesenc_epi128, reg) --#define AVX__AES_ENC_LAST( reg, ii) MM_OP_key (_mm256_aesenclast_epi128, reg) --#define AVX__AES_XOR( reg, ii) MM_OP_key (_mm256_xor_si256, reg) -+#define AVX_AES_DEC( reg, ii) MM_OP_key (_mm256_aesdec_epi128, reg) -+#define AVX_AES_DEC_LAST( reg, ii) MM_OP_key (_mm256_aesdeclast_epi128, reg) -+#define AVX_AES_ENC( reg, ii) MM_OP_key (_mm256_aesenc_epi128, reg) -+#define AVX_AES_ENC_LAST( reg, ii) MM_OP_key (_mm256_aesenclast_epi128, reg) -+#define AVX_AES_XOR( reg, ii) MM_OP_key (_mm256_xor_si256, reg) - --#define CTR_START(reg, ii) MM_OP (_mm_add_epi64, ctr, one); reg = ctr; --#define CTR_END( reg, ii) MM_XOR (data[ii], reg); -+#define CTR_START(reg, ii) MM_OP (_mm_add_epi64, ctr, one) reg = ctr; -+#define CTR_END( reg, ii) MM_XOR (data[ii], reg) - --#define AVX__CTR_START(reg, ii) MM_OP (_mm256_add_epi64, ctr2, two); reg = _mm256_xor_si256(ctr2, key); --#define AVX__CTR_END( reg, ii) AVX_XOR (((__m256i *)(void *)data)[ii], reg); -+#define AVX_CTR_START(reg, ii) MM_OP (_mm256_add_epi64, ctr2, two) reg = _mm256_xor_si256(ctr2, key); -+#define AVX_CTR_END( reg, ii) AVX_XOR (((__m256i *)(void *)data)[ii], reg) - - #define WOP_KEY(op, n) { \ - const __m128i key = w[n]; \ - WOP(op); } - --#define AVX__WOP_KEY(op, n) { \ -+#define AVX_WOP_KEY(op, n) { \ - const __m256i key = w[n]; \ - WOP(op); } - -@@ -218,6 +217,8 @@ AES_FUNC_START2 (AesCbc_Encode_HW) - - AES_FUNC_START2 (AesCbc_Decode_HW) - { -+ __m128i *p = (__m128i *)(void *)ivAes; -+ __m128i *data = (__m128i *)(void *)data8; - __m128i iv = *p; - const __m128i *wStart = p + *(const UInt32 *)(p + 1) * 2 + 2 - 1; - const __m128i *dataEnd; -@@ -228,7 +229,7 @@ AES_FUNC_START2 (AesCbc_Decode_HW) - const __m128i *w = wStart; - - WOP (DECLARE_VAR) -- WOP (LOAD_data); -+ WOP (LOAD_data) - WOP_KEY (AES_XOR, 1) - - do -@@ -239,10 +240,10 @@ AES_FUNC_START2 (AesCbc_Decode_HW) - while (w != p); - WOP_KEY (AES_DEC_LAST, 0) - -- MM_XOR (m0, iv); -+ MM_XOR (m0, iv) - WOP_M1 (XOR_data_M1) - iv = data[NUM_WAYS - 1]; -- WOP (STORE_data); -+ WOP (STORE_data) - } - WIDE_LOOP_END - -@@ -252,15 +253,15 @@ AES_FUNC_START2 (AesCbc_Decode_HW) - __m128i m = _mm_xor_si128 (w[2], *data); - do - { -- MM_OP_m (_mm_aesdec_si128, w[1]); -- MM_OP_m (_mm_aesdec_si128, w[0]); -+ MM_OP_m (_mm_aesdec_si128, w[1]) -+ MM_OP_m (_mm_aesdec_si128, w[0]) - w -= 2; - } - while (w != p); -- MM_OP_m (_mm_aesdec_si128, w[1]); -- MM_OP_m (_mm_aesdeclast_si128, w[0]); -+ MM_OP_m (_mm_aesdec_si128, w[1]) -+ MM_OP_m (_mm_aesdeclast_si128, w[0]) - -- MM_XOR (m, iv); -+ MM_XOR (m, iv) - iv = *data; - *data = m; - } -@@ -271,6 +272,8 @@ AES_FUNC_START2 (AesCbc_Decode_HW) - - AES_FUNC_START2 (AesCtr_Code_HW) - { -+ __m128i *p = (__m128i *)(void *)ivAes; -+ __m128i *data = (__m128i *)(void *)data8; - __m128i ctr = *p; - UInt32 numRoundsMinus2 = *(const UInt32 *)(p + 1) * 2 - 1; - const __m128i *dataEnd; -@@ -283,7 +286,7 @@ AES_FUNC_START2 (AesCtr_Code_HW) - const __m128i *w = p; - UInt32 r = numRoundsMinus2; - WOP (DECLARE_VAR) -- WOP (CTR_START); -+ WOP (CTR_START) - WOP_KEY (AES_XOR, 0) - w += 1; - do -@@ -294,7 +297,7 @@ AES_FUNC_START2 (AesCtr_Code_HW) - while (--r); - WOP_KEY (AES_ENC_LAST, 0) - -- WOP (CTR_END); -+ WOP (CTR_END) - } - WIDE_LOOP_END - -@@ -303,19 +306,19 @@ AES_FUNC_START2 (AesCtr_Code_HW) - UInt32 numRounds2 = *(const UInt32 *)(p - 2 + 1) - 1; - const __m128i *w = p; - __m128i m; -- MM_OP (_mm_add_epi64, ctr, one); -+ MM_OP (_mm_add_epi64, ctr, one) - m = _mm_xor_si128 (ctr, p[0]); - w += 1; - do - { -- MM_OP_m (_mm_aesenc_si128, w[0]); -- MM_OP_m (_mm_aesenc_si128, w[1]); -+ MM_OP_m (_mm_aesenc_si128, w[0]) -+ MM_OP_m (_mm_aesenc_si128, w[1]) - w += 2; - } - while (--numRounds2); -- MM_OP_m (_mm_aesenc_si128, w[0]); -- MM_OP_m (_mm_aesenclast_si128, w[1]); -- MM_XOR (*data, m); -+ MM_OP_m (_mm_aesenc_si128, w[0]) -+ MM_OP_m (_mm_aesenclast_si128, w[1]) -+ MM_XOR (*data, m) - } - - p[-2] = ctr; -@@ -325,17 +328,58 @@ AES_FUNC_START2 (AesCtr_Code_HW) - - #ifdef USE_INTEL_VAES - -+/* -+GCC before 2013-Jun: -+ : -+ #ifdef __AVX__ -+ #include -+ #endif -+GCC after 2013-Jun: -+ : -+ #include -+CLANG 3.8+: -+{ -+ : -+ #if !defined(_MSC_VER) || defined(__AVX__) -+ #include -+ #endif -+ -+ if (the compiler is clang for Windows and if global arch is not set for __AVX__) -+ [ if (defined(_MSC_VER) && !defined(__AVX__)) ] -+ { -+ doesn't include -+ and we have 2 ways to fix it: -+ 1) we can define required __AVX__ before -+ or -+ 2) we can include after -+ } -+} -+ -+If we include manually for GCC/CLANG, it's -+required that must be included before . -+*/ -+ -+/* - #if defined(__clang__) && defined(_MSC_VER) --#define __SSE4_2__ --#define __AES__ - #define __AVX__ - #define __AVX2__ - #define __VAES__ --#define __AVX512F__ --#define __AVX512VL__ - #endif -+*/ - - #include -+#if defined(__clang__) && defined(_MSC_VER) -+ #if !defined(__AVX__) -+ #include -+ #endif -+ #if !defined(__AVX2__) -+ #include -+ #endif -+ #if !defined(__VAES__) -+ #include -+ #endif -+#endif // __clang__ && _MSC_VER -+ - - #define VAES_FUNC_START2(name) \ - AES_FUNC_START (name); \ -@@ -344,6 +388,8 @@ AES_FUNC_START (name) - - VAES_FUNC_START2 (AesCbc_Decode_HW_256) - { -+ __m128i *p = (__m128i *)(void *)ivAes; -+ __m128i *data = (__m128i *)(void *)data8; - __m128i iv = *p; - const __m128i *dataEnd; - UInt32 numRounds = *(const UInt32 *)(p + 1) * 2 + 1; -@@ -353,22 +399,22 @@ VAES_FUNC_START2 (AesCbc_Decode_HW_256) - { - const __m256i *w = keys + numRounds - 2; - -- WOP (AVX__DECLARE_VAR) -- WOP (AVX__LOAD_data); -- AVX__WOP_KEY (AVX__AES_XOR, 1) -+ WOP (AVX_DECLARE_VAR) -+ WOP (AVX_LOAD_data) -+ AVX_WOP_KEY (AVX_AES_XOR, 1) - - do - { -- AVX__WOP_KEY (AVX__AES_DEC, 0) -+ AVX_WOP_KEY (AVX_AES_DEC, 0) - w--; - } - while (w != keys); -- AVX__WOP_KEY (AVX__AES_DEC_LAST, 0) -+ AVX_WOP_KEY (AVX_AES_DEC_LAST, 0) - -- AVX_XOR (m0, _mm256_setr_m128i(iv, data[0])); -- WOP_M1 (AVX__XOR_data_M1) -+ AVX_XOR (m0, _mm256_setr_m128i(iv, data[0])) -+ WOP_M1 (AVX_XOR_data_M1) - iv = data[NUM_WAYS * 2 - 1]; -- WOP (AVX__STORE_data); -+ WOP (AVX_STORE_data) - } - WIDE_LOOP_END_AVX(;) - -@@ -378,15 +424,15 @@ VAES_FUNC_START2 (AesCbc_Decode_HW_256) - __m128i m = _mm_xor_si128 (w[2], *data); - do - { -- MM_OP_m (_mm_aesdec_si128, w[1]); -- MM_OP_m (_mm_aesdec_si128, w[0]); -+ MM_OP_m (_mm_aesdec_si128, w[1]) -+ MM_OP_m (_mm_aesdec_si128, w[0]) - w -= 2; - } - while (w != p); -- MM_OP_m (_mm_aesdec_si128, w[1]); -- MM_OP_m (_mm_aesdeclast_si128, w[0]); -+ MM_OP_m (_mm_aesdec_si128, w[1]) -+ MM_OP_m (_mm_aesdeclast_si128, w[0]) - -- MM_XOR (m, iv); -+ MM_XOR (m, iv) - iv = *data; - *data = m; - } -@@ -403,18 +449,20 @@ AVX2: _mm256_add_epi64 : vpaddq ymm, ymm, ymm - _mm256_broadcastsi128_si256 : vbroadcasti128 - */ - --#define AVX__CTR_LOOP_START \ -+#define AVX_CTR_LOOP_START \ - ctr2 = _mm256_setr_m128i(_mm_sub_epi64(ctr, one), ctr); \ - two = _mm256_setr_m128i(one, one); \ - two = _mm256_add_epi64(two, two); \ - - // two = _mm256_setr_epi64x(2, 0, 2, 0); - --#define AVX__CTR_LOOP_ENC \ -+#define AVX_CTR_LOOP_ENC \ - ctr = _mm256_extracti128_si256 (ctr2, 1); \ - - VAES_FUNC_START2 (AesCtr_Code_HW_256) - { -+ __m128i *p = (__m128i *)(void *)ivAes; -+ __m128i *data = (__m128i *)(void *)data8; - __m128i ctr = *p; - UInt32 numRounds = *(const UInt32 *)(p + 1) * 2 + 1; - const __m128i *dataEnd; -@@ -422,44 +470,44 @@ VAES_FUNC_START2 (AesCtr_Code_HW_256) - __m256i ctr2, two; - p += 2; - -- WIDE_LOOP_START_AVX (AVX__CTR_LOOP_START) -+ WIDE_LOOP_START_AVX (AVX_CTR_LOOP_START) - { - const __m256i *w = keys; - UInt32 r = numRounds - 2; -- WOP (AVX__DECLARE_VAR) -- AVX__WOP_KEY (AVX__CTR_START, 0); -+ WOP (AVX_DECLARE_VAR) -+ AVX_WOP_KEY (AVX_CTR_START, 0) - - w += 1; - do - { -- AVX__WOP_KEY (AVX__AES_ENC, 0) -+ AVX_WOP_KEY (AVX_AES_ENC, 0) - w += 1; - } - while (--r); -- AVX__WOP_KEY (AVX__AES_ENC_LAST, 0) -+ AVX_WOP_KEY (AVX_AES_ENC_LAST, 0) - -- WOP (AVX__CTR_END); -+ WOP (AVX_CTR_END) - } -- WIDE_LOOP_END_AVX (AVX__CTR_LOOP_ENC) -+ WIDE_LOOP_END_AVX (AVX_CTR_LOOP_ENC) - - SINGLE_LOOP - { - UInt32 numRounds2 = *(const UInt32 *)(p - 2 + 1) - 1; - const __m128i *w = p; - __m128i m; -- MM_OP (_mm_add_epi64, ctr, one); -+ MM_OP (_mm_add_epi64, ctr, one) - m = _mm_xor_si128 (ctr, p[0]); - w += 1; - do - { -- MM_OP_m (_mm_aesenc_si128, w[0]); -- MM_OP_m (_mm_aesenc_si128, w[1]); -+ MM_OP_m (_mm_aesenc_si128, w[0]) -+ MM_OP_m (_mm_aesenc_si128, w[1]) - w += 2; - } - while (--numRounds2); -- MM_OP_m (_mm_aesenc_si128, w[0]); -- MM_OP_m (_mm_aesenclast_si128, w[1]); -- MM_XOR (*data, m); -+ MM_OP_m (_mm_aesenc_si128, w[0]) -+ MM_OP_m (_mm_aesenclast_si128, w[1]) -+ MM_XOR (*data, m) - } - - p[-2] = ctr; -@@ -477,7 +525,7 @@ VAES_FUNC_START2 (AesCtr_Code_HW_256) - #define AES_TYPE_data Byte - - #define AES_FUNC_START(name) \ -- void MY_FAST_CALL name(UInt32 *p, Byte *data, size_t numBlocks) \ -+ void Z7_FASTCALL name(UInt32 *p, Byte *data, size_t numBlocks) \ - - #define AES_COMPAT_STUB(name) \ - AES_FUNC_START(name); \ -@@ -496,8 +544,8 @@ AES_COMPAT_STUB (AesCtr_Code) - #pragma message("VAES HW_SW stub was used") - - #define VAES_COMPAT_STUB(name) \ -- void MY_FAST_CALL name ## _256(UInt32 *p, Byte *data, size_t numBlocks); \ -- void MY_FAST_CALL name ## _256(UInt32 *p, Byte *data, size_t numBlocks) \ -+ void Z7_FASTCALL name ## _256(UInt32 *p, Byte *data, size_t numBlocks); \ -+ void Z7_FASTCALL name ## _256(UInt32 *p, Byte *data, size_t numBlocks) \ - { name((AES_TYPE_keys *)(void *)p, (AES_TYPE_data *)(void *)data, numBlocks); } - - VAES_COMPAT_STUB (AesCbc_Decode_HW) -@@ -551,7 +599,8 @@ VAES_COMPAT_STUB (AesCtr_Code_HW) - typedef uint8x16_t v128; - - #define AES_FUNC_START(name) \ -- void MY_FAST_CALL name(v128 *p, v128 *data, size_t numBlocks) -+ void Z7_FASTCALL name(UInt32 *ivAes, Byte *data8, size_t numBlocks) -+ // void Z7_FASTCALL name(v128 *p, v128 *data, size_t numBlocks) - - #define AES_FUNC_START2(name) \ - AES_FUNC_START (name); \ -@@ -559,18 +608,20 @@ ATTRIB_AES \ - AES_FUNC_START (name) - - #define MM_OP(op, dest, src) dest = op(dest, src); --#define MM_OP_m(op, src) MM_OP(op, m, src); -+#define MM_OP_m(op, src) MM_OP(op, m, src) - #define MM_OP1_m(op) m = op(m); - --#define MM_XOR( dest, src) MM_OP(veorq_u8, dest, src); --#define MM_XOR_m( src) MM_XOR(m, src); -+#define MM_XOR( dest, src) MM_OP(veorq_u8, dest, src) -+#define MM_XOR_m( src) MM_XOR(m, src) - --#define AES_E_m(k) MM_OP_m (vaeseq_u8, k); --#define AES_E_MC_m(k) AES_E_m (k); MM_OP1_m(vaesmcq_u8); -+#define AES_E_m(k) MM_OP_m (vaeseq_u8, k) -+#define AES_E_MC_m(k) AES_E_m (k) MM_OP1_m(vaesmcq_u8) - - - AES_FUNC_START2 (AesCbc_Encode_HW) - { -+ v128 *p = (v128*)(void*)ivAes; -+ v128 *data = (v128*)(void*)data8; - v128 m = *p; - const v128 k0 = p[2]; - const v128 k1 = p[3]; -@@ -608,7 +659,7 @@ AES_FUNC_START2 (AesCbc_Encode_HW) - AES_E_MC_m (p[14]) - } - } -- AES_E_m (k_z1); -+ AES_E_m (k_z1) - MM_XOR_m (k_z0); - *data = m; - } -@@ -617,44 +668,44 @@ AES_FUNC_START2 (AesCbc_Encode_HW) - - - #define WOP_1(op) --#define WOP_2(op) WOP_1 (op) op (m1, 1); --#define WOP_3(op) WOP_2 (op) op (m2, 2); --#define WOP_4(op) WOP_3 (op) op (m3, 3); --#define WOP_5(op) WOP_4 (op) op (m4, 4); --#define WOP_6(op) WOP_5 (op) op (m5, 5); --#define WOP_7(op) WOP_6 (op) op (m6, 6); --#define WOP_8(op) WOP_7 (op) op (m7, 7); -+#define WOP_2(op) WOP_1 (op) op (m1, 1) -+#define WOP_3(op) WOP_2 (op) op (m2, 2) -+#define WOP_4(op) WOP_3 (op) op (m3, 3) -+#define WOP_5(op) WOP_4 (op) op (m4, 4) -+#define WOP_6(op) WOP_5 (op) op (m5, 5) -+#define WOP_7(op) WOP_6 (op) op (m6, 6) -+#define WOP_8(op) WOP_7 (op) op (m7, 7) - - #define NUM_WAYS 8 - #define WOP_M1 WOP_8 - --#define WOP(op) op (m0, 0); WOP_M1(op) -+#define WOP(op) op (m0, 0) WOP_M1(op) - --#define DECLARE_VAR(reg, ii) v128 reg -+#define DECLARE_VAR(reg, ii) v128 reg; - #define LOAD_data( reg, ii) reg = data[ii]; - #define STORE_data( reg, ii) data[ii] = reg; - #if (NUM_WAYS > 1) --#define XOR_data_M1(reg, ii) MM_XOR (reg, data[ii- 1]); -+#define XOR_data_M1(reg, ii) MM_XOR (reg, data[ii- 1]) - #endif - --#define MM_OP_key(op, reg) MM_OP (op, reg, key); -+#define MM_OP_key(op, reg) MM_OP (op, reg, key) - --#define AES_D_m(k) MM_OP_m (vaesdq_u8, k); --#define AES_D_IMC_m(k) AES_D_m (k); MM_OP1_m (vaesimcq_u8); -+#define AES_D_m(k) MM_OP_m (vaesdq_u8, k) -+#define AES_D_IMC_m(k) AES_D_m (k) MM_OP1_m (vaesimcq_u8) - - #define AES_XOR( reg, ii) MM_OP_key (veorq_u8, reg) - #define AES_D( reg, ii) MM_OP_key (vaesdq_u8, reg) - #define AES_E( reg, ii) MM_OP_key (vaeseq_u8, reg) - --#define AES_D_IMC( reg, ii) AES_D (reg, ii); reg = vaesimcq_u8(reg) --#define AES_E_MC( reg, ii) AES_E (reg, ii); reg = vaesmcq_u8(reg) -+#define AES_D_IMC( reg, ii) AES_D (reg, ii) reg = vaesimcq_u8(reg); -+#define AES_E_MC( reg, ii) AES_E (reg, ii) reg = vaesmcq_u8(reg); - --#define CTR_START(reg, ii) MM_OP (vaddq_u64, ctr, one); reg = vreinterpretq_u8_u64(ctr); --#define CTR_END( reg, ii) MM_XOR (data[ii], reg); -+#define CTR_START(reg, ii) MM_OP (vaddq_u64, ctr, one) reg = vreinterpretq_u8_u64(ctr); -+#define CTR_END( reg, ii) MM_XOR (data[ii], reg) - - #define WOP_KEY(op, n) { \ - const v128 key = w[n]; \ -- WOP(op); } -+ WOP(op) } - - #define WIDE_LOOP_START \ - dataEnd = data + numBlocks; \ -@@ -672,6 +723,8 @@ AES_FUNC_START2 (AesCbc_Encode_HW) - - AES_FUNC_START2 (AesCbc_Decode_HW) - { -+ v128 *p = (v128*)(void*)ivAes; -+ v128 *data = (v128*)(void*)data8; - v128 iv = *p; - const v128 *wStart = p + ((size_t)*(const UInt32 *)(p + 1)) * 2; - const v128 *dataEnd; -@@ -681,7 +734,7 @@ AES_FUNC_START2 (AesCbc_Decode_HW) - { - const v128 *w = wStart; - WOP (DECLARE_VAR) -- WOP (LOAD_data); -+ WOP (LOAD_data) - WOP_KEY (AES_D_IMC, 2) - do - { -@@ -695,7 +748,7 @@ AES_FUNC_START2 (AesCbc_Decode_HW) - MM_XOR (m0, iv); - WOP_M1 (XOR_data_M1) - iv = data[NUM_WAYS - 1]; -- WOP (STORE_data); -+ WOP (STORE_data) - } - WIDE_LOOP_END - -@@ -724,6 +777,8 @@ AES_FUNC_START2 (AesCbc_Decode_HW) - - AES_FUNC_START2 (AesCtr_Code_HW) - { -+ v128 *p = (v128*)(void*)ivAes; -+ v128 *data = (v128*)(void*)data8; - uint64x2_t ctr = vreinterpretq_u64_u8(*p); - const v128 *wEnd = p + ((size_t)*(const UInt32 *)(p + 1)) * 2; - const v128 *dataEnd; -@@ -735,7 +790,7 @@ AES_FUNC_START2 (AesCtr_Code_HW) - { - const v128 *w = p; - WOP (DECLARE_VAR) -- WOP (CTR_START); -+ WOP (CTR_START) - do - { - WOP_KEY (AES_E_MC, 0) -@@ -746,7 +801,7 @@ AES_FUNC_START2 (AesCtr_Code_HW) - WOP_KEY (AES_E_MC, 0) - WOP_KEY (AES_E, 1) - WOP_KEY (AES_XOR, 2) -- WOP (CTR_END); -+ WOP (CTR_END) - } - WIDE_LOOP_END - -@@ -762,10 +817,10 @@ AES_FUNC_START2 (AesCtr_Code_HW) - w += 2; - } - while (w != wEnd); -- AES_E_MC_m (w[0]); -- AES_E_m (w[1]); -- MM_XOR_m (w[2]); -- CTR_END (m, 0); -+ AES_E_MC_m (w[0]) -+ AES_E_m (w[1]) -+ MM_XOR_m (w[2]) -+ CTR_END (m, 0) - } - - p[-2] = vreinterpretq_u8_u64(ctr); -@@ -774,3 +829,12 @@ AES_FUNC_START2 (AesCtr_Code_HW) - #endif // USE_HW_AES - - #endif // MY_CPU_ARM_OR_ARM64 -+ -+#undef NUM_WAYS -+#undef WOP_M1 -+#undef WOP -+#undef DECLARE_VAR -+#undef LOAD_data -+#undef STORE_data -+#undef USE_INTEL_AES -+#undef USE_HW_AES -diff --git a/src/lzma/Alloc.c b/src/lzma/Alloc.c -index d1af76c5c..d841bf20a 100644 ---- a/src/lzma/Alloc.c -+++ b/src/lzma/Alloc.c -@@ -1,38 +1,54 @@ - /* Alloc.c -- Memory allocation functions --2021-07-13 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - --#include -- - #ifdef _WIN32 --#include -+#include "7zWindows.h" - #endif - #include - - #include "Alloc.h" - --/* #define _SZ_ALLOC_DEBUG */ -+#ifdef _WIN32 -+#ifdef Z7_LARGE_PAGES -+#if defined(__clang__) || defined(__GNUC__) -+typedef void (*Z7_voidFunction)(void); -+#define MY_CAST_FUNC (Z7_voidFunction) -+#elif defined(_MSC_VER) && _MSC_VER > 1920 -+#define MY_CAST_FUNC (void *) -+// #pragma warning(disable : 4191) // 'type cast': unsafe conversion from 'FARPROC' to 'void (__cdecl *)()' -+#else -+#define MY_CAST_FUNC -+#endif -+#endif // Z7_LARGE_PAGES -+#endif // _WIN32 -+ -+// #define SZ_ALLOC_DEBUG -+/* #define SZ_ALLOC_DEBUG */ - --/* use _SZ_ALLOC_DEBUG to debug alloc/free operations */ --#ifdef _SZ_ALLOC_DEBUG -+/* use SZ_ALLOC_DEBUG to debug alloc/free operations */ -+#ifdef SZ_ALLOC_DEBUG - -+#include - #include --int g_allocCount = 0; --int g_allocCountMid = 0; --int g_allocCountBig = 0; -+static int g_allocCount = 0; -+#ifdef _WIN32 -+static int g_allocCountMid = 0; -+static int g_allocCountBig = 0; -+#endif - - - #define CONVERT_INT_TO_STR(charType, tempSize) \ -- unsigned char temp[tempSize]; unsigned i = 0; \ -- while (val >= 10) { temp[i++] = (unsigned char)('0' + (unsigned)(val % 10)); val /= 10; } \ -+ char temp[tempSize]; unsigned i = 0; \ -+ while (val >= 10) { temp[i++] = (char)('0' + (unsigned)(val % 10)); val /= 10; } \ - *s++ = (charType)('0' + (unsigned)val); \ - while (i != 0) { i--; *s++ = temp[i]; } \ - *s = 0; - - static void ConvertUInt64ToString(UInt64 val, char *s) - { -- CONVERT_INT_TO_STR(char, 24); -+ CONVERT_INT_TO_STR(char, 24) - } - - #define GET_HEX_CHAR(t) ((char)(((t < 10) ? ('0' + t) : ('A' + (t - 10))))) -@@ -77,7 +93,7 @@ static void PrintAligned(const char *s, size_t align) - Print(s); - } - --static void PrintLn() -+static void PrintLn(void) - { - Print("\n"); - } -@@ -89,10 +105,10 @@ static void PrintHex(UInt64 v, size_t align) - PrintAligned(s, align); - } - --static void PrintDec(UInt64 v, size_t align) -+static void PrintDec(int v, size_t align) - { - char s[32]; -- ConvertUInt64ToString(v, s); -+ ConvertUInt64ToString((unsigned)v, s); - PrintAligned(s, align); - } - -@@ -102,12 +118,19 @@ static void PrintAddr(void *p) - } - - --#define PRINT_ALLOC(name, cnt, size, ptr) \ -+#define PRINT_REALLOC(name, cnt, size, ptr) { \ -+ Print(name " "); \ -+ if (!ptr) PrintDec(cnt++, 10); \ -+ PrintHex(size, 10); \ -+ PrintAddr(ptr); \ -+ PrintLn(); } -+ -+#define PRINT_ALLOC(name, cnt, size, ptr) { \ - Print(name " "); \ - PrintDec(cnt++, 10); \ - PrintHex(size, 10); \ - PrintAddr(ptr); \ -- PrintLn(); -+ PrintLn(); } - - #define PRINT_FREE(name, cnt, ptr) if (ptr) { \ - Print(name " "); \ -@@ -117,7 +140,9 @@ static void PrintAddr(void *p) - - #else - -+#ifdef _WIN32 - #define PRINT_ALLOC(name, cnt, size, ptr) -+#endif - #define PRINT_FREE(name, cnt, ptr) - #define Print(s) - #define PrintLn() -@@ -127,16 +152,31 @@ static void PrintAddr(void *p) - #endif - - -+/* -+by specification: -+ malloc(non_NULL, 0) : returns NULL or a unique pointer value that can later be successfully passed to free() -+ realloc(NULL, size) : the call is equivalent to malloc(size) -+ realloc(non_NULL, 0) : the call is equivalent to free(ptr) -+ -+in main compilers: -+ malloc(0) : returns non_NULL -+ realloc(NULL, 0) : returns non_NULL -+ realloc(non_NULL, 0) : returns NULL -+*/ -+ - - void *MyAlloc(size_t size) - { - if (size == 0) - return NULL; -- PRINT_ALLOC("Alloc ", g_allocCount, size, NULL); -- #ifdef _SZ_ALLOC_DEBUG -+ // PRINT_ALLOC("Alloc ", g_allocCount, size, NULL) -+ #ifdef SZ_ALLOC_DEBUG - { - void *p = malloc(size); -- // PRINT_ALLOC("Alloc ", g_allocCount, size, p); -+ if (p) -+ { -+ PRINT_ALLOC("Alloc ", g_allocCount, size, p) -+ } - return p; - } - #else -@@ -146,33 +186,64 @@ void *MyAlloc(size_t size) - - void MyFree(void *address) - { -- PRINT_FREE("Free ", g_allocCount, address); -+ PRINT_FREE("Free ", g_allocCount, address) - - free(address); - } - -+void *MyRealloc(void *address, size_t size) -+{ -+ if (size == 0) -+ { -+ MyFree(address); -+ return NULL; -+ } -+ // PRINT_REALLOC("Realloc ", g_allocCount, size, address) -+ #ifdef SZ_ALLOC_DEBUG -+ { -+ void *p = realloc(address, size); -+ if (p) -+ { -+ PRINT_REALLOC("Realloc ", g_allocCount, size, address) -+ } -+ return p; -+ } -+ #else -+ return realloc(address, size); -+ #endif -+} -+ -+ - #ifdef _WIN32 - - void *MidAlloc(size_t size) - { - if (size == 0) - return NULL; -- -- PRINT_ALLOC("Alloc-Mid", g_allocCountMid, size, NULL); -- -+ #ifdef SZ_ALLOC_DEBUG -+ { -+ void *p = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE); -+ if (p) -+ { -+ PRINT_ALLOC("Alloc-Mid", g_allocCountMid, size, p) -+ } -+ return p; -+ } -+ #else - return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE); -+ #endif - } - - void MidFree(void *address) - { -- PRINT_FREE("Free-Mid", g_allocCountMid, address); -+ PRINT_FREE("Free-Mid", g_allocCountMid, address) - - if (!address) - return; - VirtualFree(address, 0, MEM_RELEASE); - } - --#ifdef _7ZIP_LARGE_PAGES -+#ifdef Z7_LARGE_PAGES - - #ifdef MEM_LARGE_PAGES - #define MY__MEM_LARGE_PAGES MEM_LARGE_PAGES -@@ -183,34 +254,35 @@ void MidFree(void *address) - extern - SIZE_T g_LargePageSize; - SIZE_T g_LargePageSize = 0; --typedef SIZE_T (WINAPI *GetLargePageMinimumP)(VOID); -+typedef SIZE_T (WINAPI *Func_GetLargePageMinimum)(VOID); - --#endif // _7ZIP_LARGE_PAGES -- --void SetLargePageSize() -+void SetLargePageSize(void) - { -- #ifdef _7ZIP_LARGE_PAGES -+ #ifdef Z7_LARGE_PAGES - SIZE_T size; -- GetLargePageMinimumP largePageMinimum = (GetLargePageMinimumP) -- GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetLargePageMinimum"); -- if (!largePageMinimum) -+ const -+ Func_GetLargePageMinimum fn = -+ (Func_GetLargePageMinimum) MY_CAST_FUNC GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), -+ "GetLargePageMinimum"); -+ if (!fn) - return; -- size = largePageMinimum(); -+ size = fn(); - if (size == 0 || (size & (size - 1)) != 0) - return; - g_LargePageSize = size; - #endif - } - -+#endif // Z7_LARGE_PAGES - - void *BigAlloc(size_t size) - { - if (size == 0) - return NULL; - -- PRINT_ALLOC("Alloc-Big", g_allocCountBig, size, NULL); -- -- #ifdef _7ZIP_LARGE_PAGES -+ PRINT_ALLOC("Alloc-Big", g_allocCountBig, size, NULL) -+ -+ #ifdef Z7_LARGE_PAGES - { - SIZE_T ps = g_LargePageSize; - if (ps != 0 && ps <= (1 << 30) && size > (ps / 2)) -@@ -220,38 +292,38 @@ void *BigAlloc(size_t size) - size2 = (size + ps) & ~ps; - if (size2 >= size) - { -- void *res = VirtualAlloc(NULL, size2, MEM_COMMIT | MY__MEM_LARGE_PAGES, PAGE_READWRITE); -- if (res) -- return res; -+ void *p = VirtualAlloc(NULL, size2, MEM_COMMIT | MY__MEM_LARGE_PAGES, PAGE_READWRITE); -+ if (p) -+ { -+ PRINT_ALLOC("Alloc-BM ", g_allocCountMid, size2, p) -+ return p; -+ } - } - } - } - #endif - -- return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE); -+ return MidAlloc(size); - } - - void BigFree(void *address) - { -- PRINT_FREE("Free-Big", g_allocCountBig, address); -- -- if (!address) -- return; -- VirtualFree(address, 0, MEM_RELEASE); -+ PRINT_FREE("Free-Big", g_allocCountBig, address) -+ MidFree(address); - } - --#endif -+#endif // _WIN32 - - --static void *SzAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p); return MyAlloc(size); } --static void SzFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p); MyFree(address); } -+static void *SzAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p) return MyAlloc(size); } -+static void SzFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p) MyFree(address); } - const ISzAlloc g_Alloc = { SzAlloc, SzFree }; - - #ifdef _WIN32 --static void *SzMidAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p); return MidAlloc(size); } --static void SzMidFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p); MidFree(address); } --static void *SzBigAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p); return BigAlloc(size); } --static void SzBigFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p); BigFree(address); } -+static void *SzMidAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p) return MidAlloc(size); } -+static void SzMidFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p) MidFree(address); } -+static void *SzBigAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p) return BigAlloc(size); } -+static void SzBigFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p) BigFree(address); } - const ISzAlloc g_MidAlloc = { SzMidAlloc, SzMidFree }; - const ISzAlloc g_BigAlloc = { SzBigAlloc, SzBigFree }; - #endif -@@ -334,7 +406,7 @@ static void *SzAlignedAlloc(ISzAllocPtr pp, size_t size) - void *p; - void *pAligned; - size_t newSize; -- UNUSED_VAR(pp); -+ UNUSED_VAR(pp) - - /* also we can allocate additional dummy ALLOC_ALIGN_SIZE bytes after aligned - block to prevent cache line sharing with another allocated blocks */ -@@ -362,7 +434,7 @@ static void *SzAlignedAlloc(ISzAllocPtr pp, size_t size) - #else - - void *p; -- UNUSED_VAR(pp); -+ UNUSED_VAR(pp) - if (posix_memalign(&p, ALLOC_ALIGN_SIZE, size)) - return NULL; - -@@ -377,7 +449,7 @@ static void *SzAlignedAlloc(ISzAllocPtr pp, size_t size) - - static void SzAlignedFree(ISzAllocPtr pp, void *address) - { -- UNUSED_VAR(pp); -+ UNUSED_VAR(pp) - #ifndef USE_posix_memalign - if (address) - MyFree(((void **)address)[-1]); -@@ -401,7 +473,7 @@ const ISzAlloc g_AlignedAlloc = { SzAlignedAlloc, SzAlignedFree }; - - static void *AlignOffsetAlloc_Alloc(ISzAllocPtr pp, size_t size) - { -- CAlignOffsetAlloc *p = CONTAINER_FROM_VTBL(pp, CAlignOffsetAlloc, vt); -+ const CAlignOffsetAlloc *p = Z7_CONTAINER_FROM_VTBL_CONST(pp, CAlignOffsetAlloc, vt); - void *adr; - void *pAligned; - size_t newSize; -@@ -447,7 +519,7 @@ static void AlignOffsetAlloc_Free(ISzAllocPtr pp, void *address) - { - if (address) - { -- CAlignOffsetAlloc *p = CONTAINER_FROM_VTBL(pp, CAlignOffsetAlloc, vt); -+ const CAlignOffsetAlloc *p = Z7_CONTAINER_FROM_VTBL_CONST(pp, CAlignOffsetAlloc, vt); - PrintLn(); - Print("- Aligned Free: "); - PrintLn(); -diff --git a/src/lzma/Alloc.h b/src/lzma/Alloc.h -index 3be2041eb..fac5b62fb 100644 ---- a/src/lzma/Alloc.h -+++ b/src/lzma/Alloc.h -@@ -1,19 +1,32 @@ - /* Alloc.h -- Memory allocation functions --2021-07-13 : Igor Pavlov : Public domain */ -+2023-03-04 : Igor Pavlov : Public domain */ - --#ifndef __COMMON_ALLOC_H --#define __COMMON_ALLOC_H -+#ifndef ZIP7_INC_ALLOC_H -+#define ZIP7_INC_ALLOC_H - - #include "7zTypes.h" - - EXTERN_C_BEGIN - -+/* -+ MyFree(NULL) : is allowed, as free(NULL) -+ MyAlloc(0) : returns NULL : but malloc(0) is allowed to return NULL or non_NULL -+ MyRealloc(NULL, 0) : returns NULL : but realloc(NULL, 0) is allowed to return NULL or non_NULL -+MyRealloc() is similar to realloc() for the following cases: -+ MyRealloc(non_NULL, 0) : returns NULL and always calls MyFree(ptr) -+ MyRealloc(NULL, non_ZERO) : returns NULL, if allocation failed -+ MyRealloc(non_NULL, non_ZERO) : returns NULL, if reallocation failed -+*/ -+ - void *MyAlloc(size_t size); - void MyFree(void *address); -+void *MyRealloc(void *address, size_t size); - - #ifdef _WIN32 - -+#ifdef Z7_LARGE_PAGES - void SetLargePageSize(void); -+#endif - - void *MidAlloc(size_t size); - void MidFree(void *address); -diff --git a/src/lzma/Bcj2.c b/src/lzma/Bcj2.c -index c7b956708..7cb57ad62 100644 ---- a/src/lzma/Bcj2.c -+++ b/src/lzma/Bcj2.c -@@ -1,29 +1,24 @@ - /* Bcj2.c -- BCJ2 Decoder (Converter for x86 code) --2021-02-09 : Igor Pavlov : Public domain */ -+2023-03-01 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - - #include "Bcj2.h" - #include "CpuArch.h" - --#define CProb UInt16 -- - #define kTopValue ((UInt32)1 << 24) --#define kNumModelBits 11 --#define kBitModelTotal (1 << kNumModelBits) -+#define kNumBitModelTotalBits 11 -+#define kBitModelTotal (1 << kNumBitModelTotalBits) - #define kNumMoveBits 5 - --#define _IF_BIT_0 ttt = *prob; bound = (p->range >> kNumModelBits) * ttt; if (p->code < bound) --#define _UPDATE_0 p->range = bound; *prob = (CProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); --#define _UPDATE_1 p->range -= bound; p->code -= bound; *prob = (CProb)(ttt - (ttt >> kNumMoveBits)); -+// UInt32 bcj2_stats[256 + 2][2]; - - void Bcj2Dec_Init(CBcj2Dec *p) - { - unsigned i; -- -- p->state = BCJ2_DEC_STATE_OK; -+ p->state = BCJ2_STREAM_RC; // BCJ2_DEC_STATE_OK; - p->ip = 0; -- p->temp[3] = 0; -+ p->temp = 0; - p->range = 0; - p->code = 0; - for (i = 0; i < sizeof(p->probs) / sizeof(p->probs[0]); i++) -@@ -32,217 +27,248 @@ void Bcj2Dec_Init(CBcj2Dec *p) - - SRes Bcj2Dec_Decode(CBcj2Dec *p) - { -+ UInt32 v = p->temp; -+ // const Byte *src; - if (p->range <= 5) - { -- p->state = BCJ2_DEC_STATE_OK; -+ UInt32 code = p->code; -+ p->state = BCJ2_DEC_STATE_ERROR; /* for case if we return SZ_ERROR_DATA; */ - for (; p->range != 5; p->range++) - { -- if (p->range == 1 && p->code != 0) -+ if (p->range == 1 && code != 0) - return SZ_ERROR_DATA; -- - if (p->bufs[BCJ2_STREAM_RC] == p->lims[BCJ2_STREAM_RC]) - { - p->state = BCJ2_STREAM_RC; - return SZ_OK; - } -- -- p->code = (p->code << 8) | *(p->bufs[BCJ2_STREAM_RC])++; -+ code = (code << 8) | *(p->bufs[BCJ2_STREAM_RC])++; -+ p->code = code; - } -- -- if (p->code == 0xFFFFFFFF) -+ if (code == 0xffffffff) - return SZ_ERROR_DATA; -- -- p->range = 0xFFFFFFFF; -+ p->range = 0xffffffff; - } -- else if (p->state >= BCJ2_DEC_STATE_ORIG_0) -+ // else - { -- while (p->state <= BCJ2_DEC_STATE_ORIG_3) -+ unsigned state = p->state; -+ // we check BCJ2_IS_32BIT_STREAM() here instead of check in the main loop -+ if (BCJ2_IS_32BIT_STREAM(state)) - { -- Byte *dest = p->dest; -- if (dest == p->destLim) -+ const Byte *cur = p->bufs[state]; -+ if (cur == p->lims[state]) - return SZ_OK; -- *dest = p->temp[(size_t)p->state - BCJ2_DEC_STATE_ORIG_0]; -- p->state++; -- p->dest = dest + 1; -+ p->bufs[state] = cur + 4; -+ { -+ const UInt32 ip = p->ip + 4; -+ v = GetBe32a(cur) - ip; -+ p->ip = ip; -+ } -+ state = BCJ2_DEC_STATE_ORIG_0; - } -- } -- -- /* -- if (BCJ2_IS_32BIT_STREAM(p->state)) -- { -- const Byte *cur = p->bufs[p->state]; -- if (cur == p->lims[p->state]) -- return SZ_OK; -- p->bufs[p->state] = cur + 4; -- -+ if ((unsigned)(state - BCJ2_DEC_STATE_ORIG_0) < 4) - { -- UInt32 val; -- Byte *dest; -- SizeT rem; -- -- p->ip += 4; -- val = GetBe32(cur) - p->ip; -- dest = p->dest; -- rem = p->destLim - dest; -- if (rem < 4) -+ Byte *dest = p->dest; -+ for (;;) - { -- SizeT i; -- SetUi32(p->temp, val); -- for (i = 0; i < rem; i++) -- dest[i] = p->temp[i]; -- p->dest = dest + rem; -- p->state = BCJ2_DEC_STATE_ORIG_0 + (unsigned)rem; -- return SZ_OK; -+ if (dest == p->destLim) -+ { -+ p->state = state; -+ p->temp = v; -+ return SZ_OK; -+ } -+ *dest++ = (Byte)v; -+ p->dest = dest; -+ if (++state == BCJ2_DEC_STATE_ORIG_3 + 1) -+ break; -+ v >>= 8; - } -- SetUi32(dest, val); -- p->temp[3] = (Byte)(val >> 24); -- p->dest = dest + 4; -- p->state = BCJ2_DEC_STATE_OK; - } - } -- */ - -+ // src = p->bufs[BCJ2_STREAM_MAIN]; - for (;;) - { -+ /* - if (BCJ2_IS_32BIT_STREAM(p->state)) - p->state = BCJ2_DEC_STATE_OK; - else -+ */ - { - if (p->range < kTopValue) - { - if (p->bufs[BCJ2_STREAM_RC] == p->lims[BCJ2_STREAM_RC]) - { - p->state = BCJ2_STREAM_RC; -+ p->temp = v; - return SZ_OK; - } - p->range <<= 8; - p->code = (p->code << 8) | *(p->bufs[BCJ2_STREAM_RC])++; - } -- - { - const Byte *src = p->bufs[BCJ2_STREAM_MAIN]; - const Byte *srcLim; -- Byte *dest; -- SizeT num = (SizeT)(p->lims[BCJ2_STREAM_MAIN] - src); -- -- if (num == 0) -+ Byte *dest = p->dest; - { -- p->state = BCJ2_STREAM_MAIN; -- return SZ_OK; -+ const SizeT rem = (SizeT)(p->lims[BCJ2_STREAM_MAIN] - src); -+ SizeT num = (SizeT)(p->destLim - dest); -+ if (num >= rem) -+ num = rem; -+ #define NUM_ITERS 4 -+ #if (NUM_ITERS & (NUM_ITERS - 1)) == 0 -+ num &= ~((SizeT)NUM_ITERS - 1); // if (NUM_ITERS == (1 << x)) -+ #else -+ num -= num % NUM_ITERS; // if (NUM_ITERS != (1 << x)) -+ #endif -+ srcLim = src + num; - } -- -- dest = p->dest; -- if (num > (SizeT)(p->destLim - dest)) -+ -+ #define NUM_SHIFT_BITS 24 -+ #define ONE_ITER(indx) { \ -+ const unsigned b = src[indx]; \ -+ *dest++ = (Byte)b; \ -+ v = (v << NUM_SHIFT_BITS) | b; \ -+ if (((b + (0x100 - 0xe8)) & 0xfe) == 0) break; \ -+ if (((v - (((UInt32)0x0f << (NUM_SHIFT_BITS)) + 0x80)) & \ -+ ((((UInt32)1 << (4 + NUM_SHIFT_BITS)) - 0x1) << 4)) == 0) break; \ -+ /* ++dest */; /* v = b; */ } -+ -+ if (src != srcLim) -+ for (;;) - { -- num = (SizeT)(p->destLim - dest); -- if (num == 0) -- { -- p->state = BCJ2_DEC_STATE_ORIG; -- return SZ_OK; -- } -+ /* The dependency chain of 2-cycle for (v) calculation is not big problem here. -+ But we can remove dependency chain with v = b in the end of loop. */ -+ ONE_ITER(0) -+ #if (NUM_ITERS > 1) -+ ONE_ITER(1) -+ #if (NUM_ITERS > 2) -+ ONE_ITER(2) -+ #if (NUM_ITERS > 3) -+ ONE_ITER(3) -+ #if (NUM_ITERS > 4) -+ ONE_ITER(4) -+ #if (NUM_ITERS > 5) -+ ONE_ITER(5) -+ #if (NUM_ITERS > 6) -+ ONE_ITER(6) -+ #if (NUM_ITERS > 7) -+ ONE_ITER(7) -+ #endif -+ #endif -+ #endif -+ #endif -+ #endif -+ #endif -+ #endif -+ -+ src += NUM_ITERS; -+ if (src == srcLim) -+ break; - } -- -- srcLim = src + num; - -- if (p->temp[3] == 0x0F && (src[0] & 0xF0) == 0x80) -- *dest = src[0]; -- else for (;;) -+ if (src == srcLim) -+ #if (NUM_ITERS > 1) -+ for (;;) -+ #endif - { -- Byte b = *src; -- *dest = b; -- if (b != 0x0F) -+ #if (NUM_ITERS > 1) -+ if (src == p->lims[BCJ2_STREAM_MAIN] || dest == p->destLim) -+ #endif - { -- if ((b & 0xFE) == 0xE8) -- break; -- dest++; -- if (++src != srcLim) -- continue; -- break; -+ const SizeT num = (SizeT)(src - p->bufs[BCJ2_STREAM_MAIN]); -+ p->bufs[BCJ2_STREAM_MAIN] = src; -+ p->dest = dest; -+ p->ip += (UInt32)num; -+ /* state BCJ2_STREAM_MAIN has more priority than BCJ2_STATE_ORIG */ -+ p->state = -+ src == p->lims[BCJ2_STREAM_MAIN] ? -+ (unsigned)BCJ2_STREAM_MAIN : -+ (unsigned)BCJ2_DEC_STATE_ORIG; -+ p->temp = v; -+ return SZ_OK; - } -- dest++; -- if (++src == srcLim) -- break; -- if ((*src & 0xF0) != 0x80) -- continue; -- *dest = *src; -- break; -+ #if (NUM_ITERS > 1) -+ ONE_ITER(0) -+ src++; -+ #endif - } -- -- num = (SizeT)(src - p->bufs[BCJ2_STREAM_MAIN]); -- -- if (src == srcLim) -+ - { -- p->temp[3] = src[-1]; -- p->bufs[BCJ2_STREAM_MAIN] = src; -+ const SizeT num = (SizeT)(dest - p->dest); -+ p->dest = dest; // p->dest += num; -+ p->bufs[BCJ2_STREAM_MAIN] += num; // = src; - p->ip += (UInt32)num; -- p->dest += num; -- p->state = -- p->bufs[BCJ2_STREAM_MAIN] == -- p->lims[BCJ2_STREAM_MAIN] ? -- (unsigned)BCJ2_STREAM_MAIN : -- (unsigned)BCJ2_DEC_STATE_ORIG; -- return SZ_OK; - } -- - { - UInt32 bound, ttt; -- CProb *prob; -- Byte b = src[0]; -- Byte prev = (Byte)(num == 0 ? p->temp[3] : src[-1]); -- -- p->temp[3] = b; -- p->bufs[BCJ2_STREAM_MAIN] = src + 1; -- num++; -- p->ip += (UInt32)num; -- p->dest += num; -- -- prob = p->probs + (unsigned)(b == 0xE8 ? 2 + (unsigned)prev : (b == 0xE9 ? 1 : 0)); -- -- _IF_BIT_0 -+ CBcj2Prob *prob; // unsigned index; -+ /* -+ prob = p->probs + (unsigned)((Byte)v == 0xe8 ? -+ 2 + (Byte)(v >> 8) : -+ ((v >> 5) & 1)); // ((Byte)v < 0xe8 ? 0 : 1)); -+ */ - { -- _UPDATE_0 -+ const unsigned c = ((v + 0x17) >> 6) & 1; -+ prob = p->probs + (unsigned) -+ (((0 - c) & (Byte)(v >> NUM_SHIFT_BITS)) + c + ((v >> 5) & 1)); -+ // (Byte) -+ // 8x->0 : e9->1 : xxe8->xx+2 -+ // 8x->0x100 : e9->0x101 : xxe8->xx -+ // (((0x100 - (e & ~v)) & (0x100 | (v >> 8))) + (e & v)); -+ // (((0x101 + (~e | v)) & (0x100 | (v >> 8))) + (e & v)); -+ } -+ ttt = *prob; -+ bound = (p->range >> kNumBitModelTotalBits) * ttt; -+ if (p->code < bound) -+ { -+ // bcj2_stats[prob - p->probs][0]++; -+ p->range = bound; -+ *prob = (CBcj2Prob)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); - continue; - } -- _UPDATE_1 -- -+ { -+ // bcj2_stats[prob - p->probs][1]++; -+ p->range -= bound; -+ p->code -= bound; -+ *prob = (CBcj2Prob)(ttt - (ttt >> kNumMoveBits)); -+ } - } - } - } -- - { -- UInt32 val; -- unsigned cj = (p->temp[3] == 0xE8) ? BCJ2_STREAM_CALL : BCJ2_STREAM_JUMP; -+ /* (v == 0xe8 ? 0 : 1) uses setcc instruction with additional zero register usage in x64 MSVC. */ -+ // const unsigned cj = ((Byte)v == 0xe8) ? BCJ2_STREAM_CALL : BCJ2_STREAM_JUMP; -+ const unsigned cj = (((v + 0x57) >> 6) & 1) + BCJ2_STREAM_CALL; - const Byte *cur = p->bufs[cj]; - Byte *dest; - SizeT rem; -- - if (cur == p->lims[cj]) - { - p->state = cj; - break; - } -- -- val = GetBe32(cur); -+ v = GetBe32a(cur); - p->bufs[cj] = cur + 4; -- -- p->ip += 4; -- val -= p->ip; -+ { -+ const UInt32 ip = p->ip + 4; -+ v -= ip; -+ p->ip = ip; -+ } - dest = p->dest; - rem = (SizeT)(p->destLim - dest); -- - if (rem < 4) - { -- p->temp[0] = (Byte)val; if (rem > 0) dest[0] = (Byte)val; val >>= 8; -- p->temp[1] = (Byte)val; if (rem > 1) dest[1] = (Byte)val; val >>= 8; -- p->temp[2] = (Byte)val; if (rem > 2) dest[2] = (Byte)val; val >>= 8; -- p->temp[3] = (Byte)val; -+ if ((unsigned)rem > 0) { dest[0] = (Byte)v; v >>= 8; -+ if ((unsigned)rem > 1) { dest[1] = (Byte)v; v >>= 8; -+ if ((unsigned)rem > 2) { dest[2] = (Byte)v; v >>= 8; }}} -+ p->temp = v; - p->dest = dest + rem; - p->state = BCJ2_DEC_STATE_ORIG_0 + (unsigned)rem; - break; - } -- -- SetUi32(dest, val); -- p->temp[3] = (Byte)(val >> 24); -+ SetUi32(dest, v) -+ v >>= 24; - p->dest = dest + 4; - } - } -@@ -252,6 +278,13 @@ SRes Bcj2Dec_Decode(CBcj2Dec *p) - p->range <<= 8; - p->code = (p->code << 8) | *(p->bufs[BCJ2_STREAM_RC])++; - } -- - return SZ_OK; - } -+ -+#undef NUM_ITERS -+#undef ONE_ITER -+#undef NUM_SHIFT_BITS -+#undef kTopValue -+#undef kNumBitModelTotalBits -+#undef kBitModelTotal -+#undef kNumMoveBits -diff --git a/src/lzma/Bcj2.h b/src/lzma/Bcj2.h -index 8824080ac..4575545b6 100644 ---- a/src/lzma/Bcj2.h -+++ b/src/lzma/Bcj2.h -@@ -1,8 +1,8 @@ --/* Bcj2.h -- BCJ2 Converter for x86 code --2014-11-10 : Igor Pavlov : Public domain */ -+/* Bcj2.h -- BCJ2 converter for x86 code (Branch CALL/JUMP variant2) -+2023-03-02 : Igor Pavlov : Public domain */ - --#ifndef __BCJ2_H --#define __BCJ2_H -+#ifndef ZIP7_INC_BCJ2_H -+#define ZIP7_INC_BCJ2_H - - #include "7zTypes.h" - -@@ -26,37 +26,68 @@ enum - BCJ2_DEC_STATE_ORIG_3, - - BCJ2_DEC_STATE_ORIG, -- BCJ2_DEC_STATE_OK -+ BCJ2_DEC_STATE_ERROR /* after detected data error */ - }; - - enum - { - BCJ2_ENC_STATE_ORIG = BCJ2_NUM_STREAMS, -- BCJ2_ENC_STATE_OK -+ BCJ2_ENC_STATE_FINISHED /* it's state after fully encoded stream */ - }; - - --#define BCJ2_IS_32BIT_STREAM(s) ((s) == BCJ2_STREAM_CALL || (s) == BCJ2_STREAM_JUMP) -+/* #define BCJ2_IS_32BIT_STREAM(s) ((s) == BCJ2_STREAM_CALL || (s) == BCJ2_STREAM_JUMP) */ -+#define BCJ2_IS_32BIT_STREAM(s) ((unsigned)((unsigned)(s) - (unsigned)BCJ2_STREAM_CALL) < 2) - - /* - CBcj2Dec / CBcj2Enc - bufs sizes: - BUF_SIZE(n) = lims[n] - bufs[n] --bufs sizes for BCJ2_STREAM_CALL and BCJ2_STREAM_JUMP must be mutliply of 4: -+bufs sizes for BCJ2_STREAM_CALL and BCJ2_STREAM_JUMP must be multiply of 4: - (BUF_SIZE(BCJ2_STREAM_CALL) & 3) == 0 - (BUF_SIZE(BCJ2_STREAM_JUMP) & 3) == 0 - */ - -+// typedef UInt32 CBcj2Prob; -+typedef UInt16 CBcj2Prob; -+ -+/* -+BCJ2 encoder / decoder internal requirements: -+ - If last bytes of stream contain marker (e8/e8/0f8x), then -+ there is also encoded symbol (0 : no conversion) in RC stream. -+ - One case of overlapped instructions is supported, -+ if last byte of converted instruction is (0f) and next byte is (8x): -+ marker [xx xx xx 0f] 8x -+ then the pair (0f 8x) is treated as marker. -+*/ -+ -+/* ---------- BCJ2 Decoder ---------- */ -+ - /* - CBcj2Dec: --dest is allowed to overlap with bufs[BCJ2_STREAM_MAIN], with the following conditions: -+(dest) is allowed to overlap with bufs[BCJ2_STREAM_MAIN], with the following conditions: - bufs[BCJ2_STREAM_MAIN] >= dest && -- bufs[BCJ2_STREAM_MAIN] - dest >= tempReserv + -+ bufs[BCJ2_STREAM_MAIN] - dest >= - BUF_SIZE(BCJ2_STREAM_CALL) + - BUF_SIZE(BCJ2_STREAM_JUMP) -- tempReserv = 0 : for first call of Bcj2Dec_Decode -- tempReserv = 4 : for any other calls of Bcj2Dec_Decode -- overlap with offset = 1 is not allowed -+ reserve = bufs[BCJ2_STREAM_MAIN] - dest - -+ ( BUF_SIZE(BCJ2_STREAM_CALL) + -+ BUF_SIZE(BCJ2_STREAM_JUMP) ) -+ and additional conditions: -+ if (it's first call of Bcj2Dec_Decode() after Bcj2Dec_Init()) -+ { -+ (reserve != 1) : if (ver < v23.00) -+ } -+ else // if there are more than one calls of Bcj2Dec_Decode() after Bcj2Dec_Init()) -+ { -+ (reserve >= 6) : if (ver < v23.00) -+ (reserve >= 4) : if (ver >= v23.00) -+ We need that (reserve) because after first call of Bcj2Dec_Decode(), -+ CBcj2Dec::temp can contain up to 4 bytes for writing to (dest). -+ } -+ (reserve == 0) is allowed, if we decode full stream via single call of Bcj2Dec_Decode(). -+ (reserve == 0) also is allowed in case of multi-call, if we use fixed buffers, -+ and (reserve) is calculated from full (final) sizes of all streams before first call. - */ - - typedef struct -@@ -68,21 +99,65 @@ typedef struct - - unsigned state; /* BCJ2_STREAM_MAIN has more priority than BCJ2_STATE_ORIG */ - -- UInt32 ip; -- Byte temp[4]; -+ UInt32 ip; /* property of starting base for decoding */ -+ UInt32 temp; /* Byte temp[4]; */ - UInt32 range; - UInt32 code; -- UInt16 probs[2 + 256]; -+ CBcj2Prob probs[2 + 256]; - } CBcj2Dec; - -+ -+/* Note: -+ Bcj2Dec_Init() sets (CBcj2Dec::ip = 0) -+ if (ip != 0) property is required, the caller must set CBcj2Dec::ip after Bcj2Dec_Init() -+*/ - void Bcj2Dec_Init(CBcj2Dec *p); - --/* Returns: SZ_OK or SZ_ERROR_DATA */ -+ -+/* Bcj2Dec_Decode(): -+ returns: -+ SZ_OK -+ SZ_ERROR_DATA : if data in 5 starting bytes of BCJ2_STREAM_RC stream are not correct -+*/ - SRes Bcj2Dec_Decode(CBcj2Dec *p); - --#define Bcj2Dec_IsFinished(_p_) ((_p_)->code == 0) -+/* To check that decoding was finished you can compare -+ sizes of processed streams with sizes known from another sources. -+ You must do at least one mandatory check from the two following options: -+ - the check for size of processed output (ORIG) stream. -+ - the check for size of processed input (MAIN) stream. -+ additional optional checks: -+ - the checks for processed sizes of all input streams (MAIN, CALL, JUMP, RC) -+ - the checks Bcj2Dec_IsMaybeFinished*() -+ also before actual decoding you can check that the -+ following condition is met for stream sizes: -+ ( size(ORIG) == size(MAIN) + size(CALL) + size(JUMP) ) -+*/ - -+/* (state == BCJ2_STREAM_MAIN) means that decoder is ready for -+ additional input data in BCJ2_STREAM_MAIN stream. -+ Note that (state == BCJ2_STREAM_MAIN) is allowed for non-finished decoding. -+*/ -+#define Bcj2Dec_IsMaybeFinished_state_MAIN(_p_) ((_p_)->state == BCJ2_STREAM_MAIN) - -+/* if the stream decoding was finished correctly, then range decoder -+ part of CBcj2Dec also was finished, and then (CBcj2Dec::code == 0). -+ Note that (CBcj2Dec::code == 0) is allowed for non-finished decoding. -+*/ -+#define Bcj2Dec_IsMaybeFinished_code(_p_) ((_p_)->code == 0) -+ -+/* use Bcj2Dec_IsMaybeFinished() only as additional check -+ after at least one mandatory check from the two following options: -+ - the check for size of processed output (ORIG) stream. -+ - the check for size of processed input (MAIN) stream. -+*/ -+#define Bcj2Dec_IsMaybeFinished(_p_) ( \ -+ Bcj2Dec_IsMaybeFinished_state_MAIN(_p_) && \ -+ Bcj2Dec_IsMaybeFinished_code(_p_)) -+ -+ -+ -+/* ---------- BCJ2 Encoder ---------- */ - - typedef enum - { -@@ -91,6 +166,91 @@ typedef enum - BCJ2_ENC_FINISH_MODE_END_STREAM - } EBcj2Enc_FinishMode; - -+/* -+ BCJ2_ENC_FINISH_MODE_CONTINUE: -+ process non finished encoding. -+ It notifies the encoder that additional further calls -+ can provide more input data (src) than provided by current call. -+ In that case the CBcj2Enc encoder still can move (src) pointer -+ up to (srcLim), but CBcj2Enc encoder can store some of the last -+ processed bytes (up to 4 bytes) from src to internal CBcj2Enc::temp[] buffer. -+ at return: -+ (CBcj2Enc::src will point to position that includes -+ processed data and data copied to (temp[]) buffer) -+ That data from (temp[]) buffer will be used in further calls. -+ -+ BCJ2_ENC_FINISH_MODE_END_BLOCK: -+ finish encoding of current block (ended at srcLim) without RC flushing. -+ at return: if (CBcj2Enc::state == BCJ2_ENC_STATE_ORIG) && -+ CBcj2Enc::src == CBcj2Enc::srcLim) -+ : it shows that block encoding was finished. And the encoder is -+ ready for new (src) data or for stream finish operation. -+ finished block means -+ { -+ CBcj2Enc has completed block encoding up to (srcLim). -+ (1 + 4 bytes) or (2 + 4 bytes) CALL/JUMP cortages will -+ not cross block boundary at (srcLim). -+ temporary CBcj2Enc buffer for (ORIG) src data is empty. -+ 3 output uncompressed streams (MAIN, CALL, JUMP) were flushed. -+ RC stream was not flushed. And RC stream will cross block boundary. -+ } -+ Note: some possible implementation of BCJ2 encoder could -+ write branch marker (e8/e8/0f8x) in one call of Bcj2Enc_Encode(), -+ and it could calculate symbol for RC in another call of Bcj2Enc_Encode(). -+ BCJ2 encoder uses ip/fileIp/fileSize/relatLimit values to calculate RC symbol. -+ And these CBcj2Enc variables can have different values in different Bcj2Enc_Encode() calls. -+ So caller must finish each block with BCJ2_ENC_FINISH_MODE_END_BLOCK -+ to ensure that RC symbol is calculated and written in proper block. -+ -+ BCJ2_ENC_FINISH_MODE_END_STREAM -+ finish encoding of stream (ended at srcLim) fully including RC flushing. -+ at return: if (CBcj2Enc::state == BCJ2_ENC_STATE_FINISHED) -+ : it shows that stream encoding was finished fully, -+ and all output streams were flushed fully. -+ also Bcj2Enc_IsFinished() can be called. -+*/ -+ -+ -+/* -+ 32-bit relative offset in JUMP/CALL commands is -+ - (mod 4 GiB) for 32-bit x86 code -+ - signed Int32 for 64-bit x86-64 code -+ BCJ2 encoder also does internal relative to absolute address conversions. -+ And there are 2 possible ways to do it: -+ before v23: we used 32-bit variables and (mod 4 GiB) conversion -+ since v23: we use 64-bit variables and (signed Int32 offset) conversion. -+ The absolute address condition for conversion in v23: -+ ((UInt64)((Int64)ip64 - (Int64)fileIp64 + 5 + (Int32)offset) < (UInt64)fileSize64) -+ note that if (fileSize64 > 2 GiB). there is difference between -+ old (mod 4 GiB) way (v22) and new (signed Int32 offset) way (v23). -+ And new (v23) way is more suitable to encode 64-bit x86-64 code for (fileSize64 > 2 GiB) cases. -+*/ -+ -+/* -+// for old (v22) way for conversion: -+typedef UInt32 CBcj2Enc_ip_unsigned; -+typedef Int32 CBcj2Enc_ip_signed; -+#define BCJ2_ENC_FileSize_MAX ((UInt32)1 << 31) -+*/ -+typedef UInt64 CBcj2Enc_ip_unsigned; -+typedef Int64 CBcj2Enc_ip_signed; -+ -+/* maximum size of file that can be used for conversion condition */ -+#define BCJ2_ENC_FileSize_MAX ((CBcj2Enc_ip_unsigned)0 - 2) -+ -+/* default value of fileSize64_minus1 variable that means -+ that absolute address limitation will not be used */ -+#define BCJ2_ENC_FileSizeField_UNLIMITED ((CBcj2Enc_ip_unsigned)0 - 1) -+ -+/* calculate value that later can be set to CBcj2Enc::fileSize64_minus1 */ -+#define BCJ2_ENC_GET_FileSizeField_VAL_FROM_FileSize(fileSize) \ -+ ((CBcj2Enc_ip_unsigned)(fileSize) - 1) -+ -+/* set CBcj2Enc::fileSize64_minus1 variable from size of file */ -+#define Bcj2Enc_SET_FileSize(p, fileSize) \ -+ (p)->fileSize64_minus1 = BCJ2_ENC_GET_FileSizeField_VAL_FROM_FileSize(fileSize); -+ -+ - typedef struct - { - Byte *bufs[BCJ2_NUM_STREAMS]; -@@ -101,45 +261,71 @@ typedef struct - unsigned state; - EBcj2Enc_FinishMode finishMode; - -- Byte prevByte; -+ Byte context; -+ Byte flushRem; -+ Byte isFlushState; - - Byte cache; - UInt32 range; - UInt64 low; - UInt64 cacheSize; -+ -+ // UInt32 context; // for marker version, it can include marker flag. - -- UInt32 ip; -- -- /* 32-bit ralative offset in JUMP/CALL commands is -- - (mod 4 GB) in 32-bit mode -- - signed Int32 in 64-bit mode -- We use (mod 4 GB) check for fileSize. -- Use fileSize up to 2 GB, if you want to support 32-bit and 64-bit code conversion. */ -- UInt32 fileIp; -- UInt32 fileSize; /* (fileSize <= ((UInt32)1 << 31)), 0 means no_limit */ -- UInt32 relatLimit; /* (relatLimit <= ((UInt32)1 << 31)), 0 means desable_conversion */ -+ /* (ip64) and (fileIp64) correspond to virtual source stream position -+ that doesn't include data in temp[] */ -+ CBcj2Enc_ip_unsigned ip64; /* current (ip) position */ -+ CBcj2Enc_ip_unsigned fileIp64; /* start (ip) position of current file */ -+ CBcj2Enc_ip_unsigned fileSize64_minus1; /* size of current file (for conversion limitation) */ -+ UInt32 relatLimit; /* (relatLimit <= ((UInt32)1 << 31)) : 0 means disable_conversion */ -+ // UInt32 relatExcludeBits; - - UInt32 tempTarget; -- unsigned tempPos; -- Byte temp[4 * 2]; -- -- unsigned flushPos; -- -- UInt16 probs[2 + 256]; -+ unsigned tempPos; /* the number of bytes that were copied to temp[] buffer -+ (tempPos <= 4) outside of Bcj2Enc_Encode() */ -+ // Byte temp[4]; // for marker version -+ Byte temp[8]; -+ CBcj2Prob probs[2 + 256]; - } CBcj2Enc; - - void Bcj2Enc_Init(CBcj2Enc *p); --void Bcj2Enc_Encode(CBcj2Enc *p); - --#define Bcj2Enc_Get_InputData_Size(p) ((SizeT)((p)->srcLim - (p)->src) + (p)->tempPos) --#define Bcj2Enc_IsFinished(p) ((p)->flushPos == 5) - -+/* -+Bcj2Enc_Encode(): at exit: -+ p->State < BCJ2_NUM_STREAMS : we need more buffer space for output stream -+ (bufs[p->State] == lims[p->State]) -+ p->State == BCJ2_ENC_STATE_ORIG : we need more data in input src stream -+ (src == srcLim) -+ p->State == BCJ2_ENC_STATE_FINISHED : after fully encoded stream -+*/ -+void Bcj2Enc_Encode(CBcj2Enc *p); - --#define BCJ2_RELAT_LIMIT_NUM_BITS 26 --#define BCJ2_RELAT_LIMIT ((UInt32)1 << BCJ2_RELAT_LIMIT_NUM_BITS) -+/* Bcj2Enc encoder can look ahead for up 4 bytes of source stream. -+ CBcj2Enc::tempPos : is the number of bytes that were copied from input stream to temp[] buffer. -+ (CBcj2Enc::src) after Bcj2Enc_Encode() is starting position after -+ fully processed data and after data copied to temp buffer. -+ So if the caller needs to get real number of fully processed input -+ bytes (without look ahead data in temp buffer), -+ the caller must subtruct (CBcj2Enc::tempPos) value from processed size -+ value that is calculated based on current (CBcj2Enc::src): -+ cur_processed_pos = Calc_Big_Processed_Pos(enc.src)) - -+ Bcj2Enc_Get_AvailInputSize_in_Temp(&enc); -+*/ -+/* get the size of input data that was stored in temp[] buffer: */ -+#define Bcj2Enc_Get_AvailInputSize_in_Temp(p) ((p)->tempPos) - --/* limit for CBcj2Enc::fileSize variable */ --#define BCJ2_FileSize_MAX ((UInt32)1 << 31) -+#define Bcj2Enc_IsFinished(p) ((p)->flushRem == 0) -+ -+/* Note : the decoder supports overlapping of marker (0f 80). -+ But we can eliminate such overlapping cases by setting -+ the limit for relative offset conversion as -+ CBcj2Enc::relatLimit <= (0x0f << 24) == (240 MiB) -+*/ -+/* default value for CBcj2Enc::relatLimit */ -+#define BCJ2_ENC_RELAT_LIMIT_DEFAULT ((UInt32)0x0f << 24) -+#define BCJ2_ENC_RELAT_LIMIT_MAX ((UInt32)1 << 31) -+// #define BCJ2_RELAT_EXCLUDE_NUM_BITS 5 - - EXTERN_C_END - -diff --git a/src/lzma/Bcj2Enc.c b/src/lzma/Bcj2Enc.c -index 666303b90..9654d1d81 100644 ---- a/src/lzma/Bcj2Enc.c -+++ b/src/lzma/Bcj2Enc.c -@@ -1,60 +1,62 @@ --/* Bcj2Enc.c -- BCJ2 Encoder (Converter for x86 code) --2021-02-09 : Igor Pavlov : Public domain */ -+/* Bcj2Enc.c -- BCJ2 Encoder converter for x86 code (Branch CALL/JUMP variant2) -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - - /* #define SHOW_STAT */ -- - #ifdef SHOW_STAT - #include --#define PRF(x) x -+#define PRF2(s) printf("%s ip=%8x tempPos=%d src= %8x\n", s, (unsigned)p->ip64, p->tempPos, (unsigned)(p->srcLim - p->src)); - #else --#define PRF(x) -+#define PRF2(s) - #endif - --#include -- - #include "Bcj2.h" - #include "CpuArch.h" - --#define CProb UInt16 -- - #define kTopValue ((UInt32)1 << 24) --#define kNumModelBits 11 --#define kBitModelTotal (1 << kNumModelBits) -+#define kNumBitModelTotalBits 11 -+#define kBitModelTotal (1 << kNumBitModelTotalBits) - #define kNumMoveBits 5 - - void Bcj2Enc_Init(CBcj2Enc *p) - { - unsigned i; -- -- p->state = BCJ2_ENC_STATE_OK; -+ p->state = BCJ2_ENC_STATE_ORIG; - p->finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE; -- -- p->prevByte = 0; -- -+ p->context = 0; -+ p->flushRem = 5; -+ p->isFlushState = 0; - p->cache = 0; -- p->range = 0xFFFFFFFF; -+ p->range = 0xffffffff; - p->low = 0; - p->cacheSize = 1; -- -- p->ip = 0; -- -- p->fileIp = 0; -- p->fileSize = 0; -- p->relatLimit = BCJ2_RELAT_LIMIT; -- -+ p->ip64 = 0; -+ p->fileIp64 = 0; -+ p->fileSize64_minus1 = BCJ2_ENC_FileSizeField_UNLIMITED; -+ p->relatLimit = BCJ2_ENC_RELAT_LIMIT_DEFAULT; -+ // p->relatExcludeBits = 0; - p->tempPos = 0; -- -- p->flushPos = 0; -- - for (i = 0; i < sizeof(p->probs) / sizeof(p->probs[0]); i++) - p->probs[i] = kBitModelTotal >> 1; - } - --static BoolInt MY_FAST_CALL RangeEnc_ShiftLow(CBcj2Enc *p) -+// Z7_NO_INLINE -+Z7_FORCE_INLINE -+static BoolInt Bcj2_RangeEnc_ShiftLow(CBcj2Enc *p) - { -- if ((UInt32)p->low < (UInt32)0xFF000000 || (UInt32)(p->low >> 32) != 0) -+ const UInt32 low = (UInt32)p->low; -+ const unsigned high = (unsigned) -+ #if defined(Z7_MSC_VER_ORIGINAL) \ -+ && defined(MY_CPU_X86) \ -+ && defined(MY_CPU_LE) \ -+ && !defined(MY_CPU_64BIT) -+ // we try to rid of __aullshr() call in MSVS-x86 -+ (((const UInt32 *)&p->low)[1]); // [1] : for little-endian only -+ #else -+ (p->low >> 32); -+ #endif -+ if (low < (UInt32)0xff000000 || high != 0) - { - Byte *buf = p->bufs[BCJ2_STREAM_RC]; - do -@@ -65,247 +67,440 @@ static BoolInt MY_FAST_CALL RangeEnc_ShiftLow(CBcj2Enc *p) - p->bufs[BCJ2_STREAM_RC] = buf; - return True7z; - } -- *buf++ = (Byte)(p->cache + (Byte)(p->low >> 32)); -- p->cache = 0xFF; -+ *buf++ = (Byte)(p->cache + high); -+ p->cache = 0xff; - } - while (--p->cacheSize); - p->bufs[BCJ2_STREAM_RC] = buf; -- p->cache = (Byte)((UInt32)p->low >> 24); -+ p->cache = (Byte)(low >> 24); - } - p->cacheSize++; -- p->low = (UInt32)p->low << 8; -+ p->low = low << 8; - return False7z; - } - --static void Bcj2Enc_Encode_2(CBcj2Enc *p) --{ -- if (BCJ2_IS_32BIT_STREAM(p->state)) -+ -+/* -+We can use 2 alternative versions of code: -+1) non-marker version: -+ Byte CBcj2Enc::context -+ Byte temp[8]; -+ Last byte of marker (e8/e9/[0f]8x) can be written to temp[] buffer. -+ Encoder writes last byte of marker (e8/e9/[0f]8x) to dest, only in conjunction -+ with writing branch symbol to range coder in same Bcj2Enc_Encode_2() call. -+ -+2) marker version: -+ UInt32 CBcj2Enc::context -+ Byte CBcj2Enc::temp[4]; -+ MARKER_FLAG in CBcj2Enc::context shows that CBcj2Enc::context contains finded marker. -+ it's allowed that -+ one call of Bcj2Enc_Encode_2() writes last byte of marker (e8/e9/[0f]8x) to dest, -+ and another call of Bcj2Enc_Encode_2() does offset conversion. -+ So different values of (fileIp) and (fileSize) are possible -+ in these different Bcj2Enc_Encode_2() calls. -+ -+Also marker version requires additional if((v & MARKER_FLAG) == 0) check in main loop. -+So we use non-marker version. -+*/ -+ -+/* -+ Corner cases with overlap in multi-block. -+ before v23: there was one corner case, where converted instruction -+ could start in one sub-stream and finish in next sub-stream. -+ If multi-block (solid) encoding is used, -+ and BCJ2_ENC_FINISH_MODE_END_BLOCK is used for each sub-stream. -+ and (0f) is last byte of previous sub-stream -+ and (8x) is first byte of current sub-stream -+ then (0f 8x) pair is treated as marker by BCJ2 encoder and decoder. -+ BCJ2 encoder can converts 32-bit offset for that (0f 8x) cortage, -+ if that offset meets limit requirements. -+ If encoder allows 32-bit offset conversion for such overlap case, -+ then the data in 3 uncompressed BCJ2 streams for some sub-stream -+ can depend from data of previous sub-stream. -+ That corner case is not big problem, and it's rare case. -+ Since v23.00 we do additional check to prevent conversions in such overlap cases. -+*/ -+ -+/* -+ Bcj2Enc_Encode_2() output variables at exit: - { -- Byte *cur = p->bufs[p->state]; -- if (cur == p->lims[p->state]) -- return; -- SetBe32(cur, p->tempTarget); -- p->bufs[p->state] = cur + 4; -+ if (Bcj2Enc_Encode_2() exits with (p->state == BCJ2_ENC_STATE_ORIG)) -+ { -+ it means that encoder needs more input data. -+ if (p->srcLim == p->src) at exit, then -+ { -+ (p->finishMode != BCJ2_ENC_FINISH_MODE_END_STREAM) -+ all input data were read and processed, and we are ready for -+ new input data. -+ } -+ else -+ { -+ (p->srcLim != p->src) -+ (p->finishMode == BCJ2_ENC_FINISH_MODE_CONTINUE) -+ The encoder have found e8/e9/0f_8x marker, -+ and p->src points to last byte of that marker, -+ Bcj2Enc_Encode_2() needs more input data to get totally -+ 5 bytes (last byte of marker and 32-bit branch offset) -+ as continuous array starting from p->src. -+ (p->srcLim - p->src < 5) requirement is met after exit. -+ So non-processed resedue from p->src to p->srcLim is always less than 5 bytes. -+ } -+ } - } -+*/ - -- p->state = BCJ2_ENC_STATE_ORIG; -- -- for (;;) -+Z7_NO_INLINE -+static void Bcj2Enc_Encode_2(CBcj2Enc *p) -+{ -+ if (!p->isFlushState) - { -- if (p->range < kTopValue) -+ const Byte *src; -+ UInt32 v; - { -- if (RangeEnc_ShiftLow(p)) -- return; -- p->range <<= 8; -+ const unsigned state = p->state; -+ if (BCJ2_IS_32BIT_STREAM(state)) -+ { -+ Byte *cur = p->bufs[state]; -+ if (cur == p->lims[state]) -+ return; -+ SetBe32a(cur, p->tempTarget) -+ p->bufs[state] = cur + 4; -+ } - } -+ p->state = BCJ2_ENC_STATE_ORIG; // for main reason of exit -+ src = p->src; -+ v = p->context; -+ -+ // #define WRITE_CONTEXT p->context = v; // for marker version -+ #define WRITE_CONTEXT p->context = (Byte)v; -+ #define WRITE_CONTEXT_AND_SRC p->src = src; WRITE_CONTEXT - -+ for (;;) - { -+ // const Byte *src; -+ // UInt32 v; -+ CBcj2Enc_ip_unsigned ip; -+ if (p->range < kTopValue) -+ { -+ // to reduce register pressure and code size: we save and restore local variables. -+ WRITE_CONTEXT_AND_SRC -+ if (Bcj2_RangeEnc_ShiftLow(p)) -+ return; -+ p->range <<= 8; -+ src = p->src; -+ v = p->context; -+ } -+ // src = p->src; -+ // #define MARKER_FLAG ((UInt32)1 << 17) -+ // if ((v & MARKER_FLAG) == 0) // for marker version - { -- const Byte *src = p->src; - const Byte *srcLim; -- Byte *dest; -- SizeT num = (SizeT)(p->srcLim - src); -- -- if (p->finishMode == BCJ2_ENC_FINISH_MODE_CONTINUE) -+ Byte *dest = p->bufs[BCJ2_STREAM_MAIN]; - { -- if (num <= 4) -- return; -- num -= 4; -+ const SizeT remSrc = (SizeT)(p->srcLim - src); -+ SizeT rem = (SizeT)(p->lims[BCJ2_STREAM_MAIN] - dest); -+ if (rem >= remSrc) -+ rem = remSrc; -+ srcLim = src + rem; - } -- else if (num == 0) -- break; -- -- dest = p->bufs[BCJ2_STREAM_MAIN]; -- if (num > (SizeT)(p->lims[BCJ2_STREAM_MAIN] - dest)) -+ /* p->context contains context of previous byte: -+ bits [0 : 7] : src[-1], if (src) was changed in this call -+ bits [8 : 31] : are undefined for non-marker version -+ */ -+ // v = p->context; -+ #define NUM_SHIFT_BITS 24 -+ #define CONV_FLAG ((UInt32)1 << 16) -+ #define ONE_ITER { \ -+ b = src[0]; \ -+ *dest++ = (Byte)b; \ -+ v = (v << NUM_SHIFT_BITS) | b; \ -+ if (((b + (0x100 - 0xe8)) & 0xfe) == 0) break; \ -+ if (((v - (((UInt32)0x0f << (NUM_SHIFT_BITS)) + 0x80)) & \ -+ ((((UInt32)1 << (4 + NUM_SHIFT_BITS)) - 0x1) << 4)) == 0) break; \ -+ src++; if (src == srcLim) { break; } } -+ -+ if (src != srcLim) -+ for (;;) - { -- num = (SizeT)(p->lims[BCJ2_STREAM_MAIN] - dest); -- if (num == 0) -- { -- p->state = BCJ2_STREAM_MAIN; -- return; -- } -+ /* clang can generate ineffective code with setne instead of two jcc instructions. -+ we can use 2 iterations and external (unsigned b) to avoid that ineffective code genaration. */ -+ unsigned b; -+ ONE_ITER -+ ONE_ITER - } -- -- srcLim = src + num; -+ -+ ip = p->ip64 + (CBcj2Enc_ip_unsigned)(SizeT)(dest - p->bufs[BCJ2_STREAM_MAIN]); -+ p->bufs[BCJ2_STREAM_MAIN] = dest; -+ p->ip64 = ip; - -- if (p->prevByte == 0x0F && (src[0] & 0xF0) == 0x80) -- *dest = src[0]; -- else for (;;) -+ if (src == srcLim) - { -- Byte b = *src; -- *dest = b; -- if (b != 0x0F) -+ WRITE_CONTEXT_AND_SRC -+ if (src != p->srcLim) - { -- if ((b & 0xFE) == 0xE8) -- break; -- dest++; -- if (++src != srcLim) -- continue; -- break; -+ p->state = BCJ2_STREAM_MAIN; -+ return; - } -- dest++; -- if (++src == srcLim) -- break; -- if ((*src & 0xF0) != 0x80) -- continue; -- *dest = *src; -+ /* (p->src == p->srcLim) -+ (p->state == BCJ2_ENC_STATE_ORIG) */ -+ if (p->finishMode != BCJ2_ENC_FINISH_MODE_END_STREAM) -+ return; -+ /* (p->finishMode == BCJ2_ENC_FINISH_MODE_END_STREAM */ -+ // (p->flushRem == 5); -+ p->isFlushState = 1; - break; - } -- -- num = (SizeT)(src - p->src); -- -- if (src == srcLim) -- { -- p->prevByte = src[-1]; -- p->bufs[BCJ2_STREAM_MAIN] = dest; -- p->src = src; -- p->ip += (UInt32)num; -- continue; -- } -- -+ src++; -+ // p->src = src; -+ } -+ // ip = p->ip; // for marker version -+ /* marker was found */ -+ /* (v) contains marker that was found: -+ bits [NUM_SHIFT_BITS : NUM_SHIFT_BITS + 7] -+ : value of src[-2] : xx/xx/0f -+ bits [0 : 7] : value of src[-1] : e8/e9/8x -+ */ -+ { - { -- Byte context = (Byte)(num == 0 ? p->prevByte : src[-1]); -- BoolInt needConvert; -- -- p->bufs[BCJ2_STREAM_MAIN] = dest + 1; -- p->ip += (UInt32)num + 1; -- src++; -- -- needConvert = False7z; -- -+ #if NUM_SHIFT_BITS != 24 -+ v &= ~(UInt32)CONV_FLAG; -+ #endif -+ // UInt32 relat = 0; - if ((SizeT)(p->srcLim - src) >= 4) - { -- UInt32 relatVal = GetUi32(src); -- if ((p->fileSize == 0 || (UInt32)(p->ip + 4 + relatVal - p->fileIp) < p->fileSize) -- && ((relatVal + p->relatLimit) >> 1) < p->relatLimit) -- needConvert = True7z; -+ /* -+ if (relat != 0 || (Byte)v != 0xe8) -+ BoolInt isBigOffset = True7z; -+ */ -+ const UInt32 relat = GetUi32(src); -+ /* -+ #define EXCLUDE_FLAG ((UInt32)1 << 4) -+ #define NEED_CONVERT(rel) ((((rel) + EXCLUDE_FLAG) & (0 - EXCLUDE_FLAG * 2)) != 0) -+ if (p->relatExcludeBits != 0) -+ { -+ const UInt32 flag = (UInt32)1 << (p->relatExcludeBits - 1); -+ isBigOffset = (((relat + flag) & (0 - flag * 2)) != 0); -+ } -+ // isBigOffset = False7z; // for debug -+ */ -+ ip -= p->fileIp64; -+ // Use the following if check, if (ip) is 64-bit: -+ if (ip > (((v + 0x20) >> 5) & 1)) // 23.00 : we eliminate milti-block overlap for (Of 80) and (e8/e9) -+ if ((CBcj2Enc_ip_unsigned)((CBcj2Enc_ip_signed)ip + 4 + (Int32)relat) <= p->fileSize64_minus1) -+ if (((UInt32)(relat + p->relatLimit) >> 1) < p->relatLimit) -+ v |= CONV_FLAG; - } -- -+ else if (p->finishMode == BCJ2_ENC_FINISH_MODE_CONTINUE) - { -- UInt32 bound; -- unsigned ttt; -- Byte b = src[-1]; -- CProb *prob = p->probs + (unsigned)(b == 0xE8 ? 2 + (unsigned)context : (b == 0xE9 ? 1 : 0)); -- -- ttt = *prob; -- bound = (p->range >> kNumModelBits) * ttt; -- -- if (!needConvert) -+ // (p->srcLim - src < 4) -+ // /* -+ // for non-marker version -+ p->ip64--; // p->ip = ip - 1; -+ p->bufs[BCJ2_STREAM_MAIN]--; -+ src--; -+ v >>= NUM_SHIFT_BITS; -+ // (0 < p->srcLim - p->src <= 4) -+ // */ -+ // v |= MARKER_FLAG; // for marker version -+ /* (p->state == BCJ2_ENC_STATE_ORIG) */ -+ WRITE_CONTEXT_AND_SRC -+ return; -+ } -+ { -+ const unsigned c = ((v + 0x17) >> 6) & 1; -+ CBcj2Prob *prob = p->probs + (unsigned) -+ (((0 - c) & (Byte)(v >> NUM_SHIFT_BITS)) + c + ((v >> 5) & 1)); -+ /* -+ ((Byte)v == 0xe8 ? 2 + ((Byte)(v >> 8)) : -+ ((Byte)v < 0xe8 ? 0 : 1)); // ((v >> 5) & 1)); -+ */ -+ const unsigned ttt = *prob; -+ const UInt32 bound = (p->range >> kNumBitModelTotalBits) * ttt; -+ if ((v & CONV_FLAG) == 0) - { -+ // static int yyy = 0; yyy++; printf("\n!needConvert = %d\n", yyy); -+ // v = (Byte)v; // for marker version - p->range = bound; -- *prob = (CProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); -- p->src = src; -- p->prevByte = b; -+ *prob = (CBcj2Prob)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); -+ // WRITE_CONTEXT_AND_SRC - continue; - } -- - p->low += bound; - p->range -= bound; -- *prob = (CProb)(ttt - (ttt >> kNumMoveBits)); -- -+ *prob = (CBcj2Prob)(ttt - (ttt >> kNumMoveBits)); -+ } -+ // p->context = src[3]; -+ { -+ // const unsigned cj = ((Byte)v == 0xe8 ? BCJ2_STREAM_CALL : BCJ2_STREAM_JUMP); -+ const unsigned cj = (((v + 0x57) >> 6) & 1) + BCJ2_STREAM_CALL; -+ ip = p->ip64; -+ v = GetUi32(src); // relat -+ ip += 4; -+ p->ip64 = ip; -+ src += 4; -+ // p->src = src; - { -- UInt32 relatVal = GetUi32(src); -- UInt32 absVal; -- p->ip += 4; -- absVal = p->ip + relatVal; -- p->prevByte = src[3]; -- src += 4; -- p->src = src; -+ const UInt32 absol = (UInt32)ip + v; -+ Byte *cur = p->bufs[cj]; -+ v >>= 24; -+ // WRITE_CONTEXT -+ if (cur == p->lims[cj]) - { -- unsigned cj = (b == 0xE8) ? BCJ2_STREAM_CALL : BCJ2_STREAM_JUMP; -- Byte *cur = p->bufs[cj]; -- if (cur == p->lims[cj]) -- { -- p->state = cj; -- p->tempTarget = absVal; -- return; -- } -- SetBe32(cur, absVal); -- p->bufs[cj] = cur + 4; -+ p->state = cj; -+ p->tempTarget = absol; -+ WRITE_CONTEXT_AND_SRC -+ return; - } -+ SetBe32a(cur, absol) -+ p->bufs[cj] = cur + 4; - } - } - } - } -- } -+ } // end of loop - } - -- if (p->finishMode != BCJ2_ENC_FINISH_MODE_END_STREAM) -- return; -- -- for (; p->flushPos < 5; p->flushPos++) -- if (RangeEnc_ShiftLow(p)) -+ for (; p->flushRem != 0; p->flushRem--) -+ if (Bcj2_RangeEnc_ShiftLow(p)) - return; -- p->state = BCJ2_ENC_STATE_OK; -+ p->state = BCJ2_ENC_STATE_FINISHED; - } - - -+/* -+BCJ2 encoder needs look ahead for up to 4 bytes in (src) buffer. -+So base function Bcj2Enc_Encode_2() -+ in BCJ2_ENC_FINISH_MODE_CONTINUE mode can return with -+ (p->state == BCJ2_ENC_STATE_ORIG && p->src < p->srcLim) -+Bcj2Enc_Encode() solves that look ahead problem by using p->temp[] buffer. -+ so if (p->state == BCJ2_ENC_STATE_ORIG) after Bcj2Enc_Encode(), -+ then (p->src == p->srcLim). -+ And the caller's code is simpler with Bcj2Enc_Encode(). -+*/ -+ -+Z7_NO_INLINE - void Bcj2Enc_Encode(CBcj2Enc *p) - { -- PRF(printf("\n")); -- PRF(printf("---- ip = %8d tempPos = %8d src = %8d\n", p->ip, p->tempPos, p->srcLim - p->src)); -- -+ PRF2("\n----") - if (p->tempPos != 0) - { -+ /* extra: number of bytes that were copied from (src) to (temp) buffer in this call */ - unsigned extra = 0; -- -+ /* We will touch only minimal required number of bytes in input (src) stream. -+ So we will add input bytes from (src) stream to temp[] with step of 1 byte. -+ We don't add new bytes to temp[] before Bcj2Enc_Encode_2() call -+ in first loop iteration because -+ - previous call of Bcj2Enc_Encode() could use another (finishMode), -+ - previous call could finish with (p->state != BCJ2_ENC_STATE_ORIG). -+ the case with full temp[] buffer (p->tempPos == 4) is possible here. -+ */ - for (;;) - { -+ // (0 < p->tempPos <= 5) // in non-marker version -+ /* p->src : the current src data position including extra bytes -+ that were copied to temp[] buffer in this call */ - const Byte *src = p->src; - const Byte *srcLim = p->srcLim; -- EBcj2Enc_FinishMode finishMode = p->finishMode; -- -- p->src = p->temp; -- p->srcLim = p->temp + p->tempPos; -+ const EBcj2Enc_FinishMode finishMode = p->finishMode; - if (src != srcLim) -+ { -+ /* if there are some src data after the data copied to temp[], -+ then we use MODE_CONTINUE for temp data */ - p->finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE; -- -- PRF(printf(" ip = %8d tempPos = %8d src = %8d\n", p->ip, p->tempPos, p->srcLim - p->src)); -- -+ } -+ p->src = p->temp; -+ p->srcLim = p->temp + p->tempPos; -+ PRF2(" ") - Bcj2Enc_Encode_2(p); -- - { -- unsigned num = (unsigned)(p->src - p->temp); -- unsigned tempPos = p->tempPos - num; -+ const unsigned num = (unsigned)(p->src - p->temp); -+ const unsigned tempPos = p->tempPos - num; - unsigned i; - p->tempPos = tempPos; - for (i = 0; i < tempPos; i++) -- p->temp[i] = p->temp[(size_t)i + num]; -- -+ p->temp[i] = p->temp[(SizeT)i + num]; -+ // tempPos : number of bytes in temp buffer - p->src = src; - p->srcLim = srcLim; - p->finishMode = finishMode; -- -- if (p->state != BCJ2_ENC_STATE_ORIG || src == srcLim) -+ if (p->state != BCJ2_ENC_STATE_ORIG) -+ { -+ // (p->tempPos <= 4) // in non-marker version -+ /* if (the reason of exit from Bcj2Enc_Encode_2() -+ is not BCJ2_ENC_STATE_ORIG), -+ then we exit from Bcj2Enc_Encode() with same reason */ -+ // optional code begin : we rollback (src) and tempPos, if it's possible: -+ if (extra >= tempPos) -+ extra = tempPos; -+ p->src = src - extra; -+ p->tempPos = tempPos - extra; -+ // optional code end : rollback of (src) and tempPos - return; -- -+ } -+ /* (p->tempPos <= 4) -+ (p->state == BCJ2_ENC_STATE_ORIG) -+ so encoder needs more data than in temp[] */ -+ if (src == srcLim) -+ return; // src buffer has no more input data. -+ /* (src != srcLim) -+ so we can provide more input data from src for Bcj2Enc_Encode_2() */ - if (extra >= tempPos) - { -- p->src = src - tempPos; -+ /* (extra >= tempPos) means that temp buffer contains -+ only data from src buffer of this call. -+ So now we can encode without temp buffer */ -+ p->src = src - tempPos; // rollback (src) - p->tempPos = 0; - break; - } -- -- p->temp[tempPos] = src[0]; -+ // we append one additional extra byte from (src) to temp[] buffer: -+ p->temp[tempPos] = *src; - p->tempPos = tempPos + 1; -+ // (0 < p->tempPos <= 5) // in non-marker version - p->src = src + 1; - extra++; - } - } - } - -- PRF(printf("++++ ip = %8d tempPos = %8d src = %8d\n", p->ip, p->tempPos, p->srcLim - p->src)); -- -+ PRF2("++++") -+ // (p->tempPos == 0) - Bcj2Enc_Encode_2(p); -+ PRF2("====") - - if (p->state == BCJ2_ENC_STATE_ORIG) - { - const Byte *src = p->src; -- unsigned rem = (unsigned)(p->srcLim - src); -- unsigned i; -- for (i = 0; i < rem; i++) -- p->temp[i] = src[i]; -- p->tempPos = rem; -- p->src = src + rem; -+ const Byte *srcLim = p->srcLim; -+ const unsigned rem = (unsigned)(srcLim - src); -+ /* (rem <= 4) here. -+ if (p->src != p->srcLim), then -+ - we copy non-processed bytes from (p->src) to temp[] buffer, -+ - we set p->src equal to p->srcLim. -+ */ -+ if (rem) -+ { -+ unsigned i = 0; -+ p->src = srcLim; -+ p->tempPos = rem; -+ // (0 < p->tempPos <= 4) -+ do -+ p->temp[i] = src[i]; -+ while (++i != rem); -+ } -+ // (p->tempPos <= 4) -+ // (p->src == p->srcLim) - } - } -+ -+#undef PRF2 -+#undef CONV_FLAG -+#undef MARKER_FLAG -+#undef WRITE_CONTEXT -+#undef WRITE_CONTEXT_AND_SRC -+#undef ONE_ITER -+#undef NUM_SHIFT_BITS -+#undef kTopValue -+#undef kNumBitModelTotalBits -+#undef kBitModelTotal -+#undef kNumMoveBits -diff --git a/src/lzma/Bra.c b/src/lzma/Bra.c -index 3b854d9ca..22e0e478e 100644 ---- a/src/lzma/Bra.c -+++ b/src/lzma/Bra.c -@@ -1,230 +1,420 @@ --/* Bra.c -- Converters for RISC code --2021-02-09 : Igor Pavlov : Public domain */ -+/* Bra.c -- Branch converters for RISC code -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - --#include "CpuArch.h" - #include "Bra.h" -+#include "CpuArch.h" -+#include "RotateDefs.h" -+ -+#if defined(MY_CPU_SIZEOF_POINTER) \ -+ && ( MY_CPU_SIZEOF_POINTER == 4 \ -+ || MY_CPU_SIZEOF_POINTER == 8) -+ #define BR_CONV_USE_OPT_PC_PTR -+#endif -+ -+#ifdef BR_CONV_USE_OPT_PC_PTR -+#define BR_PC_INIT pc -= (UInt32)(SizeT)p; -+#define BR_PC_GET (pc + (UInt32)(SizeT)p) -+#else -+#define BR_PC_INIT pc += (UInt32)size; -+#define BR_PC_GET (pc - (UInt32)(SizeT)(lim - p)) -+// #define BR_PC_INIT -+// #define BR_PC_GET (pc + (UInt32)(SizeT)(p - data)) -+#endif -+ -+#define BR_CONVERT_VAL(v, c) if (encoding) v += c; else v -= c; -+// #define BR_CONVERT_VAL(v, c) if (!encoding) c = (UInt32)0 - c; v += c; -+ -+#define Z7_BRANCH_CONV(name) z7_BranchConv_ ## name -+ -+#define Z7_BRANCH_FUNC_MAIN(name) \ -+static \ -+Z7_FORCE_INLINE \ -+Z7_ATTRIB_NO_VECTOR \ -+Byte *Z7_BRANCH_CONV(name)(Byte *p, SizeT size, UInt32 pc, int encoding) - --SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) -+#define Z7_BRANCH_FUNC_IMP(name, m, encoding) \ -+Z7_NO_INLINE \ -+Z7_ATTRIB_NO_VECTOR \ -+Byte *m(name)(Byte *data, SizeT size, UInt32 pc) \ -+ { return Z7_BRANCH_CONV(name)(data, size, pc, encoding); } \ -+ -+#ifdef Z7_EXTRACT_ONLY -+#define Z7_BRANCH_FUNCS_IMP(name) \ -+ Z7_BRANCH_FUNC_IMP(name, Z7_BRANCH_CONV_DEC, 0) -+#else -+#define Z7_BRANCH_FUNCS_IMP(name) \ -+ Z7_BRANCH_FUNC_IMP(name, Z7_BRANCH_CONV_DEC, 0) \ -+ Z7_BRANCH_FUNC_IMP(name, Z7_BRANCH_CONV_ENC, 1) -+#endif -+ -+#if defined(__clang__) -+#define BR_EXTERNAL_FOR -+#define BR_NEXT_ITERATION continue; -+#else -+#define BR_EXTERNAL_FOR for (;;) -+#define BR_NEXT_ITERATION break; -+#endif -+ -+#if defined(__clang__) && (__clang_major__ >= 8) \ -+ || defined(__GNUC__) && (__GNUC__ >= 1000) \ -+ // GCC is not good for __builtin_expect() here -+ /* || defined(_MSC_VER) && (_MSC_VER >= 1920) */ -+ // #define Z7_unlikely [[unlikely]] -+ // #define Z7_LIKELY(x) (__builtin_expect((x), 1)) -+ #define Z7_UNLIKELY(x) (__builtin_expect((x), 0)) -+ // #define Z7_likely [[likely]] -+#else -+ // #define Z7_LIKELY(x) (x) -+ #define Z7_UNLIKELY(x) (x) -+ // #define Z7_likely -+#endif -+ -+ -+Z7_BRANCH_FUNC_MAIN(ARM64) - { -- Byte *p; -+ // Byte *p = data; - const Byte *lim; -- size &= ~(size_t)3; -- ip += 4; -- p = data; -- lim = data + size; -+ const UInt32 flag = (UInt32)1 << (24 - 4); -+ const UInt32 mask = ((UInt32)1 << 24) - (flag << 1); -+ size &= ~(SizeT)3; -+ // if (size == 0) return p; -+ lim = p + size; -+ BR_PC_INIT -+ pc -= 4; // because (p) will point to next instruction -+ -+ BR_EXTERNAL_FOR -+ { -+ // Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE -+ for (;;) -+ { -+ UInt32 v; -+ if Z7_UNLIKELY(p == lim) -+ return p; -+ v = GetUi32a(p); -+ p += 4; -+ if Z7_UNLIKELY(((v - 0x94000000) & 0xfc000000) == 0) -+ { -+ UInt32 c = BR_PC_GET >> 2; -+ BR_CONVERT_VAL(v, c) -+ v &= 0x03ffffff; -+ v |= 0x94000000; -+ SetUi32a(p - 4, v) -+ BR_NEXT_ITERATION -+ } -+ // v = rotlFixed(v, 8); v += (flag << 8) - 0x90; if Z7_UNLIKELY((v & ((mask << 8) + 0x9f)) == 0) -+ v -= 0x90000000; if Z7_UNLIKELY((v & 0x9f000000) == 0) -+ { -+ UInt32 z, c; -+ // v = rotrFixed(v, 8); -+ v += flag; if Z7_UNLIKELY(v & mask) continue; -+ z = (v & 0xffffffe0) | (v >> 26); -+ c = (BR_PC_GET >> (12 - 3)) & ~(UInt32)7; -+ BR_CONVERT_VAL(z, c) -+ v &= 0x1f; -+ v |= 0x90000000; -+ v |= z << 26; -+ v |= 0x00ffffe0 & ((z & (((flag << 1) - 1))) - flag); -+ SetUi32a(p - 4, v) -+ } -+ } -+ } -+} -+Z7_BRANCH_FUNCS_IMP(ARM64) - -- if (encoding) - -+Z7_BRANCH_FUNC_MAIN(ARM) -+{ -+ // Byte *p = data; -+ const Byte *lim; -+ size &= ~(SizeT)3; -+ lim = p + size; -+ BR_PC_INIT -+ /* in ARM: branch offset is relative to the +2 instructions from current instruction. -+ (p) will point to next instruction */ -+ pc += 8 - 4; -+ - for (;;) - { - for (;;) - { -- if (p >= lim) -- return (SizeT)(p - data); -- p += 4; -- if (p[-1] == 0xEB) -- break; -+ if Z7_UNLIKELY(p >= lim) { return p; } p += 4; if Z7_UNLIKELY(p[-1] == 0xeb) break; -+ if Z7_UNLIKELY(p >= lim) { return p; } p += 4; if Z7_UNLIKELY(p[-1] == 0xeb) break; - } - { -- UInt32 v = GetUi32(p - 4); -- v <<= 2; -- v += ip + (UInt32)(p - data); -- v >>= 2; -- v &= 0x00FFFFFF; -- v |= 0xEB000000; -- SetUi32(p - 4, v); -+ UInt32 v = GetUi32a(p - 4); -+ UInt32 c = BR_PC_GET >> 2; -+ BR_CONVERT_VAL(v, c) -+ v &= 0x00ffffff; -+ v |= 0xeb000000; -+ SetUi32a(p - 4, v) - } - } -+} -+Z7_BRANCH_FUNCS_IMP(ARM) -+ - -+Z7_BRANCH_FUNC_MAIN(PPC) -+{ -+ // Byte *p = data; -+ const Byte *lim; -+ size &= ~(SizeT)3; -+ lim = p + size; -+ BR_PC_INIT -+ pc -= 4; // because (p) will point to next instruction -+ - for (;;) - { -+ UInt32 v; - for (;;) - { -- if (p >= lim) -- return (SizeT)(p - data); -+ if Z7_UNLIKELY(p == lim) -+ return p; -+ // v = GetBe32a(p); -+ v = *(UInt32 *)(void *)p; - p += 4; -- if (p[-1] == 0xEB) -- break; -+ // if ((v & 0xfc000003) == 0x48000001) break; -+ // if ((p[-4] & 0xFC) == 0x48 && (p[-1] & 3) == 1) break; -+ if Z7_UNLIKELY( -+ ((v - Z7_CONV_BE_TO_NATIVE_CONST32(0x48000001)) -+ & Z7_CONV_BE_TO_NATIVE_CONST32(0xfc000003)) == 0) break; - } - { -- UInt32 v = GetUi32(p - 4); -- v <<= 2; -- v -= ip + (UInt32)(p - data); -- v >>= 2; -- v &= 0x00FFFFFF; -- v |= 0xEB000000; -- SetUi32(p - 4, v); -+ v = Z7_CONV_NATIVE_TO_BE_32(v); -+ { -+ UInt32 c = BR_PC_GET; -+ BR_CONVERT_VAL(v, c) -+ } -+ v &= 0x03ffffff; -+ v |= 0x48000000; -+ SetBe32a(p - 4, v) - } - } - } -+Z7_BRANCH_FUNCS_IMP(PPC) - - --SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) -+#ifdef Z7_CPU_FAST_ROTATE_SUPPORTED -+#define BR_SPARC_USE_ROTATE -+#endif -+ -+Z7_BRANCH_FUNC_MAIN(SPARC) - { -- Byte *p; -+ // Byte *p = data; - const Byte *lim; -- size &= ~(size_t)1; -- p = data; -- lim = data + size - 4; -- -- if (encoding) -- -+ const UInt32 flag = (UInt32)1 << 22; -+ size &= ~(SizeT)3; -+ lim = p + size; -+ BR_PC_INIT -+ pc -= 4; // because (p) will point to next instruction - for (;;) - { -- UInt32 b1; -+ UInt32 v; - for (;;) - { -- UInt32 b3; -- if (p > lim) -- return (SizeT)(p - data); -- b1 = p[1]; -- b3 = p[3]; -- p += 2; -- b1 ^= 8; -- if ((b3 & b1) >= 0xF8) -+ if Z7_UNLIKELY(p == lim) -+ return p; -+ /* // the code without GetBe32a(): -+ { const UInt32 v = GetUi16a(p) & 0xc0ff; p += 4; if (v == 0x40 || v == 0xc07f) break; } -+ */ -+ v = GetBe32a(p); -+ p += 4; -+ #ifdef BR_SPARC_USE_ROTATE -+ v = rotlFixed(v, 2); -+ v += (flag << 2) - 1; -+ if Z7_UNLIKELY((v & (3 - (flag << 3))) == 0) -+ #else -+ v += (UInt32)5 << 29; -+ v ^= (UInt32)7 << 29; -+ v += flag; -+ if Z7_UNLIKELY((v & (0 - (flag << 1))) == 0) -+ #endif - break; - } - { -- UInt32 v = -- ((UInt32)b1 << 19) -- + (((UInt32)p[1] & 0x7) << 8) -- + (((UInt32)p[-2] << 11)) -- + (p[0]); -- -- p += 2; -+ // UInt32 v = GetBe32a(p - 4); -+ #ifndef BR_SPARC_USE_ROTATE -+ v <<= 2; -+ #endif - { -- UInt32 cur = (ip + (UInt32)(p - data)) >> 1; -- v += cur; -+ UInt32 c = BR_PC_GET; -+ BR_CONVERT_VAL(v, c) - } -- -- p[-4] = (Byte)(v >> 11); -- p[-3] = (Byte)(0xF0 | ((v >> 19) & 0x7)); -- p[-2] = (Byte)v; -- p[-1] = (Byte)(0xF8 | (v >> 8)); -+ v &= (flag << 3) - 1; -+ #ifdef BR_SPARC_USE_ROTATE -+ v -= (flag << 2) - 1; -+ v = rotrFixed(v, 2); -+ #else -+ v -= (flag << 2); -+ v >>= 2; -+ v |= (UInt32)1 << 30; -+ #endif -+ SetBe32a(p - 4, v) - } - } -+} -+Z7_BRANCH_FUNCS_IMP(SPARC) -+ -+ -+Z7_BRANCH_FUNC_MAIN(ARMT) -+{ -+ // Byte *p = data; -+ Byte *lim; -+ size &= ~(SizeT)1; -+ // if (size == 0) return p; -+ if (size <= 2) return p; -+ size -= 2; -+ lim = p + size; -+ BR_PC_INIT -+ /* in ARM: branch offset is relative to the +2 instructions from current instruction. -+ (p) will point to the +2 instructions from current instruction */ -+ // pc += 4 - 4; -+ // if (encoding) pc -= 0xf800 << 1; else pc += 0xf800 << 1; -+ // #define ARMT_TAIL_PROC { goto armt_tail; } -+ #define ARMT_TAIL_PROC { return p; } - -- for (;;) -+ do - { -- UInt32 b1; -+ /* in MSVC 32-bit x86 compilers: -+ UInt32 version : it loads value from memory with movzx -+ Byte version : it loads value to 8-bit register (AL/CL) -+ movzx version is slightly faster in some cpus -+ */ -+ unsigned b1; -+ // Byte / unsigned -+ b1 = p[1]; -+ // optimized version to reduce one (p >= lim) check: -+ // unsigned a1 = p[1]; b1 = p[3]; p += 2; if Z7_LIKELY((b1 & (a1 ^ 8)) < 0xf8) - for (;;) - { -- UInt32 b3; -- if (p > lim) -- return (SizeT)(p - data); -- b1 = p[1]; -- b3 = p[3]; -- p += 2; -- b1 ^= 8; -- if ((b3 & b1) >= 0xF8) -- break; -+ unsigned b3; // Byte / UInt32 -+ /* (Byte)(b3) normalization can use low byte computations in MSVC. -+ It gives smaller code, and no loss of speed in some compilers/cpus. -+ But new MSVC 32-bit x86 compilers use more slow load -+ from memory to low byte register in that case. -+ So we try to use full 32-bit computations for faster code. -+ */ -+ // if (p >= lim) { ARMT_TAIL_PROC } b3 = b1 + 8; b1 = p[3]; p += 2; if ((b3 & b1) >= 0xf8) break; -+ if Z7_UNLIKELY(p >= lim) { ARMT_TAIL_PROC } b3 = p[3]; p += 2; if Z7_UNLIKELY((b3 & (b1 ^ 8)) >= 0xf8) break; -+ if Z7_UNLIKELY(p >= lim) { ARMT_TAIL_PROC } b1 = p[3]; p += 2; if Z7_UNLIKELY((b1 & (b3 ^ 8)) >= 0xf8) break; - } - { -+ /* we can adjust pc for (0xf800) to rid of (& 0x7FF) operation. -+ But gcc/clang for arm64 can use bfi instruction for full code here */ - UInt32 v = -- ((UInt32)b1 << 19) -+ ((UInt32)GetUi16a(p - 2) << 11) | -+ ((UInt32)GetUi16a(p) & 0x7FF); -+ /* -+ UInt32 v = -+ ((UInt32)p[1 - 2] << 19) - + (((UInt32)p[1] & 0x7) << 8) - + (((UInt32)p[-2] << 11)) - + (p[0]); -- -+ */ - p += 2; - { -- UInt32 cur = (ip + (UInt32)(p - data)) >> 1; -- v -= cur; -+ UInt32 c = BR_PC_GET >> 1; -+ BR_CONVERT_VAL(v, c) - } -- -+ SetUi16a(p - 4, (UInt16)(((v >> 11) & 0x7ff) | 0xf000)) -+ SetUi16a(p - 2, (UInt16)(v | 0xf800)) - /* -- SetUi16(p - 4, (UInt16)(((v >> 11) & 0x7FF) | 0xF000)); -- SetUi16(p - 2, (UInt16)(v | 0xF800)); -- */ -- - p[-4] = (Byte)(v >> 11); -- p[-3] = (Byte)(0xF0 | ((v >> 19) & 0x7)); -+ p[-3] = (Byte)(0xf0 | ((v >> 19) & 0x7)); - p[-2] = (Byte)v; -- p[-1] = (Byte)(0xF8 | (v >> 8)); -+ p[-1] = (Byte)(0xf8 | (v >> 8)); -+ */ - } - } -+ while (p < lim); -+ return p; -+ // armt_tail: -+ // if ((Byte)((lim[1] & 0xf8)) != 0xf0) { lim += 2; } return lim; -+ // return (Byte *)(lim + ((Byte)((lim[1] ^ 0xf0) & 0xf8) == 0 ? 0 : 2)); -+ // return (Byte *)(lim + (((lim[1] ^ ~0xfu) & ~7u) == 0 ? 0 : 2)); -+ // return (Byte *)(lim + 2 - (((((unsigned)lim[1] ^ 8) + 8) >> 7) & 2)); - } -+Z7_BRANCH_FUNCS_IMP(ARMT) - - --SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) --{ -- Byte *p; -- const Byte *lim; -- size &= ~(size_t)3; -- ip -= 4; -- p = data; -- lim = data + size; -- -- for (;;) -- { -- for (;;) -- { -- if (p >= lim) -- return (SizeT)(p - data); -- p += 4; -- /* if ((v & 0xFC000003) == 0x48000001) */ -- if ((p[-4] & 0xFC) == 0x48 && (p[-1] & 3) == 1) -- break; -- } -- { -- UInt32 v = GetBe32(p - 4); -- if (encoding) -- v += ip + (UInt32)(p - data); -- else -- v -= ip + (UInt32)(p - data); -- v &= 0x03FFFFFF; -- v |= 0x48000000; -- SetBe32(p - 4, v); -- } -- } --} -- -+// #define BR_IA64_NO_INLINE - --SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) -+Z7_BRANCH_FUNC_MAIN(IA64) - { -- Byte *p; -+ // Byte *p = data; - const Byte *lim; -- size &= ~(size_t)3; -- ip -= 4; -- p = data; -- lim = data + size; -- -+ size &= ~(SizeT)15; -+ lim = p + size; -+ pc -= 1 << 4; -+ pc >>= 4 - 1; -+ // pc -= 1 << 1; -+ - for (;;) - { -+ unsigned m; - for (;;) - { -- if (p >= lim) -- return (SizeT)(p - data); -- /* -- v = GetBe32(p); -- p += 4; -- m = v + ((UInt32)5 << 29); -- m ^= (UInt32)7 << 29; -- m += (UInt32)1 << 22; -- if ((m & ((UInt32)0x1FF << 23)) == 0) -- break; -- */ -- p += 4; -- if ((p[-4] == 0x40 && (p[-3] & 0xC0) == 0) || -- (p[-4] == 0x7F && (p[-3] >= 0xC0))) -+ if Z7_UNLIKELY(p == lim) -+ return p; -+ m = (unsigned)((UInt32)0x334b0000 >> (*p & 0x1e)); -+ p += 16; -+ pc += 1 << 1; -+ if (m &= 3) - break; - } - { -- UInt32 v = GetBe32(p - 4); -- v <<= 2; -- if (encoding) -- v += ip + (UInt32)(p - data); -- else -- v -= ip + (UInt32)(p - data); -- -- v &= 0x01FFFFFF; -- v -= (UInt32)1 << 24; -- v ^= 0xFF000000; -- v >>= 2; -- v |= 0x40000000; -- SetBe32(p - 4, v); -+ p += (ptrdiff_t)m * 5 - 20; // negative value is expected here. -+ do -+ { -+ const UInt32 t = -+ #if defined(MY_CPU_X86_OR_AMD64) -+ // we use 32-bit load here to reduce code size on x86: -+ GetUi32(p); -+ #else -+ GetUi16(p); -+ #endif -+ UInt32 z = GetUi32(p + 1) >> m; -+ p += 5; -+ if (((t >> m) & (0x70 << 1)) == 0 -+ && ((z - (0x5000000 << 1)) & (0xf000000 << 1)) == 0) -+ { -+ UInt32 v = (UInt32)((0x8fffff << 1) | 1) & z; -+ z ^= v; -+ #ifdef BR_IA64_NO_INLINE -+ v |= (v & ((UInt32)1 << (23 + 1))) >> 3; -+ { -+ UInt32 c = pc; -+ BR_CONVERT_VAL(v, c) -+ } -+ v &= (0x1fffff << 1) | 1; -+ #else -+ { -+ if (encoding) -+ { -+ // pc &= ~(0xc00000 << 1); // we just need to clear at least 2 bits -+ pc &= (0x1fffff << 1) | 1; -+ v += pc; -+ } -+ else -+ { -+ // pc |= 0xc00000 << 1; // we need to set at least 2 bits -+ pc |= ~(UInt32)((0x1fffff << 1) | 1); -+ v -= pc; -+ } -+ } -+ v &= ~(UInt32)(0x600000 << 1); -+ #endif -+ v += (0x700000 << 1); -+ v &= (0x8fffff << 1) | 1; -+ z |= v; -+ z <<= m; -+ SetUi32(p + 1 - 5, z) -+ } -+ m++; -+ } -+ while (m &= 3); // while (m < 4); - } - } - } -+Z7_BRANCH_FUNCS_IMP(IA64) -diff --git a/src/lzma/Bra.h b/src/lzma/Bra.h -index 855e37a6b..a4ee568e2 100644 ---- a/src/lzma/Bra.h -+++ b/src/lzma/Bra.h -@@ -1,64 +1,99 @@ - /* Bra.h -- Branch converters for executables --2013-01-18 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - --#ifndef __BRA_H --#define __BRA_H -+#ifndef ZIP7_INC_BRA_H -+#define ZIP7_INC_BRA_H - - #include "7zTypes.h" - - EXTERN_C_BEGIN - -+#define Z7_BRANCH_CONV_DEC(name) z7_BranchConv_ ## name ## _Dec -+#define Z7_BRANCH_CONV_ENC(name) z7_BranchConv_ ## name ## _Enc -+#define Z7_BRANCH_CONV_ST_DEC(name) z7_BranchConvSt_ ## name ## _Dec -+#define Z7_BRANCH_CONV_ST_ENC(name) z7_BranchConvSt_ ## name ## _Enc -+ -+#define Z7_BRANCH_CONV_DECL(name) Byte * name(Byte *data, SizeT size, UInt32 pc) -+#define Z7_BRANCH_CONV_ST_DECL(name) Byte * name(Byte *data, SizeT size, UInt32 pc, UInt32 *state) -+ -+typedef Z7_BRANCH_CONV_DECL( (*z7_Func_BranchConv)); -+typedef Z7_BRANCH_CONV_ST_DECL((*z7_Func_BranchConvSt)); -+ -+#define Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL 0 -+Z7_BRANCH_CONV_ST_DECL(Z7_BRANCH_CONV_ST_DEC(X86)); -+Z7_BRANCH_CONV_ST_DECL(Z7_BRANCH_CONV_ST_ENC(X86)); -+ -+#define Z7_BRANCH_FUNCS_DECL(name) \ -+Z7_BRANCH_CONV_DECL(Z7_BRANCH_CONV_DEC(name)); \ -+Z7_BRANCH_CONV_DECL(Z7_BRANCH_CONV_ENC(name)); -+ -+Z7_BRANCH_FUNCS_DECL(ARM64) -+Z7_BRANCH_FUNCS_DECL(ARM) -+Z7_BRANCH_FUNCS_DECL(ARMT) -+Z7_BRANCH_FUNCS_DECL(PPC) -+Z7_BRANCH_FUNCS_DECL(SPARC) -+Z7_BRANCH_FUNCS_DECL(IA64) -+ - /* --These functions convert relative addresses to absolute addresses --in CALL instructions to increase the compression ratio. -- -- In: -- data - data buffer -- size - size of data -- ip - current virtual Instruction Pinter (IP) value -- state - state variable for x86 converter -- encoding - 0 (for decoding), 1 (for encoding) -- -- Out: -- state - state variable for x86 converter -+These functions convert data that contain CPU instructions. -+Each such function converts relative addresses to absolute addresses in some -+branch instructions: CALL (in all converters) and JUMP (X86 converter only). -+Such conversion allows to increase compression ratio, if we compress that data. -+ -+There are 2 types of converters: -+ Byte * Conv_RISC (Byte *data, SizeT size, UInt32 pc); -+ Byte * ConvSt_X86(Byte *data, SizeT size, UInt32 pc, UInt32 *state); -+Each Converter supports 2 versions: one for encoding -+and one for decoding (_Enc/_Dec postfixes in function name). - -- Returns: -- The number of processed bytes. If you call these functions with multiple calls, -- you must start next call with first byte after block of processed bytes. -+In params: -+ data : data buffer -+ size : size of data -+ pc : current virtual Program Counter (Instruction Pinter) value -+In/Out param: -+ state : pointer to state variable (for X86 converter only) -+ -+Return: -+ The pointer to position in (data) buffer after last byte that was processed. -+ If the caller calls converter again, it must call it starting with that position. -+ But the caller is allowed to move data in buffer. so pointer to -+ current processed position also will be changed for next call. -+ Also the caller must increase internal (pc) value for next call. - -+Each converter has some characteristics: Endian, Alignment, LookAhead. - Type Endian Alignment LookAhead - -- x86 little 1 4 -+ X86 little 1 4 - ARMT little 2 2 - ARM little 4 0 -+ ARM64 little 4 0 - PPC big 4 0 - SPARC big 4 0 - IA64 little 16 0 - -- size must be >= Alignment + LookAhead, if it's not last block. -- If (size < Alignment + LookAhead), converter returns 0. -- -- Example: -+ (data) must be aligned for (Alignment). -+ processed size can be calculated as: -+ SizeT processed = Conv(data, size, pc) - data; -+ if (processed == 0) -+ it means that converter needs more data for processing. -+ If (size < Alignment + LookAhead) -+ then (processed == 0) is allowed. - -- UInt32 ip = 0; -- for () -- { -- ; size must be >= Alignment + LookAhead, if it's not last block -- SizeT processed = Convert(data, size, ip, 1); -- data += processed; -- size -= processed; -- ip += processed; -- } -+Example code for conversion in loop: -+ UInt32 pc = 0; -+ size = 0; -+ for (;;) -+ { -+ size += Load_more_input_data(data + size); -+ SizeT processed = Conv(data, size, pc) - data; -+ if (processed == 0 && no_more_input_data_after_size) -+ break; // we stop convert loop -+ data += processed; -+ size -= processed; -+ pc += processed; -+ } - */ - --#define x86_Convert_Init(state) { state = 0; } --SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding); --SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); --SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); --SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); --SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); --SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); -- - EXTERN_C_END - - #endif -diff --git a/src/lzma/Bra86.c b/src/lzma/Bra86.c -index 10a0fbd16..d81f392ae 100644 ---- a/src/lzma/Bra86.c -+++ b/src/lzma/Bra86.c -@@ -1,82 +1,187 @@ --/* Bra86.c -- Converter for x86 code (BCJ) --2021-02-09 : Igor Pavlov : Public domain */ -+/* Bra86.c -- Branch converter for X86 code (BCJ) -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - - #include "Bra.h" -+#include "CpuArch.h" - --#define Test86MSByte(b) ((((b) + 1) & 0xFE) == 0) - --SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding) -+#if defined(MY_CPU_SIZEOF_POINTER) \ -+ && ( MY_CPU_SIZEOF_POINTER == 4 \ -+ || MY_CPU_SIZEOF_POINTER == 8) -+ #define BR_CONV_USE_OPT_PC_PTR -+#endif -+ -+#ifdef BR_CONV_USE_OPT_PC_PTR -+#define BR_PC_INIT pc -= (UInt32)(SizeT)p; // (MY_uintptr_t) -+#define BR_PC_GET (pc + (UInt32)(SizeT)p) -+#else -+#define BR_PC_INIT pc += (UInt32)size; -+#define BR_PC_GET (pc - (UInt32)(SizeT)(lim - p)) -+// #define BR_PC_INIT -+// #define BR_PC_GET (pc + (UInt32)(SizeT)(p - data)) -+#endif -+ -+#define BR_CONVERT_VAL(v, c) if (encoding) v += c; else v -= c; -+// #define BR_CONVERT_VAL(v, c) if (!encoding) c = (UInt32)0 - c; v += c; -+ -+#define Z7_BRANCH_CONV_ST(name) z7_BranchConvSt_ ## name -+ -+#define BR86_NEED_CONV_FOR_MS_BYTE(b) ((((b) + 1) & 0xfe) == 0) -+ -+#ifdef MY_CPU_LE_UNALIGN -+ #define BR86_PREPARE_BCJ_SCAN const UInt32 v = GetUi32(p) ^ 0xe8e8e8e8; -+ #define BR86_IS_BCJ_BYTE(n) ((v & ((UInt32)0xfe << (n) * 8)) == 0) -+#else -+ #define BR86_PREPARE_BCJ_SCAN -+ // bad for MSVC X86 (partial write to byte reg): -+ #define BR86_IS_BCJ_BYTE(n) ((p[n - 4] & 0xfe) == 0xe8) -+ // bad for old MSVC (partial write to byte reg): -+ // #define BR86_IS_BCJ_BYTE(n) (((*p ^ 0xe8) & 0xfe) == 0) -+#endif -+ -+static -+Z7_FORCE_INLINE -+Z7_ATTRIB_NO_VECTOR -+Byte *Z7_BRANCH_CONV_ST(X86)(Byte *p, SizeT size, UInt32 pc, UInt32 *state, int encoding) - { -- SizeT pos = 0; -- UInt32 mask = *state & 7; - if (size < 5) -- return 0; -- size -= 4; -- ip += 5; -+ return p; -+ { -+ // Byte *p = data; -+ const Byte *lim = p + size - 4; -+ unsigned mask = (unsigned)*state; // & 7; -+#ifdef BR_CONV_USE_OPT_PC_PTR -+ /* if BR_CONV_USE_OPT_PC_PTR is defined: we need to adjust (pc) for (+4), -+ because call/jump offset is relative to the next instruction. -+ if BR_CONV_USE_OPT_PC_PTR is not defined : we don't need to adjust (pc) for (+4), -+ because BR_PC_GET uses (pc - (lim - p)), and lim was adjusted for (-4) before. -+ */ -+ pc += 4; -+#endif -+ BR_PC_INIT -+ goto start; - -- for (;;) -+ for (;; mask |= 4) - { -- Byte *p = data + pos; -- const Byte *limit = data + size; -- for (; p < limit; p++) -- if ((*p & 0xFE) == 0xE8) -- break; -- -+ // cont: mask |= 4; -+ start: -+ if (p >= lim) -+ goto fin; - { -- SizeT d = (SizeT)(p - data) - pos; -- pos = (SizeT)(p - data); -- if (p >= limit) -- { -- *state = (d > 2 ? 0 : mask >> (unsigned)d); -- return pos; -- } -- if (d > 2) -- mask = 0; -- else -- { -- mask >>= (unsigned)d; -- if (mask != 0 && (mask > 4 || mask == 3 || Test86MSByte(p[(size_t)(mask >> 1) + 1]))) -- { -- mask = (mask >> 1) | 4; -- pos++; -- continue; -- } -- } -+ BR86_PREPARE_BCJ_SCAN -+ p += 4; -+ if (BR86_IS_BCJ_BYTE(0)) { goto m0; } mask >>= 1; -+ if (BR86_IS_BCJ_BYTE(1)) { goto m1; } mask >>= 1; -+ if (BR86_IS_BCJ_BYTE(2)) { goto m2; } mask = 0; -+ if (BR86_IS_BCJ_BYTE(3)) { goto a3; } - } -+ goto main_loop; - -- if (Test86MSByte(p[4])) -+ m0: p--; -+ m1: p--; -+ m2: p--; -+ if (mask == 0) -+ goto a3; -+ if (p > lim) -+ goto fin_p; -+ -+ // if (((0x17u >> mask) & 1) == 0) -+ if (mask > 4 || mask == 3) -+ { -+ mask >>= 1; -+ continue; // goto cont; -+ } -+ mask >>= 1; -+ if (BR86_NEED_CONV_FOR_MS_BYTE(p[mask])) -+ continue; // goto cont; -+ // if (!BR86_NEED_CONV_FOR_MS_BYTE(p[3])) continue; // goto cont; - { -- UInt32 v = ((UInt32)p[4] << 24) | ((UInt32)p[3] << 16) | ((UInt32)p[2] << 8) | ((UInt32)p[1]); -- UInt32 cur = ip + (UInt32)pos; -- pos += 5; -- if (encoding) -- v += cur; -- else -- v -= cur; -- if (mask != 0) -+ UInt32 v = GetUi32(p); -+ UInt32 c; -+ v += (1 << 24); if (v & 0xfe000000) continue; // goto cont; -+ c = BR_PC_GET; -+ BR_CONVERT_VAL(v, c) - { -- unsigned sh = (mask & 6) << 2; -- if (Test86MSByte((Byte)(v >> sh))) -+ mask <<= 3; -+ if (BR86_NEED_CONV_FOR_MS_BYTE(v >> mask)) - { -- v ^= (((UInt32)0x100 << sh) - 1); -- if (encoding) -- v += cur; -- else -- v -= cur; -+ v ^= (((UInt32)0x100 << mask) - 1); -+ #ifdef MY_CPU_X86 -+ // for X86 : we can recalculate (c) to reduce register pressure -+ c = BR_PC_GET; -+ #endif -+ BR_CONVERT_VAL(v, c) - } - mask = 0; - } -- p[1] = (Byte)v; -- p[2] = (Byte)(v >> 8); -- p[3] = (Byte)(v >> 16); -- p[4] = (Byte)(0 - ((v >> 24) & 1)); -+ // v = (v & ((1 << 24) - 1)) - (v & (1 << 24)); -+ v &= (1 << 25) - 1; v -= (1 << 24); -+ SetUi32(p, v) -+ p += 4; -+ goto main_loop; - } -- else -+ -+ main_loop: -+ if (p >= lim) -+ goto fin; -+ for (;;) - { -- mask = (mask >> 1) | 4; -- pos++; -+ BR86_PREPARE_BCJ_SCAN -+ p += 4; -+ if (BR86_IS_BCJ_BYTE(0)) { goto a0; } -+ if (BR86_IS_BCJ_BYTE(1)) { goto a1; } -+ if (BR86_IS_BCJ_BYTE(2)) { goto a2; } -+ if (BR86_IS_BCJ_BYTE(3)) { goto a3; } -+ if (p >= lim) -+ goto fin; -+ } -+ -+ a0: p--; -+ a1: p--; -+ a2: p--; -+ a3: -+ if (p > lim) -+ goto fin_p; -+ // if (!BR86_NEED_CONV_FOR_MS_BYTE(p[3])) continue; // goto cont; -+ { -+ UInt32 v = GetUi32(p); -+ UInt32 c; -+ v += (1 << 24); if (v & 0xfe000000) continue; // goto cont; -+ c = BR_PC_GET; -+ BR_CONVERT_VAL(v, c) -+ // v = (v & ((1 << 24) - 1)) - (v & (1 << 24)); -+ v &= (1 << 25) - 1; v -= (1 << 24); -+ SetUi32(p, v) -+ p += 4; -+ goto main_loop; - } - } -+ -+fin_p: -+ p--; -+fin: -+ // the following processing for tail is optional and can be commented -+ /* -+ lim += 4; -+ for (; p < lim; p++, mask >>= 1) -+ if ((*p & 0xfe) == 0xe8) -+ break; -+ */ -+ *state = (UInt32)mask; -+ return p; -+ } - } -+ -+ -+#define Z7_BRANCH_CONV_ST_FUNC_IMP(name, m, encoding) \ -+Z7_NO_INLINE \ -+Z7_ATTRIB_NO_VECTOR \ -+Byte *m(name)(Byte *data, SizeT size, UInt32 pc, UInt32 *state) \ -+ { return Z7_BRANCH_CONV_ST(name)(data, size, pc, state, encoding); } -+ -+Z7_BRANCH_CONV_ST_FUNC_IMP(X86, Z7_BRANCH_CONV_ST_DEC, 0) -+#ifndef Z7_EXTRACT_ONLY -+Z7_BRANCH_CONV_ST_FUNC_IMP(X86, Z7_BRANCH_CONV_ST_ENC, 1) -+#endif -diff --git a/src/lzma/BraIA64.c b/src/lzma/BraIA64.c -index d1dbc62c5..9dfe3e289 100644 ---- a/src/lzma/BraIA64.c -+++ b/src/lzma/BraIA64.c -@@ -1,53 +1,14 @@ - /* BraIA64.c -- Converter for IA-64 code --2017-01-26 : Igor Pavlov : Public domain */ -+2023-02-20 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - --#include "CpuArch.h" --#include "Bra.h" -+// the code was moved to Bra.c - --SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) --{ -- SizeT i; -- if (size < 16) -- return 0; -- size -= 16; -- i = 0; -- do -- { -- unsigned m = ((UInt32)0x334B0000 >> (data[i] & 0x1E)) & 3; -- if (m) -- { -- m++; -- do -- { -- Byte *p = data + (i + (size_t)m * 5 - 8); -- if (((p[3] >> m) & 15) == 5 -- && (((p[-1] | ((UInt32)p[0] << 8)) >> m) & 0x70) == 0) -- { -- unsigned raw = GetUi32(p); -- unsigned v = raw >> m; -- v = (v & 0xFFFFF) | ((v & (1 << 23)) >> 3); -- -- v <<= 4; -- if (encoding) -- v += ip + (UInt32)i; -- else -- v -= ip + (UInt32)i; -- v >>= 4; -- -- v &= 0x1FFFFF; -- v += 0x700000; -- v &= 0x8FFFFF; -- raw &= ~((UInt32)0x8FFFFF << m); -- raw |= (v << m); -- SetUi32(p, raw); -- } -- } -- while (++m <= 4); -- } -- i += 16; -- } -- while (i <= size); -- return i; --} -+#ifdef _MSC_VER -+#pragma warning(disable : 4206) // nonstandard extension used : translation unit is empty -+#endif -+ -+#if defined(__clang__) -+#pragma GCC diagnostic ignored "-Wempty-translation-unit" -+#endif -diff --git a/src/lzma/Compiler.h b/src/lzma/Compiler.h -index a9816fa5a..185a52deb 100644 ---- a/src/lzma/Compiler.h -+++ b/src/lzma/Compiler.h -@@ -1,12 +1,37 @@ --/* Compiler.h --2021-01-05 : Igor Pavlov : Public domain */ -+/* Compiler.h : Compiler specific defines and pragmas -+2023-04-02 : Igor Pavlov : Public domain */ - --#ifndef __7Z_COMPILER_H --#define __7Z_COMPILER_H -+#ifndef ZIP7_INC_COMPILER_H -+#define ZIP7_INC_COMPILER_H -+ -+#if defined(__clang__) -+# define Z7_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) -+#endif -+#if defined(__clang__) && defined(__apple_build_version__) -+# define Z7_APPLE_CLANG_VERSION Z7_CLANG_VERSION -+#elif defined(__clang__) -+# define Z7_LLVM_CLANG_VERSION Z7_CLANG_VERSION -+#elif defined(__GNUC__) -+# define Z7_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) -+#endif -+ -+#ifdef _MSC_VER -+#if !defined(__clang__) && !defined(__GNUC__) -+#define Z7_MSC_VER_ORIGINAL _MSC_VER -+#endif -+#endif -+ -+#if defined(__MINGW32__) || defined(__MINGW64__) -+#define Z7_MINGW -+#endif -+ -+// #pragma GCC diagnostic ignored "-Wunknown-pragmas" -+ -+#ifdef __clang__ -+// padding size of '' with 4 bytes to alignment boundary -+#pragma GCC diagnostic ignored "-Wpadded" -+#endif - -- #ifdef __clang__ -- #pragma clang diagnostic ignored "-Wunused-private-field" -- #endif - - #ifdef _MSC_VER - -@@ -17,24 +42,115 @@ - #pragma warning(disable : 4214) // nonstandard extension used : bit field types other than int - #endif - -- #if _MSC_VER >= 1300 -- #pragma warning(disable : 4996) // This function or variable may be unsafe -- #else -- #pragma warning(disable : 4511) // copy constructor could not be generated -- #pragma warning(disable : 4512) // assignment operator could not be generated -- #pragma warning(disable : 4514) // unreferenced inline function has been removed -- #pragma warning(disable : 4702) // unreachable code -- #pragma warning(disable : 4710) // not inlined -- #pragma warning(disable : 4714) // function marked as __forceinline not inlined -- #pragma warning(disable : 4786) // identifier was truncated to '255' characters in the debug information -- #endif -+#if defined(_MSC_VER) && _MSC_VER >= 1800 -+#pragma warning(disable : 4464) // relative include path contains '..' -+#endif -+ -+// == 1200 : -O1 : for __forceinline -+// >= 1900 : -O1 : for printf -+#pragma warning(disable : 4710) // function not inlined -+ -+#if _MSC_VER < 1900 -+// winnt.h: 'Int64ShllMod32' -+#pragma warning(disable : 4514) // unreferenced inline function has been removed -+#endif -+ -+#if _MSC_VER < 1300 -+// #pragma warning(disable : 4702) // unreachable code -+// Bra.c : -O1: -+#pragma warning(disable : 4714) // function marked as __forceinline not inlined -+#endif -+ -+/* -+#if _MSC_VER > 1400 && _MSC_VER <= 1900 -+// strcat: This function or variable may be unsafe -+// sysinfoapi.h: kit10: GetVersion was declared deprecated -+#pragma warning(disable : 4996) -+#endif -+*/ -+ -+#if _MSC_VER > 1200 -+// -Wall warnings -+ -+#pragma warning(disable : 4711) // function selected for automatic inline expansion -+#pragma warning(disable : 4820) // '2' bytes padding added after data member -+ -+#if _MSC_VER >= 1400 && _MSC_VER < 1920 -+// 1400: string.h: _DBG_MEMCPY_INLINE_ -+// 1600 - 191x : smmintrin.h __cplusplus' -+// is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' -+#pragma warning(disable : 4668) -+ -+// 1400 - 1600 : WinDef.h : 'FARPROC' : -+// 1900 - 191x : immintrin.h: _readfsbase_u32 -+// no function prototype given : converting '()' to '(void)' -+#pragma warning(disable : 4255) -+#endif -+ -+#if _MSC_VER >= 1914 -+// Compiler will insert Spectre mitigation for memory load if /Qspectre switch specified -+#pragma warning(disable : 5045) -+#endif -+ -+#endif // _MSC_VER > 1200 -+#endif // _MSC_VER -+ -+ -+#if defined(__clang__) && (__clang_major__ >= 4) -+ #define Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE \ -+ _Pragma("clang loop unroll(disable)") \ -+ _Pragma("clang loop vectorize(disable)") -+ #define Z7_ATTRIB_NO_VECTORIZE -+#elif defined(__GNUC__) && (__GNUC__ >= 5) -+ #define Z7_ATTRIB_NO_VECTORIZE __attribute__((optimize("no-tree-vectorize"))) -+ // __attribute__((optimize("no-unroll-loops"))); -+ #define Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE -+#elif defined(_MSC_VER) && (_MSC_VER >= 1920) -+ #define Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE \ -+ _Pragma("loop( no_vector )") -+ #define Z7_ATTRIB_NO_VECTORIZE -+#else -+ #define Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE -+ #define Z7_ATTRIB_NO_VECTORIZE -+#endif -+ -+#if defined(MY_CPU_X86_OR_AMD64) && ( \ -+ defined(__clang__) && (__clang_major__ >= 4) \ -+ || defined(__GNUC__) && (__GNUC__ >= 5)) -+ #define Z7_ATTRIB_NO_SSE __attribute__((__target__("no-sse"))) -+#else -+ #define Z7_ATTRIB_NO_SSE -+#endif -+ -+#define Z7_ATTRIB_NO_VECTOR \ -+ Z7_ATTRIB_NO_VECTORIZE \ -+ Z7_ATTRIB_NO_SSE -+ -+ -+#if defined(__clang__) && (__clang_major__ >= 8) \ -+ || defined(__GNUC__) && (__GNUC__ >= 1000) \ -+ /* || defined(_MSC_VER) && (_MSC_VER >= 1920) */ -+ // GCC is not good for __builtin_expect() -+ #define Z7_LIKELY(x) (__builtin_expect((x), 1)) -+ #define Z7_UNLIKELY(x) (__builtin_expect((x), 0)) -+ // #define Z7_unlikely [[unlikely]] -+ // #define Z7_likely [[likely]] -+#else -+ #define Z7_LIKELY(x) (x) -+ #define Z7_UNLIKELY(x) (x) -+ // #define Z7_likely -+#endif - -- #ifdef __clang__ -- #pragma clang diagnostic ignored "-Wdeprecated-declarations" -- #pragma clang diagnostic ignored "-Wmicrosoft-exception-spec" -- // #pragma clang diagnostic ignored "-Wreserved-id-macro" -- #endif - -+#if (defined(Z7_CLANG_VERSION) && (Z7_CLANG_VERSION >= 36000)) -+#define Z7_DIAGNOSCTIC_IGNORE_BEGIN_RESERVED_MACRO_IDENTIFIER \ -+ _Pragma("GCC diagnostic push") \ -+ _Pragma("GCC diagnostic ignored \"-Wreserved-macro-identifier\"") -+#define Z7_DIAGNOSCTIC_IGNORE_END_RESERVED_MACRO_IDENTIFIER \ -+ _Pragma("GCC diagnostic pop") -+#else -+#define Z7_DIAGNOSCTIC_IGNORE_BEGIN_RESERVED_MACRO_IDENTIFIER -+#define Z7_DIAGNOSCTIC_IGNORE_END_RESERVED_MACRO_IDENTIFIER - #endif - - #define UNUSED_VAR(x) (void)x; -diff --git a/src/lzma/CpuArch.c b/src/lzma/CpuArch.c -index 1a1facf54..4e2af7707 100644 ---- a/src/lzma/CpuArch.c -+++ b/src/lzma/CpuArch.c -@@ -1,187 +1,318 @@ - /* CpuArch.c -- CPU specific code --2021-07-13 : Igor Pavlov : Public domain */ -+2023-05-18 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -+// #include -+ - #include "CpuArch.h" - - #ifdef MY_CPU_X86_OR_AMD64 - --#if (defined(_MSC_VER) && !defined(MY_CPU_AMD64)) || defined(__GNUC__) --#define USE_ASM -+#undef NEED_CHECK_FOR_CPUID -+#if !defined(MY_CPU_AMD64) -+#define NEED_CHECK_FOR_CPUID - #endif - --#if !defined(USE_ASM) && _MSC_VER >= 1500 --#include -+/* -+ cpuid instruction supports (subFunction) parameter in ECX, -+ that is used only with some specific (function) parameter values. -+ But we always use only (subFunction==0). -+*/ -+/* -+ __cpuid(): MSVC and GCC/CLANG use same function/macro name -+ but parameters are different. -+ We use MSVC __cpuid() parameters style for our z7_x86_cpuid() function. -+*/ -+ -+#if defined(__GNUC__) /* && (__GNUC__ >= 10) */ \ -+ || defined(__clang__) /* && (__clang_major__ >= 10) */ -+ -+/* there was some CLANG/GCC compilers that have issues with -+ rbx(ebx) handling in asm blocks in -fPIC mode (__PIC__ is defined). -+ compiler's contains the macro __cpuid() that is similar to our code. -+ The history of __cpuid() changes in CLANG/GCC: -+ GCC: -+ 2007: it preserved ebx for (__PIC__ && __i386__) -+ 2013: it preserved rbx and ebx for __PIC__ -+ 2014: it doesn't preserves rbx and ebx anymore -+ we suppose that (__GNUC__ >= 5) fixed that __PIC__ ebx/rbx problem. -+ CLANG: -+ 2014+: it preserves rbx, but only for 64-bit code. No __PIC__ check. -+ Why CLANG cares about 64-bit mode only, and doesn't care about ebx (in 32-bit)? -+ Do we need __PIC__ test for CLANG or we must care about rbx even if -+ __PIC__ is not defined? -+*/ -+ -+#define ASM_LN "\n" -+ -+#if defined(MY_CPU_AMD64) && defined(__PIC__) \ -+ && ((defined (__GNUC__) && (__GNUC__ < 5)) || defined(__clang__)) -+ -+#define x86_cpuid_MACRO(p, func) { \ -+ __asm__ __volatile__ ( \ -+ ASM_LN "mov %%rbx, %q1" \ -+ ASM_LN "cpuid" \ -+ ASM_LN "xchg %%rbx, %q1" \ -+ : "=a" ((p)[0]), "=&r" ((p)[1]), "=c" ((p)[2]), "=d" ((p)[3]) : "0" (func), "2"(0)); } -+ -+ /* "=&r" selects free register. It can select even rbx, if that register is free. -+ "=&D" for (RDI) also works, but the code can be larger with "=&D" -+ "2"(0) means (subFunction = 0), -+ 2 is (zero-based) index in the output constraint list "=c" (ECX). */ -+ -+#elif defined(MY_CPU_X86) && defined(__PIC__) \ -+ && ((defined (__GNUC__) && (__GNUC__ < 5)) || defined(__clang__)) -+ -+#define x86_cpuid_MACRO(p, func) { \ -+ __asm__ __volatile__ ( \ -+ ASM_LN "mov %%ebx, %k1" \ -+ ASM_LN "cpuid" \ -+ ASM_LN "xchg %%ebx, %k1" \ -+ : "=a" ((p)[0]), "=&r" ((p)[1]), "=c" ((p)[2]), "=d" ((p)[3]) : "0" (func), "2"(0)); } -+ -+#else -+ -+#define x86_cpuid_MACRO(p, func) { \ -+ __asm__ __volatile__ ( \ -+ ASM_LN "cpuid" \ -+ : "=a" ((p)[0]), "=b" ((p)[1]), "=c" ((p)[2]), "=d" ((p)[3]) : "0" (func), "2"(0)); } -+ - #endif - --#if defined(USE_ASM) && !defined(MY_CPU_AMD64) --static UInt32 CheckFlag(UInt32 flag) --{ -- #ifdef _MSC_VER -- __asm pushfd; -- __asm pop EAX; -- __asm mov EDX, EAX; -- __asm xor EAX, flag; -- __asm push EAX; -- __asm popfd; -- __asm pushfd; -- __asm pop EAX; -- __asm xor EAX, EDX; -- __asm push EDX; -- __asm popfd; -- __asm and flag, EAX; -- #else -+ -+void Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func) -+{ -+ x86_cpuid_MACRO(p, func) -+} -+ -+ -+Z7_NO_INLINE -+UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void) -+{ -+ #if defined(NEED_CHECK_FOR_CPUID) -+ #define EFALGS_CPUID_BIT 21 -+ UInt32 a; - __asm__ __volatile__ ( -- "pushf\n\t" -- "pop %%EAX\n\t" -- "movl %%EAX,%%EDX\n\t" -- "xorl %0,%%EAX\n\t" -- "push %%EAX\n\t" -- "popf\n\t" -- "pushf\n\t" -- "pop %%EAX\n\t" -- "xorl %%EDX,%%EAX\n\t" -- "push %%EDX\n\t" -- "popf\n\t" -- "andl %%EAX, %0\n\t": -- "=c" (flag) : "c" (flag) : -- "%eax", "%edx"); -+ ASM_LN "pushf" -+ ASM_LN "pushf" -+ ASM_LN "pop %0" -+ // ASM_LN "movl %0, %1" -+ // ASM_LN "xorl $0x200000, %0" -+ ASM_LN "btc %1, %0" -+ ASM_LN "push %0" -+ ASM_LN "popf" -+ ASM_LN "pushf" -+ ASM_LN "pop %0" -+ ASM_LN "xorl (%%esp), %0" -+ -+ ASM_LN "popf" -+ ASM_LN -+ : "=&r" (a) // "=a" -+ : "i" (EFALGS_CPUID_BIT) -+ ); -+ if ((a & (1 << EFALGS_CPUID_BIT)) == 0) -+ return 0; -+ #endif -+ { -+ UInt32 p[4]; -+ x86_cpuid_MACRO(p, 0) -+ return p[0]; -+ } -+} -+ -+#undef ASM_LN -+ -+#elif !defined(_MSC_VER) -+ -+/* -+// for gcc/clang and other: we can try to use __cpuid macro: -+#include -+void Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func) -+{ -+ __cpuid(func, p[0], p[1], p[2], p[3]); -+} -+UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void) -+{ -+ return (UInt32)__get_cpuid_max(0, NULL); -+} -+*/ -+// for unsupported cpuid: -+void Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func) -+{ -+ UNUSED_VAR(func) -+ p[0] = p[1] = p[2] = p[3] = 0; -+} -+UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void) -+{ -+ return 0; -+} -+ -+#else // _MSC_VER -+ -+#if !defined(MY_CPU_AMD64) -+ -+UInt32 __declspec(naked) Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void) -+{ -+ #if defined(NEED_CHECK_FOR_CPUID) -+ #define EFALGS_CPUID_BIT 21 -+ __asm pushfd -+ __asm pushfd -+ /* -+ __asm pop eax -+ // __asm mov edx, eax -+ __asm btc eax, EFALGS_CPUID_BIT -+ __asm push eax -+ */ -+ __asm btc dword ptr [esp], EFALGS_CPUID_BIT -+ __asm popfd -+ __asm pushfd -+ __asm pop eax -+ // __asm xor eax, edx -+ __asm xor eax, [esp] -+ // __asm push edx -+ __asm popfd -+ __asm and eax, (1 shl EFALGS_CPUID_BIT) -+ __asm jz end_func -+ #endif -+ __asm push ebx -+ __asm xor eax, eax // func -+ __asm xor ecx, ecx // subFunction (optional) for (func == 0) -+ __asm cpuid -+ __asm pop ebx -+ #if defined(NEED_CHECK_FOR_CPUID) -+ end_func: - #endif -- return flag; -+ __asm ret 0 - } --#define CHECK_CPUID_IS_SUPPORTED if (CheckFlag(1 << 18) == 0 || CheckFlag(1 << 21) == 0) return False7z; --#else --#define CHECK_CPUID_IS_SUPPORTED --#endif - --#ifndef USE_ASM -- #ifdef _MSC_VER -+void __declspec(naked) Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func) -+{ -+ UNUSED_VAR(p) -+ UNUSED_VAR(func) -+ __asm push ebx -+ __asm push edi -+ __asm mov edi, ecx // p -+ __asm mov eax, edx // func -+ __asm xor ecx, ecx // subfunction (optional) for (func == 0) -+ __asm cpuid -+ __asm mov [edi ], eax -+ __asm mov [edi + 4], ebx -+ __asm mov [edi + 8], ecx -+ __asm mov [edi + 12], edx -+ __asm pop edi -+ __asm pop ebx -+ __asm ret 0 -+} -+ -+#else // MY_CPU_AMD64 -+ - #if _MSC_VER >= 1600 -- #define MY__cpuidex __cpuidex -+ #include -+ #define MY_cpuidex __cpuidex - #else -- - /* -- __cpuid (function == 4) requires subfunction number in ECX. -+ __cpuid (func == (0 or 7)) requires subfunction number in ECX. - MSDN: The __cpuid intrinsic clears the ECX register before calling the cpuid instruction. - __cpuid() in new MSVC clears ECX. -- __cpuid() in old MSVC (14.00) doesn't clear ECX -- We still can use __cpuid for low (function) values that don't require ECX, -- but __cpuid() in old MSVC will be incorrect for some function values: (function == 4). -+ __cpuid() in old MSVC (14.00) x64 doesn't clear ECX -+ We still can use __cpuid for low (func) values that don't require ECX, -+ but __cpuid() in old MSVC will be incorrect for some func values: (func == 7). - So here we use the hack for old MSVC to send (subFunction) in ECX register to cpuid instruction, -- where ECX value is first parameter for FAST_CALL / NO_INLINE function, -- So the caller of MY__cpuidex_HACK() sets ECX as subFunction, and -+ where ECX value is first parameter for FASTCALL / NO_INLINE func, -+ So the caller of MY_cpuidex_HACK() sets ECX as subFunction, and - old MSVC for __cpuid() doesn't change ECX and cpuid instruction gets (subFunction) value. - -- DON'T remove MY_NO_INLINE and MY_FAST_CALL for MY__cpuidex_HACK() !!! -+DON'T remove Z7_NO_INLINE and Z7_FASTCALL for MY_cpuidex_HACK(): !!! - */ -- - static --MY_NO_INLINE --void MY_FAST_CALL MY__cpuidex_HACK(UInt32 subFunction, int *CPUInfo, UInt32 function) -+Z7_NO_INLINE void Z7_FASTCALL MY_cpuidex_HACK(UInt32 subFunction, UInt32 func, int *CPUInfo) - { -- UNUSED_VAR(subFunction); -- __cpuid(CPUInfo, function); -+ UNUSED_VAR(subFunction) -+ __cpuid(CPUInfo, func); - } -- -- #define MY__cpuidex(info, func, func2) MY__cpuidex_HACK(func2, info, func) -- #pragma message("======== MY__cpuidex_HACK WAS USED ========") -- #endif -- #else -- #define MY__cpuidex(info, func, func2) __cpuid(info, func) -- #pragma message("======== (INCORRECT ?) cpuid WAS USED ========") -- #endif -+ #define MY_cpuidex(info, func, func2) MY_cpuidex_HACK(func2, func, info) -+ #pragma message("======== MY_cpuidex_HACK WAS USED ========") -+ #endif // _MSC_VER >= 1600 -+ -+#if !defined(MY_CPU_AMD64) -+/* inlining for __cpuid() in MSVC x86 (32-bit) produces big ineffective code, -+ so we disable inlining here */ -+Z7_NO_INLINE - #endif -- -- -- -- --void MyCPUID(UInt32 function, UInt32 *a, UInt32 *b, UInt32 *c, UInt32 *d) -+void Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func) - { -- #ifdef USE_ASM -- -- #ifdef _MSC_VER -- -- UInt32 a2, b2, c2, d2; -- __asm xor EBX, EBX; -- __asm xor ECX, ECX; -- __asm xor EDX, EDX; -- __asm mov EAX, function; -- __asm cpuid; -- __asm mov a2, EAX; -- __asm mov b2, EBX; -- __asm mov c2, ECX; -- __asm mov d2, EDX; -- -- *a = a2; -- *b = b2; -- *c = c2; -- *d = d2; -- -- #else -- -- __asm__ __volatile__ ( -- #if defined(MY_CPU_AMD64) && defined(__PIC__) -- "mov %%rbx, %%rdi;" -- "cpuid;" -- "xchg %%rbx, %%rdi;" -- : "=a" (*a) , -- "=D" (*b) , -- #elif defined(MY_CPU_X86) && defined(__PIC__) -- "mov %%ebx, %%edi;" -- "cpuid;" -- "xchgl %%ebx, %%edi;" -- : "=a" (*a) , -- "=D" (*b) , -- #else -- "cpuid" -- : "=a" (*a) , -- "=b" (*b) , -- #endif -- "=c" (*c) , -- "=d" (*d) -- : "0" (function), "c"(0) ) ; -- -- #endif -- -- #else -+ MY_cpuidex((int *)p, (int)func, 0); -+} - -- int CPUInfo[4]; -+Z7_NO_INLINE -+UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void) -+{ -+ int a[4]; -+ MY_cpuidex(a, 0, 0); -+ return a[0]; -+} - -- MY__cpuidex(CPUInfo, (int)function, 0); -+#endif // MY_CPU_AMD64 -+#endif // _MSC_VER - -- *a = (UInt32)CPUInfo[0]; -- *b = (UInt32)CPUInfo[1]; -- *c = (UInt32)CPUInfo[2]; -- *d = (UInt32)CPUInfo[3]; -+#if defined(NEED_CHECK_FOR_CPUID) -+#define CHECK_CPUID_IS_SUPPORTED { if (z7_x86_cpuid_GetMaxFunc() == 0) return 0; } -+#else -+#define CHECK_CPUID_IS_SUPPORTED -+#endif -+#undef NEED_CHECK_FOR_CPUID - -- #endif --} - --BoolInt x86cpuid_CheckAndRead(Cx86cpuid *p) -+static -+BoolInt x86cpuid_Func_1(UInt32 *p) - { - CHECK_CPUID_IS_SUPPORTED -- MyCPUID(0, &p->maxFunc, &p->vendor[0], &p->vendor[2], &p->vendor[1]); -- MyCPUID(1, &p->ver, &p->b, &p->c, &p->d); -+ z7_x86_cpuid(p, 1); - return True7z; - } - --static const UInt32 kVendors[][3] = -+/* -+static const UInt32 kVendors[][1] = - { -- { 0x756E6547, 0x49656E69, 0x6C65746E}, -- { 0x68747541, 0x69746E65, 0x444D4163}, -- { 0x746E6543, 0x48727561, 0x736C7561} -+ { 0x756E6547 }, // , 0x49656E69, 0x6C65746E }, -+ { 0x68747541 }, // , 0x69746E65, 0x444D4163 }, -+ { 0x746E6543 } // , 0x48727561, 0x736C7561 } - }; -+*/ -+ -+/* -+typedef struct -+{ -+ UInt32 maxFunc; -+ UInt32 vendor[3]; -+ UInt32 ver; -+ UInt32 b; -+ UInt32 c; -+ UInt32 d; -+} Cx86cpuid; -+ -+enum -+{ -+ CPU_FIRM_INTEL, -+ CPU_FIRM_AMD, -+ CPU_FIRM_VIA -+}; -+int x86cpuid_GetFirm(const Cx86cpuid *p); -+#define x86cpuid_ver_GetFamily(ver) (((ver >> 16) & 0xff0) | ((ver >> 8) & 0xf)) -+#define x86cpuid_ver_GetModel(ver) (((ver >> 12) & 0xf0) | ((ver >> 4) & 0xf)) -+#define x86cpuid_ver_GetStepping(ver) (ver & 0xf) - - int x86cpuid_GetFirm(const Cx86cpuid *p) - { - unsigned i; -- for (i = 0; i < sizeof(kVendors) / sizeof(kVendors[i]); i++) -+ for (i = 0; i < sizeof(kVendors) / sizeof(kVendors[0]); i++) - { - const UInt32 *v = kVendors[i]; -- if (v[0] == p->vendor[0] && -- v[1] == p->vendor[1] && -- v[2] == p->vendor[2]) -+ if (v[0] == p->vendor[0] -+ // && v[1] == p->vendor[1] -+ // && v[2] == p->vendor[2] -+ ) - return (int)i; - } - return -1; -@@ -190,41 +321,55 @@ int x86cpuid_GetFirm(const Cx86cpuid *p) - BoolInt CPU_Is_InOrder() - { - Cx86cpuid p; -- int firm; - UInt32 family, model; - if (!x86cpuid_CheckAndRead(&p)) - return True7z; - -- family = x86cpuid_GetFamily(p.ver); -- model = x86cpuid_GetModel(p.ver); -- -- firm = x86cpuid_GetFirm(&p); -+ family = x86cpuid_ver_GetFamily(p.ver); -+ model = x86cpuid_ver_GetModel(p.ver); - -- switch (firm) -+ switch (x86cpuid_GetFirm(&p)) - { - case CPU_FIRM_INTEL: return (family < 6 || (family == 6 && ( -- /* In-Order Atom CPU */ -- model == 0x1C /* 45 nm, N4xx, D4xx, N5xx, D5xx, 230, 330 */ -- || model == 0x26 /* 45 nm, Z6xx */ -- || model == 0x27 /* 32 nm, Z2460 */ -- || model == 0x35 /* 32 nm, Z2760 */ -- || model == 0x36 /* 32 nm, N2xxx, D2xxx */ -+ // In-Order Atom CPU -+ model == 0x1C // 45 nm, N4xx, D4xx, N5xx, D5xx, 230, 330 -+ || model == 0x26 // 45 nm, Z6xx -+ || model == 0x27 // 32 nm, Z2460 -+ || model == 0x35 // 32 nm, Z2760 -+ || model == 0x36 // 32 nm, N2xxx, D2xxx - ))); - case CPU_FIRM_AMD: return (family < 5 || (family == 5 && (model < 6 || model == 0xA))); - case CPU_FIRM_VIA: return (family < 6 || (family == 6 && model < 0xF)); - } -- return True7z; -+ return False7z; // v23 : unknown processors are not In-Order - } -+*/ -+ -+#ifdef _WIN32 -+#include "7zWindows.h" -+#endif - - #if !defined(MY_CPU_AMD64) && defined(_WIN32) --#include --static BoolInt CPU_Sys_Is_SSE_Supported() -+ -+/* for legacy SSE ia32: there is no user-space cpu instruction to check -+ that OS supports SSE register storing/restoring on context switches. -+ So we need some OS-specific function to check that it's safe to use SSE registers. -+*/ -+ -+Z7_FORCE_INLINE -+static BoolInt CPU_Sys_Is_SSE_Supported(void) - { -- OSVERSIONINFO vi; -- vi.dwOSVersionInfoSize = sizeof(vi); -- if (!GetVersionEx(&vi)) -- return False7z; -- return (vi.dwMajorVersion >= 5); -+#ifdef _MSC_VER -+ #pragma warning(push) -+ #pragma warning(disable : 4996) // `GetVersion': was declared deprecated -+#endif -+ /* low byte is major version of Windows -+ We suppose that any Windows version since -+ Windows2000 (major == 5) supports SSE registers */ -+ return (Byte)GetVersion() >= 5; -+#if defined(_MSC_VER) -+ #pragma warning(pop) -+#endif - } - #define CHECK_SYS_SSE_SUPPORT if (!CPU_Sys_Is_SSE_Supported()) return False7z; - #else -@@ -232,94 +377,300 @@ static BoolInt CPU_Sys_Is_SSE_Supported() - #endif - - --static UInt32 X86_CPUID_ECX_Get_Flags() -+#if !defined(MY_CPU_AMD64) -+ -+BoolInt CPU_IsSupported_CMOV(void) - { -- Cx86cpuid p; -+ UInt32 a[4]; -+ if (!x86cpuid_Func_1(&a[0])) -+ return 0; -+ return (a[3] >> 15) & 1; -+} -+ -+BoolInt CPU_IsSupported_SSE(void) -+{ -+ UInt32 a[4]; - CHECK_SYS_SSE_SUPPORT -- if (!x86cpuid_CheckAndRead(&p)) -+ if (!x86cpuid_Func_1(&a[0])) -+ return 0; -+ return (a[3] >> 25) & 1; -+} -+ -+BoolInt CPU_IsSupported_SSE2(void) -+{ -+ UInt32 a[4]; -+ CHECK_SYS_SSE_SUPPORT -+ if (!x86cpuid_Func_1(&a[0])) -+ return 0; -+ return (a[3] >> 26) & 1; -+} -+ -+#endif -+ -+ -+static UInt32 x86cpuid_Func_1_ECX(void) -+{ -+ UInt32 a[4]; -+ CHECK_SYS_SSE_SUPPORT -+ if (!x86cpuid_Func_1(&a[0])) - return 0; -- return p.c; -+ return a[2]; - } - --BoolInt CPU_IsSupported_AES() -+BoolInt CPU_IsSupported_AES(void) - { -- return (X86_CPUID_ECX_Get_Flags() >> 25) & 1; -+ return (x86cpuid_Func_1_ECX() >> 25) & 1; - } - --BoolInt CPU_IsSupported_SSSE3() -+BoolInt CPU_IsSupported_SSSE3(void) - { -- return (X86_CPUID_ECX_Get_Flags() >> 9) & 1; -+ return (x86cpuid_Func_1_ECX() >> 9) & 1; - } - --BoolInt CPU_IsSupported_SSE41() -+BoolInt CPU_IsSupported_SSE41(void) - { -- return (X86_CPUID_ECX_Get_Flags() >> 19) & 1; -+ return (x86cpuid_Func_1_ECX() >> 19) & 1; - } - --BoolInt CPU_IsSupported_SHA() -+BoolInt CPU_IsSupported_SHA(void) - { -- Cx86cpuid p; - CHECK_SYS_SSE_SUPPORT -- if (!x86cpuid_CheckAndRead(&p)) -- return False7z; - -- if (p.maxFunc < 7) -+ if (z7_x86_cpuid_GetMaxFunc() < 7) - return False7z; - { -- UInt32 d[4] = { 0 }; -- MyCPUID(7, &d[0], &d[1], &d[2], &d[3]); -+ UInt32 d[4]; -+ z7_x86_cpuid(d, 7); - return (d[1] >> 29) & 1; - } - } - --// #include -+/* -+MSVC: _xgetbv() intrinsic is available since VS2010SP1. -+ MSVC also defines (_XCR_XFEATURE_ENABLED_MASK) macro in -+ that we can use or check. -+ For any 32-bit x86 we can use asm code in MSVC, -+ but MSVC asm code is huge after compilation. -+ So _xgetbv() is better -+ -+ICC: _xgetbv() intrinsic is available (in what version of ICC?) -+ ICC defines (__GNUC___) and it supports gnu assembler -+ also ICC supports MASM style code with -use-msasm switch. -+ but ICC doesn't support __attribute__((__target__)) -+ -+GCC/CLANG 9: -+ _xgetbv() is macro that works via __builtin_ia32_xgetbv() -+ and we need __attribute__((__target__("xsave")). -+ But with __target__("xsave") the function will be not -+ inlined to function that has no __target__("xsave") attribute. -+ If we want _xgetbv() call inlining, then we should use asm version -+ instead of calling _xgetbv(). -+ Note:intrinsic is broke before GCC 8.2: -+ https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85684 -+*/ - --#ifdef _WIN32 --#include -+#if defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1100) \ -+ || defined(_MSC_VER) && (_MSC_VER >= 1600) && (_MSC_FULL_VER >= 160040219) \ -+ || defined(__GNUC__) && (__GNUC__ >= 9) \ -+ || defined(__clang__) && (__clang_major__ >= 9) -+// we define ATTRIB_XGETBV, if we want to use predefined _xgetbv() from compiler -+#if defined(__INTEL_COMPILER) -+#define ATTRIB_XGETBV -+#elif defined(__GNUC__) || defined(__clang__) -+// we don't define ATTRIB_XGETBV here, because asm version is better for inlining. -+// #define ATTRIB_XGETBV __attribute__((__target__("xsave"))) -+#else -+#define ATTRIB_XGETBV -+#endif -+#endif -+ -+#if defined(ATTRIB_XGETBV) -+#include - #endif - --BoolInt CPU_IsSupported_AVX2() -+ -+// XFEATURE_ENABLED_MASK/XCR0 -+#define MY_XCR_XFEATURE_ENABLED_MASK 0 -+ -+#if defined(ATTRIB_XGETBV) -+ATTRIB_XGETBV -+#endif -+static UInt64 x86_xgetbv_0(UInt32 num) - { -- Cx86cpuid p; -- CHECK_SYS_SSE_SUPPORT -+#if defined(ATTRIB_XGETBV) -+ { -+ return -+ #if (defined(_MSC_VER)) -+ _xgetbv(num); -+ #else -+ __builtin_ia32_xgetbv( -+ #if !defined(__clang__) -+ (int) -+ #endif -+ num); -+ #endif -+ } -+ -+#elif defined(__GNUC__) || defined(__clang__) || defined(__SUNPRO_CC) -+ -+ UInt32 a, d; -+ #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) -+ __asm__ -+ ( -+ "xgetbv" -+ : "=a"(a), "=d"(d) : "c"(num) : "cc" -+ ); -+ #else // is old gcc -+ __asm__ -+ ( -+ ".byte 0x0f, 0x01, 0xd0" "\n\t" -+ : "=a"(a), "=d"(d) : "c"(num) : "cc" -+ ); -+ #endif -+ return ((UInt64)d << 32) | a; -+ // return a; -+ -+#elif defined(_MSC_VER) && !defined(MY_CPU_AMD64) -+ -+ UInt32 a, d; -+ __asm { -+ push eax -+ push edx -+ push ecx -+ mov ecx, num; -+ // xor ecx, ecx // = MY_XCR_XFEATURE_ENABLED_MASK -+ _emit 0x0f -+ _emit 0x01 -+ _emit 0xd0 -+ mov a, eax -+ mov d, edx -+ pop ecx -+ pop edx -+ pop eax -+ } -+ return ((UInt64)d << 32) | a; -+ // return a; -+ -+#else // it's unknown compiler -+ // #error "Need xgetbv function" -+ UNUSED_VAR(num) -+ // for MSVC-X64 we could call external function from external file. -+ /* Actually we had checked OSXSAVE/AVX in cpuid before. -+ So it's expected that OS supports at least AVX and below. */ -+ // if (num != MY_XCR_XFEATURE_ENABLED_MASK) return 0; // if not XCR0 -+ return -+ // (1 << 0) | // x87 -+ (1 << 1) // SSE -+ | (1 << 2); // AVX -+ -+#endif -+} - -+#ifdef _WIN32 -+/* -+ Windows versions do not know about new ISA extensions that -+ can be introduced. But we still can use new extensions, -+ even if Windows doesn't report about supporting them, -+ But we can use new extensions, only if Windows knows about new ISA extension -+ that changes the number or size of registers: SSE, AVX/XSAVE, AVX512 -+ So it's enough to check -+ MY_PF_AVX_INSTRUCTIONS_AVAILABLE -+ instead of -+ MY_PF_AVX2_INSTRUCTIONS_AVAILABLE -+*/ -+#define MY_PF_XSAVE_ENABLED 17 -+// #define MY_PF_SSSE3_INSTRUCTIONS_AVAILABLE 36 -+// #define MY_PF_SSE4_1_INSTRUCTIONS_AVAILABLE 37 -+// #define MY_PF_SSE4_2_INSTRUCTIONS_AVAILABLE 38 -+// #define MY_PF_AVX_INSTRUCTIONS_AVAILABLE 39 -+// #define MY_PF_AVX2_INSTRUCTIONS_AVAILABLE 40 -+// #define MY_PF_AVX512F_INSTRUCTIONS_AVAILABLE 41 -+#endif -+ -+BoolInt CPU_IsSupported_AVX(void) -+{ - #ifdef _WIN32 -- #define MY__PF_XSAVE_ENABLED 17 -- if (!IsProcessorFeaturePresent(MY__PF_XSAVE_ENABLED)) -+ if (!IsProcessorFeaturePresent(MY_PF_XSAVE_ENABLED)) - return False7z; -+ /* PF_AVX_INSTRUCTIONS_AVAILABLE probably is supported starting from -+ some latest Win10 revisions. But we need AVX in older Windows also. -+ So we don't use the following check: */ -+ /* -+ if (!IsProcessorFeaturePresent(MY_PF_AVX_INSTRUCTIONS_AVAILABLE)) -+ return False7z; -+ */ - #endif - -- if (!x86cpuid_CheckAndRead(&p)) -+ /* -+ OS must use new special XSAVE/XRSTOR instructions to save -+ AVX registers when it required for context switching. -+ At OS statring: -+ OS sets CR4.OSXSAVE flag to signal the processor that OS supports the XSAVE extensions. -+ Also OS sets bitmask in XCR0 register that defines what -+ registers will be processed by XSAVE instruction: -+ XCR0.SSE[bit 0] - x87 registers and state -+ XCR0.SSE[bit 1] - SSE registers and state -+ XCR0.AVX[bit 2] - AVX registers and state -+ CR4.OSXSAVE is reflected to CPUID.1:ECX.OSXSAVE[bit 27]. -+ So we can read that bit in user-space. -+ XCR0 is available for reading in user-space by new XGETBV instruction. -+ */ -+ { -+ const UInt32 c = x86cpuid_Func_1_ECX(); -+ if (0 == (1 -+ & (c >> 28) // AVX instructions are supported by hardware -+ & (c >> 27))) // OSXSAVE bit: XSAVE and related instructions are enabled by OS. -+ return False7z; -+ } -+ -+ /* also we can check -+ CPUID.1:ECX.XSAVE [bit 26] : that shows that -+ XSAVE, XRESTOR, XSETBV, XGETBV instructions are supported by hardware. -+ But that check is redundant, because if OSXSAVE bit is set, then XSAVE is also set */ -+ -+ /* If OS have enabled XSAVE extension instructions (OSXSAVE == 1), -+ in most cases we expect that OS also will support storing/restoring -+ for AVX and SSE states at least. -+ But to be ensure for that we call user-space instruction -+ XGETBV(0) to get XCR0 value that contains bitmask that defines -+ what exact states(registers) OS have enabled for storing/restoring. -+ */ -+ -+ { -+ const UInt32 bm = (UInt32)x86_xgetbv_0(MY_XCR_XFEATURE_ENABLED_MASK); -+ // printf("\n=== XGetBV=%d\n", bm); -+ return 1 -+ & (bm >> 1) // SSE state is supported (set by OS) for storing/restoring -+ & (bm >> 2); // AVX state is supported (set by OS) for storing/restoring -+ } -+ // since Win7SP1: we can use GetEnabledXStateFeatures(); -+} -+ -+ -+BoolInt CPU_IsSupported_AVX2(void) -+{ -+ if (!CPU_IsSupported_AVX()) - return False7z; -- if (p.maxFunc < 7) -+ if (z7_x86_cpuid_GetMaxFunc() < 7) - return False7z; - { -- UInt32 d[4] = { 0 }; -- MyCPUID(7, &d[0], &d[1], &d[2], &d[3]); -+ UInt32 d[4]; -+ z7_x86_cpuid(d, 7); - // printf("\ncpuid(7): ebx=%8x ecx=%8x\n", d[1], d[2]); - return 1 - & (d[1] >> 5); // avx2 - } - } - --BoolInt CPU_IsSupported_VAES_AVX2() -+BoolInt CPU_IsSupported_VAES_AVX2(void) - { -- Cx86cpuid p; -- CHECK_SYS_SSE_SUPPORT -- -- #ifdef _WIN32 -- #define MY__PF_XSAVE_ENABLED 17 -- if (!IsProcessorFeaturePresent(MY__PF_XSAVE_ENABLED)) -+ if (!CPU_IsSupported_AVX()) - return False7z; -- #endif -- -- if (!x86cpuid_CheckAndRead(&p)) -- return False7z; -- if (p.maxFunc < 7) -+ if (z7_x86_cpuid_GetMaxFunc() < 7) - return False7z; - { -- UInt32 d[4] = { 0 }; -- MyCPUID(7, &d[0], &d[1], &d[2], &d[3]); -+ UInt32 d[4]; -+ z7_x86_cpuid(d, 7); - // printf("\ncpuid(7): ebx=%8x ecx=%8x\n", d[1], d[2]); - return 1 - & (d[1] >> 5) // avx2 -@@ -328,20 +679,15 @@ BoolInt CPU_IsSupported_VAES_AVX2() - } - } - --BoolInt CPU_IsSupported_PageGB() -+BoolInt CPU_IsSupported_PageGB(void) - { -- Cx86cpuid cpuid; -- if (!x86cpuid_CheckAndRead(&cpuid)) -- return False7z; -+ CHECK_CPUID_IS_SUPPORTED - { -- UInt32 d[4] = { 0 }; -- MyCPUID(0x80000000, &d[0], &d[1], &d[2], &d[3]); -+ UInt32 d[4]; -+ z7_x86_cpuid(d, 0x80000000); - if (d[0] < 0x80000001) - return False7z; -- } -- { -- UInt32 d[4] = { 0 }; -- MyCPUID(0x80000001, &d[0], &d[1], &d[2], &d[3]); -+ z7_x86_cpuid(d, 0x80000001); - return (d[3] >> 26) & 1; - } - } -@@ -351,11 +697,11 @@ BoolInt CPU_IsSupported_PageGB() - - #ifdef _WIN32 - --#include -+#include "7zWindows.h" - --BoolInt CPU_IsSupported_CRC32() { return IsProcessorFeaturePresent(PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } --BoolInt CPU_IsSupported_CRYPTO() { return IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } --BoolInt CPU_IsSupported_NEON() { return IsProcessorFeaturePresent(PF_ARM_NEON_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } -+BoolInt CPU_IsSupported_CRC32(void) { return IsProcessorFeaturePresent(PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } -+BoolInt CPU_IsSupported_CRYPTO(void) { return IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } -+BoolInt CPU_IsSupported_NEON(void) { return IsProcessorFeaturePresent(PF_ARM_NEON_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } - - #else - -@@ -378,28 +724,27 @@ static void Print_sysctlbyname(const char *name) - } - } - */ -+/* -+ Print_sysctlbyname("hw.pagesize"); -+ Print_sysctlbyname("machdep.cpu.brand_string"); -+*/ - --static BoolInt My_sysctlbyname_Get_BoolInt(const char *name) -+static BoolInt z7_sysctlbyname_Get_BoolInt(const char *name) - { - UInt32 val = 0; -- if (My_sysctlbyname_Get_UInt32(name, &val) == 0 && val == 1) -+ if (z7_sysctlbyname_Get_UInt32(name, &val) == 0 && val == 1) - return 1; - return 0; - } - -- /* -- Print_sysctlbyname("hw.pagesize"); -- Print_sysctlbyname("machdep.cpu.brand_string"); -- */ -- - BoolInt CPU_IsSupported_CRC32(void) - { -- return My_sysctlbyname_Get_BoolInt("hw.optional.armv8_crc32"); -+ return z7_sysctlbyname_Get_BoolInt("hw.optional.armv8_crc32"); - } - - BoolInt CPU_IsSupported_NEON(void) - { -- return My_sysctlbyname_Get_BoolInt("hw.optional.neon"); -+ return z7_sysctlbyname_Get_BoolInt("hw.optional.neon"); - } - - #ifdef MY_CPU_ARM64 -@@ -461,15 +806,15 @@ MY_HWCAP_CHECK_FUNC (AES) - - #include - --int My_sysctlbyname_Get(const char *name, void *buf, size_t *bufSize) -+int z7_sysctlbyname_Get(const char *name, void *buf, size_t *bufSize) - { - return sysctlbyname(name, buf, bufSize, NULL, 0); - } - --int My_sysctlbyname_Get_UInt32(const char *name, UInt32 *val) -+int z7_sysctlbyname_Get_UInt32(const char *name, UInt32 *val) - { - size_t bufSize = sizeof(*val); -- int res = My_sysctlbyname_Get(name, val, &bufSize); -+ const int res = z7_sysctlbyname_Get(name, val, &bufSize); - if (res == 0 && bufSize != sizeof(*val)) - return EFAULT; - return res; -diff --git a/src/lzma/CpuArch.h b/src/lzma/CpuArch.h -index 529d3a502..8e5d8a543 100644 ---- a/src/lzma/CpuArch.h -+++ b/src/lzma/CpuArch.h -@@ -1,8 +1,8 @@ - /* CpuArch.h -- CPU specific code --2021-07-13 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - --#ifndef __CPU_ARCH_H --#define __CPU_ARCH_H -+#ifndef ZIP7_INC_CPU_ARCH_H -+#define ZIP7_INC_CPU_ARCH_H - - #include "7zTypes.h" - -@@ -51,7 +51,13 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. - || defined(__AARCH64EB__) \ - || defined(__aarch64__) - #define MY_CPU_ARM64 -- #define MY_CPU_NAME "arm64" -+ #ifdef __ILP32__ -+ #define MY_CPU_NAME "arm64-32" -+ #define MY_CPU_SIZEOF_POINTER 4 -+ #else -+ #define MY_CPU_NAME "arm64" -+ #define MY_CPU_SIZEOF_POINTER 8 -+ #endif - #define MY_CPU_64BIT - #endif - -@@ -68,8 +74,10 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. - #define MY_CPU_ARM - - #if defined(__thumb__) || defined(__THUMBEL__) || defined(_M_ARMT) -+ #define MY_CPU_ARMT - #define MY_CPU_NAME "armt" - #else -+ #define MY_CPU_ARM32 - #define MY_CPU_NAME "arm" - #endif - /* #define MY_CPU_32BIT */ -@@ -103,6 +111,8 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. - || defined(__PPC__) \ - || defined(_POWER) - -+#define MY_CPU_PPC_OR_PPC64 -+ - #if defined(__ppc64__) \ - || defined(__powerpc64__) \ - || defined(_LP64) \ -@@ -123,12 +133,15 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. - #endif - - --#if defined(__sparc64__) -- #define MY_CPU_NAME "sparc64" -- #define MY_CPU_64BIT --#elif defined(__sparc__) -- #define MY_CPU_NAME "sparc" -- /* #define MY_CPU_32BIT */ -+#if defined(__riscv) \ -+ || defined(__riscv__) -+ #if __riscv_xlen == 32 -+ #define MY_CPU_NAME "riscv32" -+ #elif __riscv_xlen == 64 -+ #define MY_CPU_NAME "riscv64" -+ #else -+ #define MY_CPU_NAME "riscv" -+ #endif - #endif - - -@@ -194,6 +207,9 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. - #error Stop_Compiling_Bad_Endian - #endif - -+#if !defined(MY_CPU_LE) && !defined(MY_CPU_BE) -+ #error Stop_Compiling_CPU_ENDIAN_must_be_detected_at_compile_time -+#endif - - #if defined(MY_CPU_32BIT) && defined(MY_CPU_64BIT) - #error Stop_Compiling_Bad_32_64_BIT -@@ -250,6 +266,67 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. - - - -+#ifdef __has_builtin -+ #define Z7_has_builtin(x) __has_builtin(x) -+#else -+ #define Z7_has_builtin(x) 0 -+#endif -+ -+ -+#define Z7_BSWAP32_CONST(v) \ -+ ( (((UInt32)(v) << 24) ) \ -+ | (((UInt32)(v) << 8) & (UInt32)0xff0000) \ -+ | (((UInt32)(v) >> 8) & (UInt32)0xff00 ) \ -+ | (((UInt32)(v) >> 24) )) -+ -+ -+#if defined(_MSC_VER) && (_MSC_VER >= 1300) -+ -+#include -+ -+/* Note: these macros will use bswap instruction (486), that is unsupported in 386 cpu */ -+ -+#pragma intrinsic(_byteswap_ushort) -+#pragma intrinsic(_byteswap_ulong) -+#pragma intrinsic(_byteswap_uint64) -+ -+#define Z7_BSWAP16(v) _byteswap_ushort(v) -+#define Z7_BSWAP32(v) _byteswap_ulong (v) -+#define Z7_BSWAP64(v) _byteswap_uint64(v) -+#define Z7_CPU_FAST_BSWAP_SUPPORTED -+ -+#elif (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) \ -+ || (defined(__clang__) && Z7_has_builtin(__builtin_bswap16)) -+ -+#define Z7_BSWAP16(v) __builtin_bswap16(v) -+#define Z7_BSWAP32(v) __builtin_bswap32(v) -+#define Z7_BSWAP64(v) __builtin_bswap64(v) -+#define Z7_CPU_FAST_BSWAP_SUPPORTED -+ -+#else -+ -+#define Z7_BSWAP16(v) ((UInt16) \ -+ ( ((UInt32)(v) << 8) \ -+ | ((UInt32)(v) >> 8) \ -+ )) -+ -+#define Z7_BSWAP32(v) Z7_BSWAP32_CONST(v) -+ -+#define Z7_BSWAP64(v) \ -+ ( ( ( (UInt64)(v) ) << 8 * 7 ) \ -+ | ( ( (UInt64)(v) & ((UInt32)0xff << 8 * 1) ) << 8 * 5 ) \ -+ | ( ( (UInt64)(v) & ((UInt32)0xff << 8 * 2) ) << 8 * 3 ) \ -+ | ( ( (UInt64)(v) & ((UInt32)0xff << 8 * 3) ) << 8 * 1 ) \ -+ | ( ( (UInt64)(v) >> 8 * 1 ) & ((UInt32)0xff << 8 * 3) ) \ -+ | ( ( (UInt64)(v) >> 8 * 3 ) & ((UInt32)0xff << 8 * 2) ) \ -+ | ( ( (UInt64)(v) >> 8 * 5 ) & ((UInt32)0xff << 8 * 1) ) \ -+ | ( ( (UInt64)(v) >> 8 * 7 ) ) \ -+ ) -+ -+#endif -+ -+ -+ - #ifdef MY_CPU_LE - #if defined(MY_CPU_X86_OR_AMD64) \ - || defined(MY_CPU_ARM64) -@@ -269,13 +346,11 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. - #define GetUi32(p) (*(const UInt32 *)(const void *)(p)) - #ifdef MY_CPU_LE_UNALIGN_64 - #define GetUi64(p) (*(const UInt64 *)(const void *)(p)) -+#define SetUi64(p, v) { *(UInt64 *)(void *)(p) = (v); } - #endif - - #define SetUi16(p, v) { *(UInt16 *)(void *)(p) = (v); } - #define SetUi32(p, v) { *(UInt32 *)(void *)(p) = (v); } --#ifdef MY_CPU_LE_UNALIGN_64 --#define SetUi64(p, v) { *(UInt64 *)(void *)(p) = (v); } --#endif - - #else - -@@ -302,51 +377,26 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. - #endif - - --#ifndef MY_CPU_LE_UNALIGN_64 -- -+#ifndef GetUi64 - #define GetUi64(p) (GetUi32(p) | ((UInt64)GetUi32(((const Byte *)(p)) + 4) << 32)) -+#endif - -+#ifndef SetUi64 - #define SetUi64(p, v) { Byte *_ppp2_ = (Byte *)(p); UInt64 _vvv2_ = (v); \ -- SetUi32(_ppp2_ , (UInt32)_vvv2_); \ -- SetUi32(_ppp2_ + 4, (UInt32)(_vvv2_ >> 32)); } -- -+ SetUi32(_ppp2_ , (UInt32)_vvv2_) \ -+ SetUi32(_ppp2_ + 4, (UInt32)(_vvv2_ >> 32)) } - #endif - - -+#if defined(MY_CPU_LE_UNALIGN) && defined(Z7_CPU_FAST_BSWAP_SUPPORTED) - -+#define GetBe32(p) Z7_BSWAP32 (*(const UInt32 *)(const void *)(p)) -+#define SetBe32(p, v) { (*(UInt32 *)(void *)(p)) = Z7_BSWAP32(v); } - --#ifdef __has_builtin -- #define MY__has_builtin(x) __has_builtin(x) --#else -- #define MY__has_builtin(x) 0 -+#if defined(MY_CPU_LE_UNALIGN_64) -+#define GetBe64(p) Z7_BSWAP64 (*(const UInt64 *)(const void *)(p)) - #endif - --#if defined(MY_CPU_LE_UNALIGN) && /* defined(_WIN64) && */ defined(_MSC_VER) && (_MSC_VER >= 1300) -- --/* Note: we use bswap instruction, that is unsupported in 386 cpu */ -- --#include -- --#pragma intrinsic(_byteswap_ushort) --#pragma intrinsic(_byteswap_ulong) --#pragma intrinsic(_byteswap_uint64) -- --/* #define GetBe16(p) _byteswap_ushort(*(const UInt16 *)(const Byte *)(p)) */ --#define GetBe32(p) _byteswap_ulong (*(const UInt32 *)(const void *)(p)) --#define GetBe64(p) _byteswap_uint64(*(const UInt64 *)(const void *)(p)) -- --#define SetBe32(p, v) (*(UInt32 *)(void *)(p)) = _byteswap_ulong(v) -- --#elif defined(MY_CPU_LE_UNALIGN) && ( \ -- (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) \ -- || (defined(__clang__) && MY__has_builtin(__builtin_bswap16)) ) -- --/* #define GetBe16(p) __builtin_bswap16(*(const UInt16 *)(const void *)(p)) */ --#define GetBe32(p) __builtin_bswap32(*(const UInt32 *)(const void *)(p)) --#define GetBe64(p) __builtin_bswap64(*(const UInt64 *)(const void *)(p)) -- --#define SetBe32(p, v) (*(UInt32 *)(void *)(p)) = __builtin_bswap32(v) -- - #else - - #define GetBe32(p) ( \ -@@ -355,8 +405,6 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. - ((UInt32)((const Byte *)(p))[2] << 8) | \ - ((const Byte *)(p))[3] ) - --#define GetBe64(p) (((UInt64)GetBe32(p) << 32) | GetBe32(((const Byte *)(p)) + 4)) -- - #define SetBe32(p, v) { Byte *_ppp_ = (Byte *)(p); UInt32 _vvv_ = (v); \ - _ppp_[0] = (Byte)(_vvv_ >> 24); \ - _ppp_[1] = (Byte)(_vvv_ >> 16); \ -@@ -365,50 +413,83 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. - - #endif - -+#ifndef GetBe64 -+#define GetBe64(p) (((UInt64)GetBe32(p) << 32) | GetBe32(((const Byte *)(p)) + 4)) -+#endif - - #ifndef GetBe16 -- - #define GetBe16(p) ( (UInt16) ( \ - ((UInt16)((const Byte *)(p))[0] << 8) | \ - ((const Byte *)(p))[1] )) -+#endif - -+ -+#if defined(MY_CPU_BE) -+#define Z7_CONV_BE_TO_NATIVE_CONST32(v) (v) -+#define Z7_CONV_LE_TO_NATIVE_CONST32(v) Z7_BSWAP32_CONST(v) -+#define Z7_CONV_NATIVE_TO_BE_32(v) (v) -+#elif defined(MY_CPU_LE) -+#define Z7_CONV_BE_TO_NATIVE_CONST32(v) Z7_BSWAP32_CONST(v) -+#define Z7_CONV_LE_TO_NATIVE_CONST32(v) (v) -+#define Z7_CONV_NATIVE_TO_BE_32(v) Z7_BSWAP32(v) -+#else -+#error Stop_Compiling_Unknown_Endian_CONV - #endif - - -+#if defined(MY_CPU_BE) - --#ifdef MY_CPU_X86_OR_AMD64 -+#define GetBe32a(p) (*(const UInt32 *)(const void *)(p)) -+#define GetBe16a(p) (*(const UInt16 *)(const void *)(p)) -+#define SetBe32a(p, v) { *(UInt32 *)(void *)(p) = (v); } -+#define SetBe16a(p, v) { *(UInt16 *)(void *)(p) = (v); } - --typedef struct --{ -- UInt32 maxFunc; -- UInt32 vendor[3]; -- UInt32 ver; -- UInt32 b; -- UInt32 c; -- UInt32 d; --} Cx86cpuid; -+#define GetUi32a(p) GetUi32(p) -+#define GetUi16a(p) GetUi16(p) -+#define SetUi32a(p, v) SetUi32(p, v) -+#define SetUi16a(p, v) SetUi16(p, v) - --enum --{ -- CPU_FIRM_INTEL, -- CPU_FIRM_AMD, -- CPU_FIRM_VIA --}; -+#elif defined(MY_CPU_LE) - --void MyCPUID(UInt32 function, UInt32 *a, UInt32 *b, UInt32 *c, UInt32 *d); -+#define GetUi32a(p) (*(const UInt32 *)(const void *)(p)) -+#define GetUi16a(p) (*(const UInt16 *)(const void *)(p)) -+#define SetUi32a(p, v) { *(UInt32 *)(void *)(p) = (v); } -+#define SetUi16a(p, v) { *(UInt16 *)(void *)(p) = (v); } - --BoolInt x86cpuid_CheckAndRead(Cx86cpuid *p); --int x86cpuid_GetFirm(const Cx86cpuid *p); -+#define GetBe32a(p) GetBe32(p) -+#define GetBe16a(p) GetBe16(p) -+#define SetBe32a(p, v) SetBe32(p, v) -+#define SetBe16a(p, v) SetBe16(p, v) - --#define x86cpuid_GetFamily(ver) (((ver >> 16) & 0xFF0) | ((ver >> 8) & 0xF)) --#define x86cpuid_GetModel(ver) (((ver >> 12) & 0xF0) | ((ver >> 4) & 0xF)) --#define x86cpuid_GetStepping(ver) (ver & 0xF) -+#else -+#error Stop_Compiling_Unknown_Endian_CPU_a -+#endif - --BoolInt CPU_Is_InOrder(void); -+ -+#if defined(MY_CPU_X86_OR_AMD64) \ -+ || defined(MY_CPU_ARM_OR_ARM64) \ -+ || defined(MY_CPU_PPC_OR_PPC64) -+ #define Z7_CPU_FAST_ROTATE_SUPPORTED -+#endif -+ -+ -+#ifdef MY_CPU_X86_OR_AMD64 -+ -+void Z7_FASTCALL z7_x86_cpuid(UInt32 a[4], UInt32 function); -+UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void); -+#if defined(MY_CPU_AMD64) -+#define Z7_IF_X86_CPUID_SUPPORTED -+#else -+#define Z7_IF_X86_CPUID_SUPPORTED if (z7_x86_cpuid_GetMaxFunc()) -+#endif - - BoolInt CPU_IsSupported_AES(void); -+BoolInt CPU_IsSupported_AVX(void); - BoolInt CPU_IsSupported_AVX2(void); - BoolInt CPU_IsSupported_VAES_AVX2(void); -+BoolInt CPU_IsSupported_CMOV(void); -+BoolInt CPU_IsSupported_SSE(void); -+BoolInt CPU_IsSupported_SSE2(void); - BoolInt CPU_IsSupported_SSSE3(void); - BoolInt CPU_IsSupported_SSE41(void); - BoolInt CPU_IsSupported_SHA(void); -@@ -433,8 +514,8 @@ BoolInt CPU_IsSupported_AES(void); - #endif - - #if defined(__APPLE__) --int My_sysctlbyname_Get(const char *name, void *buf, size_t *bufSize); --int My_sysctlbyname_Get_UInt32(const char *name, UInt32 *val); -+int z7_sysctlbyname_Get(const char *name, void *buf, size_t *bufSize); -+int z7_sysctlbyname_Get_UInt32(const char *name, UInt32 *val); - #endif - - EXTERN_C_END -diff --git a/src/lzma/Delta.h b/src/lzma/Delta.h -index 2fa54ad67..706095417 100644 ---- a/src/lzma/Delta.h -+++ b/src/lzma/Delta.h -@@ -1,8 +1,8 @@ - /* Delta.h -- Delta converter --2013-01-18 : Igor Pavlov : Public domain */ -+2023-03-03 : Igor Pavlov : Public domain */ - --#ifndef __DELTA_H --#define __DELTA_H -+#ifndef ZIP7_INC_DELTA_H -+#define ZIP7_INC_DELTA_H - - #include "7zTypes.h" - -diff --git a/src/lzma/DllSecur.c b/src/lzma/DllSecur.c -index d81508c0b..02a0f977e 100644 ---- a/src/lzma/DllSecur.c -+++ b/src/lzma/DllSecur.c -@@ -1,110 +1,111 @@ - /* DllSecur.c -- DLL loading security --2021-12-25 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - - #ifdef _WIN32 - --#include -+#include "7zWindows.h" - - #include "DllSecur.h" - - #ifndef UNDER_CE - -+#if (defined(__GNUC__) && (__GNUC__ >= 8)) || defined(__clang__) -+ // #pragma GCC diagnostic ignored "-Wcast-function-type" -+#endif -+ -+#if defined(__clang__) || defined(__GNUC__) -+typedef void (*Z7_voidFunction)(void); -+#define MY_CAST_FUNC (Z7_voidFunction) -+#elif defined(_MSC_VER) && _MSC_VER > 1920 -+#define MY_CAST_FUNC (void *) -+// #pragma warning(disable : 4191) // 'type cast': unsafe conversion from 'FARPROC' to 'void (__cdecl *)()' -+#else -+#define MY_CAST_FUNC -+#endif -+ - typedef BOOL (WINAPI *Func_SetDefaultDllDirectories)(DWORD DirectoryFlags); - - #define MY_LOAD_LIBRARY_SEARCH_USER_DIRS 0x400 - #define MY_LOAD_LIBRARY_SEARCH_SYSTEM32 0x800 - -+#define DELIM "\0" -+ - static const char * const g_Dlls = -+ "userenv" -+ DELIM "setupapi" -+ DELIM "apphelp" -+ DELIM "propsys" -+ DELIM "dwmapi" -+ DELIM "cryptbase" -+ DELIM "oleacc" -+ DELIM "clbcatq" -+ DELIM "version" - #ifndef _CONSOLE -- "UXTHEME\0" -+ DELIM "uxtheme" - #endif -- "USERENV\0" -- "SETUPAPI\0" -- "APPHELP\0" -- "PROPSYS\0" -- "DWMAPI\0" -- "CRYPTBASE\0" -- "OLEACC\0" -- "CLBCATQ\0" -- "VERSION\0" -- ; -+ DELIM; -+ -+#endif - -+#ifdef __clang__ -+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations" -+#endif -+#if defined (_MSC_VER) && _MSC_VER >= 1900 -+// sysinfoapi.h: kit10: GetVersion was declared deprecated -+#pragma warning(disable : 4996) - #endif - --// #define MY_CAST_FUNC (void(*)()) --#define MY_CAST_FUNC -+#define IF_NON_VISTA_SET_DLL_DIRS_AND_RETURN \ -+ if ((UInt16)GetVersion() != 6) { \ -+ const \ -+ Func_SetDefaultDllDirectories setDllDirs = \ -+ (Func_SetDefaultDllDirectories) MY_CAST_FUNC GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), \ -+ "SetDefaultDllDirectories"); \ -+ if (setDllDirs) if (setDllDirs(MY_LOAD_LIBRARY_SEARCH_SYSTEM32 | MY_LOAD_LIBRARY_SEARCH_USER_DIRS)) return; } - --void My_SetDefaultDllDirectories() -+void My_SetDefaultDllDirectories(void) - { - #ifndef UNDER_CE -- -- OSVERSIONINFO vi; -- vi.dwOSVersionInfoSize = sizeof(vi); -- if (!GetVersionEx(&vi) || vi.dwMajorVersion != 6 || vi.dwMinorVersion != 0) -- { -- Func_SetDefaultDllDirectories setDllDirs = (Func_SetDefaultDllDirectories) -- MY_CAST_FUNC GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "SetDefaultDllDirectories"); -- if (setDllDirs) -- if (setDllDirs(MY_LOAD_LIBRARY_SEARCH_SYSTEM32 | MY_LOAD_LIBRARY_SEARCH_USER_DIRS)) -- return; -- } -- -+ IF_NON_VISTA_SET_DLL_DIRS_AND_RETURN - #endif - } - - --void LoadSecurityDlls() -+void LoadSecurityDlls(void) - { - #ifndef UNDER_CE -- -- wchar_t buf[MAX_PATH + 100]; -- -- { -- // at Vista (ver 6.0) : CoCreateInstance(CLSID_ShellLink, ...) doesn't work after SetDefaultDllDirectories() : Check it ??? -- OSVERSIONINFO vi; -- vi.dwOSVersionInfoSize = sizeof(vi); -- if (!GetVersionEx(&vi) || vi.dwMajorVersion != 6 || vi.dwMinorVersion != 0) -- { -- Func_SetDefaultDllDirectories setDllDirs = (Func_SetDefaultDllDirectories) -- MY_CAST_FUNC GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "SetDefaultDllDirectories"); -- if (setDllDirs) -- if (setDllDirs(MY_LOAD_LIBRARY_SEARCH_SYSTEM32 | MY_LOAD_LIBRARY_SEARCH_USER_DIRS)) -- return; -- } -- } -- -- { -- unsigned len = GetSystemDirectoryW(buf, MAX_PATH + 2); -- if (len == 0 || len > MAX_PATH) -- return; -- } -+ // at Vista (ver 6.0) : CoCreateInstance(CLSID_ShellLink, ...) doesn't work after SetDefaultDllDirectories() : Check it ??? -+ IF_NON_VISTA_SET_DLL_DIRS_AND_RETURN - { -+ wchar_t buf[MAX_PATH + 100]; - const char *dll; -- unsigned pos = (unsigned)lstrlenW(buf); -- -+ unsigned pos = GetSystemDirectoryW(buf, MAX_PATH + 2); -+ if (pos == 0 || pos > MAX_PATH) -+ return; - if (buf[pos - 1] != '\\') - buf[pos++] = '\\'; -- -- for (dll = g_Dlls; dll[0] != 0;) -+ for (dll = g_Dlls; *dll != 0;) - { -- unsigned k = 0; -+ wchar_t *dest = &buf[pos]; - for (;;) - { -- char c = *dll++; -- buf[pos + k] = (Byte)c; -- k++; -+ const char c = *dll++; - if (c == 0) - break; -+ *dest++ = (Byte)c; - } -- -- lstrcatW(buf, L".dll"); -+ dest[0] = '.'; -+ dest[1] = 'd'; -+ dest[2] = 'l'; -+ dest[3] = 'l'; -+ dest[4] = 0; -+ // lstrcatW(buf, L".dll"); - LoadLibraryExW(buf, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); - } - } -- - #endif - } - --#endif -+#endif // _WIN32 -diff --git a/src/lzma/DllSecur.h b/src/lzma/DllSecur.h -index 64ff26cd9..9fa415382 100644 ---- a/src/lzma/DllSecur.h -+++ b/src/lzma/DllSecur.h -@@ -1,8 +1,8 @@ - /* DllSecur.h -- DLL loading for security --2018-02-19 : Igor Pavlov : Public domain */ -+2023-03-03 : Igor Pavlov : Public domain */ - --#ifndef __DLL_SECUR_H --#define __DLL_SECUR_H -+#ifndef ZIP7_INC_DLL_SECUR_H -+#define ZIP7_INC_DLL_SECUR_H - - #include "7zTypes.h" - -diff --git a/src/lzma/LzFind.c b/src/lzma/LzFind.c -index 1b73c2848..0fbd5aae5 100644 ---- a/src/lzma/LzFind.c -+++ b/src/lzma/LzFind.c -@@ -1,5 +1,5 @@ - /* LzFind.c -- Match finder for LZ algorithms --2021-11-29 : Igor Pavlov : Public domain */ -+2023-03-14 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -17,7 +17,7 @@ - #define kEmptyHashValue 0 - - #define kMaxValForNormalize ((UInt32)0) --// #define kMaxValForNormalize ((UInt32)(1 << 20) + 0xFFF) // for debug -+// #define kMaxValForNormalize ((UInt32)(1 << 20) + 0xfff) // for debug - - // #define kNormalizeAlign (1 << 7) // alignment for speculated accesses - -@@ -67,10 +67,10 @@ - - static void LzInWindow_Free(CMatchFinder *p, ISzAllocPtr alloc) - { -- if (!p->directInput) -+ // if (!p->directInput) - { -- ISzAlloc_Free(alloc, p->bufferBase); -- p->bufferBase = NULL; -+ ISzAlloc_Free(alloc, p->bufBase); -+ p->bufBase = NULL; - } - } - -@@ -79,7 +79,7 @@ static int LzInWindow_Create2(CMatchFinder *p, UInt32 blockSize, ISzAllocPtr all - { - if (blockSize == 0) - return 0; -- if (!p->bufferBase || p->blockSize != blockSize) -+ if (!p->bufBase || p->blockSize != blockSize) - { - // size_t blockSizeT; - LzInWindow_Free(p, alloc); -@@ -101,11 +101,11 @@ static int LzInWindow_Create2(CMatchFinder *p, UInt32 blockSize, ISzAllocPtr all - #endif - */ - -- p->bufferBase = (Byte *)ISzAlloc_Alloc(alloc, blockSize); -- // printf("\nbufferBase = %p\n", p->bufferBase); -+ p->bufBase = (Byte *)ISzAlloc_Alloc(alloc, blockSize); -+ // printf("\nbufferBase = %p\n", p->bufBase); - // return 0; // for debug - } -- return (p->bufferBase != NULL); -+ return (p->bufBase != NULL); - } - - static const Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p) { return p->buffer; } -@@ -113,7 +113,7 @@ static const Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p) { return - static UInt32 MatchFinder_GetNumAvailableBytes(CMatchFinder *p) { return GET_AVAIL_BYTES(p); } - - --MY_NO_INLINE -+Z7_NO_INLINE - static void MatchFinder_ReadBlock(CMatchFinder *p) - { - if (p->streamEndWasReached || p->result != SZ_OK) -@@ -127,8 +127,8 @@ static void MatchFinder_ReadBlock(CMatchFinder *p) - UInt32 curSize = 0xFFFFFFFF - GET_AVAIL_BYTES(p); - if (curSize > p->directInputRem) - curSize = (UInt32)p->directInputRem; -- p->directInputRem -= curSize; - p->streamPos += curSize; -+ p->directInputRem -= curSize; - if (p->directInputRem == 0) - p->streamEndWasReached = 1; - return; -@@ -136,8 +136,8 @@ static void MatchFinder_ReadBlock(CMatchFinder *p) - - for (;;) - { -- Byte *dest = p->buffer + GET_AVAIL_BYTES(p); -- size_t size = (size_t)(p->bufferBase + p->blockSize - dest); -+ const Byte *dest = p->buffer + GET_AVAIL_BYTES(p); -+ size_t size = (size_t)(p->bufBase + p->blockSize - dest); - if (size == 0) - { - /* we call ReadBlock() after NeedMove() and MoveBlock(). -@@ -153,7 +153,14 @@ static void MatchFinder_ReadBlock(CMatchFinder *p) - // #define kRead 3 - // if (size > kRead) size = kRead; // for debug - -- p->result = ISeqInStream_Read(p->stream, dest, &size); -+ /* -+ // we need cast (Byte *)dest. -+ #ifdef __clang__ -+ #pragma GCC diagnostic ignored "-Wcast-qual" -+ #endif -+ */ -+ p->result = ISeqInStream_Read(p->stream, -+ p->bufBase + (dest - p->bufBase), &size); - if (p->result != SZ_OK) - return; - if (size == 0) -@@ -173,14 +180,14 @@ static void MatchFinder_ReadBlock(CMatchFinder *p) - - - --MY_NO_INLINE -+Z7_NO_INLINE - void MatchFinder_MoveBlock(CMatchFinder *p) - { -- const size_t offset = (size_t)(p->buffer - p->bufferBase) - p->keepSizeBefore; -+ const size_t offset = (size_t)(p->buffer - p->bufBase) - p->keepSizeBefore; - const size_t keepBefore = (offset & (kBlockMoveAlign - 1)) + p->keepSizeBefore; -- p->buffer = p->bufferBase + keepBefore; -- memmove(p->bufferBase, -- p->bufferBase + (offset & ~((size_t)kBlockMoveAlign - 1)), -+ p->buffer = p->bufBase + keepBefore; -+ memmove(p->bufBase, -+ p->bufBase + (offset & ~((size_t)kBlockMoveAlign - 1)), - keepBefore + (size_t)GET_AVAIL_BYTES(p)); - } - -@@ -198,7 +205,7 @@ int MatchFinder_NeedMove(CMatchFinder *p) - return 0; - if (p->streamEndWasReached || p->result != SZ_OK) - return 0; -- return ((size_t)(p->bufferBase + p->blockSize - p->buffer) <= p->keepSizeAfter); -+ return ((size_t)(p->bufBase + p->blockSize - p->buffer) <= p->keepSizeAfter); - } - - void MatchFinder_ReadIfRequired(CMatchFinder *p) -@@ -214,6 +221,8 @@ static void MatchFinder_SetDefaultSettings(CMatchFinder *p) - p->cutValue = 32; - p->btMode = 1; - p->numHashBytes = 4; -+ p->numHashBytes_Min = 2; -+ p->numHashOutBits = 0; - p->bigHash = 0; - } - -@@ -222,8 +231,10 @@ static void MatchFinder_SetDefaultSettings(CMatchFinder *p) - void MatchFinder_Construct(CMatchFinder *p) - { - unsigned i; -- p->bufferBase = NULL; -+ p->buffer = NULL; -+ p->bufBase = NULL; - p->directInput = 0; -+ p->stream = NULL; - p->hash = NULL; - p->expectedDataSize = (UInt64)(Int64)-1; - MatchFinder_SetDefaultSettings(p); -@@ -238,6 +249,8 @@ void MatchFinder_Construct(CMatchFinder *p) - } - } - -+#undef kCrcPoly -+ - static void MatchFinder_FreeThisClassMemory(CMatchFinder *p, ISzAllocPtr alloc) - { - ISzAlloc_Free(alloc, p->hash); -@@ -252,7 +265,7 @@ void MatchFinder_Free(CMatchFinder *p, ISzAllocPtr alloc) - - static CLzRef* AllocRefs(size_t num, ISzAllocPtr alloc) - { -- size_t sizeInBytes = (size_t)num * sizeof(CLzRef); -+ const size_t sizeInBytes = (size_t)num * sizeof(CLzRef); - if (sizeInBytes / sizeof(CLzRef) != num) - return NULL; - return (CLzRef *)ISzAlloc_Alloc(alloc, sizeInBytes); -@@ -298,6 +311,62 @@ static UInt32 GetBlockSize(CMatchFinder *p, UInt32 historySize) - } - - -+// input is historySize -+static UInt32 MatchFinder_GetHashMask2(CMatchFinder *p, UInt32 hs) -+{ -+ if (p->numHashBytes == 2) -+ return (1 << 16) - 1; -+ if (hs != 0) -+ hs--; -+ hs |= (hs >> 1); -+ hs |= (hs >> 2); -+ hs |= (hs >> 4); -+ hs |= (hs >> 8); -+ // we propagated 16 bits in (hs). Low 16 bits must be set later -+ if (hs >= (1 << 24)) -+ { -+ if (p->numHashBytes == 3) -+ hs = (1 << 24) - 1; -+ /* if (bigHash) mode, GetHeads4b() in LzFindMt.c needs (hs >= ((1 << 24) - 1))) */ -+ } -+ // (hash_size >= (1 << 16)) : Required for (numHashBytes > 2) -+ hs |= (1 << 16) - 1; /* don't change it! */ -+ // bt5: we adjust the size with recommended minimum size -+ if (p->numHashBytes >= 5) -+ hs |= (256 << kLzHash_CrcShift_2) - 1; -+ return hs; -+} -+ -+// input is historySize -+static UInt32 MatchFinder_GetHashMask(CMatchFinder *p, UInt32 hs) -+{ -+ if (p->numHashBytes == 2) -+ return (1 << 16) - 1; -+ if (hs != 0) -+ hs--; -+ hs |= (hs >> 1); -+ hs |= (hs >> 2); -+ hs |= (hs >> 4); -+ hs |= (hs >> 8); -+ // we propagated 16 bits in (hs). Low 16 bits must be set later -+ hs >>= 1; -+ if (hs >= (1 << 24)) -+ { -+ if (p->numHashBytes == 3) -+ hs = (1 << 24) - 1; -+ else -+ hs >>= 1; -+ /* if (bigHash) mode, GetHeads4b() in LzFindMt.c needs (hs >= ((1 << 24) - 1))) */ -+ } -+ // (hash_size >= (1 << 16)) : Required for (numHashBytes > 2) -+ hs |= (1 << 16) - 1; /* don't change it! */ -+ // bt5: we adjust the size with recommended minimum size -+ if (p->numHashBytes >= 5) -+ hs |= (256 << kLzHash_CrcShift_2) - 1; -+ return hs; -+} -+ -+ - int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, - UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, - ISzAllocPtr alloc) -@@ -318,78 +387,91 @@ int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, - p->blockSize = 0; - if (p->directInput || LzInWindow_Create2(p, GetBlockSize(p, historySize), alloc)) - { -- const UInt32 newCyclicBufferSize = historySize + 1; // do not change it -- UInt32 hs; -- p->matchMaxLen = matchMaxLen; -+ size_t hashSizeSum; - { -- // UInt32 hs4; -- p->fixedHashSize = 0; -- hs = (1 << 16) - 1; -- if (p->numHashBytes != 2) -+ UInt32 hs; -+ UInt32 hsCur; -+ -+ if (p->numHashOutBits != 0) - { -- hs = historySize; -- if (hs > p->expectedDataSize) -- hs = (UInt32)p->expectedDataSize; -- if (hs != 0) -- hs--; -- hs |= (hs >> 1); -- hs |= (hs >> 2); -- hs |= (hs >> 4); -- hs |= (hs >> 8); -- // we propagated 16 bits in (hs). Low 16 bits must be set later -- hs >>= 1; -- if (hs >= (1 << 24)) -- { -- if (p->numHashBytes == 3) -- hs = (1 << 24) - 1; -- else -- hs >>= 1; -- /* if (bigHash) mode, GetHeads4b() in LzFindMt.c needs (hs >= ((1 << 24) - 1))) */ -- } -- -- // hs = ((UInt32)1 << 25) - 1; // for test -- -+ unsigned numBits = p->numHashOutBits; -+ const unsigned nbMax = -+ (p->numHashBytes == 2 ? 16 : -+ (p->numHashBytes == 3 ? 24 : 32)); -+ if (numBits > nbMax) -+ numBits = nbMax; -+ if (numBits >= 32) -+ hs = (UInt32)0 - 1; -+ else -+ hs = ((UInt32)1 << numBits) - 1; - // (hash_size >= (1 << 16)) : Required for (numHashBytes > 2) - hs |= (1 << 16) - 1; /* don't change it! */ -- -- // bt5: we adjust the size with recommended minimum size - if (p->numHashBytes >= 5) - hs |= (256 << kLzHash_CrcShift_2) - 1; -+ { -+ const UInt32 hs2 = MatchFinder_GetHashMask2(p, historySize); -+ if (hs > hs2) -+ hs = hs2; -+ } -+ hsCur = hs; -+ if (p->expectedDataSize < historySize) -+ { -+ const UInt32 hs2 = MatchFinder_GetHashMask2(p, (UInt32)p->expectedDataSize); -+ if (hsCur > hs2) -+ hsCur = hs2; -+ } - } -- p->hashMask = hs; -- hs++; -- -- /* -- hs4 = (1 << 20); -- if (hs4 > hs) -- hs4 = hs; -- // hs4 = (1 << 16); // for test -- p->hash4Mask = hs4 - 1; -- */ -+ else -+ { -+ hs = MatchFinder_GetHashMask(p, historySize); -+ hsCur = hs; -+ if (p->expectedDataSize < historySize) -+ { -+ hsCur = MatchFinder_GetHashMask(p, (UInt32)p->expectedDataSize); -+ if (hsCur > hs) // is it possible? -+ hsCur = hs; -+ } -+ } -+ -+ p->hashMask = hsCur; - -- if (p->numHashBytes > 2) p->fixedHashSize += kHash2Size; -- if (p->numHashBytes > 3) p->fixedHashSize += kHash3Size; -- // if (p->numHashBytes > 4) p->fixedHashSize += hs4; // kHash4Size; -- hs += p->fixedHashSize; -+ hashSizeSum = hs; -+ hashSizeSum++; -+ if (hashSizeSum < hs) -+ return 0; -+ { -+ UInt32 fixedHashSize = 0; -+ if (p->numHashBytes > 2 && p->numHashBytes_Min <= 2) fixedHashSize += kHash2Size; -+ if (p->numHashBytes > 3 && p->numHashBytes_Min <= 3) fixedHashSize += kHash3Size; -+ // if (p->numHashBytes > 4) p->fixedHashSize += hs4; // kHash4Size; -+ hashSizeSum += fixedHashSize; -+ p->fixedHashSize = fixedHashSize; -+ } - } - -+ p->matchMaxLen = matchMaxLen; -+ - { - size_t newSize; - size_t numSons; -+ const UInt32 newCyclicBufferSize = historySize + 1; // do not change it - p->historySize = historySize; -- p->hashSizeSum = hs; - p->cyclicBufferSize = newCyclicBufferSize; // it must be = (historySize + 1) - - numSons = newCyclicBufferSize; - if (p->btMode) - numSons <<= 1; -- newSize = hs + numSons; -+ newSize = hashSizeSum + numSons; -+ -+ if (numSons < newCyclicBufferSize || newSize < numSons) -+ return 0; - - // aligned size is not required here, but it can be better for some loops - #define NUM_REFS_ALIGN_MASK 0xF - newSize = (newSize + NUM_REFS_ALIGN_MASK) & ~(size_t)NUM_REFS_ALIGN_MASK; - -- if (p->hash && p->numRefs == newSize) -+ // 22.02: we don't reallocate buffer, if old size is enough -+ if (p->hash && p->numRefs >= newSize) - return 1; - - MatchFinder_FreeThisClassMemory(p, alloc); -@@ -398,7 +480,7 @@ int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, - - if (p->hash) - { -- p->son = p->hash + p->hashSizeSum; -+ p->son = p->hash + hashSizeSum; - return 1; - } - } -@@ -470,7 +552,8 @@ void MatchFinder_Init_HighHash(CMatchFinder *p) - - void MatchFinder_Init_4(CMatchFinder *p) - { -- p->buffer = p->bufferBase; -+ if (!p->directInput) -+ p->buffer = p->bufBase; - { - /* kEmptyHashValue = 0 (Zero) is used in hash tables as NO-VALUE marker. - the code in CMatchFinderMt expects (pos = 1) */ -@@ -507,20 +590,20 @@ void MatchFinder_Init(CMatchFinder *p) - - - #ifdef MY_CPU_X86_OR_AMD64 -- #if defined(__clang__) && (__clang_major__ >= 8) \ -- || defined(__GNUC__) && (__GNUC__ >= 8) \ -- || defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1900) -- #define USE_SATUR_SUB_128 -- #define USE_AVX2 -- #define ATTRIB_SSE41 __attribute__((__target__("sse4.1"))) -- #define ATTRIB_AVX2 __attribute__((__target__("avx2"))) -+ #if defined(__clang__) && (__clang_major__ >= 4) \ -+ || defined(Z7_GCC_VERSION) && (Z7_GCC_VERSION >= 40701) -+ // || defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1900) -+ -+ #define USE_LZFIND_SATUR_SUB_128 -+ #define USE_LZFIND_SATUR_SUB_256 -+ #define LZFIND_ATTRIB_SSE41 __attribute__((__target__("sse4.1"))) -+ #define LZFIND_ATTRIB_AVX2 __attribute__((__target__("avx2"))) - #elif defined(_MSC_VER) - #if (_MSC_VER >= 1600) -- #define USE_SATUR_SUB_128 -- #if (_MSC_VER >= 1900) -- #define USE_AVX2 -- #include // avx -- #endif -+ #define USE_LZFIND_SATUR_SUB_128 -+ #endif -+ #if (_MSC_VER >= 1900) -+ #define USE_LZFIND_SATUR_SUB_256 - #endif - #endif - -@@ -529,16 +612,16 @@ void MatchFinder_Init(CMatchFinder *p) - - #if defined(__clang__) && (__clang_major__ >= 8) \ - || defined(__GNUC__) && (__GNUC__ >= 8) -- #define USE_SATUR_SUB_128 -+ #define USE_LZFIND_SATUR_SUB_128 - #ifdef MY_CPU_ARM64 -- // #define ATTRIB_SSE41 __attribute__((__target__(""))) -+ // #define LZFIND_ATTRIB_SSE41 __attribute__((__target__(""))) - #else -- // #define ATTRIB_SSE41 __attribute__((__target__("fpu=crypto-neon-fp-armv8"))) -+ // #define LZFIND_ATTRIB_SSE41 __attribute__((__target__("fpu=crypto-neon-fp-armv8"))) - #endif - - #elif defined(_MSC_VER) - #if (_MSC_VER >= 1910) -- #define USE_SATUR_SUB_128 -+ #define USE_LZFIND_SATUR_SUB_128 - #endif - #endif - -@@ -550,121 +633,130 @@ void MatchFinder_Init(CMatchFinder *p) - - #endif - --/* --#ifndef ATTRIB_SSE41 -- #define ATTRIB_SSE41 --#endif --#ifndef ATTRIB_AVX2 -- #define ATTRIB_AVX2 --#endif --*/ - --#ifdef USE_SATUR_SUB_128 -+#ifdef USE_LZFIND_SATUR_SUB_128 - --// #define _SHOW_HW_STATUS -+// #define Z7_SHOW_HW_STATUS - --#ifdef _SHOW_HW_STATUS -+#ifdef Z7_SHOW_HW_STATUS - #include --#define _PRF(x) x --_PRF(;) -+#define PRF(x) x -+PRF(;) - #else --#define _PRF(x) -+#define PRF(x) - #endif - -+ - #ifdef MY_CPU_ARM_OR_ARM64 - - #ifdef MY_CPU_ARM64 --// #define FORCE_SATUR_SUB_128 -+// #define FORCE_LZFIND_SATUR_SUB_128 - #endif -+typedef uint32x4_t LzFind_v128; -+#define SASUB_128_V(v, s) \ -+ vsubq_u32(vmaxq_u32(v, s), s) - --typedef uint32x4_t v128; --#define SASUB_128(i) \ -- *(v128 *)(void *)(items + (i) * 4) = \ -- vsubq_u32(vmaxq_u32(*(const v128 *)(const void *)(items + (i) * 4), sub2), sub2); -- --#else -+#else // MY_CPU_ARM_OR_ARM64 - - #include // sse4.1 - --typedef __m128i v128; --#define SASUB_128(i) \ -- *(v128 *)(void *)(items + (i) * 4) = \ -- _mm_sub_epi32(_mm_max_epu32(*(const v128 *)(const void *)(items + (i) * 4), sub2), sub2); // SSE 4.1 -+typedef __m128i LzFind_v128; -+// SSE 4.1 -+#define SASUB_128_V(v, s) \ -+ _mm_sub_epi32(_mm_max_epu32(v, s), s) - --#endif -+#endif // MY_CPU_ARM_OR_ARM64 - - -+#define SASUB_128(i) \ -+ *( LzFind_v128 *)( void *)(items + (i) * 4) = SASUB_128_V( \ -+ *(const LzFind_v128 *)(const void *)(items + (i) * 4), sub2); -+ - --MY_NO_INLINE -+Z7_NO_INLINE - static --#ifdef ATTRIB_SSE41 --ATTRIB_SSE41 -+#ifdef LZFIND_ATTRIB_SSE41 -+LZFIND_ATTRIB_SSE41 - #endif - void --MY_FAST_CALL -+Z7_FASTCALL - LzFind_SaturSub_128(UInt32 subValue, CLzRef *items, const CLzRef *lim) - { -- v128 sub2 = -+ const LzFind_v128 sub2 = - #ifdef MY_CPU_ARM_OR_ARM64 - vdupq_n_u32(subValue); - #else - _mm_set_epi32((Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue); - #endif -+ Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE - do - { -- SASUB_128(0) -- SASUB_128(1) -- SASUB_128(2) -- SASUB_128(3) -- items += 4 * 4; -+ SASUB_128(0) SASUB_128(1) items += 2 * 4; -+ SASUB_128(0) SASUB_128(1) items += 2 * 4; - } - while (items != lim); - } - - - --#ifdef USE_AVX2 -+#ifdef USE_LZFIND_SATUR_SUB_256 - - #include // avx -+/* -+clang :immintrin.h uses -+#if !(defined(_MSC_VER) || defined(__SCE__)) || __has_feature(modules) || \ -+ defined(__AVX2__) -+#include -+#endif -+so we need for clang-cl */ - --#define SASUB_256(i) *(__m256i *)(void *)(items + (i) * 8) = _mm256_sub_epi32(_mm256_max_epu32(*(const __m256i *)(const void *)(items + (i) * 8), sub2), sub2); // AVX2 -+#if defined(__clang__) -+#include -+#include -+#endif - --MY_NO_INLINE -+// AVX2: -+#define SASUB_256(i) \ -+ *( __m256i *)( void *)(items + (i) * 8) = \ -+ _mm256_sub_epi32(_mm256_max_epu32( \ -+ *(const __m256i *)(const void *)(items + (i) * 8), sub2), sub2); -+ -+Z7_NO_INLINE - static --#ifdef ATTRIB_AVX2 --ATTRIB_AVX2 -+#ifdef LZFIND_ATTRIB_AVX2 -+LZFIND_ATTRIB_AVX2 - #endif - void --MY_FAST_CALL -+Z7_FASTCALL - LzFind_SaturSub_256(UInt32 subValue, CLzRef *items, const CLzRef *lim) - { -- __m256i sub2 = _mm256_set_epi32( -+ const __m256i sub2 = _mm256_set_epi32( - (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue, - (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue); -+ Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE - do - { -- SASUB_256(0) -- SASUB_256(1) -- items += 2 * 8; -+ SASUB_256(0) SASUB_256(1) items += 2 * 8; -+ SASUB_256(0) SASUB_256(1) items += 2 * 8; - } - while (items != lim); - } --#endif // USE_AVX2 -+#endif // USE_LZFIND_SATUR_SUB_256 - --#ifndef FORCE_SATUR_SUB_128 --typedef void (MY_FAST_CALL *LZFIND_SATUR_SUB_CODE_FUNC)( -+#ifndef FORCE_LZFIND_SATUR_SUB_128 -+typedef void (Z7_FASTCALL *LZFIND_SATUR_SUB_CODE_FUNC)( - UInt32 subValue, CLzRef *items, const CLzRef *lim); - static LZFIND_SATUR_SUB_CODE_FUNC g_LzFind_SaturSub; --#endif // FORCE_SATUR_SUB_128 -+#endif // FORCE_LZFIND_SATUR_SUB_128 - --#endif // USE_SATUR_SUB_128 -+#endif // USE_LZFIND_SATUR_SUB_128 - - - // kEmptyHashValue must be zero --// #define SASUB_32(i) v = items[i]; m = v - subValue; if (v < subValue) m = kEmptyHashValue; items[i] = m; --#define SASUB_32(i) v = items[i]; if (v < subValue) v = subValue; items[i] = v - subValue; -+// #define SASUB_32(i) { UInt32 v = items[i]; UInt32 m = v - subValue; if (v < subValue) m = kEmptyHashValue; items[i] = m; } -+#define SASUB_32(i) { UInt32 v = items[i]; if (v < subValue) v = subValue; items[i] = v - subValue; } - --#ifdef FORCE_SATUR_SUB_128 -+#ifdef FORCE_LZFIND_SATUR_SUB_128 - - #define DEFAULT_SaturSub LzFind_SaturSub_128 - -@@ -672,24 +764,19 @@ static LZFIND_SATUR_SUB_CODE_FUNC g_LzFind_SaturSub; - - #define DEFAULT_SaturSub LzFind_SaturSub_32 - --MY_NO_INLINE -+Z7_NO_INLINE - static - void --MY_FAST_CALL -+Z7_FASTCALL - LzFind_SaturSub_32(UInt32 subValue, CLzRef *items, const CLzRef *lim) - { -+ Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE - do - { -- UInt32 v; -- SASUB_32(0) -- SASUB_32(1) -- SASUB_32(2) -- SASUB_32(3) -- SASUB_32(4) -- SASUB_32(5) -- SASUB_32(6) -- SASUB_32(7) -- items += 8; -+ SASUB_32(0) SASUB_32(1) items += 2; -+ SASUB_32(0) SASUB_32(1) items += 2; -+ SASUB_32(0) SASUB_32(1) items += 2; -+ SASUB_32(0) SASUB_32(1) items += 2; - } - while (items != lim); - } -@@ -697,27 +784,23 @@ LzFind_SaturSub_32(UInt32 subValue, CLzRef *items, const CLzRef *lim) - #endif - - --MY_NO_INLINE -+Z7_NO_INLINE - void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems) - { -- #define K_NORM_ALIGN_BLOCK_SIZE (1 << 6) -- -- CLzRef *lim; -- -- for (; numItems != 0 && ((unsigned)(ptrdiff_t)items & (K_NORM_ALIGN_BLOCK_SIZE - 1)) != 0; numItems--) -+ #define LZFIND_NORM_ALIGN_BLOCK_SIZE (1 << 7) -+ Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE -+ for (; numItems != 0 && ((unsigned)(ptrdiff_t)items & (LZFIND_NORM_ALIGN_BLOCK_SIZE - 1)) != 0; numItems--) - { -- UInt32 v; -- SASUB_32(0); -+ SASUB_32(0) - items++; - } -- - { -- #define K_NORM_ALIGN_MASK (K_NORM_ALIGN_BLOCK_SIZE / 4 - 1) -- lim = items + (numItems & ~(size_t)K_NORM_ALIGN_MASK); -- numItems &= K_NORM_ALIGN_MASK; -+ const size_t k_Align_Mask = (LZFIND_NORM_ALIGN_BLOCK_SIZE / 4 - 1); -+ CLzRef *lim = items + (numItems & ~(size_t)k_Align_Mask); -+ numItems &= k_Align_Mask; - if (items != lim) - { -- #if defined(USE_SATUR_SUB_128) && !defined(FORCE_SATUR_SUB_128) -+ #if defined(USE_LZFIND_SATUR_SUB_128) && !defined(FORCE_LZFIND_SATUR_SUB_128) - if (g_LzFind_SaturSub) - g_LzFind_SaturSub(subValue, items, lim); - else -@@ -726,12 +809,10 @@ void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems) - } - items = lim; - } -- -- -+ Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE - for (; numItems != 0; numItems--) - { -- UInt32 v; -- SASUB_32(0); -+ SASUB_32(0) - items++; - } - } -@@ -740,7 +821,7 @@ void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems) - - // call MatchFinder_CheckLimits() only after (p->pos++) update - --MY_NO_INLINE -+Z7_NO_INLINE - static void MatchFinder_CheckLimits(CMatchFinder *p) - { - if (// !p->streamEndWasReached && p->result == SZ_OK && -@@ -768,11 +849,14 @@ static void MatchFinder_CheckLimits(CMatchFinder *p) - const UInt32 subValue = (p->pos - p->historySize - 1) /* & ~(UInt32)(kNormalizeAlign - 1) */; - // const UInt32 subValue = (1 << 15); // for debug - // printf("\nMatchFinder_Normalize() subValue == 0x%x\n", subValue); -- size_t numSonRefs = p->cyclicBufferSize; -- if (p->btMode) -- numSonRefs <<= 1; -- Inline_MatchFinder_ReduceOffsets(p, subValue); -- MatchFinder_Normalize3(subValue, p->hash, (size_t)p->hashSizeSum + numSonRefs); -+ MatchFinder_REDUCE_OFFSETS(p, subValue) -+ MatchFinder_Normalize3(subValue, p->hash, (size_t)p->hashMask + 1 + p->fixedHashSize); -+ { -+ size_t numSonRefs = p->cyclicBufferSize; -+ if (p->btMode) -+ numSonRefs <<= 1; -+ MatchFinder_Normalize3(subValue, p->son, numSonRefs); -+ } - } - - if (p->cyclicBufferPos == p->cyclicBufferSize) -@@ -785,7 +869,7 @@ static void MatchFinder_CheckLimits(CMatchFinder *p) - /* - (lenLimit > maxLen) - */ --MY_FORCE_INLINE -+Z7_FORCE_INLINE - static UInt32 * Hc_GetMatchesSpec(size_t lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, - size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, - UInt32 *d, unsigned maxLen) -@@ -867,7 +951,7 @@ static UInt32 * Hc_GetMatchesSpec(size_t lenLimit, UInt32 curMatch, UInt32 pos, - } - - --MY_FORCE_INLINE -+Z7_FORCE_INLINE - UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, - size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, - UInt32 *d, UInt32 maxLen) -@@ -1004,7 +1088,7 @@ static void SkipMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const - - #define MOVE_POS_RET MOVE_POS return distances; - --MY_NO_INLINE -+Z7_NO_INLINE - static void MatchFinder_MovePos(CMatchFinder *p) - { - /* we go here at the end of stream data, when (avail < num_hash_bytes) -@@ -1015,11 +1099,11 @@ static void MatchFinder_MovePos(CMatchFinder *p) - if (p->btMode) - p->sons[(p->cyclicBufferPos << p->btMode) + 1] = 0; // kEmptyHashValue - */ -- MOVE_POS; -+ MOVE_POS - } - - #define GET_MATCHES_HEADER2(minLen, ret_op) \ -- unsigned lenLimit; UInt32 hv; Byte *cur; UInt32 curMatch; \ -+ unsigned lenLimit; UInt32 hv; const Byte *cur; UInt32 curMatch; \ - lenLimit = (unsigned)p->lenLimit; { if (lenLimit < minLen) { MatchFinder_MovePos(p); ret_op; }} \ - cur = p->buffer; - -@@ -1028,11 +1112,11 @@ static void MatchFinder_MovePos(CMatchFinder *p) - - #define MF_PARAMS(p) lenLimit, curMatch, p->pos, p->buffer, p->son, p->cyclicBufferPos, p->cyclicBufferSize, p->cutValue - --#define SKIP_FOOTER SkipMatchesSpec(MF_PARAMS(p)); MOVE_POS; } while (--num); -+#define SKIP_FOOTER SkipMatchesSpec(MF_PARAMS(p)); MOVE_POS } while (--num); - - #define GET_MATCHES_FOOTER_BASE(_maxLen_, func) \ - distances = func(MF_PARAMS(p), \ -- distances, (UInt32)_maxLen_); MOVE_POS_RET; -+ distances, (UInt32)_maxLen_); MOVE_POS_RET - - #define GET_MATCHES_FOOTER_BT(_maxLen_) \ - GET_MATCHES_FOOTER_BASE(_maxLen_, GetMatchesSpec1) -@@ -1052,7 +1136,7 @@ static void MatchFinder_MovePos(CMatchFinder *p) - static UInt32* Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) - { - GET_MATCHES_HEADER(2) -- HASH2_CALC; -+ HASH2_CALC - curMatch = p->hash[hv]; - p->hash[hv] = p->pos; - GET_MATCHES_FOOTER_BT(1) -@@ -1061,7 +1145,7 @@ static UInt32* Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) - UInt32* Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) - { - GET_MATCHES_HEADER(3) -- HASH_ZIP_CALC; -+ HASH_ZIP_CALC - curMatch = p->hash[hv]; - p->hash[hv] = p->pos; - GET_MATCHES_FOOTER_BT(2) -@@ -1082,7 +1166,7 @@ static UInt32* Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) - UInt32 *hash; - GET_MATCHES_HEADER(3) - -- HASH3_CALC; -+ HASH3_CALC - - hash = p->hash; - pos = p->pos; -@@ -1107,7 +1191,7 @@ static UInt32* Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) - if (maxLen == lenLimit) - { - SkipMatchesSpec(MF_PARAMS(p)); -- MOVE_POS_RET; -+ MOVE_POS_RET - } - } - -@@ -1123,7 +1207,7 @@ static UInt32* Bt4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) - UInt32 *hash; - GET_MATCHES_HEADER(4) - -- HASH4_CALC; -+ HASH4_CALC - - hash = p->hash; - pos = p->pos; -@@ -1190,7 +1274,7 @@ static UInt32* Bt5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) - UInt32 *hash; - GET_MATCHES_HEADER(5) - -- HASH5_CALC; -+ HASH5_CALC - - hash = p->hash; - pos = p->pos; -@@ -1246,7 +1330,7 @@ static UInt32* Bt5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) - if (maxLen == lenLimit) - { - SkipMatchesSpec(MF_PARAMS(p)); -- MOVE_POS_RET; -+ MOVE_POS_RET - } - break; - } -@@ -1263,7 +1347,7 @@ static UInt32* Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) - UInt32 *hash; - GET_MATCHES_HEADER(4) - -- HASH4_CALC; -+ HASH4_CALC - - hash = p->hash; - pos = p->pos; -@@ -1314,12 +1398,12 @@ static UInt32* Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) - if (maxLen == lenLimit) - { - p->son[p->cyclicBufferPos] = curMatch; -- MOVE_POS_RET; -+ MOVE_POS_RET - } - break; - } - -- GET_MATCHES_FOOTER_HC(maxLen); -+ GET_MATCHES_FOOTER_HC(maxLen) - } - - -@@ -1330,7 +1414,7 @@ static UInt32 * Hc5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) - UInt32 *hash; - GET_MATCHES_HEADER(5) - -- HASH5_CALC; -+ HASH5_CALC - - hash = p->hash; - pos = p->pos; -@@ -1386,19 +1470,19 @@ static UInt32 * Hc5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) - if (maxLen == lenLimit) - { - p->son[p->cyclicBufferPos] = curMatch; -- MOVE_POS_RET; -+ MOVE_POS_RET - } - break; - } - -- GET_MATCHES_FOOTER_HC(maxLen); -+ GET_MATCHES_FOOTER_HC(maxLen) - } - - - UInt32* Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) - { - GET_MATCHES_HEADER(3) -- HASH_ZIP_CALC; -+ HASH_ZIP_CALC - curMatch = p->hash[hv]; - p->hash[hv] = p->pos; - GET_MATCHES_FOOTER_HC(2) -@@ -1409,7 +1493,7 @@ static void Bt2_MatchFinder_Skip(CMatchFinder *p, UInt32 num) - { - SKIP_HEADER(2) - { -- HASH2_CALC; -+ HASH2_CALC - curMatch = p->hash[hv]; - p->hash[hv] = p->pos; - } -@@ -1420,7 +1504,7 @@ void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num) - { - SKIP_HEADER(3) - { -- HASH_ZIP_CALC; -+ HASH_ZIP_CALC - curMatch = p->hash[hv]; - p->hash[hv] = p->pos; - } -@@ -1433,7 +1517,7 @@ static void Bt3_MatchFinder_Skip(CMatchFinder *p, UInt32 num) - { - UInt32 h2; - UInt32 *hash; -- HASH3_CALC; -+ HASH3_CALC - hash = p->hash; - curMatch = (hash + kFix3HashSize)[hv]; - hash[h2] = -@@ -1448,7 +1532,7 @@ static void Bt4_MatchFinder_Skip(CMatchFinder *p, UInt32 num) - { - UInt32 h2, h3; - UInt32 *hash; -- HASH4_CALC; -+ HASH4_CALC - hash = p->hash; - curMatch = (hash + kFix4HashSize)[hv]; - hash [h2] = -@@ -1464,7 +1548,7 @@ static void Bt5_MatchFinder_Skip(CMatchFinder *p, UInt32 num) - { - UInt32 h2, h3; - UInt32 *hash; -- HASH5_CALC; -+ HASH5_CALC - hash = p->hash; - curMatch = (hash + kFix5HashSize)[hv]; - hash [h2] = -@@ -1478,7 +1562,7 @@ static void Bt5_MatchFinder_Skip(CMatchFinder *p, UInt32 num) - - #define HC_SKIP_HEADER(minLen) \ - do { if (p->lenLimit < minLen) { MatchFinder_MovePos(p); num--; continue; } { \ -- Byte *cur; \ -+ const Byte *cur; \ - UInt32 *hash; \ - UInt32 *son; \ - UInt32 pos = p->pos; \ -@@ -1510,7 +1594,7 @@ static void Hc4_MatchFinder_Skip(CMatchFinder *p, UInt32 num) - HC_SKIP_HEADER(4) - - UInt32 h2, h3; -- HASH4_CALC; -+ HASH4_CALC - curMatch = (hash + kFix4HashSize)[hv]; - hash [h2] = - (hash + kFix3HashSize)[h3] = -@@ -1540,7 +1624,7 @@ void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num) - { - HC_SKIP_HEADER(3) - -- HASH_ZIP_CALC; -+ HASH_ZIP_CALC - curMatch = hash[hv]; - hash[hv] = pos; - -@@ -1590,17 +1674,17 @@ void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder2 *vTable) - - - --void LzFindPrepare() -+void LzFindPrepare(void) - { -- #ifndef FORCE_SATUR_SUB_128 -- #ifdef USE_SATUR_SUB_128 -+ #ifndef FORCE_LZFIND_SATUR_SUB_128 -+ #ifdef USE_LZFIND_SATUR_SUB_128 - LZFIND_SATUR_SUB_CODE_FUNC f = NULL; - #ifdef MY_CPU_ARM_OR_ARM64 - { - if (CPU_IsSupported_NEON()) - { - // #pragma message ("=== LzFind NEON") -- _PRF(printf("\n=== LzFind NEON\n")); -+ PRF(printf("\n=== LzFind NEON\n")); - f = LzFind_SaturSub_128; - } - // f = 0; // for debug -@@ -1609,20 +1693,25 @@ void LzFindPrepare() - if (CPU_IsSupported_SSE41()) - { - // #pragma message ("=== LzFind SSE41") -- _PRF(printf("\n=== LzFind SSE41\n")); -+ PRF(printf("\n=== LzFind SSE41\n")); - f = LzFind_SaturSub_128; - -- #ifdef USE_AVX2 -+ #ifdef USE_LZFIND_SATUR_SUB_256 - if (CPU_IsSupported_AVX2()) - { - // #pragma message ("=== LzFind AVX2") -- _PRF(printf("\n=== LzFind AVX2\n")); -+ PRF(printf("\n=== LzFind AVX2\n")); - f = LzFind_SaturSub_256; - } - #endif - } - #endif // MY_CPU_ARM_OR_ARM64 - g_LzFind_SaturSub = f; -- #endif // USE_SATUR_SUB_128 -- #endif // FORCE_SATUR_SUB_128 -+ #endif // USE_LZFIND_SATUR_SUB_128 -+ #endif // FORCE_LZFIND_SATUR_SUB_128 - } -+ -+ -+#undef MOVE_POS -+#undef MOVE_POS_RET -+#undef PRF -diff --git a/src/lzma/LzFind.h b/src/lzma/LzFind.h -index eea873ff6..a3f72c987 100644 ---- a/src/lzma/LzFind.h -+++ b/src/lzma/LzFind.h -@@ -1,8 +1,8 @@ - /* LzFind.h -- Match finder for LZ algorithms --2021-07-13 : Igor Pavlov : Public domain */ -+2023-03-04 : Igor Pavlov : Public domain */ - --#ifndef __LZ_FIND_H --#define __LZ_FIND_H -+#ifndef ZIP7_INC_LZ_FIND_H -+#define ZIP7_INC_LZ_FIND_H - - #include "7zTypes.h" - -@@ -10,9 +10,9 @@ EXTERN_C_BEGIN - - typedef UInt32 CLzRef; - --typedef struct _CMatchFinder -+typedef struct - { -- Byte *buffer; -+ const Byte *buffer; - UInt32 pos; - UInt32 posLimit; - UInt32 streamPos; /* wrap over Zero is allowed (streamPos < pos). Use (UInt32)(streamPos - pos) */ -@@ -32,8 +32,8 @@ typedef struct _CMatchFinder - UInt32 hashMask; - UInt32 cutValue; - -- Byte *bufferBase; -- ISeqInStream *stream; -+ Byte *bufBase; -+ ISeqInStreamPtr stream; - - UInt32 blockSize; - UInt32 keepSizeBefore; -@@ -43,7 +43,9 @@ typedef struct _CMatchFinder - size_t directInputRem; - UInt32 historySize; - UInt32 fixedHashSize; -- UInt32 hashSizeSum; -+ Byte numHashBytes_Min; -+ Byte numHashOutBits; -+ Byte _pad2_[2]; - SRes result; - UInt32 crc[256]; - size_t numRefs; -@@ -69,24 +71,45 @@ void MatchFinder_ReadIfRequired(CMatchFinder *p); - - void MatchFinder_Construct(CMatchFinder *p); - --/* Conditions: -- historySize <= 3 GB -- keepAddBufferBefore + matchMaxLen + keepAddBufferAfter < 511MB -+/* (directInput = 0) is default value. -+ It's required to provide correct (directInput) value -+ before calling MatchFinder_Create(). -+ You can set (directInput) by any of the following calls: -+ - MatchFinder_SET_DIRECT_INPUT_BUF() -+ - MatchFinder_SET_STREAM() -+ - MatchFinder_SET_STREAM_MODE() - */ -+ -+#define MatchFinder_SET_DIRECT_INPUT_BUF(p, _src_, _srcLen_) { \ -+ (p)->stream = NULL; \ -+ (p)->directInput = 1; \ -+ (p)->buffer = (_src_); \ -+ (p)->directInputRem = (_srcLen_); } -+ -+/* -+#define MatchFinder_SET_STREAM_MODE(p) { \ -+ (p)->directInput = 0; } -+*/ -+ -+#define MatchFinder_SET_STREAM(p, _stream_) { \ -+ (p)->stream = _stream_; \ -+ (p)->directInput = 0; } -+ -+ - int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, - UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, - ISzAllocPtr alloc); - void MatchFinder_Free(CMatchFinder *p, ISzAllocPtr alloc); - void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems); --// void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue); - - /* --#define Inline_MatchFinder_InitPos(p, val) \ -+#define MatchFinder_INIT_POS(p, val) \ - (p)->pos = (val); \ - (p)->streamPos = (val); - */ - --#define Inline_MatchFinder_ReduceOffsets(p, subValue) \ -+// void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue); -+#define MatchFinder_REDUCE_OFFSETS(p, subValue) \ - (p)->pos -= (subValue); \ - (p)->streamPos -= (subValue); - -@@ -107,7 +130,7 @@ 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 -+typedef struct - { - Mf_Init_Func Init; - Mf_GetNumAvailableBytes_Func GetNumAvailableBytes; -diff --git a/src/lzma/LzFindMt.c b/src/lzma/LzFindMt.c -index 1e0bfc87b..776be3ac6 100644 ---- a/src/lzma/LzFindMt.c -+++ b/src/lzma/LzFindMt.c -@@ -1,5 +1,5 @@ - /* LzFindMt.c -- multithreaded Match finder for LZ algorithms --2021-12-21 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -69,7 +69,7 @@ extern UInt64 g_NumIters_Bytes; - UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ - h3 = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); } - --#define __MT_HASH4_CALC { \ -+#define MT_HASH4_CALC { \ - UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ - h2 = temp & (kHash2Size - 1); \ - temp ^= ((UInt32)cur[2] << 8); \ -@@ -79,14 +79,14 @@ extern UInt64 g_NumIters_Bytes; - */ - - --MY_NO_INLINE -+Z7_NO_INLINE - static void MtSync_Construct(CMtSync *p) - { - p->affinity = 0; - p->wasCreated = False7z; - p->csWasInitialized = False7z; - p->csWasEntered = False7z; -- Thread_Construct(&p->thread); -+ Thread_CONSTRUCT(&p->thread) - Event_Construct(&p->canStart); - Event_Construct(&p->wasStopped); - Semaphore_Construct(&p->freeSemaphore); -@@ -116,7 +116,7 @@ static void MtSync_Construct(CMtSync *p) - (p)->csWasEntered = False7z; } - - --MY_NO_INLINE -+Z7_NO_INLINE - static UInt32 MtSync_GetNextBlock(CMtSync *p) - { - UInt32 numBlocks = 0; -@@ -140,14 +140,14 @@ static UInt32 MtSync_GetNextBlock(CMtSync *p) - - // buffer is UNLOCKED here - Semaphore_Wait(&p->filledSemaphore); -- LOCK_BUFFER(p); -+ LOCK_BUFFER(p) - return numBlocks; - } - - - /* if Writing (Processing) thread was started, we must call MtSync_StopWriting() */ - --MY_NO_INLINE -+Z7_NO_INLINE - static void MtSync_StopWriting(CMtSync *p) - { - if (!Thread_WasCreated(&p->thread) || p->needStart) -@@ -185,7 +185,7 @@ static void MtSync_StopWriting(CMtSync *p) - } - - --MY_NO_INLINE -+Z7_NO_INLINE - static void MtSync_Destruct(CMtSync *p) - { - PRF(printf("\nMtSync_Destruct %p\n", p)); -@@ -220,11 +220,11 @@ static void MtSync_Destruct(CMtSync *p) - - // #define RINOK_THREAD(x) { if ((x) != 0) return SZ_ERROR_THREAD; } - // we want to get real system error codes here instead of SZ_ERROR_THREAD --#define RINOK_THREAD(x) RINOK(x) -+#define RINOK_THREAD(x) RINOK_WRes(x) - - - // call it before each new file (when new starting is required): --MY_NO_INLINE -+Z7_NO_INLINE - static SRes MtSync_Init(CMtSync *p, UInt32 numBlocks) - { - WRes wres; -@@ -245,12 +245,12 @@ static WRes MtSync_Create_WRes(CMtSync *p, THREAD_FUNC_TYPE startAddress, void * - if (p->wasCreated) - return SZ_OK; - -- RINOK_THREAD(CriticalSection_Init(&p->cs)); -+ RINOK_THREAD(CriticalSection_Init(&p->cs)) - p->csWasInitialized = True7z; - p->csWasEntered = False7z; - -- RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->canStart)); -- RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->wasStopped)); -+ RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->canStart)) -+ RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->wasStopped)) - - p->needStart = True7z; - p->exit = True7z; /* p->exit is unused before (canStart) Event. -@@ -264,13 +264,13 @@ static WRes MtSync_Create_WRes(CMtSync *p, THREAD_FUNC_TYPE startAddress, void * - else - wres = Thread_Create(&p->thread, startAddress, obj); - -- RINOK_THREAD(wres); -+ RINOK_THREAD(wres) - p->wasCreated = True7z; - return SZ_OK; - } - - --MY_NO_INLINE -+Z7_NO_INLINE - static SRes MtSync_Create(CMtSync *p, THREAD_FUNC_TYPE startAddress, void *obj) - { - const WRes wres = MtSync_Create_WRes(p, startAddress, obj); -@@ -519,7 +519,7 @@ static void HashThreadFunc(CMatchFinderMt *mt) - if (mf->pos > (UInt32)kMtMaxValForNormalize - num) - { - const UInt32 subValue = (mf->pos - mf->historySize - 1); // & ~(UInt32)(kNormalizeAlign - 1); -- Inline_MatchFinder_ReduceOffsets(mf, subValue); -+ MatchFinder_REDUCE_OFFSETS(mf, subValue) - MatchFinder_Normalize3(subValue, mf->hash + mf->fixedHashSize, (size_t)mf->hashMask + 1); - } - -@@ -560,7 +560,7 @@ static void HashThreadFunc(CMatchFinderMt *mt) - */ - - --UInt32 * MY_FAST_CALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, -+UInt32 * Z7_FASTCALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, - UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, - size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, - UInt32 *posRes); -@@ -749,7 +749,7 @@ static void BtFillBlock(CMatchFinderMt *p, UInt32 globalBlockIndex) - } - - --MY_NO_INLINE -+Z7_NO_INLINE - static void BtThreadFunc(CMatchFinderMt *mt) - { - CMtSync *p = &mt->btSync; -@@ -864,15 +864,15 @@ SRes MatchFinderMt_Create(CMatchFinderMt *p, UInt32 historySize, UInt32 keepAddB - if (!MatchFinder_Create(mf, historySize, keepAddBufferBefore, matchMaxLen, keepAddBufferAfter, alloc)) - return SZ_ERROR_MEM; - -- RINOK(MtSync_Create(&p->hashSync, HashThreadFunc2, p)); -- RINOK(MtSync_Create(&p->btSync, BtThreadFunc2, p)); -+ RINOK(MtSync_Create(&p->hashSync, HashThreadFunc2, p)) -+ RINOK(MtSync_Create(&p->btSync, BtThreadFunc2, p)) - return SZ_OK; - } - - - SRes MatchFinderMt_InitMt(CMatchFinderMt *p) - { -- RINOK(MtSync_Init(&p->hashSync, kMtHashNumBlocks)); -+ RINOK(MtSync_Init(&p->hashSync, kMtHashNumBlocks)) - return MtSync_Init(&p->btSync, kMtBtNumBlocks); - } - -@@ -941,7 +941,7 @@ void MatchFinderMt_ReleaseStream(CMatchFinderMt *p) - } - - --MY_NO_INLINE -+Z7_NO_INLINE - static UInt32 MatchFinderMt_GetNextBlock_Bt(CMatchFinderMt *p) - { - if (p->failure_LZ_BT) -@@ -1163,7 +1163,7 @@ UInt32* MatchFinderMt_GetMatches_Bt4(CMatchFinderMt *p, UInt32 *d) - */ - - --static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) -+static UInt32 * MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) - { - UInt32 h2, h3, /* h4, */ c2, c3 /* , c4 */; - UInt32 *hash = p->hash; -@@ -1179,9 +1179,8 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) - (hash + kFix3HashSize)[h3] = m; - // (hash + kFix4HashSize)[h4] = m; - -- #define _USE_H2 -- -- #ifdef _USE_H2 -+ // #define BT5_USE_H2 -+ // #ifdef BT5_USE_H2 - if (c2 >= matchMinPos && cur[(ptrdiff_t)c2 - (ptrdiff_t)m] == cur[0]) - { - d[1] = m - c2 - 1; -@@ -1197,8 +1196,8 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) - } - d[0] = 3; - d += 2; -- -- #ifdef _USE_H4 -+ -+ #ifdef BT5_USE_H4 - if (c4 >= matchMinPos) - if ( - cur[(ptrdiff_t)c4 - (ptrdiff_t)m] == cur[0] && -@@ -1214,7 +1213,7 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) - d[0] = 2; - d += 2; - } -- #endif -+ // #endif - - if (c3 >= matchMinPos && cur[(ptrdiff_t)c3 - (ptrdiff_t)m] == cur[0]) - { -@@ -1228,7 +1227,7 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) - d += 2; - } - -- #ifdef _USE_H4 -+ #ifdef BT5_USE_H4 - if (c4 >= matchMinPos) - if ( - cur[(ptrdiff_t)c4 - (ptrdiff_t)m] == cur[0] && -@@ -1244,7 +1243,7 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) - } - - --static UInt32* MatchFinderMt2_GetMatches(CMatchFinderMt *p, UInt32 *d) -+static UInt32 * MatchFinderMt2_GetMatches(CMatchFinderMt *p, UInt32 *d) - { - const UInt32 *bt = p->btBufPos; - const UInt32 len = *bt++; -@@ -1268,7 +1267,7 @@ static UInt32* MatchFinderMt2_GetMatches(CMatchFinderMt *p, UInt32 *d) - - - --static UInt32* MatchFinderMt_GetMatches(CMatchFinderMt *p, UInt32 *d) -+static UInt32 * MatchFinderMt_GetMatches(CMatchFinderMt *p, UInt32 *d) - { - const UInt32 *bt = p->btBufPos; - UInt32 len = *bt++; -@@ -1398,3 +1397,10 @@ void MatchFinderMt_CreateVTable(CMatchFinderMt *p, IMatchFinder2 *vTable) - break; - } - } -+ -+#undef RINOK_THREAD -+#undef PRF -+#undef MF -+#undef GetUi24hi_from32 -+#undef LOCK_BUFFER -+#undef UNLOCK_BUFFER -diff --git a/src/lzma/LzFindMt.h b/src/lzma/LzFindMt.h -index 660b7244d..db5923ea0 100644 ---- a/src/lzma/LzFindMt.h -+++ b/src/lzma/LzFindMt.h -@@ -1,15 +1,15 @@ - /* LzFindMt.h -- multithreaded Match finder for LZ algorithms --2021-07-12 : Igor Pavlov : Public domain */ -+2023-03-05 : Igor Pavlov : Public domain */ - --#ifndef __LZ_FIND_MT_H --#define __LZ_FIND_MT_H -+#ifndef ZIP7_INC_LZ_FIND_MT_H -+#define ZIP7_INC_LZ_FIND_MT_H - - #include "LzFind.h" - #include "Threads.h" - - EXTERN_C_BEGIN - --typedef struct _CMtSync -+typedef struct - { - UInt32 numProcessedBlocks; - CThread thread; -@@ -39,7 +39,7 @@ typedef UInt32 * (*Mf_Mix_Matches)(void *p, UInt32 matchMinPos, UInt32 *distance - typedef void (*Mf_GetHeads)(const Byte *buffer, UInt32 pos, - UInt32 *hash, UInt32 hashMask, UInt32 *heads, UInt32 numHeads, const UInt32 *crc); - --typedef struct _CMatchFinderMt -+typedef struct - { - /* LZ */ - const Byte *pointerToCurPos; -diff --git a/src/lzma/LzFindOpt.c b/src/lzma/LzFindOpt.c -index 8ff006e07..85bdc136d 100644 ---- a/src/lzma/LzFindOpt.c -+++ b/src/lzma/LzFindOpt.c -@@ -1,5 +1,5 @@ - /* LzFindOpt.c -- multithreaded Match finder for LZ algorithms --2021-07-13 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -41,8 +41,8 @@ UInt64 g_NumIters_Bytes; - // #define CYC_TO_POS_OFFSET 1 // for debug - - /* --MY_NO_INLINE --UInt32 * MY_FAST_CALL GetMatchesSpecN_1(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, -+Z7_NO_INLINE -+UInt32 * Z7_FASTCALL GetMatchesSpecN_1(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, - UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, UInt32 *posRes) - { - do -@@ -214,13 +214,13 @@ else - to eliminate "movsx" BUG in old MSVC x64 compiler. - */ - --UInt32 * MY_FAST_CALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, -+UInt32 * Z7_FASTCALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, - UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, - size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, - UInt32 *posRes); - --MY_NO_INLINE --UInt32 * MY_FAST_CALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, -+Z7_NO_INLINE -+UInt32 * Z7_FASTCALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, - UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, - size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, - UInt32 *posRes) -@@ -404,7 +404,7 @@ else - /* - typedef UInt32 uint32plus; // size_t - --UInt32 * MY_FAST_CALL GetMatchesSpecN_3(uint32plus lenLimit, size_t pos, const Byte *cur, CLzRef *son, -+UInt32 * Z7_FASTCALL GetMatchesSpecN_3(uint32plus lenLimit, size_t pos, const Byte *cur, CLzRef *son, - UInt32 _cutValue, UInt32 *d, uint32plus _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, - size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, - UInt32 *posRes) -diff --git a/src/lzma/LzHash.h b/src/lzma/LzHash.h -index 77b898cfa..2b6290b64 100644 ---- a/src/lzma/LzHash.h -+++ b/src/lzma/LzHash.h -@@ -1,8 +1,8 @@ --/* LzHash.h -- HASH functions for LZ algorithms --2019-10-30 : Igor Pavlov : Public domain */ -+/* LzHash.h -- HASH constants for LZ algorithms -+2023-03-05 : Igor Pavlov : Public domain */ - --#ifndef __LZ_HASH_H --#define __LZ_HASH_H -+#ifndef ZIP7_INC_LZ_HASH_H -+#define ZIP7_INC_LZ_HASH_H - - /* - (kHash2Size >= (1 << 8)) : Required -diff --git a/src/lzma/Lzma2Dec.c b/src/lzma/Lzma2Dec.c -index 3f4ca29ea..8c4d464c0 100644 ---- a/src/lzma/Lzma2Dec.c -+++ b/src/lzma/Lzma2Dec.c -@@ -1,5 +1,5 @@ - /* Lzma2Dec.c -- LZMA2 Decoder --2021-02-09 : Igor Pavlov : Public domain */ -+2023-03-03 : Igor Pavlov : Public domain */ - - /* #define SHOW_DEBUG_INFO */ - -@@ -71,14 +71,14 @@ static SRes Lzma2Dec_GetOldProps(Byte prop, Byte *props) - SRes Lzma2Dec_AllocateProbs(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc) - { - Byte props[LZMA_PROPS_SIZE]; -- RINOK(Lzma2Dec_GetOldProps(prop, props)); -+ RINOK(Lzma2Dec_GetOldProps(prop, props)) - return LzmaDec_AllocateProbs(&p->decoder, props, LZMA_PROPS_SIZE, alloc); - } - - SRes Lzma2Dec_Allocate(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc) - { - Byte props[LZMA_PROPS_SIZE]; -- RINOK(Lzma2Dec_GetOldProps(prop, props)); -+ RINOK(Lzma2Dec_GetOldProps(prop, props)) - return LzmaDec_Allocate(&p->decoder, props, LZMA_PROPS_SIZE, alloc); - } - -@@ -474,8 +474,8 @@ SRes Lzma2Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, - SizeT outSize = *destLen, inSize = *srcLen; - *destLen = *srcLen = 0; - *status = LZMA_STATUS_NOT_SPECIFIED; -- Lzma2Dec_Construct(&p); -- RINOK(Lzma2Dec_AllocateProbs(&p, prop, alloc)); -+ Lzma2Dec_CONSTRUCT(&p) -+ RINOK(Lzma2Dec_AllocateProbs(&p, prop, alloc)) - p.decoder.dic = dest; - p.decoder.dicBufSize = outSize; - Lzma2Dec_Init(&p); -@@ -487,3 +487,5 @@ SRes Lzma2Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, - Lzma2Dec_FreeProbs(&p, alloc); - return res; - } -+ -+#undef PRF -diff --git a/src/lzma/Lzma2Dec.h b/src/lzma/Lzma2Dec.h -index b8ddeac89..1f5233a72 100644 ---- a/src/lzma/Lzma2Dec.h -+++ b/src/lzma/Lzma2Dec.h -@@ -1,8 +1,8 @@ - /* Lzma2Dec.h -- LZMA2 Decoder --2018-02-19 : Igor Pavlov : Public domain */ -+2023-03-03 : Igor Pavlov : Public domain */ - --#ifndef __LZMA2_DEC_H --#define __LZMA2_DEC_H -+#ifndef ZIP7_INC_LZMA2_DEC_H -+#define ZIP7_INC_LZMA2_DEC_H - - #include "LzmaDec.h" - -@@ -22,9 +22,10 @@ typedef struct - CLzmaDec decoder; - } CLzma2Dec; - --#define Lzma2Dec_Construct(p) LzmaDec_Construct(&(p)->decoder) --#define Lzma2Dec_FreeProbs(p, alloc) LzmaDec_FreeProbs(&(p)->decoder, alloc) --#define Lzma2Dec_Free(p, alloc) LzmaDec_Free(&(p)->decoder, alloc) -+#define Lzma2Dec_CONSTRUCT(p) LzmaDec_CONSTRUCT(&(p)->decoder) -+#define Lzma2Dec_Construct(p) Lzma2Dec_CONSTRUCT(p) -+#define Lzma2Dec_FreeProbs(p, alloc) LzmaDec_FreeProbs(&(p)->decoder, alloc) -+#define Lzma2Dec_Free(p, alloc) LzmaDec_Free(&(p)->decoder, alloc) - - SRes Lzma2Dec_AllocateProbs(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc); - SRes Lzma2Dec_Allocate(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc); -@@ -90,7 +91,7 @@ Lzma2Dec_GetUnpackExtra() returns the value that shows - at current input positon. - */ - --#define Lzma2Dec_GetUnpackExtra(p) ((p)->isExtraMode ? (p)->unpackSize : 0); -+#define Lzma2Dec_GetUnpackExtra(p) ((p)->isExtraMode ? (p)->unpackSize : 0) - - - /* ---------- One Call Interface ---------- */ -diff --git a/src/lzma/Lzma2DecMt.c b/src/lzma/Lzma2DecMt.c -index 51a237a85..9ada455bf 100644 ---- a/src/lzma/Lzma2DecMt.c -+++ b/src/lzma/Lzma2DecMt.c -@@ -1,44 +1,44 @@ - /* Lzma2DecMt.c -- LZMA2 Decoder Multi-thread --2021-04-01 : Igor Pavlov : Public domain */ -+2023-04-13 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - - // #define SHOW_DEBUG_INFO -- --// #define _7ZIP_ST -+// #define Z7_ST - - #ifdef SHOW_DEBUG_INFO - #include - #endif - --#ifndef _7ZIP_ST --#ifdef SHOW_DEBUG_INFO --#define PRF(x) x --#else --#define PRF(x) --#endif --#define PRF_STR(s) PRF(printf("\n" s "\n")) --#define PRF_STR_INT_2(s, d1, d2) PRF(printf("\n" s " %d %d\n", (unsigned)d1, (unsigned)d2)) --#endif -- - #include "Alloc.h" - - #include "Lzma2Dec.h" - #include "Lzma2DecMt.h" - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - #include "MtDec.h" - - #define LZMA2DECMT_OUT_BLOCK_MAX_DEFAULT (1 << 28) - #endif - - -+#ifndef Z7_ST -+#ifdef SHOW_DEBUG_INFO -+#define PRF(x) x -+#else -+#define PRF(x) -+#endif -+#define PRF_STR(s) PRF(printf("\n" s "\n");) -+#define PRF_STR_INT_2(s, d1, d2) PRF(printf("\n" s " %d %d\n", (unsigned)d1, (unsigned)d2);) -+#endif -+ -+ - void Lzma2DecMtProps_Init(CLzma2DecMtProps *p) - { - p->inBufSize_ST = 1 << 20; - p->outStep_ST = 1 << 20; - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - p->numThreads = 1; - p->inBufSize_MT = 1 << 18; - p->outBlockMax = LZMA2DECMT_OUT_BLOCK_MAX_DEFAULT; -@@ -48,7 +48,7 @@ void Lzma2DecMtProps_Init(CLzma2DecMtProps *p) - - - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - - /* ---------- CLzma2DecMtThread ---------- */ - -@@ -81,7 +81,7 @@ typedef struct - - /* ---------- CLzma2DecMt ---------- */ - --typedef struct -+struct CLzma2DecMt - { - // ISzAllocPtr alloc; - ISzAllocPtr allocMid; -@@ -90,9 +90,9 @@ typedef struct - CLzma2DecMtProps props; - Byte prop; - -- ISeqInStream *inStream; -- ISeqOutStream *outStream; -- ICompressProgress *progress; -+ ISeqInStreamPtr inStream; -+ ISeqOutStreamPtr outStream; -+ ICompressProgressPtr progress; - - BoolInt finishMode; - BoolInt outSize_Defined; -@@ -111,14 +111,13 @@ typedef struct - size_t inPos; - size_t inLim; - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - UInt64 outProcessed_Parse; - BoolInt mtc_WasConstructed; - CMtDec mtc; -- CLzma2DecMtThread coders[MTDEC__THREADS_MAX]; -+ CLzma2DecMtThread coders[MTDEC_THREADS_MAX]; - #endif -- --} CLzma2DecMt; -+}; - - - -@@ -142,11 +141,11 @@ CLzma2DecMtHandle Lzma2DecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid) - - // Lzma2DecMtProps_Init(&p->props); - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - p->mtc_WasConstructed = False7z; - { - unsigned i; -- for (i = 0; i < MTDEC__THREADS_MAX; i++) -+ for (i = 0; i < MTDEC_THREADS_MAX; i++) - { - CLzma2DecMtThread *t = &p->coders[i]; - t->dec_created = False7z; -@@ -156,16 +155,16 @@ CLzma2DecMtHandle Lzma2DecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid) - } - #endif - -- return p; -+ return (CLzma2DecMtHandle)(void *)p; - } - - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - - static void Lzma2DecMt_FreeOutBufs(CLzma2DecMt *p) - { - unsigned i; -- for (i = 0; i < MTDEC__THREADS_MAX; i++) -+ for (i = 0; i < MTDEC_THREADS_MAX; i++) - { - CLzma2DecMtThread *t = &p->coders[i]; - if (t->outBuf) -@@ -196,13 +195,15 @@ static void Lzma2DecMt_FreeSt(CLzma2DecMt *p) - } - - --void Lzma2DecMt_Destroy(CLzma2DecMtHandle pp) -+// #define GET_CLzma2DecMt_p CLzma2DecMt *p = (CLzma2DecMt *)(void *)pp; -+ -+void Lzma2DecMt_Destroy(CLzma2DecMtHandle p) - { -- CLzma2DecMt *p = (CLzma2DecMt *)pp; -+ // GET_CLzma2DecMt_p - - Lzma2DecMt_FreeSt(p); - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - - if (p->mtc_WasConstructed) - { -@@ -211,7 +212,7 @@ void Lzma2DecMt_Destroy(CLzma2DecMtHandle pp) - } - { - unsigned i; -- for (i = 0; i < MTDEC__THREADS_MAX; i++) -+ for (i = 0; i < MTDEC_THREADS_MAX; i++) - { - CLzma2DecMtThread *t = &p->coders[i]; - if (t->dec_created) -@@ -226,19 +227,19 @@ void Lzma2DecMt_Destroy(CLzma2DecMtHandle pp) - - #endif - -- ISzAlloc_Free(p->alignOffsetAlloc.baseAlloc, pp); -+ ISzAlloc_Free(p->alignOffsetAlloc.baseAlloc, p); - } - - - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - - static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCallbackInfo *cc) - { - CLzma2DecMt *me = (CLzma2DecMt *)obj; - CLzma2DecMtThread *t = &me->coders[coderIndex]; - -- PRF_STR_INT_2("Parse", coderIndex, cc->srcSize); -+ PRF_STR_INT_2("Parse", coderIndex, cc->srcSize) - - cc->state = MTDEC_PARSE_CONTINUE; - -@@ -246,7 +247,7 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa - { - if (!t->dec_created) - { -- Lzma2Dec_Construct(&t->dec); -+ Lzma2Dec_CONSTRUCT(&t->dec) - t->dec_created = True7z; - AlignOffsetAlloc_CreateVTable(&t->alloc); - { -@@ -297,7 +298,7 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa - // that must be finished at position <= outBlockMax. - - { -- const SizeT srcOrig = cc->srcSize; -+ const size_t srcOrig = cc->srcSize; - SizeT srcSize_Point = 0; - SizeT dicPos_Point = 0; - -@@ -306,10 +307,10 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa - - for (;;) - { -- SizeT srcCur = srcOrig - cc->srcSize; -+ SizeT srcCur = (SizeT)(srcOrig - cc->srcSize); - - status = Lzma2Dec_Parse(&t->dec, -- limit - t->dec.decoder.dicPos, -+ (SizeT)limit - t->dec.decoder.dicPos, - cc->src + cc->srcSize, &srcCur, - checkFinishBlock); - -@@ -333,7 +334,7 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa - if (t->dec.decoder.dicPos >= (1 << 14)) - break; - dicPos_Point = t->dec.decoder.dicPos; -- srcSize_Point = cc->srcSize; -+ srcSize_Point = (SizeT)cc->srcSize; - continue; - } - -@@ -391,7 +392,7 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa - if (unpackRem != 0) - { - /* we also reserve space for max possible number of output bytes of current LZMA chunk */ -- SizeT rem = limit - dicPos; -+ size_t rem = limit - dicPos; - if (rem > unpackRem) - rem = unpackRem; - dicPos += rem; -@@ -444,7 +445,7 @@ static SRes Lzma2DecMt_MtCallback_PreCode(void *pp, unsigned coderIndex) - } - - t->dec.decoder.dic = dest; -- t->dec.decoder.dicBufSize = t->outPreSize; -+ t->dec.decoder.dicBufSize = (SizeT)t->outPreSize; - - t->needInit = True7z; - -@@ -462,7 +463,7 @@ static SRes Lzma2DecMt_MtCallback_Code(void *pp, unsigned coderIndex, - - UNUSED_VAR(srcFinished) - -- PRF_STR_INT_2("Code", coderIndex, srcSize); -+ PRF_STR_INT_2("Code", coderIndex, srcSize) - - *inCodePos = t->inCodeSize; - *outCodePos = 0; -@@ -476,13 +477,13 @@ static SRes Lzma2DecMt_MtCallback_Code(void *pp, unsigned coderIndex, - - { - ELzmaStatus status; -- size_t srcProcessed = srcSize; -+ SizeT srcProcessed = (SizeT)srcSize; - BoolInt blockWasFinished = - ((int)t->parseStatus == LZMA_STATUS_FINISHED_WITH_MARK - || t->parseStatus == LZMA2_PARSE_STATUS_NEW_BLOCK); - - SRes res = Lzma2Dec_DecodeToDic(&t->dec, -- t->outPreSize, -+ (SizeT)t->outPreSize, - src, &srcProcessed, - blockWasFinished ? LZMA_FINISH_END : LZMA_FINISH_ANY, - &status); -@@ -540,7 +541,7 @@ static SRes Lzma2DecMt_MtCallback_Write(void *pp, unsigned coderIndex, - UNUSED_VAR(srcSize) - UNUSED_VAR(isCross) - -- PRF_STR_INT_2("Write", coderIndex, srcSize); -+ PRF_STR_INT_2("Write", coderIndex, srcSize) - - *needContinue = False7z; - *canRecode = True7z; -@@ -588,7 +589,7 @@ static SRes Lzma2DecMt_MtCallback_Write(void *pp, unsigned coderIndex, - *needContinue = needContinue2; - return SZ_OK; - } -- RINOK(MtProgress_ProgressAdd(&me->mtc.mtProgress, 0, 0)); -+ RINOK(MtProgress_ProgressAdd(&me->mtc.mtProgress, 0, 0)) - } - } - -@@ -611,11 +612,11 @@ static SRes Lzma2Dec_Prepare_ST(CLzma2DecMt *p) - { - if (!p->dec_created) - { -- Lzma2Dec_Construct(&p->dec); -+ Lzma2Dec_CONSTRUCT(&p->dec) - p->dec_created = True7z; - } - -- RINOK(Lzma2Dec_Allocate(&p->dec, p->prop, &p->alignOffsetAlloc.vt)); -+ RINOK(Lzma2Dec_Allocate(&p->dec, p->prop, &p->alignOffsetAlloc.vt)) - - if (!p->inBuf || p->inBufSize != p->props.inBufSize_ST) - { -@@ -634,7 +635,7 @@ static SRes Lzma2Dec_Prepare_ST(CLzma2DecMt *p) - - - static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - , BoolInt tMode - #endif - ) -@@ -646,7 +647,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p - - CLzma2Dec *dec; - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - if (tMode) - { - Lzma2DecMt_FreeOutBufs(p); -@@ -654,7 +655,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p - } - #endif - -- RINOK(Lzma2Dec_Prepare_ST(p)); -+ RINOK(Lzma2Dec_Prepare_ST(p)) - - dec = &p->dec; - -@@ -681,7 +682,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p - - if (inPos == inLim) - { -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - if (tMode) - { - inData = MtDec_Read(&p->mtc, &inLim); -@@ -710,7 +711,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p - { - SizeT next = dec->decoder.dicBufSize; - if (next - wrPos > p->props.outStep_ST) -- next = wrPos + p->props.outStep_ST; -+ next = wrPos + (SizeT)p->props.outStep_ST; - size = next - dicPos; - } - -@@ -726,7 +727,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p - } - } - -- inProcessed = inLim - inPos; -+ inProcessed = (SizeT)(inLim - inPos); - - res = Lzma2Dec_DecodeToDic(dec, dicPos + size, inData + inPos, &inProcessed, finishMode, &status); - -@@ -755,7 +756,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p - dec->decoder.dicPos = 0; - wrPos = dec->decoder.dicPos; - -- RINOK(res2); -+ RINOK(res2) - - if (needStop) - { -@@ -788,7 +789,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p - UInt64 outDelta = p->outProcessed - outPrev; - if (inDelta >= (1 << 22) || outDelta >= (1 << 22)) - { -- RINOK(ICompressProgress_Progress(p->progress, p->inProcessed, p->outProcessed)); -+ RINOK(ICompressProgress_Progress(p->progress, p->inProcessed, p->outProcessed)) - inPrev = p->inProcessed; - outPrev = p->outProcessed; - } -@@ -798,20 +799,20 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p - - - --SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, -+SRes Lzma2DecMt_Decode(CLzma2DecMtHandle p, - Byte prop, - const CLzma2DecMtProps *props, -- ISeqOutStream *outStream, const UInt64 *outDataSize, int finishMode, -+ ISeqOutStreamPtr outStream, const UInt64 *outDataSize, int finishMode, - // Byte *outBuf, size_t *outBufSize, -- ISeqInStream *inStream, -+ ISeqInStreamPtr inStream, - // const Byte *inData, size_t inDataSize, - UInt64 *inProcessed, - // UInt64 *outProcessed, - int *isMT, -- ICompressProgress *progress) -+ ICompressProgressPtr progress) - { -- CLzma2DecMt *p = (CLzma2DecMt *)pp; -- #ifndef _7ZIP_ST -+ // GET_CLzma2DecMt_p -+ #ifndef Z7_ST - BoolInt tMode; - #endif - -@@ -845,7 +846,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, - *isMT = False7z; - - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - - tMode = False7z; - -@@ -939,7 +940,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, - p->readWasFinished = p->mtc.readWasFinished; - p->inProcessed = p->mtc.inProcessed; - -- PRF_STR("----- decoding ST -----"); -+ PRF_STR("----- decoding ST -----") - } - } - -@@ -950,7 +951,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, - - { - SRes res = Lzma2Dec_Decode_ST(p -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - , tMode - #endif - ); -@@ -967,7 +968,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, - res = p->readRes; - - /* -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - if (res == SZ_OK && tMode && p->mtc.parseRes != SZ_OK) - res = p->mtc.parseRes; - #endif -@@ -980,13 +981,13 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, - - /* ---------- Read from CLzma2DecMtHandle Interface ---------- */ - --SRes Lzma2DecMt_Init(CLzma2DecMtHandle pp, -+SRes Lzma2DecMt_Init(CLzma2DecMtHandle p, - Byte prop, - const CLzma2DecMtProps *props, - const UInt64 *outDataSize, int finishMode, -- ISeqInStream *inStream) -+ ISeqInStreamPtr inStream) - { -- CLzma2DecMt *p = (CLzma2DecMt *)pp; -+ // GET_CLzma2DecMt_p - - if (prop > 40) - return SZ_ERROR_UNSUPPORTED; -@@ -1015,11 +1016,11 @@ SRes Lzma2DecMt_Init(CLzma2DecMtHandle pp, - } - - --SRes Lzma2DecMt_Read(CLzma2DecMtHandle pp, -+SRes Lzma2DecMt_Read(CLzma2DecMtHandle p, - Byte *data, size_t *outSize, - UInt64 *inStreamProcessed) - { -- CLzma2DecMt *p = (CLzma2DecMt *)pp; -+ // GET_CLzma2DecMt_p - ELzmaFinishMode finishMode; - SRes readRes; - size_t size = *outSize; -@@ -1055,8 +1056,8 @@ SRes Lzma2DecMt_Read(CLzma2DecMtHandle pp, - readRes = ISeqInStream_Read(p->inStream, p->inBuf, &p->inLim); - } - -- inCur = p->inLim - p->inPos; -- outCur = size; -+ inCur = (SizeT)(p->inLim - p->inPos); -+ outCur = (SizeT)size; - - res = Lzma2Dec_DecodeToBuf(&p->dec, data, &outCur, - p->inBuf + p->inPos, &inCur, finishMode, &status); -@@ -1088,3 +1089,7 @@ SRes Lzma2DecMt_Read(CLzma2DecMtHandle pp, - return readRes; - } - } -+ -+#undef PRF -+#undef PRF_STR -+#undef PRF_STR_INT_2 -diff --git a/src/lzma/Lzma2DecMt.h b/src/lzma/Lzma2DecMt.h -index 7791c310b..93a5cd59e 100644 ---- a/src/lzma/Lzma2DecMt.h -+++ b/src/lzma/Lzma2DecMt.h -@@ -1,8 +1,8 @@ - /* Lzma2DecMt.h -- LZMA2 Decoder Multi-thread --2018-02-17 : Igor Pavlov : Public domain */ -+2023-04-13 : Igor Pavlov : Public domain */ - --#ifndef __LZMA2_DEC_MT_H --#define __LZMA2_DEC_MT_H -+#ifndef ZIP7_INC_LZMA2_DEC_MT_H -+#define ZIP7_INC_LZMA2_DEC_MT_H - - #include "7zTypes.h" - -@@ -13,7 +13,7 @@ typedef struct - size_t inBufSize_ST; - size_t outStep_ST; - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - unsigned numThreads; - size_t inBufSize_MT; - size_t outBlockMax; -@@ -38,7 +38,9 @@ void Lzma2DecMtProps_Init(CLzma2DecMtProps *p); - SZ_ERROR_THREAD - error in multithreading functions (only for Mt version) - */ - --typedef void * CLzma2DecMtHandle; -+typedef struct CLzma2DecMt CLzma2DecMt; -+typedef CLzma2DecMt * CLzma2DecMtHandle; -+// Z7_DECLARE_HANDLE(CLzma2DecMtHandle) - - CLzma2DecMtHandle Lzma2DecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid); - void Lzma2DecMt_Destroy(CLzma2DecMtHandle p); -@@ -46,11 +48,11 @@ void Lzma2DecMt_Destroy(CLzma2DecMtHandle p); - SRes Lzma2DecMt_Decode(CLzma2DecMtHandle p, - Byte prop, - const CLzma2DecMtProps *props, -- ISeqOutStream *outStream, -+ ISeqOutStreamPtr outStream, - const UInt64 *outDataSize, // NULL means undefined - int finishMode, // 0 - partial unpacking is allowed, 1 - if lzma2 stream must be finished - // Byte *outBuf, size_t *outBufSize, -- ISeqInStream *inStream, -+ ISeqInStreamPtr inStream, - // const Byte *inData, size_t inDataSize, - - // out variables: -@@ -58,7 +60,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle p, - int *isMT, /* out: (*isMT == 0), if single thread decoding was used */ - - // UInt64 *outProcessed, -- ICompressProgress *progress); -+ ICompressProgressPtr progress); - - - /* ---------- Read from CLzma2DecMtHandle Interface ---------- */ -@@ -67,7 +69,7 @@ SRes Lzma2DecMt_Init(CLzma2DecMtHandle pp, - Byte prop, - const CLzma2DecMtProps *props, - const UInt64 *outDataSize, int finishMode, -- ISeqInStream *inStream); -+ ISeqInStreamPtr inStream); - - SRes Lzma2DecMt_Read(CLzma2DecMtHandle pp, - Byte *data, size_t *outSize, -diff --git a/src/lzma/Lzma2Enc.c b/src/lzma/Lzma2Enc.c -index 4799b65ad..f31c3ddad 100644 ---- a/src/lzma/Lzma2Enc.c -+++ b/src/lzma/Lzma2Enc.c -@@ -1,18 +1,18 @@ - /* Lzma2Enc.c -- LZMA2 Encoder --2021-02-09 : Igor Pavlov : Public domain */ -+2023-04-13 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - - #include - --/* #define _7ZIP_ST */ -+/* #define Z7_ST */ - - #include "Lzma2Enc.h" - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - #include "MtCoder.h" - #else --#define MTCODER__THREADS_MAX 1 -+#define MTCODER_THREADS_MAX 1 - #endif - - #define LZMA2_CONTROL_LZMA (1 << 7) -@@ -40,7 +40,7 @@ - typedef struct - { - ISeqInStream vt; -- ISeqInStream *realStream; -+ ISeqInStreamPtr realStream; - UInt64 limit; - UInt64 processed; - int finished; -@@ -53,15 +53,15 @@ static void LimitedSeqInStream_Init(CLimitedSeqInStream *p) - p->finished = 0; - } - --static SRes LimitedSeqInStream_Read(const ISeqInStream *pp, void *data, size_t *size) -+static SRes LimitedSeqInStream_Read(ISeqInStreamPtr pp, void *data, size_t *size) - { -- CLimitedSeqInStream *p = CONTAINER_FROM_VTBL(pp, CLimitedSeqInStream, vt); -+ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CLimitedSeqInStream) - size_t size2 = *size; - SRes res = SZ_OK; - - if (p->limit != (UInt64)(Int64)-1) - { -- UInt64 rem = p->limit - p->processed; -+ const UInt64 rem = p->limit - p->processed; - if (size2 > rem) - size2 = (size_t)rem; - } -@@ -95,8 +95,8 @@ static SRes Lzma2EncInt_InitStream(CLzma2EncInt *p, const CLzma2EncProps *props) - { - SizeT propsSize = LZMA_PROPS_SIZE; - Byte propsEncoded[LZMA_PROPS_SIZE]; -- RINOK(LzmaEnc_SetProps(p->enc, &props->lzmaProps)); -- RINOK(LzmaEnc_WriteProperties(p->enc, propsEncoded, &propsSize)); -+ RINOK(LzmaEnc_SetProps(p->enc, &props->lzmaProps)) -+ RINOK(LzmaEnc_WriteProperties(p->enc, propsEncoded, &propsSize)) - p->propsByte = propsEncoded[0]; - p->propsAreSet = True7z; - } -@@ -111,23 +111,23 @@ static void Lzma2EncInt_InitBlock(CLzma2EncInt *p) - } - - --SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp, ISeqInStream *inStream, UInt32 keepWindowSize, -+SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle p, ISeqInStreamPtr inStream, UInt32 keepWindowSize, - ISzAllocPtr alloc, ISzAllocPtr allocBig); --SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen, -+SRes LzmaEnc_MemPrepare(CLzmaEncHandle p, const Byte *src, SizeT srcLen, - UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig); --SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit, -+SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle p, BoolInt reInit, - Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize); --const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp); --void LzmaEnc_Finish(CLzmaEncHandle pp); --void LzmaEnc_SaveState(CLzmaEncHandle pp); --void LzmaEnc_RestoreState(CLzmaEncHandle pp); -+const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle p); -+void LzmaEnc_Finish(CLzmaEncHandle p); -+void LzmaEnc_SaveState(CLzmaEncHandle p); -+void LzmaEnc_RestoreState(CLzmaEncHandle p); - - /* --UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp); -+UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle p); - */ - - static SRes Lzma2EncInt_EncodeSubblock(CLzma2EncInt *p, Byte *outBuf, -- size_t *packSizeRes, ISeqOutStream *outStream) -+ size_t *packSizeRes, ISeqOutStreamPtr outStream) - { - size_t packSizeLimit = *packSizeRes; - size_t packSize = packSizeLimit; -@@ -167,7 +167,7 @@ static SRes Lzma2EncInt_EncodeSubblock(CLzma2EncInt *p, Byte *outBuf, - - while (unpackSize > 0) - { -- UInt32 u = (unpackSize < LZMA2_COPY_CHUNK_SIZE) ? unpackSize : LZMA2_COPY_CHUNK_SIZE; -+ const UInt32 u = (unpackSize < LZMA2_COPY_CHUNK_SIZE) ? unpackSize : LZMA2_COPY_CHUNK_SIZE; - if (packSizeLimit - destPos < u + 3) - return SZ_ERROR_OUTPUT_EOF; - outBuf[destPos++] = (Byte)(p->srcPos == 0 ? LZMA2_CONTROL_COPY_RESET_DIC : LZMA2_CONTROL_COPY_NO_RESET); -@@ -196,9 +196,9 @@ static SRes Lzma2EncInt_EncodeSubblock(CLzma2EncInt *p, Byte *outBuf, - - { - size_t destPos = 0; -- UInt32 u = unpackSize - 1; -- UInt32 pm = (UInt32)(packSize - 1); -- unsigned mode = (p->srcPos == 0) ? 3 : (p->needInitState ? (p->needInitProp ? 2 : 1) : 0); -+ const UInt32 u = unpackSize - 1; -+ const UInt32 pm = (UInt32)(packSize - 1); -+ const unsigned mode = (p->srcPos == 0) ? 3 : (p->needInitState ? (p->needInitProp ? 2 : 1) : 0); - - PRF(printf(" ")); - -@@ -231,7 +231,7 @@ static SRes Lzma2EncInt_EncodeSubblock(CLzma2EncInt *p, Byte *outBuf, - void Lzma2EncProps_Init(CLzma2EncProps *p) - { - LzmaEncProps_Init(&p->lzmaProps); -- p->blockSize = LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO; -+ p->blockSize = LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO; - p->numBlockThreads_Reduced = -1; - p->numBlockThreads_Max = -1; - p->numTotalThreads = -1; -@@ -251,8 +251,8 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p) - t2 = p->numBlockThreads_Max; - t3 = p->numTotalThreads; - -- if (t2 > MTCODER__THREADS_MAX) -- t2 = MTCODER__THREADS_MAX; -+ if (t2 > MTCODER_THREADS_MAX) -+ t2 = MTCODER_THREADS_MAX; - - if (t3 <= 0) - { -@@ -268,8 +268,8 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p) - t1 = 1; - t2 = t3; - } -- if (t2 > MTCODER__THREADS_MAX) -- t2 = MTCODER__THREADS_MAX; -+ if (t2 > MTCODER_THREADS_MAX) -+ t2 = MTCODER_THREADS_MAX; - } - else if (t1 <= 0) - { -@@ -286,8 +286,8 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p) - - fileSize = p->lzmaProps.reduceSize; - -- if ( p->blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID -- && p->blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO -+ if ( p->blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID -+ && p->blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO - && (p->blockSize < fileSize || fileSize == (UInt64)(Int64)-1)) - p->lzmaProps.reduceSize = p->blockSize; - -@@ -297,19 +297,19 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p) - - t1 = p->lzmaProps.numThreads; - -- if (p->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID) -+ if (p->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID) - { - t2r = t2 = 1; - t3 = t1; - } -- else if (p->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO && t2 <= 1) -+ else if (p->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO && t2 <= 1) - { - /* if there is no block multi-threading, we use SOLID block */ -- p->blockSize = LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID; -+ p->blockSize = LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID; - } - else - { -- if (p->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO) -+ if (p->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO) - { - const UInt32 kMinSize = (UInt32)1 << 20; - const UInt32 kMaxSize = (UInt32)1 << 28; -@@ -344,7 +344,7 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p) - } - - --static SRes Progress(ICompressProgress *p, UInt64 inSize, UInt64 outSize) -+static SRes Progress(ICompressProgressPtr p, UInt64 inSize, UInt64 outSize) - { - return (p && ICompressProgress_Progress(p, inSize, outSize) != SZ_OK) ? SZ_ERROR_PROGRESS : SZ_OK; - } -@@ -352,7 +352,7 @@ static SRes Progress(ICompressProgress *p, UInt64 inSize, UInt64 outSize) - - /* ---------- Lzma2 ---------- */ - --typedef struct -+struct CLzma2Enc - { - Byte propEncoded; - CLzma2EncProps props; -@@ -363,23 +363,22 @@ typedef struct - ISzAllocPtr alloc; - ISzAllocPtr allocBig; - -- CLzma2EncInt coders[MTCODER__THREADS_MAX]; -+ CLzma2EncInt coders[MTCODER_THREADS_MAX]; - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - -- ISeqOutStream *outStream; -+ ISeqOutStreamPtr outStream; - Byte *outBuf; - size_t outBuf_Rem; /* remainder in outBuf */ - - size_t outBufSize; /* size of allocated outBufs[i] */ -- size_t outBufsDataSizes[MTCODER__BLOCKS_MAX]; -+ size_t outBufsDataSizes[MTCODER_BLOCKS_MAX]; - BoolInt mtCoder_WasConstructed; - CMtCoder mtCoder; -- Byte *outBufs[MTCODER__BLOCKS_MAX]; -+ Byte *outBufs[MTCODER_BLOCKS_MAX]; - - #endif -- --} CLzma2Enc; -+}; - - - -@@ -396,30 +395,30 @@ CLzma2EncHandle Lzma2Enc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig) - p->allocBig = allocBig; - { - unsigned i; -- for (i = 0; i < MTCODER__THREADS_MAX; i++) -+ for (i = 0; i < MTCODER_THREADS_MAX; i++) - p->coders[i].enc = NULL; - } - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - p->mtCoder_WasConstructed = False7z; - { - unsigned i; -- for (i = 0; i < MTCODER__BLOCKS_MAX; i++) -+ for (i = 0; i < MTCODER_BLOCKS_MAX; i++) - p->outBufs[i] = NULL; - p->outBufSize = 0; - } - #endif - -- return p; -+ return (CLzma2EncHandle)p; - } - - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - - static void Lzma2Enc_FreeOutBufs(CLzma2Enc *p) - { - unsigned i; -- for (i = 0; i < MTCODER__BLOCKS_MAX; i++) -+ for (i = 0; i < MTCODER_BLOCKS_MAX; i++) - if (p->outBufs[i]) - { - ISzAlloc_Free(p->alloc, p->outBufs[i]); -@@ -430,12 +429,13 @@ static void Lzma2Enc_FreeOutBufs(CLzma2Enc *p) - - #endif - -+// #define GET_CLzma2Enc_p CLzma2Enc *p = (CLzma2Enc *)(void *)p; - --void Lzma2Enc_Destroy(CLzma2EncHandle pp) -+void Lzma2Enc_Destroy(CLzma2EncHandle p) - { -- CLzma2Enc *p = (CLzma2Enc *)pp; -+ // GET_CLzma2Enc_p - unsigned i; -- for (i = 0; i < MTCODER__THREADS_MAX; i++) -+ for (i = 0; i < MTCODER_THREADS_MAX; i++) - { - CLzma2EncInt *t = &p->coders[i]; - if (t->enc) -@@ -446,7 +446,7 @@ void Lzma2Enc_Destroy(CLzma2EncHandle pp) - } - - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - if (p->mtCoder_WasConstructed) - { - MtCoder_Destruct(&p->mtCoder); -@@ -458,13 +458,13 @@ void Lzma2Enc_Destroy(CLzma2EncHandle pp) - ISzAlloc_Free(p->alloc, p->tempBufLzma); - p->tempBufLzma = NULL; - -- ISzAlloc_Free(p->alloc, pp); -+ ISzAlloc_Free(p->alloc, p); - } - - --SRes Lzma2Enc_SetProps(CLzma2EncHandle pp, const CLzma2EncProps *props) -+SRes Lzma2Enc_SetProps(CLzma2EncHandle p, const CLzma2EncProps *props) - { -- CLzma2Enc *p = (CLzma2Enc *)pp; -+ // GET_CLzma2Enc_p - CLzmaEncProps lzmaProps = props->lzmaProps; - LzmaEncProps_Normalize(&lzmaProps); - if (lzmaProps.lc + lzmaProps.lp > LZMA2_LCLP_MAX) -@@ -475,16 +475,16 @@ SRes Lzma2Enc_SetProps(CLzma2EncHandle pp, const CLzma2EncProps *props) - } - - --void Lzma2Enc_SetDataSize(CLzmaEncHandle pp, UInt64 expectedDataSiize) -+void Lzma2Enc_SetDataSize(CLzma2EncHandle p, UInt64 expectedDataSiize) - { -- CLzma2Enc *p = (CLzma2Enc *)pp; -+ // GET_CLzma2Enc_p - p->expectedDataSize = expectedDataSiize; - } - - --Byte Lzma2Enc_WriteProperties(CLzma2EncHandle pp) -+Byte Lzma2Enc_WriteProperties(CLzma2EncHandle p) - { -- CLzma2Enc *p = (CLzma2Enc *)pp; -+ // GET_CLzma2Enc_p - unsigned i; - UInt32 dicSize = LzmaEncProps_GetDictSize(&p->props.lzmaProps); - for (i = 0; i < 40; i++) -@@ -497,12 +497,12 @@ Byte Lzma2Enc_WriteProperties(CLzma2EncHandle pp) - static SRes Lzma2Enc_EncodeMt1( - CLzma2Enc *me, - CLzma2EncInt *p, -- ISeqOutStream *outStream, -+ ISeqOutStreamPtr outStream, - Byte *outBuf, size_t *outBufSize, -- ISeqInStream *inStream, -+ ISeqInStreamPtr inStream, - const Byte *inData, size_t inDataSize, - int finished, -- ICompressProgress *progress) -+ ICompressProgressPtr progress) - { - UInt64 unpackTotal = 0; - UInt64 packTotal = 0; -@@ -540,12 +540,12 @@ static SRes Lzma2Enc_EncodeMt1( - } - } - -- RINOK(Lzma2EncInt_InitStream(p, &me->props)); -+ RINOK(Lzma2EncInt_InitStream(p, &me->props)) - - for (;;) - { - SRes res = SZ_OK; -- size_t inSizeCur = 0; -+ SizeT inSizeCur = 0; - - Lzma2EncInt_InitBlock(p); - -@@ -559,7 +559,7 @@ static SRes Lzma2Enc_EncodeMt1( - if (me->expectedDataSize != (UInt64)(Int64)-1 - && me->expectedDataSize >= unpackTotal) - expected = me->expectedDataSize - unpackTotal; -- if (me->props.blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID -+ if (me->props.blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID - && expected > me->props.blockSize) - expected = (size_t)me->props.blockSize; - -@@ -569,14 +569,14 @@ static SRes Lzma2Enc_EncodeMt1( - &limitedInStream.vt, - LZMA2_KEEP_WINDOW_SIZE, - me->alloc, -- me->allocBig)); -+ me->allocBig)) - } - else - { -- inSizeCur = inDataSize - (size_t)unpackTotal; -- if (me->props.blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID -+ inSizeCur = (SizeT)(inDataSize - (size_t)unpackTotal); -+ if (me->props.blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID - && inSizeCur > me->props.blockSize) -- inSizeCur = (size_t)me->props.blockSize; -+ inSizeCur = (SizeT)(size_t)me->props.blockSize; - - // LzmaEnc_SetDataSize(p->enc, inSizeCur); - -@@ -584,7 +584,7 @@ static SRes Lzma2Enc_EncodeMt1( - inData + (size_t)unpackTotal, inSizeCur, - LZMA2_KEEP_WINDOW_SIZE, - me->alloc, -- me->allocBig)); -+ me->allocBig)) - } - - for (;;) -@@ -621,7 +621,7 @@ static SRes Lzma2Enc_EncodeMt1( - - unpackTotal += p->srcPos; - -- RINOK(res); -+ RINOK(res) - - if (p->srcPos != (inStream ? limitedInStream.processed : inSizeCur)) - return SZ_ERROR_FAIL; -@@ -652,12 +652,12 @@ static SRes Lzma2Enc_EncodeMt1( - - - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - --static SRes Lzma2Enc_MtCallback_Code(void *pp, unsigned coderIndex, unsigned outBufIndex, -+static SRes Lzma2Enc_MtCallback_Code(void *p, unsigned coderIndex, unsigned outBufIndex, - const Byte *src, size_t srcSize, int finished) - { -- CLzma2Enc *me = (CLzma2Enc *)pp; -+ CLzma2Enc *me = (CLzma2Enc *)p; - size_t destSize = me->outBufSize; - SRes res; - CMtProgressThunk progressThunk; -@@ -692,9 +692,9 @@ static SRes Lzma2Enc_MtCallback_Code(void *pp, unsigned coderIndex, unsigned out - } - - --static SRes Lzma2Enc_MtCallback_Write(void *pp, unsigned outBufIndex) -+static SRes Lzma2Enc_MtCallback_Write(void *p, unsigned outBufIndex) - { -- CLzma2Enc *me = (CLzma2Enc *)pp; -+ CLzma2Enc *me = (CLzma2Enc *)p; - size_t size = me->outBufsDataSizes[outBufIndex]; - const Byte *data = me->outBufs[outBufIndex]; - -@@ -713,14 +713,14 @@ static SRes Lzma2Enc_MtCallback_Write(void *pp, unsigned outBufIndex) - - - --SRes Lzma2Enc_Encode2(CLzma2EncHandle pp, -- ISeqOutStream *outStream, -+SRes Lzma2Enc_Encode2(CLzma2EncHandle p, -+ ISeqOutStreamPtr outStream, - Byte *outBuf, size_t *outBufSize, -- ISeqInStream *inStream, -+ ISeqInStreamPtr inStream, - const Byte *inData, size_t inDataSize, -- ICompressProgress *progress) -+ ICompressProgressPtr progress) - { -- CLzma2Enc *p = (CLzma2Enc *)pp; -+ // GET_CLzma2Enc_p - - if (inStream && inData) - return SZ_ERROR_PARAM; -@@ -730,11 +730,11 @@ SRes Lzma2Enc_Encode2(CLzma2EncHandle pp, - - { - unsigned i; -- for (i = 0; i < MTCODER__THREADS_MAX; i++) -+ for (i = 0; i < MTCODER_THREADS_MAX; i++) - p->coders[i].propsAreSet = False7z; - } - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - - if (p->props.numBlockThreads_Reduced > 1) - { -@@ -772,7 +772,7 @@ SRes Lzma2Enc_Encode2(CLzma2EncHandle pp, - return SZ_ERROR_PARAM; /* SZ_ERROR_MEM */ - - { -- size_t destBlockSize = p->mtCoder.blockSize + (p->mtCoder.blockSize >> 10) + 16; -+ const size_t destBlockSize = p->mtCoder.blockSize + (p->mtCoder.blockSize >> 10) + 16; - if (destBlockSize < p->mtCoder.blockSize) - return SZ_ERROR_PARAM; - if (p->outBufSize != destBlockSize) -@@ -784,7 +784,7 @@ SRes Lzma2Enc_Encode2(CLzma2EncHandle pp, - p->mtCoder.expectedDataSize = p->expectedDataSize; - - { -- SRes res = MtCoder_Code(&p->mtCoder); -+ const SRes res = MtCoder_Code(&p->mtCoder); - if (!outStream) - *outBufSize = (size_t)(p->outBuf - outBuf); - return res; -@@ -801,3 +801,5 @@ SRes Lzma2Enc_Encode2(CLzma2EncHandle pp, - True7z, /* finished */ - progress); - } -+ -+#undef PRF -diff --git a/src/lzma/Lzma2Enc.h b/src/lzma/Lzma2Enc.h -index 6a6110ff7..cb25275c6 100644 ---- a/src/lzma/Lzma2Enc.h -+++ b/src/lzma/Lzma2Enc.h -@@ -1,15 +1,15 @@ - /* Lzma2Enc.h -- LZMA2 Encoder --2017-07-27 : Igor Pavlov : Public domain */ -+2023-04-13 : Igor Pavlov : Public domain */ - --#ifndef __LZMA2_ENC_H --#define __LZMA2_ENC_H -+#ifndef ZIP7_INC_LZMA2_ENC_H -+#define ZIP7_INC_LZMA2_ENC_H - - #include "LzmaEnc.h" - - EXTERN_C_BEGIN - --#define LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO 0 --#define LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID ((UInt64)(Int64)-1) -+#define LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO 0 -+#define LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID ((UInt64)(Int64)-1) - - typedef struct - { -@@ -36,7 +36,9 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p); - SZ_ERROR_THREAD - error in multithreading functions (only for Mt version) - */ - --typedef void * CLzma2EncHandle; -+typedef struct CLzma2Enc CLzma2Enc; -+typedef CLzma2Enc * CLzma2EncHandle; -+// Z7_DECLARE_HANDLE(CLzma2EncHandle) - - CLzma2EncHandle Lzma2Enc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig); - void Lzma2Enc_Destroy(CLzma2EncHandle p); -@@ -44,11 +46,11 @@ SRes Lzma2Enc_SetProps(CLzma2EncHandle p, const CLzma2EncProps *props); - void Lzma2Enc_SetDataSize(CLzma2EncHandle p, UInt64 expectedDataSiize); - Byte Lzma2Enc_WriteProperties(CLzma2EncHandle p); - SRes Lzma2Enc_Encode2(CLzma2EncHandle p, -- ISeqOutStream *outStream, -+ ISeqOutStreamPtr outStream, - Byte *outBuf, size_t *outBufSize, -- ISeqInStream *inStream, -+ ISeqInStreamPtr inStream, - const Byte *inData, size_t inDataSize, -- ICompressProgress *progress); -+ ICompressProgressPtr progress); - - EXTERN_C_END - -diff --git a/src/lzma/Lzma86.h b/src/lzma/Lzma86.h -index bebed5cb7..e7707e2c4 100644 ---- a/src/lzma/Lzma86.h -+++ b/src/lzma/Lzma86.h -@@ -1,8 +1,8 @@ - /* Lzma86.h -- LZMA + x86 (BCJ) Filter --2013-01-18 : Igor Pavlov : Public domain */ -+2023-03-03 : Igor Pavlov : Public domain */ - --#ifndef __LZMA86_H --#define __LZMA86_H -+#ifndef ZIP7_INC_LZMA86_H -+#define ZIP7_INC_LZMA86_H - - #include "7zTypes.h" - -diff --git a/src/lzma/Lzma86Dec.c b/src/lzma/Lzma86Dec.c -index 21031745c..f094d4c35 100644 ---- a/src/lzma/Lzma86Dec.c -+++ b/src/lzma/Lzma86Dec.c -@@ -1,5 +1,5 @@ - /* Lzma86Dec.c -- LZMA + x86 (BCJ) Filter Decoder --2016-05-16 : Igor Pavlov : Public domain */ -+2023-03-03 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -46,9 +46,8 @@ SRes Lzma86_Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen) - return res; - if (useFilter == 1) - { -- UInt32 x86State; -- x86_Convert_Init(x86State); -- x86_Convert(dest, *destLen, 0, &x86State, 0); -+ UInt32 x86State = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL; -+ z7_BranchConvSt_X86_Dec(dest, *destLen, 0, &x86State); - } - return SZ_OK; - } -diff --git a/src/lzma/Lzma86Enc.c b/src/lzma/Lzma86Enc.c -index 2aed6758f..e87e2c7ce 100644 ---- a/src/lzma/Lzma86Enc.c -+++ b/src/lzma/Lzma86Enc.c -@@ -1,5 +1,5 @@ - /* Lzma86Enc.c -- LZMA + x86 (BCJ) Filter Encoder --2018-07-04 : Igor Pavlov : Public domain */ -+2023-03-03 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -46,9 +46,8 @@ int Lzma86_Encode(Byte *dest, size_t *destLen, const Byte *src, size_t srcLen, - memcpy(filteredStream, src, srcLen); - } - { -- UInt32 x86State; -- x86_Convert_Init(x86State); -- x86_Convert(filteredStream, srcLen, 0, &x86State, 1); -+ UInt32 x86State = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL; -+ z7_BranchConvSt_X86_Enc(filteredStream, srcLen, 0, &x86State); - } - } - -diff --git a/src/lzma/LzmaDec.c b/src/lzma/LzmaDec.c -index 536fc6ed3..535c60c08 100644 ---- a/src/lzma/LzmaDec.c -+++ b/src/lzma/LzmaDec.c -@@ -1,5 +1,5 @@ - /* LzmaDec.c -- LZMA Decoder --2021-04-01 : Igor Pavlov : Public domain */ -+2023-04-07 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -8,15 +8,15 @@ - /* #include "CpuArch.h" */ - #include "LzmaDec.h" - --#define kNumTopBits 24 --#define kTopValue ((UInt32)1 << kNumTopBits) -+// #define kNumTopBits 24 -+#define kTopValue ((UInt32)1 << 24) - - #define kNumBitModelTotalBits 11 - #define kBitModelTotal (1 << kNumBitModelTotalBits) - - #define RC_INIT_SIZE 5 - --#ifndef _LZMA_DEC_OPT -+#ifndef Z7_LZMA_DEC_OPT - - #define kNumMoveBits 5 - #define NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | (*buf++); } -@@ -25,14 +25,14 @@ - #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; } -+ { UPDATE_0(p) i = (i + i); A0; } else \ -+ { UPDATE_1(p) i = (i + i) + 1; A1; } - - #define TREE_GET_BIT(probs, i) { GET_BIT2(probs + i, i, ;, ;); } - - #define REV_BIT(p, i, A0, A1) IF_BIT_0(p + i) \ -- { UPDATE_0(p + i); A0; } else \ -- { UPDATE_1(p + i); A1; } -+ { UPDATE_0(p + i) A0; } else \ -+ { UPDATE_1(p + i) A1; } - #define REV_BIT_VAR( p, i, m) REV_BIT(p, i, i += m; m += m, m += m; i += m; ) - #define REV_BIT_CONST(p, i, m) REV_BIT(p, i, i += m; , i += m * 2; ) - #define REV_BIT_LAST( p, i, m) REV_BIT(p, i, i -= m , ; ) -@@ -40,19 +40,19 @@ - #define TREE_DECODE(probs, limit, i) \ - { i = 1; do { TREE_GET_BIT(probs, i); } while (i < limit); i -= limit; } - --/* #define _LZMA_SIZE_OPT */ -+/* #define Z7_LZMA_SIZE_OPT */ - --#ifdef _LZMA_SIZE_OPT -+#ifdef Z7_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); \ -+ 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 - -@@ -64,25 +64,25 @@ - probLit = prob + (offs + bit + symbol); \ - GET_BIT2(probLit, symbol, offs ^= bit; , ;) - --#endif // _LZMA_DEC_OPT -+#endif // Z7_LZMA_DEC_OPT - - - #define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_INPUT_EOF; range <<= 8; code = (code << 8) | (*buf++); } - --#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK; bound = (range >> kNumBitModelTotalBits) * (UInt32)ttt; if (code < bound) -+#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK bound = (range >> kNumBitModelTotalBits) * (UInt32)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; } -+ { 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 REV_BIT_CHECK(p, i, m) IF_BIT_0_CHECK(p + i) \ -- { UPDATE_0_CHECK; i += m; m += m; } else \ -- { UPDATE_1_CHECK; m += m; i += m; } -+ { UPDATE_0_CHECK i += m; m += m; } else \ -+ { UPDATE_1_CHECK m += m; i += m; } - - - #define kNumPosBitsMax 4 -@@ -224,14 +224,14 @@ LZMA_DECODE_REAL() - */ - - --#ifdef _LZMA_DEC_OPT -+#ifdef Z7_LZMA_DEC_OPT - --int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit); -+int Z7_FASTCALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit); - - #else - - static --int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit) -+int Z7_FASTCALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit) - { - CLzmaProb *probs = GET_PROBS; - unsigned state = (unsigned)p->state; -@@ -263,7 +263,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit - IF_BIT_0(prob) - { - unsigned symbol; -- UPDATE_0(prob); -+ UPDATE_0(prob) - prob = probs + Literal; - if (processedPos != 0 || checkDicSize != 0) - prob += (UInt32)3 * ((((processedPos << 8) + dic[(dicPos == 0 ? dicBufSize : dicPos) - 1]) & lpMask) << lc); -@@ -273,7 +273,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit - { - state -= (state < 4) ? state : 3; - symbol = 1; -- #ifdef _LZMA_SIZE_OPT -+ #ifdef Z7_LZMA_SIZE_OPT - do { NORMAL_LITER_DEC } while (symbol < 0x100); - #else - NORMAL_LITER_DEC -@@ -292,7 +292,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit - unsigned offs = 0x100; - state -= (state < 10) ? 3 : 6; - symbol = 1; -- #ifdef _LZMA_SIZE_OPT -+ #ifdef Z7_LZMA_SIZE_OPT - do - { - unsigned bit; -@@ -321,25 +321,25 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit - } - - { -- UPDATE_1(prob); -+ UPDATE_1(prob) - prob = probs + IsRep + state; - IF_BIT_0(prob) - { -- UPDATE_0(prob); -+ UPDATE_0(prob) - state += kNumStates; - prob = probs + LenCoder; - } - else - { -- UPDATE_1(prob); -+ UPDATE_1(prob) - prob = probs + IsRepG0 + state; - IF_BIT_0(prob) - { -- UPDATE_0(prob); -+ UPDATE_0(prob) - prob = probs + IsRep0Long + COMBINED_PS_STATE; - IF_BIT_0(prob) - { -- UPDATE_0(prob); -+ UPDATE_0(prob) - - // that case was checked before with kBadRepCode - // if (checkDicSize == 0 && processedPos == 0) { len = kMatchSpecLen_Error_Data + 1; break; } -@@ -353,30 +353,30 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit - state = state < kNumLitStates ? 9 : 11; - continue; - } -- UPDATE_1(prob); -+ UPDATE_1(prob) - } - else - { - UInt32 distance; -- UPDATE_1(prob); -+ UPDATE_1(prob) - prob = probs + IsRepG1 + state; - IF_BIT_0(prob) - { -- UPDATE_0(prob); -+ UPDATE_0(prob) - distance = rep1; - } - else - { -- UPDATE_1(prob); -+ UPDATE_1(prob) - prob = probs + IsRepG2 + state; - IF_BIT_0(prob) - { -- UPDATE_0(prob); -+ UPDATE_0(prob) - distance = rep2; - } - else - { -- UPDATE_1(prob); -+ UPDATE_1(prob) - distance = rep3; - rep3 = rep2; - } -@@ -389,37 +389,37 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit - prob = probs + RepLenCoder; - } - -- #ifdef _LZMA_SIZE_OPT -+ #ifdef Z7_LZMA_SIZE_OPT - { - unsigned lim, offset; - CLzmaProb *probLen = prob + LenChoice; - IF_BIT_0(probLen) - { -- UPDATE_0(probLen); -+ UPDATE_0(probLen) - probLen = prob + LenLow + GET_LEN_STATE; - offset = 0; - lim = (1 << kLenNumLowBits); - } - else - { -- UPDATE_1(probLen); -+ UPDATE_1(probLen) - probLen = prob + LenChoice2; - IF_BIT_0(probLen) - { -- UPDATE_0(probLen); -+ UPDATE_0(probLen) - probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); - offset = kLenNumLowSymbols; - lim = (1 << kLenNumLowBits); - } - else - { -- UPDATE_1(probLen); -+ UPDATE_1(probLen) - probLen = prob + LenHigh; - offset = kLenNumLowSymbols * 2; - lim = (1 << kLenNumHighBits); - } - } -- TREE_DECODE(probLen, lim, len); -+ TREE_DECODE(probLen, lim, len) - len += offset; - } - #else -@@ -427,32 +427,32 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit - CLzmaProb *probLen = prob + LenChoice; - IF_BIT_0(probLen) - { -- UPDATE_0(probLen); -+ UPDATE_0(probLen) - probLen = prob + LenLow + GET_LEN_STATE; - len = 1; -- TREE_GET_BIT(probLen, len); -- TREE_GET_BIT(probLen, len); -- TREE_GET_BIT(probLen, len); -+ TREE_GET_BIT(probLen, len) -+ TREE_GET_BIT(probLen, len) -+ TREE_GET_BIT(probLen, len) - len -= 8; - } - else - { -- UPDATE_1(probLen); -+ UPDATE_1(probLen) - probLen = prob + LenChoice2; - IF_BIT_0(probLen) - { -- UPDATE_0(probLen); -+ UPDATE_0(probLen) - probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); - len = 1; -- TREE_GET_BIT(probLen, len); -- TREE_GET_BIT(probLen, len); -- TREE_GET_BIT(probLen, len); -+ TREE_GET_BIT(probLen, len) -+ TREE_GET_BIT(probLen, len) -+ TREE_GET_BIT(probLen, len) - } - else - { -- UPDATE_1(probLen); -+ UPDATE_1(probLen) - probLen = prob + LenHigh; -- TREE_DECODE(probLen, (1 << kLenNumHighBits), len); -+ TREE_DECODE(probLen, (1 << kLenNumHighBits), len) - len += kLenNumLowSymbols * 2; - } - } -@@ -464,7 +464,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit - UInt32 distance; - prob = probs + PosSlot + - ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits); -- TREE_6_DECODE(prob, distance); -+ TREE_6_DECODE(prob, distance) - if (distance >= kStartPosModelIndex) - { - unsigned posSlot = (unsigned)distance; -@@ -479,7 +479,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit - distance++; - do - { -- REV_BIT_VAR(prob, distance, m); -+ REV_BIT_VAR(prob, distance, m) - } - while (--numDirectBits); - distance -= m; -@@ -514,10 +514,10 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit - distance <<= kNumAlignBits; - { - unsigned i = 1; -- REV_BIT_CONST(prob, i, 1); -- REV_BIT_CONST(prob, i, 2); -- REV_BIT_CONST(prob, i, 4); -- REV_BIT_LAST (prob, i, 8); -+ REV_BIT_CONST(prob, i, 1) -+ REV_BIT_CONST(prob, i, 2) -+ REV_BIT_CONST(prob, i, 4) -+ REV_BIT_LAST (prob, i, 8) - distance |= i; - } - if (distance == (UInt32)0xFFFFFFFF) -@@ -592,7 +592,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit - } - while (dicPos < limit && buf < bufLimit); - -- NORMALIZE; -+ NORMALIZE - - p->buf = buf; - p->range = range; -@@ -613,7 +613,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit - - - --static void MY_FAST_CALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit) -+static void Z7_FASTCALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit) - { - unsigned len = (unsigned)p->remainLen; - if (len == 0 /* || len >= kMatchSpecLenStart */) -@@ -683,7 +683,7 @@ and we support the following state of (p->checkDicSize): - (p->checkDicSize == p->prop.dicSize) - */ - --static int MY_FAST_CALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit) -+static int Z7_FASTCALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit) - { - if (p->checkDicSize == 0) - { -@@ -767,54 +767,54 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt - else - { - unsigned len; -- UPDATE_1_CHECK; -+ UPDATE_1_CHECK - - prob = probs + IsRep + state; - IF_BIT_0_CHECK(prob) - { -- UPDATE_0_CHECK; -+ UPDATE_0_CHECK - state = 0; - prob = probs + LenCoder; - res = DUMMY_MATCH; - } - else - { -- UPDATE_1_CHECK; -+ UPDATE_1_CHECK - res = DUMMY_REP; - prob = probs + IsRepG0 + state; - IF_BIT_0_CHECK(prob) - { -- UPDATE_0_CHECK; -+ UPDATE_0_CHECK - prob = probs + IsRep0Long + COMBINED_PS_STATE; - IF_BIT_0_CHECK(prob) - { -- UPDATE_0_CHECK; -+ UPDATE_0_CHECK - break; - } - else - { -- UPDATE_1_CHECK; -+ UPDATE_1_CHECK - } - } - else - { -- UPDATE_1_CHECK; -+ UPDATE_1_CHECK - prob = probs + IsRepG1 + state; - IF_BIT_0_CHECK(prob) - { -- UPDATE_0_CHECK; -+ UPDATE_0_CHECK - } - else - { -- UPDATE_1_CHECK; -+ UPDATE_1_CHECK - prob = probs + IsRepG2 + state; - IF_BIT_0_CHECK(prob) - { -- UPDATE_0_CHECK; -+ UPDATE_0_CHECK - } - else - { -- UPDATE_1_CHECK; -+ UPDATE_1_CHECK - } - } - } -@@ -826,31 +826,31 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt - const CLzmaProb *probLen = prob + LenChoice; - IF_BIT_0_CHECK(probLen) - { -- UPDATE_0_CHECK; -+ UPDATE_0_CHECK - probLen = prob + LenLow + GET_LEN_STATE; - offset = 0; - limit = 1 << kLenNumLowBits; - } - else - { -- UPDATE_1_CHECK; -+ UPDATE_1_CHECK - probLen = prob + LenChoice2; - IF_BIT_0_CHECK(probLen) - { -- UPDATE_0_CHECK; -+ UPDATE_0_CHECK - probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); - offset = kLenNumLowSymbols; - limit = 1 << kLenNumLowBits; - } - else - { -- UPDATE_1_CHECK; -+ UPDATE_1_CHECK - probLen = prob + LenHigh; - offset = kLenNumLowSymbols * 2; - limit = 1 << kLenNumHighBits; - } - } -- TREE_DECODE_CHECK(probLen, limit, len); -+ TREE_DECODE_CHECK(probLen, limit, len) - len += offset; - } - -@@ -860,7 +860,7 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt - prob = probs + PosSlot + - ((len < kNumLenToPosStates - 1 ? len : kNumLenToPosStates - 1) << - kNumPosSlotBits); -- TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot); -+ TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot) - if (posSlot >= kStartPosModelIndex) - { - unsigned numDirectBits = ((posSlot >> 1) - 1); -@@ -888,7 +888,7 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt - unsigned m = 1; - do - { -- REV_BIT_CHECK(prob, i, m); -+ REV_BIT_CHECK(prob, i, m) - } - while (--numDirectBits); - } -@@ -897,7 +897,7 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt - } - break; - } -- NORMALIZE_CHECK; -+ NORMALIZE_CHECK - - *bufOut = buf; - return res; -@@ -943,7 +943,7 @@ When the decoder lookahead, and the lookahead symbol is not end_marker, we have - */ - - --#define RETURN__NOT_FINISHED__FOR_FINISH \ -+#define RETURN_NOT_FINISHED_FOR_FINISH \ - *status = LZMA_STATUS_NOT_FINISHED; \ - return SZ_ERROR_DATA; // for strict mode - // return SZ_OK; // for relaxed mode -@@ -1029,7 +1029,7 @@ SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *sr - } - if (p->remainLen != 0) - { -- RETURN__NOT_FINISHED__FOR_FINISH; -+ RETURN_NOT_FINISHED_FOR_FINISH - } - checkEndMarkNow = 1; - } -@@ -1072,7 +1072,7 @@ SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *sr - for (i = 0; i < (unsigned)dummyProcessed; i++) - p->tempBuf[i] = src[i]; - // p->remainLen = kMatchSpecLen_Error_Data; -- RETURN__NOT_FINISHED__FOR_FINISH; -+ RETURN_NOT_FINISHED_FOR_FINISH - } - - bufLimit = src; -@@ -1150,7 +1150,7 @@ SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *sr - (*srcLen) += (unsigned)dummyProcessed - p->tempBufSize; - p->tempBufSize = (unsigned)dummyProcessed; - // p->remainLen = kMatchSpecLen_Error_Data; -- RETURN__NOT_FINISHED__FOR_FINISH; -+ RETURN_NOT_FINISHED_FOR_FINISH - } - } - -@@ -1299,8 +1299,8 @@ static SRes LzmaDec_AllocateProbs2(CLzmaDec *p, const CLzmaProps *propNew, ISzAl - SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc) - { - CLzmaProps propNew; -- RINOK(LzmaProps_Decode(&propNew, props, propsSize)); -- RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)); -+ RINOK(LzmaProps_Decode(&propNew, props, propsSize)) -+ RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)) - p->prop = propNew; - return SZ_OK; - } -@@ -1309,14 +1309,14 @@ SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAll - { - CLzmaProps propNew; - SizeT dicBufSize; -- RINOK(LzmaProps_Decode(&propNew, props, propsSize)); -- RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)); -+ RINOK(LzmaProps_Decode(&propNew, props, propsSize)) -+ RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)) - - { - UInt32 dictSize = propNew.dicSize; - SizeT mask = ((UInt32)1 << 12) - 1; - if (dictSize >= ((UInt32)1 << 30)) mask = ((UInt32)1 << 22) - 1; -- else if (dictSize >= ((UInt32)1 << 22)) mask = ((UInt32)1 << 20) - 1;; -+ else if (dictSize >= ((UInt32)1 << 22)) mask = ((UInt32)1 << 20) - 1; - dicBufSize = ((SizeT)dictSize + mask) & ~mask; - if (dicBufSize < dictSize) - dicBufSize = dictSize; -@@ -1348,8 +1348,8 @@ SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, - *status = LZMA_STATUS_NOT_SPECIFIED; - if (inSize < RC_INIT_SIZE) - return SZ_ERROR_INPUT_EOF; -- LzmaDec_Construct(&p); -- RINOK(LzmaDec_AllocateProbs(&p, propData, propSize, alloc)); -+ LzmaDec_CONSTRUCT(&p) -+ RINOK(LzmaDec_AllocateProbs(&p, propData, propSize, alloc)) - p.dic = dest; - p.dicBufSize = outSize; - LzmaDec_Init(&p); -diff --git a/src/lzma/LzmaDec.h b/src/lzma/LzmaDec.h -index 6f1296250..b0ce28fa0 100644 ---- a/src/lzma/LzmaDec.h -+++ b/src/lzma/LzmaDec.h -@@ -1,19 +1,19 @@ - /* LzmaDec.h -- LZMA Decoder --2020-03-19 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - --#ifndef __LZMA_DEC_H --#define __LZMA_DEC_H -+#ifndef ZIP7_INC_LZMA_DEC_H -+#define ZIP7_INC_LZMA_DEC_H - - #include "7zTypes.h" - - EXTERN_C_BEGIN - --/* #define _LZMA_PROB32 */ --/* _LZMA_PROB32 can increase the speed on some CPUs, -+/* #define Z7_LZMA_PROB32 */ -+/* Z7_LZMA_PROB32 can increase the speed on some CPUs, - but memory usage for CLzmaDec::probs will be doubled in that case */ - - typedef --#ifdef _LZMA_PROB32 -+#ifdef Z7_LZMA_PROB32 - UInt32 - #else - UInt16 -@@ -25,7 +25,7 @@ typedef - - #define LZMA_PROPS_SIZE 5 - --typedef struct _CLzmaProps -+typedef struct - { - Byte lc; - Byte lp; -@@ -73,7 +73,8 @@ typedef struct - Byte tempBuf[LZMA_REQUIRED_INPUT_MAX]; - } CLzmaDec; - --#define LzmaDec_Construct(p) { (p)->dic = NULL; (p)->probs = NULL; } -+#define LzmaDec_CONSTRUCT(p) { (p)->dic = NULL; (p)->probs = NULL; } -+#define LzmaDec_Construct(p) LzmaDec_CONSTRUCT(p) - - void LzmaDec_Init(CLzmaDec *p); - -diff --git a/src/lzma/LzmaEnc.c b/src/lzma/LzmaEnc.c -index 2fa3456b7..664397349 100644 ---- a/src/lzma/LzmaEnc.c -+++ b/src/lzma/LzmaEnc.c -@@ -1,5 +1,5 @@ - /* LzmaEnc.c -- LZMA Encoder --2021-11-18: Igor Pavlov : Public domain */ -+2023-04-13: Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -16,22 +16,22 @@ - #include "LzmaEnc.h" - - #include "LzFind.h" --#ifndef _7ZIP_ST -+#ifndef Z7_ST - #include "LzFindMt.h" - #endif - - /* the following LzmaEnc_* declarations is internal LZMA interface for LZMA2 encoder */ - --SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp, ISeqInStream *inStream, UInt32 keepWindowSize, -+SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle p, ISeqInStreamPtr inStream, UInt32 keepWindowSize, - ISzAllocPtr alloc, ISzAllocPtr allocBig); --SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen, -+SRes LzmaEnc_MemPrepare(CLzmaEncHandle p, const Byte *src, SizeT srcLen, - UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig); --SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit, -+SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle p, BoolInt reInit, - Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize); --const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp); --void LzmaEnc_Finish(CLzmaEncHandle pp); --void LzmaEnc_SaveState(CLzmaEncHandle pp); --void LzmaEnc_RestoreState(CLzmaEncHandle pp); -+const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle p); -+void LzmaEnc_Finish(CLzmaEncHandle p); -+void LzmaEnc_SaveState(CLzmaEncHandle p); -+void LzmaEnc_RestoreState(CLzmaEncHandle p); - - #ifdef SHOW_STAT - static unsigned g_STAT_OFFSET = 0; -@@ -40,8 +40,8 @@ static unsigned g_STAT_OFFSET = 0; - /* for good normalization speed we still reserve 256 MB before 4 GB range */ - #define kLzmaMaxHistorySize ((UInt32)15 << 28) - --#define kNumTopBits 24 --#define kTopValue ((UInt32)1 << kNumTopBits) -+// #define kNumTopBits 24 -+#define kTopValue ((UInt32)1 << 24) - - #define kNumBitModelTotalBits 11 - #define kBitModelTotal (1 << kNumBitModelTotalBits) -@@ -60,6 +60,7 @@ void LzmaEncProps_Init(CLzmaEncProps *p) - p->dictSize = p->mc = 0; - p->reduceSize = (UInt64)(Int64)-1; - p->lc = p->lp = p->pb = p->algo = p->fb = p->btMode = p->numHashBytes = p->numThreads = -1; -+ p->numHashOutBits = 0; - p->writeEndMark = 0; - p->affinity = 0; - } -@@ -99,7 +100,7 @@ void LzmaEncProps_Normalize(CLzmaEncProps *p) - - if (p->numThreads < 0) - p->numThreads = -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - ((p->btMode && p->algo) ? 2 : 1); - #else - 1; -@@ -293,7 +294,7 @@ typedef struct - #define kNumFullDistances (1 << (kEndPosModelIndex >> 1)) - - typedef --#ifdef _LZMA_PROB32 -+#ifdef Z7_LZMA_PROB32 - UInt32 - #else - UInt16 -@@ -350,7 +351,7 @@ typedef struct - Byte *buf; - Byte *bufLim; - Byte *bufBase; -- ISeqOutStream *outStream; -+ ISeqOutStreamPtr outStream; - UInt64 processed; - SRes res; - } CRangeEnc; -@@ -383,7 +384,7 @@ typedef struct - typedef UInt32 CProbPrice; - - --typedef struct -+struct CLzmaEnc - { - void *matchFinderObj; - IMatchFinder2 matchFinder; -@@ -426,7 +427,7 @@ typedef struct - UInt32 dictSize; - SRes result; - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - BoolInt mtMode; - // begin of CMatchFinderMt is used in LZ thread - CMatchFinderMt matchFinderMt; -@@ -439,7 +440,7 @@ typedef struct - - // we suppose that we have 8-bytes alignment after CMatchFinder - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - Byte pad[128]; - #endif - -@@ -479,77 +480,59 @@ typedef struct - CSaveState saveState; - - // BoolInt mf_Failure; -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - Byte pad2[128]; - #endif --} CLzmaEnc; -+}; - - - #define MFB (p->matchFinderBase) - /* --#ifndef _7ZIP_ST -+#ifndef Z7_ST - #define MFB (p->matchFinderMt.MatchFinder) - #endif - */ - --#define COPY_ARR(dest, src, arr) memcpy(dest->arr, src->arr, sizeof(src->arr)); -- --void LzmaEnc_SaveState(CLzmaEncHandle pp) --{ -- CLzmaEnc *p = (CLzmaEnc *)pp; -- CSaveState *dest = &p->saveState; -- -- dest->state = p->state; -- -- dest->lenProbs = p->lenProbs; -- dest->repLenProbs = p->repLenProbs; -- -- COPY_ARR(dest, p, reps); -- -- COPY_ARR(dest, p, posAlignEncoder); -- COPY_ARR(dest, p, isRep); -- COPY_ARR(dest, p, isRepG0); -- COPY_ARR(dest, p, isRepG1); -- COPY_ARR(dest, p, isRepG2); -- COPY_ARR(dest, p, isMatch); -- COPY_ARR(dest, p, isRep0Long); -- COPY_ARR(dest, p, posSlotEncoder); -- COPY_ARR(dest, p, posEncoders); -- -- memcpy(dest->litProbs, p->litProbs, ((UInt32)0x300 << p->lclp) * sizeof(CLzmaProb)); -+// #define GET_CLzmaEnc_p CLzmaEnc *p = (CLzmaEnc*)(void *)p; -+// #define GET_const_CLzmaEnc_p const CLzmaEnc *p = (const CLzmaEnc*)(const void *)p; -+ -+#define COPY_ARR(dest, src, arr) memcpy((dest)->arr, (src)->arr, sizeof((src)->arr)); -+ -+#define COPY_LZMA_ENC_STATE(d, s, p) \ -+ (d)->state = (s)->state; \ -+ COPY_ARR(d, s, reps) \ -+ COPY_ARR(d, s, posAlignEncoder) \ -+ COPY_ARR(d, s, isRep) \ -+ COPY_ARR(d, s, isRepG0) \ -+ COPY_ARR(d, s, isRepG1) \ -+ COPY_ARR(d, s, isRepG2) \ -+ COPY_ARR(d, s, isMatch) \ -+ COPY_ARR(d, s, isRep0Long) \ -+ COPY_ARR(d, s, posSlotEncoder) \ -+ COPY_ARR(d, s, posEncoders) \ -+ (d)->lenProbs = (s)->lenProbs; \ -+ (d)->repLenProbs = (s)->repLenProbs; \ -+ memcpy((d)->litProbs, (s)->litProbs, ((UInt32)0x300 << (p)->lclp) * sizeof(CLzmaProb)); -+ -+void LzmaEnc_SaveState(CLzmaEncHandle p) -+{ -+ // GET_CLzmaEnc_p -+ CSaveState *v = &p->saveState; -+ COPY_LZMA_ENC_STATE(v, p, p) - } - -- --void LzmaEnc_RestoreState(CLzmaEncHandle pp) -+void LzmaEnc_RestoreState(CLzmaEncHandle p) - { -- CLzmaEnc *dest = (CLzmaEnc *)pp; -- const CSaveState *p = &dest->saveState; -- -- dest->state = p->state; -- -- dest->lenProbs = p->lenProbs; -- dest->repLenProbs = p->repLenProbs; -- -- COPY_ARR(dest, p, reps); -- -- COPY_ARR(dest, p, posAlignEncoder); -- COPY_ARR(dest, p, isRep); -- COPY_ARR(dest, p, isRepG0); -- COPY_ARR(dest, p, isRepG1); -- COPY_ARR(dest, p, isRepG2); -- COPY_ARR(dest, p, isMatch); -- COPY_ARR(dest, p, isRep0Long); -- COPY_ARR(dest, p, posSlotEncoder); -- COPY_ARR(dest, p, posEncoders); -- -- memcpy(dest->litProbs, p->litProbs, ((UInt32)0x300 << dest->lclp) * sizeof(CLzmaProb)); -+ // GET_CLzmaEnc_p -+ const CSaveState *v = &p->saveState; -+ COPY_LZMA_ENC_STATE(p, v, p) - } - - -- --SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) -+Z7_NO_INLINE -+SRes LzmaEnc_SetProps(CLzmaEncHandle p, const CLzmaEncProps *props2) - { -- CLzmaEnc *p = (CLzmaEnc *)pp; -+ // GET_CLzmaEnc_p - CLzmaEncProps props = *props2; - LzmaEncProps_Normalize(&props); - -@@ -585,6 +568,7 @@ SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) - p->fastMode = (props.algo == 0); - // p->_maxMode = True7z; - MFB.btMode = (Byte)(props.btMode ? 1 : 0); -+ // MFB.btMode = (Byte)(props.btMode); - { - unsigned numHashBytes = 4; - if (props.btMode) -@@ -595,13 +579,15 @@ SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) - if (props.numHashBytes >= 5) numHashBytes = 5; - - MFB.numHashBytes = numHashBytes; -+ // MFB.numHashBytes_Min = 2; -+ MFB.numHashOutBits = (Byte)props.numHashOutBits; - } - - MFB.cutValue = props.mc; - - p->writeEndMark = (BoolInt)props.writeEndMark; - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - /* - if (newMultiThread != _multiThread) - { -@@ -618,9 +604,9 @@ SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) - } - - --void LzmaEnc_SetDataSize(CLzmaEncHandle pp, UInt64 expectedDataSiize) -+void LzmaEnc_SetDataSize(CLzmaEncHandle p, UInt64 expectedDataSiize) - { -- CLzmaEnc *p = (CLzmaEnc *)pp; -+ // GET_CLzmaEnc_p - MFB.expectedDataSize = expectedDataSiize; - } - -@@ -684,7 +670,7 @@ static void RangeEnc_Init(CRangeEnc *p) - p->res = SZ_OK; - } - --MY_NO_INLINE static void RangeEnc_FlushStream(CRangeEnc *p) -+Z7_NO_INLINE static void RangeEnc_FlushStream(CRangeEnc *p) - { - const size_t num = (size_t)(p->buf - p->bufBase); - if (p->res == SZ_OK) -@@ -696,7 +682,7 @@ MY_NO_INLINE static void RangeEnc_FlushStream(CRangeEnc *p) - p->buf = p->bufBase; - } - --MY_NO_INLINE static void MY_FAST_CALL RangeEnc_ShiftLow(CRangeEnc *p) -+Z7_NO_INLINE static void Z7_FASTCALL RangeEnc_ShiftLow(CRangeEnc *p) - { - UInt32 low = (UInt32)p->low; - unsigned high = (unsigned)(p->low >> 32); -@@ -741,9 +727,9 @@ static void RangeEnc_FlushData(CRangeEnc *p) - ttt = *(prob); \ - newBound = (range >> kNumBitModelTotalBits) * ttt; - --// #define _LZMA_ENC_USE_BRANCH -+// #define Z7_LZMA_ENC_USE_BRANCH - --#ifdef _LZMA_ENC_USE_BRANCH -+#ifdef Z7_LZMA_ENC_USE_BRANCH - - #define RC_BIT(p, prob, bit) { \ - RC_BIT_PRE(p, prob) \ -@@ -811,7 +797,7 @@ static void LitEnc_Encode(CRangeEnc *p, CLzmaProb *probs, UInt32 sym) - CLzmaProb *prob = probs + (sym >> 8); - UInt32 bit = (sym >> 7) & 1; - sym <<= 1; -- RC_BIT(p, prob, bit); -+ RC_BIT(p, prob, bit) - } - while (sym < 0x10000); - p->range = range; -@@ -833,7 +819,7 @@ static void LitEnc_EncodeMatched(CRangeEnc *p, CLzmaProb *probs, UInt32 sym, UIn - bit = (sym >> 7) & 1; - sym <<= 1; - offs &= ~(matchByte ^ sym); -- RC_BIT(p, prob, bit); -+ RC_BIT(p, prob, bit) - } - while (sym < 0x10000); - p->range = range; -@@ -867,10 +853,10 @@ static void LzmaEnc_InitPriceTables(CProbPrice *ProbPrices) - - - #define GET_PRICE(prob, bit) \ -- p->ProbPrices[((prob) ^ (unsigned)(((-(int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits]; -+ p->ProbPrices[((prob) ^ (unsigned)(((-(int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits] - - #define GET_PRICEa(prob, bit) \ -- ProbPrices[((prob) ^ (unsigned)((-((int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits]; -+ ProbPrices[((prob) ^ (unsigned)((-((int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits] - - #define GET_PRICE_0(prob) p->ProbPrices[(prob) >> kNumMoveReducingBits] - #define GET_PRICE_1(prob) p->ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits] -@@ -921,7 +907,7 @@ static void RcTree_ReverseEncode(CRangeEnc *rc, CLzmaProb *probs, unsigned numBi - unsigned bit = sym & 1; - // RangeEnc_EncodeBit(rc, probs + m, bit); - sym >>= 1; -- RC_BIT(rc, probs + m, bit); -+ RC_BIT(rc, probs + m, bit) - m = (m << 1) | bit; - } - while (--numBits); -@@ -944,15 +930,15 @@ static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, unsigned sym, unsigned posS - UInt32 range, ttt, newBound; - CLzmaProb *probs = p->low; - range = rc->range; -- RC_BIT_PRE(rc, probs); -+ RC_BIT_PRE(rc, probs) - if (sym >= kLenNumLowSymbols) - { -- RC_BIT_1(rc, probs); -+ RC_BIT_1(rc, probs) - probs += kLenNumLowSymbols; -- RC_BIT_PRE(rc, probs); -+ RC_BIT_PRE(rc, probs) - if (sym >= kLenNumLowSymbols * 2) - { -- RC_BIT_1(rc, probs); -+ RC_BIT_1(rc, probs) - rc->range = range; - // RcTree_Encode(rc, p->high, kLenNumHighBits, sym - kLenNumLowSymbols * 2); - LitEnc_Encode(rc, p->high, sym - kLenNumLowSymbols * 2); -@@ -965,11 +951,11 @@ static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, unsigned sym, unsigned posS - { - unsigned m; - unsigned bit; -- RC_BIT_0(rc, probs); -+ RC_BIT_0(rc, probs) - probs += (posState << (1 + kLenNumLowBits)); -- bit = (sym >> 2) ; RC_BIT(rc, probs + 1, bit); m = (1 << 1) + bit; -- bit = (sym >> 1) & 1; RC_BIT(rc, probs + m, bit); m = (m << 1) + bit; -- bit = sym & 1; RC_BIT(rc, probs + m, bit); -+ bit = (sym >> 2) ; RC_BIT(rc, probs + 1, bit) m = (1 << 1) + bit; -+ bit = (sym >> 1) & 1; RC_BIT(rc, probs + m, bit) m = (m << 1) + bit; -+ bit = sym & 1; RC_BIT(rc, probs + m, bit) - rc->range = range; - } - } -@@ -990,7 +976,7 @@ static void SetPrices_3(const CLzmaProb *probs, UInt32 startPrice, UInt32 *price - } - - --MY_NO_INLINE static void MY_FAST_CALL LenPriceEnc_UpdateTables( -+Z7_NO_INLINE static void Z7_FASTCALL LenPriceEnc_UpdateTables( - CLenPriceEnc *p, - unsigned numPosStates, - const CLenEnc *enc, -@@ -1152,7 +1138,7 @@ static unsigned ReadMatchDistances(CLzmaEnc *p, unsigned *numPairsRes) - + GET_PRICE_1(p->isRep[state]) \ - + GET_PRICE_0(p->isRepG0[state]) - --MY_FORCE_INLINE -+Z7_FORCE_INLINE - static UInt32 GetPrice_PureRep(const CLzmaEnc *p, unsigned repIndex, size_t state, size_t posState) - { - UInt32 price; -@@ -1331,7 +1317,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) - LitEnc_GetPrice(probs, curByte, p->ProbPrices)); - } - -- MakeAs_Lit(&p->opt[1]); -+ MakeAs_Lit(&p->opt[1]) - - matchPrice = GET_PRICE_1(p->isMatch[p->state][posState]); - repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[p->state]); -@@ -1343,7 +1329,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) - if (shortRepPrice < p->opt[1].price) - { - p->opt[1].price = shortRepPrice; -- MakeAs_ShortRep(&p->opt[1]); -+ MakeAs_ShortRep(&p->opt[1]) - } - if (last < 2) - { -@@ -1410,7 +1396,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) - else - { - unsigned slot; -- GetPosSlot2(dist, slot); -+ GetPosSlot2(dist, slot) - price += p->alignPrices[dist & kAlignMask]; - price += p->posSlotPrices[lenToPosState][slot]; - } -@@ -1486,7 +1472,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) - unsigned delta = best - cur; - if (delta != 0) - { -- MOVE_POS(p, delta); -+ MOVE_POS(p, delta) - } - } - cur = best; -@@ -1633,7 +1619,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) - { - nextOpt->price = litPrice; - nextOpt->len = 1; -- MakeAs_Lit(nextOpt); -+ MakeAs_Lit(nextOpt) - nextIsLit = True7z; - } - } -@@ -1667,7 +1653,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) - { - nextOpt->price = shortRepPrice; - nextOpt->len = 1; -- MakeAs_ShortRep(nextOpt); -+ MakeAs_ShortRep(nextOpt) - nextIsLit = False7z; - } - } -@@ -1871,7 +1857,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) - dist = MATCHES[(size_t)offs + 1]; - - // if (dist >= kNumFullDistances) -- GetPosSlot2(dist, posSlot); -+ GetPosSlot2(dist, posSlot) - - for (len = /*2*/ startLen; ; len++) - { -@@ -1962,7 +1948,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) - break; - dist = MATCHES[(size_t)offs + 1]; - // if (dist >= kNumFullDistances) -- GetPosSlot2(dist, posSlot); -+ GetPosSlot2(dist, posSlot) - } - } - } -@@ -2138,7 +2124,7 @@ static void WriteEndMarker(CLzmaEnc *p, unsigned posState) - { - UInt32 ttt, newBound; - RC_BIT_PRE(p, probs + m) -- RC_BIT_1(&p->rc, probs + m); -+ RC_BIT_1(&p->rc, probs + m) - m = (m << 1) + 1; - } - while (m < (1 << kNumPosSlotBits)); -@@ -2163,7 +2149,7 @@ static void WriteEndMarker(CLzmaEnc *p, unsigned posState) - { - UInt32 ttt, newBound; - RC_BIT_PRE(p, probs + m) -- RC_BIT_1(&p->rc, probs + m); -+ RC_BIT_1(&p->rc, probs + m) - m = (m << 1) + 1; - } - while (m < kAlignTableSize); -@@ -2179,7 +2165,7 @@ static SRes CheckErrors(CLzmaEnc *p) - if (p->rc.res != SZ_OK) - p->result = SZ_ERROR_WRITE; - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - if ( - // p->mf_Failure || - (p->mtMode && -@@ -2187,7 +2173,7 @@ static SRes CheckErrors(CLzmaEnc *p) - p->matchFinderMt.failure_LZ_BT)) - ) - { -- p->result = MY_HRES_ERROR__INTERNAL_ERROR; -+ p->result = MY_HRES_ERROR_INTERNAL_ERROR; - // printf("\nCheckErrors p->matchFinderMt.failureLZ\n"); - } - #endif -@@ -2201,7 +2187,7 @@ static SRes CheckErrors(CLzmaEnc *p) - } - - --MY_NO_INLINE static SRes Flush(CLzmaEnc *p, UInt32 nowPos) -+Z7_NO_INLINE static SRes Flush(CLzmaEnc *p, UInt32 nowPos) - { - /* ReleaseMFStream(); */ - p->finished = True7z; -@@ -2213,7 +2199,7 @@ MY_NO_INLINE static SRes Flush(CLzmaEnc *p, UInt32 nowPos) - } - - --MY_NO_INLINE static void FillAlignPrices(CLzmaEnc *p) -+Z7_NO_INLINE static void FillAlignPrices(CLzmaEnc *p) - { - unsigned i; - const CProbPrice *ProbPrices = p->ProbPrices; -@@ -2237,7 +2223,7 @@ MY_NO_INLINE static void FillAlignPrices(CLzmaEnc *p) - } - - --MY_NO_INLINE static void FillDistancesPrices(CLzmaEnc *p) -+Z7_NO_INLINE static void FillDistancesPrices(CLzmaEnc *p) - { - // int y; for (y = 0; y < 100; y++) { - -@@ -2337,7 +2323,7 @@ static void LzmaEnc_Construct(CLzmaEnc *p) - RangeEnc_Construct(&p->rc); - MatchFinder_Construct(&MFB); - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - p->matchFinderMt.MatchFinder = &MFB; - MatchFinderMt_Construct(&p->matchFinderMt); - #endif -@@ -2345,7 +2331,7 @@ static void LzmaEnc_Construct(CLzmaEnc *p) - { - CLzmaEncProps props; - LzmaEncProps_Init(&props); -- LzmaEnc_SetProps(p, &props); -+ LzmaEnc_SetProps((CLzmaEncHandle)(void *)p, &props); - } - - #ifndef LZMA_LOG_BSR -@@ -2376,7 +2362,7 @@ static void LzmaEnc_FreeLits(CLzmaEnc *p, ISzAllocPtr alloc) - - static void LzmaEnc_Destruct(CLzmaEnc *p, ISzAllocPtr alloc, ISzAllocPtr allocBig) - { -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - MatchFinderMt_Destruct(&p->matchFinderMt, allocBig); - #endif - -@@ -2387,21 +2373,22 @@ static void LzmaEnc_Destruct(CLzmaEnc *p, ISzAllocPtr alloc, ISzAllocPtr allocBi - - void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAllocPtr alloc, ISzAllocPtr allocBig) - { -- LzmaEnc_Destruct((CLzmaEnc *)p, alloc, allocBig); -+ // GET_CLzmaEnc_p -+ LzmaEnc_Destruct(p, alloc, allocBig); - ISzAlloc_Free(alloc, p); - } - - --MY_NO_INLINE -+Z7_NO_INLINE - static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpackSize) - { - UInt32 nowPos32, startPos32; - if (p->needInit) - { -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - if (p->mtMode) - { -- RINOK(MatchFinderMt_InitMt(&p->matchFinderMt)); -+ RINOK(MatchFinderMt_InitMt(&p->matchFinderMt)) - } - #endif - p->matchFinder.Init(p->matchFinderObj); -@@ -2410,7 +2397,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa - - if (p->finished) - return p->result; -- RINOK(CheckErrors(p)); -+ RINOK(CheckErrors(p)) - - nowPos32 = (UInt32)p->nowPos64; - startPos32 = nowPos32; -@@ -2473,7 +2460,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa - const Byte *data; - unsigned state; - -- RC_BIT_0(&p->rc, probs); -+ RC_BIT_0(&p->rc, probs) - p->rc.range = range; - data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset; - probs = LIT_PROBS(nowPos32, *(data - 1)); -@@ -2487,53 +2474,53 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa - } - else - { -- RC_BIT_1(&p->rc, probs); -+ RC_BIT_1(&p->rc, probs) - probs = &p->isRep[p->state]; - RC_BIT_PRE(&p->rc, probs) - - if (dist < LZMA_NUM_REPS) - { -- RC_BIT_1(&p->rc, probs); -+ RC_BIT_1(&p->rc, probs) - probs = &p->isRepG0[p->state]; - RC_BIT_PRE(&p->rc, probs) - if (dist == 0) - { -- RC_BIT_0(&p->rc, probs); -+ RC_BIT_0(&p->rc, probs) - probs = &p->isRep0Long[p->state][posState]; - RC_BIT_PRE(&p->rc, probs) - if (len != 1) - { -- RC_BIT_1_BASE(&p->rc, probs); -+ RC_BIT_1_BASE(&p->rc, probs) - } - else - { -- RC_BIT_0_BASE(&p->rc, probs); -+ RC_BIT_0_BASE(&p->rc, probs) - p->state = kShortRepNextStates[p->state]; - } - } - else - { -- RC_BIT_1(&p->rc, probs); -+ RC_BIT_1(&p->rc, probs) - probs = &p->isRepG1[p->state]; - RC_BIT_PRE(&p->rc, probs) - if (dist == 1) - { -- RC_BIT_0_BASE(&p->rc, probs); -+ RC_BIT_0_BASE(&p->rc, probs) - dist = p->reps[1]; - } - else - { -- RC_BIT_1(&p->rc, probs); -+ RC_BIT_1(&p->rc, probs) - probs = &p->isRepG2[p->state]; - RC_BIT_PRE(&p->rc, probs) - if (dist == 2) - { -- RC_BIT_0_BASE(&p->rc, probs); -+ RC_BIT_0_BASE(&p->rc, probs) - dist = p->reps[2]; - } - else - { -- RC_BIT_1_BASE(&p->rc, probs); -+ RC_BIT_1_BASE(&p->rc, probs) - dist = p->reps[3]; - p->reps[3] = p->reps[2]; - } -@@ -2557,7 +2544,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa - else - { - unsigned posSlot; -- RC_BIT_0(&p->rc, probs); -+ RC_BIT_0(&p->rc, probs) - p->rc.range = range; - p->state = kMatchNextStates[p->state]; - -@@ -2571,7 +2558,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa - p->reps[0] = dist + 1; - - p->matchPriceCount++; -- GetPosSlot(dist, posSlot); -+ GetPosSlot(dist, posSlot) - // RcTree_Encode_PosSlot(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], posSlot); - { - UInt32 sym = (UInt32)posSlot + (1 << kNumPosSlotBits); -@@ -2582,7 +2569,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa - CLzmaProb *prob = probs + (sym >> kNumPosSlotBits); - UInt32 bit = (sym >> (kNumPosSlotBits - 1)) & 1; - sym <<= 1; -- RC_BIT(&p->rc, prob, bit); -+ RC_BIT(&p->rc, prob, bit) - } - while (sym < (1 << kNumPosSlotBits * 2)); - p->rc.range = range; -@@ -2626,10 +2613,10 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa - { - unsigned m = 1; - unsigned bit; -- bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit; -- bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit; -- bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit; -- bit = dist & 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); -+ bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit) m = (m << 1) + bit; -+ bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit) m = (m << 1) + bit; -+ bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit) m = (m << 1) + bit; -+ bit = dist & 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit) - p->rc.range = range; - // p->alignPriceCount++; - } -@@ -2704,7 +2691,7 @@ static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr alloc, - if (!RangeEnc_Alloc(&p->rc, alloc)) - return SZ_ERROR_MEM; - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - p->mtMode = (p->multiThread && !p->fastMode && (MFB.btMode != 0)); - #endif - -@@ -2748,15 +2735,14 @@ static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr alloc, - (numFastBytes + LZMA_MATCH_LEN_MAX + 1) - */ - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - if (p->mtMode) - { - RINOK(MatchFinderMt_Create(&p->matchFinderMt, dictSize, beforeSize, - p->numFastBytes, LZMA_MATCH_LEN_MAX + 1 /* 18.04 */ -- , allocBig)); -+ , allocBig)) - p->matchFinderObj = &p->matchFinderMt; -- MFB.bigHash = (Byte)( -- (p->dictSize > kBigHashDicLimit && MFB.hashMask >= 0xFFFFFF) ? 1 : 0); -+ MFB.bigHash = (Byte)(MFB.hashMask >= 0xFFFFFF ? 1 : 0); - MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder); - } - else -@@ -2872,59 +2858,53 @@ static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr - - p->finished = False7z; - p->result = SZ_OK; -- RINOK(LzmaEnc_Alloc(p, keepWindowSize, alloc, allocBig)); -+ p->nowPos64 = 0; -+ p->needInit = 1; -+ 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, ISeqOutStream *outStream, ISeqInStream *inStream, -+static SRes LzmaEnc_Prepare(CLzmaEncHandle p, -+ ISeqOutStreamPtr outStream, -+ ISeqInStreamPtr inStream, - ISzAllocPtr alloc, ISzAllocPtr allocBig) - { -- CLzmaEnc *p = (CLzmaEnc *)pp; -- MFB.stream = inStream; -- p->needInit = 1; -+ // GET_CLzmaEnc_p -+ MatchFinder_SET_STREAM(&MFB, inStream) - p->rc.outStream = outStream; - return LzmaEnc_AllocAndInit(p, 0, alloc, allocBig); - } - --SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp, -- ISeqInStream *inStream, UInt32 keepWindowSize, -+SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle p, -+ ISeqInStreamPtr inStream, UInt32 keepWindowSize, - ISzAllocPtr alloc, ISzAllocPtr allocBig) - { -- CLzmaEnc *p = (CLzmaEnc *)pp; -- MFB.stream = inStream; -- p->needInit = 1; -+ // GET_CLzmaEnc_p -+ MatchFinder_SET_STREAM(&MFB, inStream) - return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig); - } - --static void LzmaEnc_SetInputBuf(CLzmaEnc *p, const Byte *src, SizeT srcLen) --{ -- MFB.directInput = 1; -- MFB.bufferBase = (Byte *)src; -- MFB.directInputRem = srcLen; --} -- --SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen, -- UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig) -+SRes LzmaEnc_MemPrepare(CLzmaEncHandle p, -+ const Byte *src, SizeT srcLen, -+ UInt32 keepWindowSize, -+ ISzAllocPtr alloc, ISzAllocPtr allocBig) - { -- CLzmaEnc *p = (CLzmaEnc *)pp; -- LzmaEnc_SetInputBuf(p, src, srcLen); -- p->needInit = 1; -- -- LzmaEnc_SetDataSize(pp, srcLen); -+ // GET_CLzmaEnc_p -+ MatchFinder_SET_DIRECT_INPUT_BUF(&MFB, src, srcLen) -+ LzmaEnc_SetDataSize(p, srcLen); - return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig); - } - --void LzmaEnc_Finish(CLzmaEncHandle pp) -+void LzmaEnc_Finish(CLzmaEncHandle p) - { -- #ifndef _7ZIP_ST -- CLzmaEnc *p = (CLzmaEnc *)pp; -+ #ifndef Z7_ST -+ // GET_CLzmaEnc_p - if (p->mtMode) - MatchFinderMt_ReleaseStream(&p->matchFinderMt); - #else -- UNUSED_VAR(pp); -+ UNUSED_VAR(p) - #endif - } - -@@ -2933,13 +2913,13 @@ typedef struct - { - ISeqOutStream vt; - Byte *data; -- SizeT rem; -+ size_t rem; - BoolInt overflow; - } CLzmaEnc_SeqOutStreamBuf; - --static size_t SeqOutStreamBuf_Write(const ISeqOutStream *pp, const void *data, size_t size) -+static size_t SeqOutStreamBuf_Write(ISeqOutStreamPtr pp, const void *data, size_t size) - { -- CLzmaEnc_SeqOutStreamBuf *p = CONTAINER_FROM_VTBL(pp, CLzmaEnc_SeqOutStreamBuf, vt); -+ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CLzmaEnc_SeqOutStreamBuf) - if (p->rem < size) - { - size = p->rem; -@@ -2956,24 +2936,25 @@ static size_t SeqOutStreamBuf_Write(const ISeqOutStream *pp, const void *data, s - - - /* --UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp) -+UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle p) - { -- const CLzmaEnc *p = (CLzmaEnc *)pp; -+ GET_const_CLzmaEnc_p - return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj); - } - */ - --const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp) -+const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle p) - { -- const CLzmaEnc *p = (CLzmaEnc *)pp; -+ // GET_const_CLzmaEnc_p - return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset; - } - - --SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit, -+// (desiredPackSize == 0) is not allowed -+SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle p, BoolInt reInit, - Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize) - { -- CLzmaEnc *p = (CLzmaEnc *)pp; -+ // GET_CLzmaEnc_p - UInt64 nowPos64; - SRes res; - CLzmaEnc_SeqOutStreamBuf outStream; -@@ -2990,14 +2971,10 @@ SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit, - if (reInit) - LzmaEnc_Init(p); - LzmaEnc_InitPrices(p); -- -- nowPos64 = p->nowPos64; - RangeEnc_Init(&p->rc); - p->rc.outStream = &outStream.vt; -- -- if (desiredPackSize == 0) -- return SZ_ERROR_OUTPUT_EOF; -- -+ nowPos64 = p->nowPos64; -+ - res = LzmaEnc_CodeOneBlock(p, desiredPackSize, *unpackSize); - - *unpackSize = (UInt32)(p->nowPos64 - nowPos64); -@@ -3009,12 +2986,12 @@ SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit, - } - - --MY_NO_INLINE --static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress) -+Z7_NO_INLINE -+static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgressPtr progress) - { - SRes res = SZ_OK; - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - Byte allocaDummy[0x300]; - allocaDummy[0] = 0; - allocaDummy[1] = allocaDummy[0]; -@@ -3036,7 +3013,7 @@ static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress) - } - } - -- LzmaEnc_Finish(p); -+ LzmaEnc_Finish((CLzmaEncHandle)(void *)p); - - /* - if (res == SZ_OK && !Inline_MatchFinder_IsFinishedOK(&MFB)) -@@ -3048,21 +3025,22 @@ static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress) - } - - --SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress, -+SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, ICompressProgressPtr progress, - ISzAllocPtr alloc, ISzAllocPtr allocBig) - { -- RINOK(LzmaEnc_Prepare(pp, outStream, inStream, alloc, allocBig)); -- return LzmaEnc_Encode2((CLzmaEnc *)pp, progress); -+ // GET_CLzmaEnc_p -+ RINOK(LzmaEnc_Prepare(p, outStream, inStream, alloc, allocBig)) -+ return LzmaEnc_Encode2(p, progress); - } - - --SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size) -+SRes LzmaEnc_WriteProperties(CLzmaEncHandle p, Byte *props, SizeT *size) - { - if (*size < LZMA_PROPS_SIZE) - return SZ_ERROR_PARAM; - *size = LZMA_PROPS_SIZE; - { -- const CLzmaEnc *p = (const CLzmaEnc *)pp; -+ // GET_CLzmaEnc_p - const UInt32 dictSize = p->dictSize; - UInt32 v; - props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc); -@@ -3086,23 +3064,24 @@ SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size) - while (v < dictSize); - } - -- SetUi32(props + 1, v); -+ SetUi32(props + 1, v) - return SZ_OK; - } - } - - --unsigned LzmaEnc_IsWriteEndMark(CLzmaEncHandle pp) -+unsigned LzmaEnc_IsWriteEndMark(CLzmaEncHandle p) - { -- return (unsigned)((CLzmaEnc *)pp)->writeEndMark; -+ // GET_CLzmaEnc_p -+ return (unsigned)p->writeEndMark; - } - - --SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, -- int writeEndMark, ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig) -+SRes LzmaEnc_MemEncode(CLzmaEncHandle p, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, -+ int writeEndMark, ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig) - { - SRes res; -- CLzmaEnc *p = (CLzmaEnc *)pp; -+ // GET_CLzmaEnc_p - - CLzmaEnc_SeqOutStreamBuf outStream; - -@@ -3114,7 +3093,7 @@ SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte - p->writeEndMark = writeEndMark; - p->rc.outStream = &outStream.vt; - -- res = LzmaEnc_MemPrepare(pp, src, srcLen, 0, alloc, allocBig); -+ res = LzmaEnc_MemPrepare(p, src, srcLen, 0, alloc, allocBig); - - if (res == SZ_OK) - { -@@ -3123,7 +3102,7 @@ SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte - res = SZ_ERROR_FAIL; - } - -- *destLen -= outStream.rem; -+ *destLen -= (SizeT)outStream.rem; - if (outStream.overflow) - return SZ_ERROR_OUTPUT_EOF; - return res; -@@ -3132,9 +3111,9 @@ SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte - - SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, - const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark, -- ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig) -+ ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig) - { -- CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc); -+ CLzmaEncHandle p = LzmaEnc_Create(alloc); - SRes res; - if (!p) - return SZ_ERROR_MEM; -@@ -3154,10 +3133,10 @@ SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, - - - /* --#ifndef _7ZIP_ST --void LzmaEnc_GetLzThreads(CLzmaEncHandle pp, HANDLE lz_threads[2]) -+#ifndef Z7_ST -+void LzmaEnc_GetLzThreads(CLzmaEncHandle p, HANDLE lz_threads[2]) - { -- const CLzmaEnc *p = (CLzmaEnc *)pp; -+ GET_const_CLzmaEnc_p - lz_threads[0] = p->matchFinderMt.hashSync.thread; - lz_threads[1] = p->matchFinderMt.btSync.thread; - } -diff --git a/src/lzma/LzmaEnc.h b/src/lzma/LzmaEnc.h -index bc2ed5042..9f8039a10 100644 ---- a/src/lzma/LzmaEnc.h -+++ b/src/lzma/LzmaEnc.h -@@ -1,8 +1,8 @@ - /* LzmaEnc.h -- LZMA Encoder --2019-10-30 : Igor Pavlov : Public domain */ -+2023-04-13 : Igor Pavlov : Public domain */ - --#ifndef __LZMA_ENC_H --#define __LZMA_ENC_H -+#ifndef ZIP7_INC_LZMA_ENC_H -+#define ZIP7_INC_LZMA_ENC_H - - #include "7zTypes.h" - -@@ -10,7 +10,7 @@ EXTERN_C_BEGIN - - #define LZMA_PROPS_SIZE 5 - --typedef struct _CLzmaEncProps -+typedef struct - { - int level; /* 0 <= level <= 9 */ - UInt32 dictSize; /* (1 << 12) <= dictSize <= (1 << 27) for 32-bit version -@@ -23,10 +23,13 @@ typedef struct _CLzmaEncProps - 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 */ -+ unsigned numHashOutBits; /* default = ? */ - 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 */ - -+ // int _pad; -+ - UInt64 reduceSize; /* estimated size of data that will be compressed. default = (UInt64)(Int64)-1. - Encoder uses this value to reduce dictionary size */ - -@@ -51,7 +54,9 @@ UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2); - SZ_ERROR_THREAD - error in multithreading functions (only for Mt version) - */ - --typedef void * CLzmaEncHandle; -+typedef struct CLzmaEnc CLzmaEnc; -+typedef CLzmaEnc * CLzmaEncHandle; -+// Z7_DECLARE_HANDLE(CLzmaEncHandle) - - CLzmaEncHandle LzmaEnc_Create(ISzAllocPtr alloc); - void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAllocPtr alloc, ISzAllocPtr allocBig); -@@ -61,17 +66,17 @@ void LzmaEnc_SetDataSize(CLzmaEncHandle p, UInt64 expectedDataSiize); - SRes LzmaEnc_WriteProperties(CLzmaEncHandle p, Byte *properties, SizeT *size); - unsigned LzmaEnc_IsWriteEndMark(CLzmaEncHandle p); - --SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStream *outStream, ISeqInStream *inStream, -- ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); -+SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, -+ ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); - SRes LzmaEnc_MemEncode(CLzmaEncHandle p, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, -- int writeEndMark, ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); -+ int writeEndMark, ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); - - - /* ---------- One Call Interface ---------- */ - - SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, - const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark, -- ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); -+ ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); - - EXTERN_C_END - -diff --git a/src/lzma/LzmaLib.c b/src/lzma/LzmaLib.c -index 706e9e58c..785e88487 100644 ---- a/src/lzma/LzmaLib.c -+++ b/src/lzma/LzmaLib.c -@@ -1,12 +1,14 @@ - /* LzmaLib.c -- LZMA library wrapper --2015-06-13 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ -+ -+#include "Precomp.h" - - #include "Alloc.h" - #include "LzmaDec.h" - #include "LzmaEnc.h" - #include "LzmaLib.h" - --MY_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, -+Z7_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, - unsigned char *outProps, size_t *outPropsSize, - int level, /* 0 <= level <= 9, default = 5 */ - unsigned dictSize, /* use (1 << N) or (3 << N). 4 KB < dictSize <= 128 MB */ -@@ -32,7 +34,7 @@ MY_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char - } - - --MY_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t *srcLen, -+Z7_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t *srcLen, - const unsigned char *props, size_t propsSize) - { - ELzmaStatus status; -diff --git a/src/lzma/LzmaLib.h b/src/lzma/LzmaLib.h -index c343a8596..d7c0724de 100644 ---- a/src/lzma/LzmaLib.h -+++ b/src/lzma/LzmaLib.h -@@ -1,14 +1,14 @@ - /* LzmaLib.h -- LZMA library interface --2021-04-03 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - --#ifndef __LZMA_LIB_H --#define __LZMA_LIB_H -+#ifndef ZIP7_INC_LZMA_LIB_H -+#define ZIP7_INC_LZMA_LIB_H - - #include "7zTypes.h" - - EXTERN_C_BEGIN - --#define MY_STDAPI int MY_STD_CALL -+#define Z7_STDAPI int Z7_STDCALL - - #define LZMA_PROPS_SIZE 5 - -@@ -100,7 +100,7 @@ numThreads - The number of thereads. 1 or 2. The default value is 2. - SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version) - */ - --MY_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, -+Z7_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, - unsigned char *outProps, size_t *outPropsSize, /* *outPropsSize must be = 5 */ - int level, /* 0 <= level <= 9, default = 5 */ - unsigned dictSize, /* default = (1 << 24) */ -@@ -130,7 +130,7 @@ LzmaUncompress - SZ_ERROR_INPUT_EOF - it needs more bytes in input buffer (src) - */ - --MY_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, SizeT *srcLen, -+Z7_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, SizeT *srcLen, - const unsigned char *props, size_t propsSize); - - EXTERN_C_END -diff --git a/src/lzma/MtCoder.c b/src/lzma/MtCoder.c -index b05fdcace..3fd718e44 100644 ---- a/src/lzma/MtCoder.c -+++ b/src/lzma/MtCoder.c -@@ -1,28 +1,28 @@ - /* MtCoder.c -- Multi-thread Coder --2021-12-21 : Igor Pavlov : Public domain */ -+2023-04-13 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - - #include "MtCoder.h" - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - --static SRes MtProgressThunk_Progress(const ICompressProgress *pp, UInt64 inSize, UInt64 outSize) -+static SRes MtProgressThunk_Progress(ICompressProgressPtr pp, UInt64 inSize, UInt64 outSize) - { -- CMtProgressThunk *thunk = CONTAINER_FROM_VTBL(pp, CMtProgressThunk, vt); -+ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CMtProgressThunk) - UInt64 inSize2 = 0; - UInt64 outSize2 = 0; - if (inSize != (UInt64)(Int64)-1) - { -- inSize2 = inSize - thunk->inSize; -- thunk->inSize = inSize; -+ inSize2 = inSize - p->inSize; -+ p->inSize = inSize; - } - if (outSize != (UInt64)(Int64)-1) - { -- outSize2 = outSize - thunk->outSize; -- thunk->outSize = outSize; -+ outSize2 = outSize - p->outSize; -+ p->outSize = outSize; - } -- return MtProgress_ProgressAdd(thunk->mtProgress, inSize2, outSize2); -+ return MtProgress_ProgressAdd(p->mtProgress, inSize2, outSize2); - } - - -@@ -36,20 +36,12 @@ void MtProgressThunk_CreateVTable(CMtProgressThunk *p) - #define RINOK_THREAD(x) { if ((x) != 0) return SZ_ERROR_THREAD; } - - --static WRes ArEvent_OptCreate_And_Reset(CEvent *p) --{ -- if (Event_IsCreated(p)) -- return Event_Reset(p); -- return AutoResetEvent_CreateNotSignaled(p); --} -- -- - static THREAD_FUNC_DECL ThreadFunc(void *pp); - - - static SRes MtCoderThread_CreateAndStart(CMtCoderThread *t) - { -- WRes wres = ArEvent_OptCreate_And_Reset(&t->startEvent); -+ WRes wres = AutoResetEvent_OptCreate_And_Reset(&t->startEvent); - if (wres == 0) - { - t->stop = False7z; -@@ -84,24 +76,6 @@ static void MtCoderThread_Destruct(CMtCoderThread *t) - - - --static SRes FullRead(ISeqInStream *stream, Byte *data, size_t *processedSize) --{ -- size_t size = *processedSize; -- *processedSize = 0; -- while (size != 0) -- { -- size_t cur = size; -- SRes res = ISeqInStream_Read(stream, data, &cur); -- *processedSize += cur; -- data += cur; -- size -= cur; -- RINOK(res); -- if (cur == 0) -- return SZ_OK; -- } -- return SZ_OK; --} -- - - /* - ThreadFunc2() returns: -@@ -152,7 +126,7 @@ static SRes ThreadFunc2(CMtCoderThread *t) - } - if (res == SZ_OK) - { -- res = FullRead(mtc->inStream, t->inBuf, &size); -+ res = SeqInStream_ReadMax(mtc->inStream, t->inBuf, &size); - readProcessed = mtc->readProcessed + size; - mtc->readProcessed = readProcessed; - } -@@ -253,7 +227,7 @@ static SRes ThreadFunc2(CMtCoderThread *t) - block->finished = finished; - } - -- #ifdef MTCODER__USE_WRITE_THREAD -+ #ifdef MTCODER_USE_WRITE_THREAD - RINOK_THREAD(Event_Set(&mtc->writeEvents[bi])) - #else - { -@@ -352,7 +326,7 @@ static THREAD_FUNC_DECL ThreadFunc(void *pp) - MtProgress_SetError(&mtc->mtProgress, res); - } - -- #ifndef MTCODER__USE_WRITE_THREAD -+ #ifndef MTCODER_USE_WRITE_THREAD - { - unsigned numFinished = (unsigned)InterlockedIncrement(&mtc->numFinishedThreads); - if (numFinished == mtc->numStartedThreads) -@@ -389,7 +363,7 @@ void MtCoder_Construct(CMtCoder *p) - Event_Construct(&p->readEvent); - Semaphore_Construct(&p->blocksSemaphore); - -- for (i = 0; i < MTCODER__THREADS_MAX; i++) -+ for (i = 0; i < MTCODER_THREADS_MAX; i++) - { - CMtCoderThread *t = &p->threads[i]; - t->mtCoder = p; -@@ -397,11 +371,11 @@ void MtCoder_Construct(CMtCoder *p) - t->inBuf = NULL; - t->stop = False7z; - Event_Construct(&t->startEvent); -- Thread_Construct(&t->thread); -+ Thread_CONSTRUCT(&t->thread) - } - -- #ifdef MTCODER__USE_WRITE_THREAD -- for (i = 0; i < MTCODER__BLOCKS_MAX; i++) -+ #ifdef MTCODER_USE_WRITE_THREAD -+ for (i = 0; i < MTCODER_BLOCKS_MAX; i++) - Event_Construct(&p->writeEvents[i]); - #else - Event_Construct(&p->finishedEvent); -@@ -424,14 +398,14 @@ static void MtCoder_Free(CMtCoder *p) - Event_Set(&p->readEvent); - */ - -- for (i = 0; i < MTCODER__THREADS_MAX; i++) -+ for (i = 0; i < MTCODER_THREADS_MAX; i++) - MtCoderThread_Destruct(&p->threads[i]); - - Event_Close(&p->readEvent); - Semaphore_Close(&p->blocksSemaphore); - -- #ifdef MTCODER__USE_WRITE_THREAD -- for (i = 0; i < MTCODER__BLOCKS_MAX; i++) -+ #ifdef MTCODER_USE_WRITE_THREAD -+ for (i = 0; i < MTCODER_BLOCKS_MAX; i++) - Event_Close(&p->writeEvents[i]); - #else - Event_Close(&p->finishedEvent); -@@ -455,20 +429,20 @@ SRes MtCoder_Code(CMtCoder *p) - unsigned i; - SRes res = SZ_OK; - -- if (numThreads > MTCODER__THREADS_MAX) -- numThreads = MTCODER__THREADS_MAX; -- numBlocksMax = MTCODER__GET_NUM_BLOCKS_FROM_THREADS(numThreads); -+ if (numThreads > MTCODER_THREADS_MAX) -+ numThreads = MTCODER_THREADS_MAX; -+ numBlocksMax = MTCODER_GET_NUM_BLOCKS_FROM_THREADS(numThreads); - - if (p->blockSize < ((UInt32)1 << 26)) numBlocksMax++; - if (p->blockSize < ((UInt32)1 << 24)) numBlocksMax++; - if (p->blockSize < ((UInt32)1 << 22)) numBlocksMax++; - -- if (numBlocksMax > MTCODER__BLOCKS_MAX) -- numBlocksMax = MTCODER__BLOCKS_MAX; -+ if (numBlocksMax > MTCODER_BLOCKS_MAX) -+ numBlocksMax = MTCODER_BLOCKS_MAX; - - if (p->blockSize != p->allocatedBufsSize) - { -- for (i = 0; i < MTCODER__THREADS_MAX; i++) -+ for (i = 0; i < MTCODER_THREADS_MAX; i++) - { - CMtCoderThread *t = &p->threads[i]; - if (t->inBuf) -@@ -484,23 +458,23 @@ SRes MtCoder_Code(CMtCoder *p) - - MtProgress_Init(&p->mtProgress, p->progress); - -- #ifdef MTCODER__USE_WRITE_THREAD -+ #ifdef MTCODER_USE_WRITE_THREAD - for (i = 0; i < numBlocksMax; i++) - { -- RINOK_THREAD(ArEvent_OptCreate_And_Reset(&p->writeEvents[i])); -+ RINOK_THREAD(AutoResetEvent_OptCreate_And_Reset(&p->writeEvents[i])) - } - #else -- RINOK_THREAD(ArEvent_OptCreate_And_Reset(&p->finishedEvent)); -+ RINOK_THREAD(AutoResetEvent_OptCreate_And_Reset(&p->finishedEvent)) - #endif - - { -- RINOK_THREAD(ArEvent_OptCreate_And_Reset(&p->readEvent)); -- RINOK_THREAD(Semaphore_OptCreateInit(&p->blocksSemaphore, numBlocksMax, numBlocksMax)); -+ RINOK_THREAD(AutoResetEvent_OptCreate_And_Reset(&p->readEvent)) -+ RINOK_THREAD(Semaphore_OptCreateInit(&p->blocksSemaphore, numBlocksMax, numBlocksMax)) - } - -- for (i = 0; i < MTCODER__BLOCKS_MAX - 1; i++) -+ for (i = 0; i < MTCODER_BLOCKS_MAX - 1; i++) - p->freeBlockList[i] = i + 1; -- p->freeBlockList[MTCODER__BLOCKS_MAX - 1] = (unsigned)(int)-1; -+ p->freeBlockList[MTCODER_BLOCKS_MAX - 1] = (unsigned)(int)-1; - p->freeBlockHead = 0; - - p->readProcessed = 0; -@@ -508,10 +482,10 @@ SRes MtCoder_Code(CMtCoder *p) - p->numBlocksMax = numBlocksMax; - p->stopReading = False7z; - -- #ifndef MTCODER__USE_WRITE_THREAD -+ #ifndef MTCODER_USE_WRITE_THREAD - p->writeIndex = 0; - p->writeRes = SZ_OK; -- for (i = 0; i < MTCODER__BLOCKS_MAX; i++) -+ for (i = 0; i < MTCODER_BLOCKS_MAX; i++) - p->ReadyBlocks[i] = False7z; - p->numFinishedThreads = 0; - #endif -@@ -522,12 +496,12 @@ SRes MtCoder_Code(CMtCoder *p) - // for (i = 0; i < numThreads; i++) - { - CMtCoderThread *nextThread = &p->threads[p->numStartedThreads++]; -- RINOK(MtCoderThread_CreateAndStart(nextThread)); -+ RINOK(MtCoderThread_CreateAndStart(nextThread)) - } - - RINOK_THREAD(Event_Set(&p->readEvent)) - -- #ifdef MTCODER__USE_WRITE_THREAD -+ #ifdef MTCODER_USE_WRITE_THREAD - { - unsigned bi = 0; - -@@ -582,7 +556,7 @@ SRes MtCoder_Code(CMtCoder *p) - if (res == SZ_OK) - res = p->mtProgress.res; - -- #ifndef MTCODER__USE_WRITE_THREAD -+ #ifndef MTCODER_USE_WRITE_THREAD - if (res == SZ_OK) - res = p->writeRes; - #endif -@@ -593,3 +567,5 @@ SRes MtCoder_Code(CMtCoder *p) - } - - #endif -+ -+#undef RINOK_THREAD -diff --git a/src/lzma/MtCoder.h b/src/lzma/MtCoder.h -index 5a5f4d11b..1231d3c2a 100644 ---- a/src/lzma/MtCoder.h -+++ b/src/lzma/MtCoder.h -@@ -1,30 +1,30 @@ - /* MtCoder.h -- Multi-thread Coder --2018-07-04 : Igor Pavlov : Public domain */ -+2023-04-13 : Igor Pavlov : Public domain */ - --#ifndef __MT_CODER_H --#define __MT_CODER_H -+#ifndef ZIP7_INC_MT_CODER_H -+#define ZIP7_INC_MT_CODER_H - - #include "MtDec.h" - - EXTERN_C_BEGIN - - /* -- if ( defined MTCODER__USE_WRITE_THREAD) : main thread writes all data blocks to output stream -- if (not defined MTCODER__USE_WRITE_THREAD) : any coder thread can write data blocks to output stream -+ if ( defined MTCODER_USE_WRITE_THREAD) : main thread writes all data blocks to output stream -+ if (not defined MTCODER_USE_WRITE_THREAD) : any coder thread can write data blocks to output stream - */ --/* #define MTCODER__USE_WRITE_THREAD */ -+/* #define MTCODER_USE_WRITE_THREAD */ - --#ifndef _7ZIP_ST -- #define MTCODER__GET_NUM_BLOCKS_FROM_THREADS(numThreads) ((numThreads) + (numThreads) / 8 + 1) -- #define MTCODER__THREADS_MAX 64 -- #define MTCODER__BLOCKS_MAX (MTCODER__GET_NUM_BLOCKS_FROM_THREADS(MTCODER__THREADS_MAX) + 3) -+#ifndef Z7_ST -+ #define MTCODER_GET_NUM_BLOCKS_FROM_THREADS(numThreads) ((numThreads) + (numThreads) / 8 + 1) -+ #define MTCODER_THREADS_MAX 64 -+ #define MTCODER_BLOCKS_MAX (MTCODER_GET_NUM_BLOCKS_FROM_THREADS(MTCODER_THREADS_MAX) + 3) - #else -- #define MTCODER__THREADS_MAX 1 -- #define MTCODER__BLOCKS_MAX 1 -+ #define MTCODER_THREADS_MAX 1 -+ #define MTCODER_BLOCKS_MAX 1 - #endif - - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - - - typedef struct -@@ -37,15 +37,15 @@ typedef struct - - void MtProgressThunk_CreateVTable(CMtProgressThunk *p); - --#define MtProgressThunk_Init(p) { (p)->inSize = 0; (p)->outSize = 0; } -+#define MtProgressThunk_INIT(p) { (p)->inSize = 0; (p)->outSize = 0; } - - --struct _CMtCoder; -+struct CMtCoder_; - - - typedef struct - { -- struct _CMtCoder *mtCoder; -+ struct CMtCoder_ *mtCoder; - unsigned index; - int stop; - Byte *inBuf; -@@ -71,7 +71,7 @@ typedef struct - } CMtCoderBlock; - - --typedef struct _CMtCoder -+typedef struct CMtCoder_ - { - /* input variables */ - -@@ -79,11 +79,11 @@ typedef struct _CMtCoder - unsigned numThreadsMax; - UInt64 expectedDataSize; - -- ISeqInStream *inStream; -+ ISeqInStreamPtr inStream; - const Byte *inData; - size_t inDataSize; - -- ICompressProgress *progress; -+ ICompressProgressPtr progress; - ISzAllocPtr allocBig; - - IMtCoderCallback2 *mtCallback; -@@ -100,13 +100,13 @@ typedef struct _CMtCoder - BoolInt stopReading; - SRes readRes; - -- #ifdef MTCODER__USE_WRITE_THREAD -- CAutoResetEvent writeEvents[MTCODER__BLOCKS_MAX]; -+ #ifdef MTCODER_USE_WRITE_THREAD -+ CAutoResetEvent writeEvents[MTCODER_BLOCKS_MAX]; - #else - CAutoResetEvent finishedEvent; - SRes writeRes; - unsigned writeIndex; -- Byte ReadyBlocks[MTCODER__BLOCKS_MAX]; -+ Byte ReadyBlocks[MTCODER_BLOCKS_MAX]; - LONG numFinishedThreads; - #endif - -@@ -120,11 +120,11 @@ typedef struct _CMtCoder - CCriticalSection cs; - - unsigned freeBlockHead; -- unsigned freeBlockList[MTCODER__BLOCKS_MAX]; -+ unsigned freeBlockList[MTCODER_BLOCKS_MAX]; - - CMtProgress mtProgress; -- CMtCoderBlock blocks[MTCODER__BLOCKS_MAX]; -- CMtCoderThread threads[MTCODER__THREADS_MAX]; -+ CMtCoderBlock blocks[MTCODER_BLOCKS_MAX]; -+ CMtCoderThread threads[MTCODER_THREADS_MAX]; - } CMtCoder; - - -diff --git a/src/lzma/MtDec.c b/src/lzma/MtDec.c -index b75e892fe..80c186950 100644 ---- a/src/lzma/MtDec.c -+++ b/src/lzma/MtDec.c -@@ -1,5 +1,5 @@ - /* MtDec.c -- Multi-thread Decoder --2021-12-21 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -14,7 +14,7 @@ - - #include "MtDec.h" - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - - #ifdef SHOW_DEBUG_INFO - #define PRF(x) x -@@ -24,7 +24,7 @@ - - #define PRF_STR_INT(s, d) PRF(printf("\n" s " %d\n", (unsigned)d)) - --void MtProgress_Init(CMtProgress *p, ICompressProgress *progress) -+void MtProgress_Init(CMtProgress *p, ICompressProgressPtr progress) - { - p->progress = progress; - p->res = SZ_OK; -@@ -81,36 +81,28 @@ void MtProgress_SetError(CMtProgress *p, SRes res) - #define RINOK_THREAD(x) RINOK_WRes(x) - - --static WRes ArEvent_OptCreate_And_Reset(CEvent *p) -+struct CMtDecBufLink_ - { -- if (Event_IsCreated(p)) -- return Event_Reset(p); -- return AutoResetEvent_CreateNotSignaled(p); --} -- -- --struct __CMtDecBufLink --{ -- struct __CMtDecBufLink *next; -+ struct CMtDecBufLink_ *next; - void *pad[3]; - }; - --typedef struct __CMtDecBufLink CMtDecBufLink; -+typedef struct CMtDecBufLink_ CMtDecBufLink; - - #define MTDEC__LINK_DATA_OFFSET sizeof(CMtDecBufLink) - #define MTDEC__DATA_PTR_FROM_LINK(link) ((Byte *)(link) + MTDEC__LINK_DATA_OFFSET) - - - --static THREAD_FUNC_DECL ThreadFunc(void *pp); -+static THREAD_FUNC_DECL MtDec_ThreadFunc(void *pp); - - - static WRes MtDecThread_CreateEvents(CMtDecThread *t) - { -- WRes wres = ArEvent_OptCreate_And_Reset(&t->canWrite); -+ WRes wres = AutoResetEvent_OptCreate_And_Reset(&t->canWrite); - if (wres == 0) - { -- wres = ArEvent_OptCreate_And_Reset(&t->canRead); -+ wres = AutoResetEvent_OptCreate_And_Reset(&t->canRead); - if (wres == 0) - return SZ_OK; - } -@@ -126,7 +118,7 @@ static SRes MtDecThread_CreateAndStart(CMtDecThread *t) - { - if (Thread_WasCreated(&t->thread)) - return SZ_OK; -- wres = Thread_Create(&t->thread, ThreadFunc, t); -+ wres = Thread_Create(&t->thread, MtDec_ThreadFunc, t); - if (wres == 0) - return SZ_OK; - } -@@ -167,7 +159,7 @@ static void MtDecThread_CloseThread(CMtDecThread *t) - static void MtDec_CloseThreads(CMtDec *p) - { - unsigned i; -- for (i = 0; i < MTDEC__THREADS_MAX; i++) -+ for (i = 0; i < MTDEC_THREADS_MAX; i++) - MtDecThread_CloseThread(&p->threads[i]); - } - -@@ -179,25 +171,6 @@ static void MtDecThread_Destruct(CMtDecThread *t) - - - --static SRes FullRead(ISeqInStream *stream, Byte *data, size_t *processedSize) --{ -- size_t size = *processedSize; -- *processedSize = 0; -- while (size != 0) -- { -- size_t cur = size; -- SRes res = ISeqInStream_Read(stream, data, &cur); -- *processedSize += cur; -- data += cur; -- size -= cur; -- RINOK(res); -- if (cur == 0) -- return SZ_OK; -- } -- return SZ_OK; --} -- -- - static SRes MtDec_GetError_Spec(CMtDec *p, UInt64 interruptIndex, BoolInt *wasInterrupted) - { - SRes res; -@@ -253,7 +226,7 @@ Byte *MtDec_GetCrossBuff(CMtDec *p) - - - /* -- ThreadFunc2() returns: -+ MtDec_ThreadFunc2() returns: - 0 - in all normal cases (even for stream error or memory allocation error) - (!= 0) - WRes error return by system threading function - */ -@@ -261,11 +234,11 @@ Byte *MtDec_GetCrossBuff(CMtDec *p) - // #define MTDEC_ProgessStep (1 << 22) - #define MTDEC_ProgessStep (1 << 0) - --static WRes ThreadFunc2(CMtDecThread *t) -+static WRes MtDec_ThreadFunc2(CMtDecThread *t) - { - CMtDec *p = t->mtDec; - -- PRF_STR_INT("ThreadFunc2", t->index); -+ PRF_STR_INT("MtDec_ThreadFunc2", t->index) - - // SetThreadAffinityMask(GetCurrentThread(), 1 << t->index); - -@@ -295,13 +268,13 @@ static WRes ThreadFunc2(CMtDecThread *t) - // CMtDecCallbackInfo parse; - CMtDecThread *nextThread; - -- PRF_STR_INT("=============== Event_Wait(&t->canRead)", t->index); -+ PRF_STR_INT("=============== Event_Wait(&t->canRead)", t->index) - -- RINOK_THREAD(Event_Wait(&t->canRead)); -+ RINOK_THREAD(Event_Wait(&t->canRead)) - if (p->exitThread) - return 0; - -- PRF_STR_INT("after Event_Wait(&t->canRead)", t->index); -+ PRF_STR_INT("after Event_Wait(&t->canRead)", t->index) - - // if (t->index == 3) return 19; // for test - -@@ -373,7 +346,7 @@ static WRes ThreadFunc2(CMtDecThread *t) - { - size = p->inBufSize; - -- res = FullRead(p->inStream, data, &size); -+ res = SeqInStream_ReadMax(p->inStream, data, &size); - - // size = 10; // test - -@@ -615,7 +588,7 @@ static WRes ThreadFunc2(CMtDecThread *t) - // if ( !finish ) we must call Event_Set(&nextThread->canWrite) in any case - // if ( finish ) we switch to single-thread mode and there are 2 ways at the end of current iteration (current block): - // - if (needContinue) after Write(&needContinue), we restore decoding with new iteration -- // - otherwise we stop decoding and exit from ThreadFunc2() -+ // - otherwise we stop decoding and exit from MtDec_ThreadFunc2() - - // Don't change (finish) variable in the further code - -@@ -688,7 +661,7 @@ static WRes ThreadFunc2(CMtDecThread *t) - - // ---------- WRITE ---------- - -- RINOK_THREAD(Event_Wait(&t->canWrite)); -+ RINOK_THREAD(Event_Wait(&t->canWrite)) - - { - BoolInt isErrorMode = False7z; -@@ -801,14 +774,14 @@ static WRes ThreadFunc2(CMtDecThread *t) - - if (!finish) - { -- RINOK_THREAD(Event_Set(&nextThread->canWrite)); -+ RINOK_THREAD(Event_Set(&nextThread->canWrite)) - } - else - { - if (needContinue) - { - // we restore decoding with new iteration -- RINOK_THREAD(Event_Set(&p->threads[0].canWrite)); -+ RINOK_THREAD(Event_Set(&p->threads[0].canWrite)) - } - else - { -@@ -817,7 +790,7 @@ static WRes ThreadFunc2(CMtDecThread *t) - return SZ_OK; - p->exitThread = True7z; - } -- RINOK_THREAD(Event_Set(&p->threads[0].canRead)); -+ RINOK_THREAD(Event_Set(&p->threads[0].canRead)) - } - } - } -@@ -836,7 +809,7 @@ static WRes ThreadFunc2(CMtDecThread *t) - #endif - - --static THREAD_FUNC_DECL ThreadFunc1(void *pp) -+static THREAD_FUNC_DECL MtDec_ThreadFunc1(void *pp) - { - WRes res; - -@@ -845,7 +818,7 @@ static THREAD_FUNC_DECL ThreadFunc1(void *pp) - - // fprintf(stdout, "\n%d = %p\n", t->index, &t); - -- res = ThreadFunc2(t); -+ res = MtDec_ThreadFunc2(t); - p = t->mtDec; - if (res == 0) - return (THREAD_FUNC_RET_TYPE)(UINT_PTR)p->exitThreadWRes; -@@ -862,14 +835,14 @@ static THREAD_FUNC_DECL ThreadFunc1(void *pp) - return (THREAD_FUNC_RET_TYPE)(UINT_PTR)res; - } - --static MY_NO_INLINE THREAD_FUNC_DECL ThreadFunc(void *pp) -+static Z7_NO_INLINE THREAD_FUNC_DECL MtDec_ThreadFunc(void *pp) - { - #ifdef USE_ALLOCA - CMtDecThread *t = (CMtDecThread *)pp; - // fprintf(stderr, "\n%d = %p - before", t->index, &t); - t->allocaPtr = alloca(t->index * 128); - #endif -- return ThreadFunc1(pp); -+ return MtDec_ThreadFunc1(pp); - } - - -@@ -883,7 +856,7 @@ int MtDec_PrepareRead(CMtDec *p) - - { - unsigned i; -- for (i = 0; i < MTDEC__THREADS_MAX; i++) -+ for (i = 0; i < MTDEC_THREADS_MAX; i++) - if (i > p->numStartedThreads - || p->numFilledThreads <= - (i >= p->filledThreadStart ? -@@ -987,7 +960,7 @@ void MtDec_Construct(CMtDec *p) - - p->allocatedBufsSize = 0; - -- for (i = 0; i < MTDEC__THREADS_MAX; i++) -+ for (i = 0; i < MTDEC_THREADS_MAX; i++) - { - CMtDecThread *t = &p->threads[i]; - t->mtDec = p; -@@ -995,7 +968,7 @@ void MtDec_Construct(CMtDec *p) - t->inBuf = NULL; - Event_Construct(&t->canRead); - Event_Construct(&t->canWrite); -- Thread_Construct(&t->thread); -+ Thread_CONSTRUCT(&t->thread) - } - - // Event_Construct(&p->finishedEvent); -@@ -1010,7 +983,7 @@ static void MtDec_Free(CMtDec *p) - - p->exitThread = True7z; - -- for (i = 0; i < MTDEC__THREADS_MAX; i++) -+ for (i = 0; i < MTDEC_THREADS_MAX; i++) - MtDecThread_Destruct(&p->threads[i]); - - // Event_Close(&p->finishedEvent); -@@ -1061,15 +1034,15 @@ SRes MtDec_Code(CMtDec *p) - - { - unsigned numThreads = p->numThreadsMax; -- if (numThreads > MTDEC__THREADS_MAX) -- numThreads = MTDEC__THREADS_MAX; -+ if (numThreads > MTDEC_THREADS_MAX) -+ numThreads = MTDEC_THREADS_MAX; - p->numStartedThreads_Limit = numThreads; - p->numStartedThreads = 0; - } - - if (p->inBufSize != p->allocatedBufsSize) - { -- for (i = 0; i < MTDEC__THREADS_MAX; i++) -+ for (i = 0; i < MTDEC_THREADS_MAX; i++) - { - CMtDecThread *t = &p->threads[i]; - if (t->inBuf) -@@ -1086,7 +1059,7 @@ SRes MtDec_Code(CMtDec *p) - - MtProgress_Init(&p->mtProgress, p->progress); - -- // RINOK_THREAD(ArEvent_OptCreate_And_Reset(&p->finishedEvent)); -+ // RINOK_THREAD(AutoResetEvent_OptCreate_And_Reset(&p->finishedEvent)) - p->exitThread = False7z; - p->exitThreadWRes = 0; - -@@ -1098,7 +1071,7 @@ SRes MtDec_Code(CMtDec *p) - wres = MtDecThread_CreateEvents(nextThread); - if (wres == 0) { wres = Event_Set(&nextThread->canWrite); - if (wres == 0) { wres = Event_Set(&nextThread->canRead); -- if (wres == 0) { THREAD_FUNC_RET_TYPE res = ThreadFunc(nextThread); -+ if (wres == 0) { THREAD_FUNC_RET_TYPE res = MtDec_ThreadFunc(nextThread); - wres = (WRes)(UINT_PTR)res; - if (wres != 0) - { -@@ -1137,3 +1110,5 @@ SRes MtDec_Code(CMtDec *p) - } - - #endif -+ -+#undef PRF -diff --git a/src/lzma/MtDec.h b/src/lzma/MtDec.h -index c2da46ae2..c28e8d9ac 100644 ---- a/src/lzma/MtDec.h -+++ b/src/lzma/MtDec.h -@@ -1,46 +1,46 @@ - /* MtDec.h -- Multi-thread Decoder --2020-03-05 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - --#ifndef __MT_DEC_H --#define __MT_DEC_H -+#ifndef ZIP7_INC_MT_DEC_H -+#define ZIP7_INC_MT_DEC_H - - #include "7zTypes.h" - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - #include "Threads.h" - #endif - - EXTERN_C_BEGIN - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - --#ifndef _7ZIP_ST -- #define MTDEC__THREADS_MAX 32 -+#ifndef Z7_ST -+ #define MTDEC_THREADS_MAX 32 - #else -- #define MTDEC__THREADS_MAX 1 -+ #define MTDEC_THREADS_MAX 1 - #endif - - - typedef struct - { -- ICompressProgress *progress; -+ ICompressProgressPtr progress; - SRes res; - UInt64 totalInSize; - UInt64 totalOutSize; - CCriticalSection cs; - } CMtProgress; - --void MtProgress_Init(CMtProgress *p, ICompressProgress *progress); -+void MtProgress_Init(CMtProgress *p, ICompressProgressPtr progress); - SRes MtProgress_Progress_ST(CMtProgress *p); - SRes MtProgress_ProgressAdd(CMtProgress *p, UInt64 inSize, UInt64 outSize); - SRes MtProgress_GetError(CMtProgress *p); - void MtProgress_SetError(CMtProgress *p, SRes res); - --struct _CMtDec; -+struct CMtDec; - - typedef struct - { -- struct _CMtDec *mtDec; -+ struct CMtDec_ *mtDec; - unsigned index; - void *inBuf; - -@@ -117,7 +117,7 @@ typedef struct - - - --typedef struct _CMtDec -+typedef struct CMtDec_ - { - /* input variables */ - -@@ -126,11 +126,11 @@ typedef struct _CMtDec - // size_t inBlockMax; - unsigned numThreadsMax_2; - -- ISeqInStream *inStream; -+ ISeqInStreamPtr inStream; - // const Byte *inData; - // size_t inDataSize; - -- ICompressProgress *progress; -+ ICompressProgressPtr progress; - ISzAllocPtr alloc; - - IMtDecCallback2 *mtCallback; -@@ -171,11 +171,11 @@ typedef struct _CMtDec - unsigned filledThreadStart; - unsigned numFilledThreads; - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - BoolInt needInterrupt; - UInt64 interruptIndex; - CMtProgress mtProgress; -- CMtDecThread threads[MTDEC__THREADS_MAX]; -+ CMtDecThread threads[MTDEC_THREADS_MAX]; - #endif - } CMtDec; - -diff --git a/src/lzma/Ppmd.h b/src/lzma/Ppmd.h -index b19879208..66b26266f 100644 ---- a/src/lzma/Ppmd.h -+++ b/src/lzma/Ppmd.h -@@ -1,9 +1,9 @@ - /* Ppmd.h -- PPMD codec common code --2021-04-13 : Igor Pavlov : Public domain -+2023-03-05 : Igor Pavlov : Public domain - This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */ - --#ifndef __PPMD_H --#define __PPMD_H -+#ifndef ZIP7_INC_PPMD_H -+#define ZIP7_INC_PPMD_H - - #include "CpuArch.h" - -@@ -48,8 +48,10 @@ typedef struct - Byte Count; /* Count to next change of Shift */ - } CPpmd_See; - --#define Ppmd_See_Update(p) if ((p)->Shift < PPMD_PERIOD_BITS && --(p)->Count == 0) \ -- { (p)->Summ = (UInt16)((p)->Summ << 1); (p)->Count = (Byte)(3 << (p)->Shift++); } -+#define Ppmd_See_UPDATE(p) \ -+ { if ((p)->Shift < PPMD_PERIOD_BITS && --(p)->Count == 0) \ -+ { (p)->Summ = (UInt16)((p)->Summ << 1); \ -+ (p)->Count = (Byte)(3 << (p)->Shift++); }} - - - typedef struct -diff --git a/src/lzma/Ppmd7.c b/src/lzma/Ppmd7.c -index e5c6114af..5d32607fc 100644 ---- a/src/lzma/Ppmd7.c -+++ b/src/lzma/Ppmd7.c -@@ -1,5 +1,5 @@ - /* Ppmd7.c -- PPMdH codec --2021-04-13 : Igor Pavlov : Public domain -+2023-04-02 : Igor Pavlov : Public domain - This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */ - - #include "Precomp.h" -@@ -14,7 +14,7 @@ This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */ - MY_ALIGN(16) - static const Byte PPMD7_kExpEscape[16] = { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 }; - MY_ALIGN(16) --static const UInt16 kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051}; -+static const UInt16 PPMD7_kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051}; - - #define MAX_FREQ 124 - #define UNIT_SIZE 12 -@@ -33,7 +33,7 @@ static const UInt16 kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x - #define ONE_STATE(ctx) Ppmd7Context_OneState(ctx) - #define SUFFIX(ctx) CTX((ctx)->Suffix) - --typedef CPpmd7_Context * CTX_PTR; -+typedef CPpmd7_Context * PPMD7_CTX_PTR; - - struct CPpmd7_Node_; - -@@ -107,14 +107,14 @@ BoolInt Ppmd7_Alloc(CPpmd7 *p, UInt32 size, ISzAllocPtr alloc) - // ---------- Internal Memory Allocator ---------- - - /* We can use CPpmd7_Node in list of free units (as in Ppmd8) -- But we still need one additional list walk pass in GlueFreeBlocks(). -- So we use simple CPpmd_Void_Ref instead of CPpmd7_Node in InsertNode() / RemoveNode() -+ But we still need one additional list walk pass in Ppmd7_GlueFreeBlocks(). -+ So we use simple CPpmd_Void_Ref instead of CPpmd7_Node in Ppmd7_InsertNode() / Ppmd7_RemoveNode() - */ - - #define EMPTY_NODE 0 - - --static void InsertNode(CPpmd7 *p, void *node, unsigned indx) -+static void Ppmd7_InsertNode(CPpmd7 *p, void *node, unsigned indx) - { - *((CPpmd_Void_Ref *)node) = p->FreeList[indx]; - // ((CPpmd7_Node *)node)->Next = (CPpmd7_Node_Ref)p->FreeList[indx]; -@@ -124,7 +124,7 @@ static void InsertNode(CPpmd7 *p, void *node, unsigned indx) - } - - --static void *RemoveNode(CPpmd7 *p, unsigned indx) -+static void *Ppmd7_RemoveNode(CPpmd7 *p, unsigned indx) - { - CPpmd_Void_Ref *node = (CPpmd_Void_Ref *)Ppmd7_GetPtr(p, p->FreeList[indx]); - p->FreeList[indx] = *node; -@@ -134,32 +134,32 @@ static void *RemoveNode(CPpmd7 *p, unsigned indx) - } - - --static void SplitBlock(CPpmd7 *p, void *ptr, unsigned oldIndx, unsigned newIndx) -+static void Ppmd7_SplitBlock(CPpmd7 *p, void *ptr, unsigned oldIndx, unsigned newIndx) - { - unsigned i, nu = I2U(oldIndx) - I2U(newIndx); - ptr = (Byte *)ptr + U2B(I2U(newIndx)); - if (I2U(i = U2I(nu)) != nu) - { - unsigned k = I2U(--i); -- InsertNode(p, ((Byte *)ptr) + U2B(k), nu - k - 1); -+ Ppmd7_InsertNode(p, ((Byte *)ptr) + U2B(k), nu - k - 1); - } -- InsertNode(p, ptr, i); -+ Ppmd7_InsertNode(p, ptr, i); - } - - - /* we use CPpmd7_Node_Union union to solve XLC -O2 strict pointer aliasing problem */ - --typedef union _CPpmd7_Node_Union -+typedef union - { - CPpmd7_Node Node; - CPpmd7_Node_Ref NextRef; - } CPpmd7_Node_Union; - --/* Original PPmdH (Ppmd7) code uses doubly linked list in GlueFreeBlocks() -+/* Original PPmdH (Ppmd7) code uses doubly linked list in Ppmd7_GlueFreeBlocks() - we use single linked list similar to Ppmd8 code */ - - --static void GlueFreeBlocks(CPpmd7 *p) -+static void Ppmd7_GlueFreeBlocks(CPpmd7 *p) - { - /* - we use first UInt16 field of 12-bytes UNITs as record type stamp -@@ -239,27 +239,27 @@ static void GlueFreeBlocks(CPpmd7 *p) - if (nu == 0) - continue; - for (; nu > 128; nu -= 128, node += 128) -- InsertNode(p, node, PPMD_NUM_INDEXES - 1); -+ Ppmd7_InsertNode(p, node, PPMD_NUM_INDEXES - 1); - if (I2U(i = U2I(nu)) != nu) - { - unsigned k = I2U(--i); -- InsertNode(p, node + k, (unsigned)nu - k - 1); -+ Ppmd7_InsertNode(p, node + k, (unsigned)nu - k - 1); - } -- InsertNode(p, node, i); -+ Ppmd7_InsertNode(p, node, i); - } - } - - --MY_NO_INLINE --static void *AllocUnitsRare(CPpmd7 *p, unsigned indx) -+Z7_NO_INLINE -+static void *Ppmd7_AllocUnitsRare(CPpmd7 *p, unsigned indx) - { - unsigned i; - - if (p->GlueCount == 0) - { -- GlueFreeBlocks(p); -+ Ppmd7_GlueFreeBlocks(p); - if (p->FreeList[indx] != 0) -- return RemoveNode(p, indx); -+ return Ppmd7_RemoveNode(p, indx); - } - - i = indx; -@@ -277,17 +277,17 @@ static void *AllocUnitsRare(CPpmd7 *p, unsigned indx) - while (p->FreeList[i] == 0); - - { -- void *block = RemoveNode(p, i); -- SplitBlock(p, block, i, indx); -+ void *block = Ppmd7_RemoveNode(p, i); -+ Ppmd7_SplitBlock(p, block, i, indx); - return block; - } - } - - --static void *AllocUnits(CPpmd7 *p, unsigned indx) -+static void *Ppmd7_AllocUnits(CPpmd7 *p, unsigned indx) - { - if (p->FreeList[indx] != 0) -- return RemoveNode(p, indx); -+ return Ppmd7_RemoveNode(p, indx); - { - UInt32 numBytes = U2B(I2U(indx)); - Byte *lo = p->LoUnit; -@@ -297,11 +297,11 @@ static void *AllocUnits(CPpmd7 *p, unsigned indx) - return lo; - } - } -- return AllocUnitsRare(p, indx); -+ return Ppmd7_AllocUnitsRare(p, indx); - } - - --#define MyMem12Cpy(dest, src, num) \ -+#define MEM_12_CPY(dest, src, num) \ - { UInt32 *d = (UInt32 *)dest; const UInt32 *z = (const UInt32 *)src; UInt32 n = num; \ - do { d[0] = z[0]; d[1] = z[1]; d[2] = z[2]; z += 3; d += 3; } while (--n); } - -@@ -315,12 +315,12 @@ static void *ShrinkUnits(CPpmd7 *p, void *oldPtr, unsigned oldNU, unsigned newNU - return oldPtr; - if (p->FreeList[i1] != 0) - { -- void *ptr = RemoveNode(p, i1); -- MyMem12Cpy(ptr, oldPtr, newNU); -- InsertNode(p, oldPtr, i0); -+ void *ptr = Ppmd7_RemoveNode(p, i1); -+ MEM_12_CPY(ptr, oldPtr, newNU) -+ Ppmd7_InsertNode(p, oldPtr, i0); - return ptr; - } -- SplitBlock(p, oldPtr, i0, i1); -+ Ppmd7_SplitBlock(p, oldPtr, i0, i1); - return oldPtr; - } - */ -@@ -329,14 +329,14 @@ static void *ShrinkUnits(CPpmd7 *p, void *oldPtr, unsigned oldNU, unsigned newNU - #define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) - static void SetSuccessor(CPpmd_State *p, CPpmd_Void_Ref v) - { -- Ppmd_SET_SUCCESSOR(p, v); -+ Ppmd_SET_SUCCESSOR(p, v) - } - - - --MY_NO_INLINE -+Z7_NO_INLINE - static --void RestartModel(CPpmd7 *p) -+void Ppmd7_RestartModel(CPpmd7 *p) - { - unsigned i, k; - -@@ -352,8 +352,8 @@ void RestartModel(CPpmd7 *p) - p->PrevSuccess = 0; - - { -- CPpmd7_Context *mc = (CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */ -- CPpmd_State *s = (CPpmd_State *)p->LoUnit; /* AllocUnits(p, PPMD_NUM_INDEXES - 1); */ -+ CPpmd7_Context *mc = (PPMD7_CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */ -+ CPpmd_State *s = (CPpmd_State *)p->LoUnit; /* Ppmd7_AllocUnits(p, PPMD_NUM_INDEXES - 1); */ - - p->LoUnit += U2B(256 / 2); - p->MaxContext = p->MinContext = mc; -@@ -391,7 +391,7 @@ void RestartModel(CPpmd7 *p) - { - unsigned m; - UInt16 *dest = p->BinSumm[i] + k; -- UInt16 val = (UInt16)(PPMD_BIN_SCALE - kInitBinEsc[k] / (i + 2)); -+ const UInt16 val = (UInt16)(PPMD_BIN_SCALE - PPMD7_kInitBinEsc[k] / (i + 2)); - for (m = 0; m < 64; m += 8) - dest[m] = val; - } -@@ -423,13 +423,13 @@ void Ppmd7_Init(CPpmd7 *p, unsigned maxOrder) - { - p->MaxOrder = maxOrder; - -- RestartModel(p); -+ Ppmd7_RestartModel(p); - } - - - - /* -- CreateSuccessors() -+ Ppmd7_CreateSuccessors() - It's called when (FoundState->Successor) is RAW-Successor, - that is the link to position in Raw text. - So we create Context records and write the links to -@@ -445,10 +445,10 @@ void Ppmd7_Init(CPpmd7 *p, unsigned maxOrder) - also it can return pointer to real context of same order, - */ - --MY_NO_INLINE --static CTX_PTR CreateSuccessors(CPpmd7 *p) -+Z7_NO_INLINE -+static PPMD7_CTX_PTR Ppmd7_CreateSuccessors(CPpmd7 *p) - { -- CTX_PTR c = p->MinContext; -+ PPMD7_CTX_PTR c = p->MinContext; - CPpmd_Byte_Ref upBranch = (CPpmd_Byte_Ref)SUCCESSOR(p->FoundState); - Byte newSym, newFreq; - unsigned numPs = 0; -@@ -522,15 +522,15 @@ static CTX_PTR CreateSuccessors(CPpmd7 *p) - - do - { -- CTX_PTR c1; -+ PPMD7_CTX_PTR c1; - /* = AllocContext(p); */ - if (p->HiUnit != p->LoUnit) -- c1 = (CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); -+ c1 = (PPMD7_CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); - else if (p->FreeList[0] != 0) -- c1 = (CTX_PTR)RemoveNode(p, 0); -+ c1 = (PPMD7_CTX_PTR)Ppmd7_RemoveNode(p, 0); - else - { -- c1 = (CTX_PTR)AllocUnitsRare(p, 0); -+ c1 = (PPMD7_CTX_PTR)Ppmd7_AllocUnitsRare(p, 0); - if (!c1) - return NULL; - } -@@ -550,16 +550,16 @@ static CTX_PTR CreateSuccessors(CPpmd7 *p) - - - --#define SwapStates(s) \ -+#define SWAP_STATES(s) \ - { CPpmd_State tmp = s[0]; s[0] = s[-1]; s[-1] = tmp; } - - - void Ppmd7_UpdateModel(CPpmd7 *p); --MY_NO_INLINE -+Z7_NO_INLINE - void Ppmd7_UpdateModel(CPpmd7 *p) - { - CPpmd_Void_Ref maxSuccessor, minSuccessor; -- CTX_PTR c, mc; -+ PPMD7_CTX_PTR c, mc; - unsigned s0, ns; - - -@@ -592,7 +592,7 @@ void Ppmd7_UpdateModel(CPpmd7 *p) - - if (s[0].Freq >= s[-1].Freq) - { -- SwapStates(s); -+ SWAP_STATES(s) - s--; - } - } -@@ -610,10 +610,10 @@ void Ppmd7_UpdateModel(CPpmd7 *p) - { - /* MAX ORDER context */ - /* (FoundState->Successor) is RAW-Successor. */ -- p->MaxContext = p->MinContext = CreateSuccessors(p); -+ p->MaxContext = p->MinContext = Ppmd7_CreateSuccessors(p); - if (!p->MinContext) - { -- RestartModel(p); -+ Ppmd7_RestartModel(p); - return; - } - SetSuccessor(p->FoundState, REF(p->MinContext)); -@@ -629,7 +629,7 @@ void Ppmd7_UpdateModel(CPpmd7 *p) - p->Text = text; - if (text >= p->UnitsStart) - { -- RestartModel(p); -+ Ppmd7_RestartModel(p); - return; - } - maxSuccessor = REF(text); -@@ -645,10 +645,10 @@ void Ppmd7_UpdateModel(CPpmd7 *p) - if (minSuccessor <= maxSuccessor) - { - // minSuccessor is RAW-Successor. So we will create real contexts records: -- CTX_PTR cs = CreateSuccessors(p); -+ PPMD7_CTX_PTR cs = Ppmd7_CreateSuccessors(p); - if (!cs) - { -- RestartModel(p); -+ Ppmd7_RestartModel(p); - return; - } - minSuccessor = REF(cs); -@@ -715,16 +715,16 @@ void Ppmd7_UpdateModel(CPpmd7 *p) - unsigned i = U2I(oldNU); - if (i != U2I((size_t)oldNU + 1)) - { -- void *ptr = AllocUnits(p, i + 1); -+ void *ptr = Ppmd7_AllocUnits(p, i + 1); - void *oldPtr; - if (!ptr) - { -- RestartModel(p); -+ Ppmd7_RestartModel(p); - return; - } - oldPtr = STATS(c); -- MyMem12Cpy(ptr, oldPtr, oldNU); -- InsertNode(p, oldPtr, i); -+ MEM_12_CPY(ptr, oldPtr, oldNU) -+ Ppmd7_InsertNode(p, oldPtr, i); - c->Union4.Stats = STATS_REF(ptr); - } - } -@@ -739,10 +739,10 @@ void Ppmd7_UpdateModel(CPpmd7 *p) - else - { - // instead of One-symbol context we create 2-symbol context -- CPpmd_State *s = (CPpmd_State*)AllocUnits(p, 0); -+ CPpmd_State *s = (CPpmd_State*)Ppmd7_AllocUnits(p, 0); - if (!s) - { -- RestartModel(p); -+ Ppmd7_RestartModel(p); - return; - } - { -@@ -795,8 +795,8 @@ void Ppmd7_UpdateModel(CPpmd7 *p) - - - --MY_NO_INLINE --static void Rescale(CPpmd7 *p) -+Z7_NO_INLINE -+static void Ppmd7_Rescale(CPpmd7 *p) - { - unsigned i, adder, sumFreq, escFreq; - CPpmd_State *stats = STATS(p->MinContext); -@@ -885,7 +885,7 @@ static void Rescale(CPpmd7 *p) - *s = *stats; - s->Freq = (Byte)freq; // (freq <= 260 / 4) - p->FoundState = s; -- InsertNode(p, stats, U2I(n0)); -+ Ppmd7_InsertNode(p, stats, U2I(n0)); - return; - } - -@@ -899,13 +899,13 @@ static void Rescale(CPpmd7 *p) - { - if (p->FreeList[i1] != 0) - { -- void *ptr = RemoveNode(p, i1); -+ void *ptr = Ppmd7_RemoveNode(p, i1); - p->MinContext->Union4.Stats = STATS_REF(ptr); -- MyMem12Cpy(ptr, (const void *)stats, n1); -- InsertNode(p, stats, i0); -+ MEM_12_CPY(ptr, (const void *)stats, n1) -+ Ppmd7_InsertNode(p, stats, i0); - } - else -- SplitBlock(p, stats, i0, i1); -+ Ppmd7_SplitBlock(p, stats, i0, i1); - } - } - } -@@ -948,9 +948,9 @@ CPpmd_See *Ppmd7_MakeEscFreq(CPpmd7 *p, unsigned numMasked, UInt32 *escFreq) - } - - --static void NextContext(CPpmd7 *p) -+static void Ppmd7_NextContext(CPpmd7 *p) - { -- CTX_PTR c = CTX(SUCCESSOR(p->FoundState)); -+ PPMD7_CTX_PTR c = CTX(SUCCESSOR(p->FoundState)); - if (p->OrderFall == 0 && (const Byte *)c > p->Text) - p->MaxContext = p->MinContext = c; - else -@@ -967,12 +967,12 @@ void Ppmd7_Update1(CPpmd7 *p) - s->Freq = (Byte)freq; - if (freq > s[-1].Freq) - { -- SwapStates(s); -+ SWAP_STATES(s) - p->FoundState = --s; - if (freq > MAX_FREQ) -- Rescale(p); -+ Ppmd7_Rescale(p); - } -- NextContext(p); -+ Ppmd7_NextContext(p); - } - - -@@ -988,8 +988,8 @@ void Ppmd7_Update1_0(CPpmd7 *p) - freq += 4; - s->Freq = (Byte)freq; - if (freq > MAX_FREQ) -- Rescale(p); -- NextContext(p); -+ Ppmd7_Rescale(p); -+ Ppmd7_NextContext(p); - } - - -@@ -1000,7 +1000,7 @@ void Ppmd7_UpdateBin(CPpmd7 *p) - p->FoundState->Freq = (Byte)(freq + (freq < 128)); - p->PrevSuccess = 1; - p->RunLength++; -- NextContext(p); -+ Ppmd7_NextContext(p); - } - */ - -@@ -1013,7 +1013,7 @@ void Ppmd7_Update2(CPpmd7 *p) - p->MinContext->Union2.SummFreq = (UInt16)(p->MinContext->Union2.SummFreq + 4); - s->Freq = (Byte)freq; - if (freq > MAX_FREQ) -- Rescale(p); -+ Ppmd7_Rescale(p); - Ppmd7_UpdateModel(p); - } - -@@ -1042,8 +1042,8 @@ Last UNIT of array at offset (Size - 12) is root order-0 CPpmd7_Context record. - The code can free UNITs memory blocks that were allocated to store CPpmd_State vectors. - The code doesn't free UNITs allocated for CPpmd7_Context records. - --The code calls RestartModel(), when there is no free memory for allocation. --And RestartModel() changes the state to orignal start state, with full free block. -+The code calls Ppmd7_RestartModel(), when there is no free memory for allocation. -+And Ppmd7_RestartModel() changes the state to orignal start state, with full free block. - - - The code allocates UNITs with the following order: -@@ -1051,14 +1051,14 @@ The code allocates UNITs with the following order: - Allocation of 1 UNIT for Context record - - from free space (HiUnit) down to (LoUnit) - - from FreeList[0] -- - AllocUnitsRare() -+ - Ppmd7_AllocUnitsRare() - --AllocUnits() for CPpmd_State vectors: -+Ppmd7_AllocUnits() for CPpmd_State vectors: - - from FreeList[i] - - from free space (LoUnit) up to (HiUnit) -- - AllocUnitsRare() -+ - Ppmd7_AllocUnitsRare() - --AllocUnitsRare() -+Ppmd7_AllocUnitsRare() - - if (GlueCount == 0) - { Glue lists, GlueCount = 255, allocate from FreeList[i]] } - - loop for all higher sized FreeList[...] lists -@@ -1093,8 +1093,8 @@ The PPMd code tries to fulfill the condition: - We have (Sum(Stats[].Freq) <= 256 * 124), because of (MAX_FREQ = 124) - So (4 = 128 - 124) is average reserve for Escape_Freq for each symbol. - If (CPpmd_State::Freq) is not aligned for 4, the reserve can be 5, 6 or 7. --SummFreq and Escape_Freq can be changed in Rescale() and *Update*() functions. --Rescale() can remove symbols only from max-order contexts. So Escape_Freq can increase after multiple calls of Rescale() for -+SummFreq and Escape_Freq can be changed in Ppmd7_Rescale() and *Update*() functions. -+Ppmd7_Rescale() can remove symbols only from max-order contexts. So Escape_Freq can increase after multiple calls of Ppmd7_Rescale() for - max-order context. - - When the PPMd code still break (Total <= RC::Range) condition in range coder, -@@ -1102,3 +1102,21 @@ we have two ways to resolve that problem: - 1) we can report error, if we want to keep compatibility with original PPMd code that has no fix for such cases. - 2) we can reduce (Total) value to (RC::Range) by reducing (Escape_Freq) part of (Total) value. - */ -+ -+#undef MAX_FREQ -+#undef UNIT_SIZE -+#undef U2B -+#undef U2I -+#undef I2U -+#undef I2U_UInt16 -+#undef REF -+#undef STATS_REF -+#undef CTX -+#undef STATS -+#undef ONE_STATE -+#undef SUFFIX -+#undef NODE -+#undef EMPTY_NODE -+#undef MEM_12_CPY -+#undef SUCCESSOR -+#undef SWAP_STATES -diff --git a/src/lzma/Ppmd7.h b/src/lzma/Ppmd7.h -index d31809aeb..d9eb326d6 100644 ---- a/src/lzma/Ppmd7.h -+++ b/src/lzma/Ppmd7.h -@@ -1,11 +1,11 @@ - /* Ppmd7.h -- Ppmd7 (PPMdH) compression codec --2021-04-13 : Igor Pavlov : Public domain -+2023-04-02 : Igor Pavlov : Public domain - This code is based on: - PPMd var.H (2001): Dmitry Shkarin : Public domain */ - - --#ifndef __PPMD7_H --#define __PPMD7_H -+#ifndef ZIP7_INC_PPMD7_H -+#define ZIP7_INC_PPMD7_H - - #include "Ppmd.h" - -@@ -55,7 +55,7 @@ typedef struct - UInt32 Range; - UInt32 Code; - UInt32 Low; -- IByteIn *Stream; -+ IByteInPtr Stream; - } CPpmd7_RangeDec; - - -@@ -66,7 +66,7 @@ typedef struct - // Byte _dummy_[3]; - UInt64 Low; - UInt64 CacheSize; -- IByteOut *Stream; -+ IByteOutPtr Stream; - } CPpmd7z_RangeEnc; - - -diff --git a/src/lzma/Ppmd7Dec.c b/src/lzma/Ppmd7Dec.c -index f446a315c..7d2e55643 100644 ---- a/src/lzma/Ppmd7Dec.c -+++ b/src/lzma/Ppmd7Dec.c -@@ -1,5 +1,5 @@ - /* Ppmd7Dec.c -- Ppmd7z (PPMdH with 7z Range Coder) Decoder --2021-04-13 : Igor Pavlov : Public domain -+2023-04-02 : Igor Pavlov : Public domain - This code is based on: - PPMd var.H (2001): Dmitry Shkarin : Public domain */ - -@@ -8,7 +8,7 @@ This code is based on: - - #include "Ppmd7.h" - --#define kTopValue (1 << 24) -+#define kTopValue ((UInt32)1 << 24) - - - #define READ_BYTE(p) IByteIn_Read((p)->Stream) -@@ -37,9 +37,9 @@ BoolInt Ppmd7z_RangeDec_Init(CPpmd7_RangeDec *p) - - #define R (&p->rc.dec) - --MY_FORCE_INLINE --// MY_NO_INLINE --static void RangeDec_Decode(CPpmd7 *p, UInt32 start, UInt32 size) -+Z7_FORCE_INLINE -+// Z7_NO_INLINE -+static void Ppmd7z_RD_Decode(CPpmd7 *p, UInt32 start, UInt32 size) - { - - -@@ -48,18 +48,18 @@ static void RangeDec_Decode(CPpmd7 *p, UInt32 start, UInt32 size) - RC_NORM_LOCAL(R) - } - --#define RC_Decode(start, size) RangeDec_Decode(p, start, size); --#define RC_DecodeFinal(start, size) RC_Decode(start, size) RC_NORM_REMOTE(R) --#define RC_GetThreshold(total) (R->Code / (R->Range /= (total))) -+#define RC_Decode(start, size) Ppmd7z_RD_Decode(p, start, size); -+#define RC_DecodeFinal(start, size) RC_Decode(start, size) RC_NORM_REMOTE(R) -+#define RC_GetThreshold(total) (R->Code / (R->Range /= (total))) - - - #define CTX(ref) ((CPpmd7_Context *)Ppmd7_GetContext(p, ref)) --typedef CPpmd7_Context * CTX_PTR; -+// typedef CPpmd7_Context * CTX_PTR; - #define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) - void Ppmd7_UpdateModel(CPpmd7 *p); - - #define MASK(sym) ((unsigned char *)charMask)[sym] --// MY_FORCE_INLINE -+// Z7_FORCE_INLINE - // static - int Ppmd7z_DecodeSymbol(CPpmd7 *p) - { -@@ -70,7 +70,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) - CPpmd_State *s = Ppmd7_GetStats(p, p->MinContext); - unsigned i; - UInt32 count, hiCnt; -- UInt32 summFreq = p->MinContext->Union2.SummFreq; -+ const UInt32 summFreq = p->MinContext->Union2.SummFreq; - - - -@@ -81,7 +81,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) - if ((Int32)(count -= s->Freq) < 0) - { - Byte sym; -- RC_DecodeFinal(0, s->Freq); -+ RC_DecodeFinal(0, s->Freq) - p->FoundState = s; - sym = s->Symbol; - Ppmd7_Update1_0(p); -@@ -96,7 +96,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) - if ((Int32)(count -= (++s)->Freq) < 0) - { - Byte sym; -- RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq); -+ RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq) - p->FoundState = s; - sym = s->Symbol; - Ppmd7_Update1(p); -@@ -109,10 +109,10 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) - return PPMD7_SYM_ERROR; - - hiCnt -= count; -- RC_Decode(hiCnt, summFreq - hiCnt); -+ RC_Decode(hiCnt, summFreq - hiCnt) - - p->HiBitsFlag = PPMD7_HiBitsFlag_3(p->FoundState->Symbol); -- PPMD_SetAllBitsIn256Bytes(charMask); -+ PPMD_SetAllBitsIn256Bytes(charMask) - // i = p->MinContext->NumStats - 1; - // do { MASK((--s)->Symbol) = 0; } while (--i); - { -@@ -152,7 +152,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) - // Ppmd7_UpdateBin(p); - { - unsigned freq = s->Freq; -- CTX_PTR c = CTX(SUCCESSOR(s)); -+ CPpmd7_Context *c = CTX(SUCCESSOR(s)); - sym = s->Symbol; - p->FoundState = s; - p->PrevSuccess = 1; -@@ -176,7 +176,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) - R->Range -= size0; - RC_NORM_LOCAL(R) - -- PPMD_SetAllBitsIn256Bytes(charMask); -+ PPMD_SetAllBitsIn256Bytes(charMask) - MASK(Ppmd7Context_OneState(p->MinContext)->Symbol) = 0; - p->PrevSuccess = 0; - } -@@ -245,13 +245,13 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) - { - count -= s->Freq & (unsigned)(MASK((s)->Symbol)); s++; if ((Int32)count < 0) break; - // count -= s->Freq & (unsigned)(MASK((s)->Symbol)); s++; if ((Int32)count < 0) break; -- }; -+ } - } - s--; -- RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq); -+ RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq) - - // new (see->Summ) value can overflow over 16-bits in some rare cases -- Ppmd_See_Update(see); -+ Ppmd_See_UPDATE(see) - p->FoundState = s; - sym = s->Symbol; - Ppmd7_Update2(p); -@@ -261,7 +261,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) - if (count >= freqSum) - return PPMD7_SYM_ERROR; - -- RC_Decode(hiCnt, freqSum - hiCnt); -+ RC_Decode(hiCnt, freqSum - hiCnt) - - // We increase (see->Summ) for sum of Freqs of all non_Masked symbols. - // new (see->Summ) value can overflow over 16-bits in some rare cases -@@ -295,3 +295,18 @@ Byte *Ppmd7z_DecodeSymbols(CPpmd7 *p, Byte *buf, const Byte *lim) - return buf; - } - */ -+ -+#undef kTopValue -+#undef READ_BYTE -+#undef RC_NORM_BASE -+#undef RC_NORM_1 -+#undef RC_NORM -+#undef RC_NORM_LOCAL -+#undef RC_NORM_REMOTE -+#undef R -+#undef RC_Decode -+#undef RC_DecodeFinal -+#undef RC_GetThreshold -+#undef CTX -+#undef SUCCESSOR -+#undef MASK -diff --git a/src/lzma/Ppmd7Enc.c b/src/lzma/Ppmd7Enc.c -index 62139c5b6..41106bab4 100644 ---- a/src/lzma/Ppmd7Enc.c -+++ b/src/lzma/Ppmd7Enc.c -@@ -1,5 +1,5 @@ - /* Ppmd7Enc.c -- Ppmd7z (PPMdH with 7z Range Coder) Encoder --2021-04-13 : Igor Pavlov : Public domain -+2023-04-02 : Igor Pavlov : Public domain - This code is based on: - PPMd var.H (2001): Dmitry Shkarin : Public domain */ - -@@ -8,7 +8,7 @@ This code is based on: - - #include "Ppmd7.h" - --#define kTopValue (1 << 24) -+#define kTopValue ((UInt32)1 << 24) - - #define R (&p->rc.enc) - -@@ -20,8 +20,8 @@ void Ppmd7z_Init_RangeEnc(CPpmd7 *p) - R->CacheSize = 1; - } - --MY_NO_INLINE --static void RangeEnc_ShiftLow(CPpmd7 *p) -+Z7_NO_INLINE -+static void Ppmd7z_RangeEnc_ShiftLow(CPpmd7 *p) - { - if ((UInt32)R->Low < (UInt32)0xFF000000 || (unsigned)(R->Low >> 32) != 0) - { -@@ -38,53 +38,53 @@ static void RangeEnc_ShiftLow(CPpmd7 *p) - R->Low = (UInt32)((UInt32)R->Low << 8); - } - --#define RC_NORM_BASE(p) if (R->Range < kTopValue) { R->Range <<= 8; RangeEnc_ShiftLow(p); --#define RC_NORM_1(p) RC_NORM_BASE(p) } --#define RC_NORM(p) RC_NORM_BASE(p) RC_NORM_BASE(p) }} -+#define RC_NORM_BASE(p) if (R->Range < kTopValue) { R->Range <<= 8; Ppmd7z_RangeEnc_ShiftLow(p); -+#define RC_NORM_1(p) RC_NORM_BASE(p) } -+#define RC_NORM(p) RC_NORM_BASE(p) RC_NORM_BASE(p) }} - - // we must use only one type of Normalization from two: LOCAL or REMOTE - #define RC_NORM_LOCAL(p) // RC_NORM(p) - #define RC_NORM_REMOTE(p) RC_NORM(p) - - /* --#define RangeEnc_Encode(p, start, _size_) \ -+#define Ppmd7z_RangeEnc_Encode(p, start, _size_) \ - { UInt32 size = _size_; \ - R->Low += start * R->Range; \ - R->Range *= size; \ - RC_NORM_LOCAL(p); } - */ - --MY_FORCE_INLINE --// MY_NO_INLINE --static void RangeEnc_Encode(CPpmd7 *p, UInt32 start, UInt32 size) -+Z7_FORCE_INLINE -+// Z7_NO_INLINE -+static void Ppmd7z_RangeEnc_Encode(CPpmd7 *p, UInt32 start, UInt32 size) - { - R->Low += start * R->Range; - R->Range *= size; -- RC_NORM_LOCAL(p); -+ RC_NORM_LOCAL(p) - } - - void Ppmd7z_Flush_RangeEnc(CPpmd7 *p) - { - unsigned i; - for (i = 0; i < 5; i++) -- RangeEnc_ShiftLow(p); -+ Ppmd7z_RangeEnc_ShiftLow(p); - } - - - --#define RC_Encode(start, size) RangeEnc_Encode(p, start, size); --#define RC_EncodeFinal(start, size) RC_Encode(start, size); RC_NORM_REMOTE(p); -+#define RC_Encode(start, size) Ppmd7z_RangeEnc_Encode(p, start, size); -+#define RC_EncodeFinal(start, size) RC_Encode(start, size) RC_NORM_REMOTE(p) - - #define CTX(ref) ((CPpmd7_Context *)Ppmd7_GetContext(p, ref)) - #define SUFFIX(ctx) CTX((ctx)->Suffix) --typedef CPpmd7_Context * CTX_PTR; -+// typedef CPpmd7_Context * CTX_PTR; - #define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) - - void Ppmd7_UpdateModel(CPpmd7 *p); - - #define MASK(sym) ((unsigned char *)charMask)[sym] - --MY_FORCE_INLINE -+Z7_FORCE_INLINE - static - void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) - { -@@ -104,7 +104,7 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) - if (s->Symbol == symbol) - { - // R->Range /= p->MinContext->Union2.SummFreq; -- RC_EncodeFinal(0, s->Freq); -+ RC_EncodeFinal(0, s->Freq) - p->FoundState = s; - Ppmd7_Update1_0(p); - return; -@@ -117,7 +117,7 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) - if ((++s)->Symbol == symbol) - { - // R->Range /= p->MinContext->Union2.SummFreq; -- RC_EncodeFinal(sum, s->Freq); -+ RC_EncodeFinal(sum, s->Freq) - p->FoundState = s; - Ppmd7_Update1(p); - return; -@@ -127,10 +127,10 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) - while (--i); - - // R->Range /= p->MinContext->Union2.SummFreq; -- RC_Encode(sum, p->MinContext->Union2.SummFreq - sum); -+ RC_Encode(sum, p->MinContext->Union2.SummFreq - sum) - - p->HiBitsFlag = PPMD7_HiBitsFlag_3(p->FoundState->Symbol); -- PPMD_SetAllBitsIn256Bytes(charMask); -+ PPMD_SetAllBitsIn256Bytes(charMask) - // MASK(s->Symbol) = 0; - // i = p->MinContext->NumStats - 1; - // do { MASK((--s)->Symbol) = 0; } while (--i); -@@ -153,20 +153,20 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) - UInt16 *prob = Ppmd7_GetBinSumm(p); - CPpmd_State *s = Ppmd7Context_OneState(p->MinContext); - UInt32 pr = *prob; -- UInt32 bound = (R->Range >> 14) * pr; -+ const UInt32 bound = (R->Range >> 14) * pr; - pr = PPMD_UPDATE_PROB_1(pr); - if (s->Symbol == symbol) - { - *prob = (UInt16)(pr + (1 << PPMD_INT_BITS)); - // RangeEnc_EncodeBit_0(p, bound); - R->Range = bound; -- RC_NORM_1(p); -+ RC_NORM_1(p) - - // p->FoundState = s; - // Ppmd7_UpdateBin(p); - { -- unsigned freq = s->Freq; -- CTX_PTR c = CTX(SUCCESSOR(s)); -+ const unsigned freq = s->Freq; -+ CPpmd7_Context *c = CTX(SUCCESSOR(s)); - p->FoundState = s; - p->PrevSuccess = 1; - p->RunLength++; -@@ -187,7 +187,7 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) - R->Range -= bound; - RC_NORM_LOCAL(p) - -- PPMD_SetAllBitsIn256Bytes(charMask); -+ PPMD_SetAllBitsIn256Bytes(charMask) - MASK(s->Symbol) = 0; - p->PrevSuccess = 0; - } -@@ -248,14 +248,14 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) - - do - { -- unsigned cur = s->Symbol; -+ const unsigned cur = s->Symbol; - if ((int)cur == symbol) - { -- UInt32 low = sum; -- UInt32 freq = s->Freq; -+ const UInt32 low = sum; -+ const UInt32 freq = s->Freq; - unsigned num2; - -- Ppmd_See_Update(see); -+ Ppmd_See_UPDATE(see) - p->FoundState = s; - sum += escFreq; - -@@ -279,7 +279,7 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) - - - R->Range /= sum; -- RC_EncodeFinal(low, freq); -+ RC_EncodeFinal(low, freq) - Ppmd7_Update2(p); - return; - } -@@ -289,21 +289,21 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) - while (--i); - - { -- UInt32 total = sum + escFreq; -+ const UInt32 total = sum + escFreq; - see->Summ = (UInt16)(see->Summ + total); - - R->Range /= total; -- RC_Encode(sum, escFreq); -+ RC_Encode(sum, escFreq) - } - - { -- CPpmd_State *s2 = Ppmd7_GetStats(p, p->MinContext); -+ const CPpmd_State *s2 = Ppmd7_GetStats(p, p->MinContext); - s--; - MASK(s->Symbol) = 0; - do - { -- unsigned sym0 = s2[0].Symbol; -- unsigned sym1 = s2[1].Symbol; -+ const unsigned sym0 = s2[0].Symbol; -+ const unsigned sym1 = s2[1].Symbol; - s2 += 2; - MASK(sym0) = 0; - MASK(sym1) = 0; -@@ -321,3 +321,18 @@ void Ppmd7z_EncodeSymbols(CPpmd7 *p, const Byte *buf, const Byte *lim) - Ppmd7z_EncodeSymbol(p, *buf); - } - } -+ -+#undef kTopValue -+#undef WRITE_BYTE -+#undef RC_NORM_BASE -+#undef RC_NORM_1 -+#undef RC_NORM -+#undef RC_NORM_LOCAL -+#undef RC_NORM_REMOTE -+#undef R -+#undef RC_Encode -+#undef RC_EncodeFinal -+#undef SUFFIX -+#undef CTX -+#undef SUCCESSOR -+#undef MASK -diff --git a/src/lzma/Precomp.h b/src/lzma/Precomp.h -index e8ff8b40e..69afb2ffd 100644 ---- a/src/lzma/Precomp.h -+++ b/src/lzma/Precomp.h -@@ -1,8 +1,8 @@ - /* Precomp.h -- StdAfx --2013-11-12 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - --#ifndef __7Z_PRECOMP_H --#define __7Z_PRECOMP_H -+#ifndef ZIP7_INC_PRECOMP_H -+#define ZIP7_INC_PRECOMP_H - - #include "Compiler.h" - /* #include "7zTypes.h" */ -diff --git a/src/lzma/RotateDefs.h b/src/lzma/RotateDefs.h -index 8f01d1a6c..c16b4f8e6 100644 ---- a/src/lzma/RotateDefs.h -+++ b/src/lzma/RotateDefs.h -@@ -1,14 +1,14 @@ - /* RotateDefs.h -- Rotate functions --2015-03-25 : Igor Pavlov : Public domain */ -+2023-06-18 : Igor Pavlov : Public domain */ - --#ifndef __ROTATE_DEFS_H --#define __ROTATE_DEFS_H -+#ifndef ZIP7_INC_ROTATE_DEFS_H -+#define ZIP7_INC_ROTATE_DEFS_H - - #ifdef _MSC_VER - - #include - --/* don't use _rotl with MINGW. It can insert slow call to function. */ -+/* don't use _rotl with old MINGW. It can insert slow call to function. */ - - /* #if (_MSC_VER >= 1200) */ - #pragma intrinsic(_rotl) -@@ -18,12 +18,32 @@ - #define rotlFixed(x, n) _rotl((x), (n)) - #define rotrFixed(x, n) _rotr((x), (n)) - -+#if (_MSC_VER >= 1300) -+#define Z7_ROTL64(x, n) _rotl64((x), (n)) -+#define Z7_ROTR64(x, n) _rotr64((x), (n)) -+#else -+#define Z7_ROTL64(x, n) (((x) << (n)) | ((x) >> (64 - (n)))) -+#define Z7_ROTR64(x, n) (((x) >> (n)) | ((x) << (64 - (n)))) -+#endif -+ - #else - - /* new compilers can translate these macros to fast commands. */ - -+#if defined(__clang__) && (__clang_major__ >= 4) \ -+ || defined(__GNUC__) && (__GNUC__ >= 5) -+/* GCC 4.9.0 and clang 3.5 can recognize more correct version: */ -+#define rotlFixed(x, n) (((x) << (n)) | ((x) >> (-(n) & 31))) -+#define rotrFixed(x, n) (((x) >> (n)) | ((x) << (-(n) & 31))) -+#define Z7_ROTL64(x, n) (((x) << (n)) | ((x) >> (-(n) & 63))) -+#define Z7_ROTR64(x, n) (((x) >> (n)) | ((x) << (-(n) & 63))) -+#else -+/* for old GCC / clang: */ - #define rotlFixed(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) - #define rotrFixed(x, n) (((x) >> (n)) | ((x) << (32 - (n)))) -+#define Z7_ROTL64(x, n) (((x) << (n)) | ((x) >> (64 - (n)))) -+#define Z7_ROTR64(x, n) (((x) >> (n)) | ((x) << (64 - (n)))) -+#endif - - #endif - -diff --git a/src/lzma/Sha256.c b/src/lzma/Sha256.c -index 595eeae98..b119ce83f 100644 ---- a/src/lzma/Sha256.c -+++ b/src/lzma/Sha256.c -@@ -1,5 +1,5 @@ - /* Sha256.c -- SHA-256 Hash --2021-04-01 : Igor Pavlov : Public domain -+2023-04-02 : Igor Pavlov : Public domain - This code is based on public domain code from Wei Dai's Crypto++ library. */ - - #include "Precomp.h" -@@ -17,48 +17,48 @@ This code is based on public domain code from Wei Dai's Crypto++ library. */ - #ifdef MY_CPU_X86_OR_AMD64 - #ifdef _MSC_VER - #if _MSC_VER >= 1200 -- #define _SHA_SUPPORTED -+ #define Z7_COMPILER_SHA256_SUPPORTED - #endif - #elif defined(__clang__) - #if (__clang_major__ >= 8) // fix that check -- #define _SHA_SUPPORTED -+ #define Z7_COMPILER_SHA256_SUPPORTED - #endif - #elif defined(__GNUC__) - #if (__GNUC__ >= 8) // fix that check -- #define _SHA_SUPPORTED -+ #define Z7_COMPILER_SHA256_SUPPORTED - #endif - #elif defined(__INTEL_COMPILER) - #if (__INTEL_COMPILER >= 1800) // fix that check -- #define _SHA_SUPPORTED -+ #define Z7_COMPILER_SHA256_SUPPORTED - #endif - #endif - #elif defined(MY_CPU_ARM_OR_ARM64) - #ifdef _MSC_VER - #if _MSC_VER >= 1910 -- #define _SHA_SUPPORTED -+ #define Z7_COMPILER_SHA256_SUPPORTED - #endif - #elif defined(__clang__) - #if (__clang_major__ >= 8) // fix that check -- #define _SHA_SUPPORTED -+ #define Z7_COMPILER_SHA256_SUPPORTED - #endif - #elif defined(__GNUC__) - #if (__GNUC__ >= 6) // fix that check -- #define _SHA_SUPPORTED -+ #define Z7_COMPILER_SHA256_SUPPORTED - #endif - #endif - #endif - --void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); -+void Z7_FASTCALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); - --#ifdef _SHA_SUPPORTED -- void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); -+#ifdef Z7_COMPILER_SHA256_SUPPORTED -+ void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); - -- static SHA256_FUNC_UPDATE_BLOCKS g_FUNC_UPDATE_BLOCKS = Sha256_UpdateBlocks; -- static SHA256_FUNC_UPDATE_BLOCKS g_FUNC_UPDATE_BLOCKS_HW; -+ static SHA256_FUNC_UPDATE_BLOCKS g_SHA256_FUNC_UPDATE_BLOCKS = Sha256_UpdateBlocks; -+ static SHA256_FUNC_UPDATE_BLOCKS g_SHA256_FUNC_UPDATE_BLOCKS_HW; - -- #define UPDATE_BLOCKS(p) p->func_UpdateBlocks -+ #define SHA256_UPDATE_BLOCKS(p) p->func_UpdateBlocks - #else -- #define UPDATE_BLOCKS(p) Sha256_UpdateBlocks -+ #define SHA256_UPDATE_BLOCKS(p) Sha256_UpdateBlocks - #endif - - -@@ -66,16 +66,16 @@ BoolInt Sha256_SetFunction(CSha256 *p, unsigned algo) - { - SHA256_FUNC_UPDATE_BLOCKS func = Sha256_UpdateBlocks; - -- #ifdef _SHA_SUPPORTED -+ #ifdef Z7_COMPILER_SHA256_SUPPORTED - if (algo != SHA256_ALGO_SW) - { - if (algo == SHA256_ALGO_DEFAULT) -- func = g_FUNC_UPDATE_BLOCKS; -+ func = g_SHA256_FUNC_UPDATE_BLOCKS; - else - { - if (algo != SHA256_ALGO_HW) - return False7z; -- func = g_FUNC_UPDATE_BLOCKS_HW; -+ func = g_SHA256_FUNC_UPDATE_BLOCKS_HW; - if (!func) - return False7z; - } -@@ -92,17 +92,18 @@ BoolInt Sha256_SetFunction(CSha256 *p, unsigned algo) - - /* define it for speed optimization */ - --#ifdef _SFX -+#ifdef Z7_SFX - #define STEP_PRE 1 - #define STEP_MAIN 1 - #else - #define STEP_PRE 2 - #define STEP_MAIN 4 -- // #define _SHA256_UNROLL -+ // #define Z7_SHA256_UNROLL - #endif - -+#undef Z7_SHA256_BIG_W - #if STEP_MAIN != 16 -- #define _SHA256_BIG_W -+ #define Z7_SHA256_BIG_W - #endif - - -@@ -124,8 +125,8 @@ void Sha256_InitState(CSha256 *p) - void Sha256_Init(CSha256 *p) - { - p->func_UpdateBlocks = -- #ifdef _SHA_SUPPORTED -- g_FUNC_UPDATE_BLOCKS; -+ #ifdef Z7_COMPILER_SHA256_SUPPORTED -+ g_SHA256_FUNC_UPDATE_BLOCKS; - #else - NULL; - #endif -@@ -145,7 +146,7 @@ void Sha256_Init(CSha256 *p) - - #define blk2_main(j, i) s1(w(j, (i)-2)) + w(j, (i)-7) + s0(w(j, (i)-15)) - --#ifdef _SHA256_BIG_W -+#ifdef Z7_SHA256_BIG_W - // we use +i instead of +(i) to change the order to solve CLANG compiler warning for signed/unsigned. - #define w(j, i) W[(size_t)(j) + i] - #define blk2(j, i) (w(j, i) = w(j, (i)-16) + blk2_main(j, i)) -@@ -176,7 +177,7 @@ void Sha256_Init(CSha256 *p) - #define R1_PRE(i) T1( W_PRE, i) - #define R1_MAIN(i) T1( W_MAIN, i) - --#if (!defined(_SHA256_UNROLL) || STEP_MAIN < 8) && (STEP_MAIN >= 4) -+#if (!defined(Z7_SHA256_UNROLL) || STEP_MAIN < 8) && (STEP_MAIN >= 4) - #define R2_MAIN(i) \ - R1_MAIN(i) \ - R1_MAIN(i + 1) \ -@@ -185,7 +186,7 @@ void Sha256_Init(CSha256 *p) - - - --#if defined(_SHA256_UNROLL) && STEP_MAIN >= 8 -+#if defined(Z7_SHA256_UNROLL) && STEP_MAIN >= 8 - - #define T4( a,b,c,d,e,f,g,h, wx, i) \ - h += S1(e) + Ch(e,f,g) + K[(i)+(size_t)(j)] + wx(i); \ -@@ -223,7 +224,7 @@ void Sha256_Init(CSha256 *p) - - #endif - --void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); -+void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); - - // static - extern MY_ALIGN(64) -@@ -252,11 +253,11 @@ const UInt32 SHA256_K_ARRAY[64] = { - #define K SHA256_K_ARRAY - - --MY_NO_INLINE --void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks) -+Z7_NO_INLINE -+void Z7_FASTCALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks) - { - UInt32 W -- #ifdef _SHA256_BIG_W -+ #ifdef Z7_SHA256_BIG_W - [64]; - #else - [16]; -@@ -266,7 +267,7 @@ void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t - - UInt32 a,b,c,d,e,f,g,h; - -- #if !defined(_SHA256_UNROLL) || (STEP_MAIN <= 4) || (STEP_PRE <= 4) -+ #if !defined(Z7_SHA256_UNROLL) || (STEP_MAIN <= 4) || (STEP_PRE <= 4) - UInt32 tmp; - #endif - -@@ -297,12 +298,12 @@ void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t - - #else - -- R1_PRE(0); -+ R1_PRE(0) - #if STEP_PRE >= 2 -- R1_PRE(1); -+ R1_PRE(1) - #if STEP_PRE >= 4 -- R1_PRE(2); -- R1_PRE(3); -+ R1_PRE(2) -+ R1_PRE(3) - #endif - #endif - -@@ -311,32 +312,32 @@ void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t - - for (j = 16; j < 64; j += STEP_MAIN) - { -- #if defined(_SHA256_UNROLL) && STEP_MAIN >= 8 -+ #if defined(Z7_SHA256_UNROLL) && STEP_MAIN >= 8 - - #if STEP_MAIN < 8 -- R4_MAIN(0); -+ R4_MAIN(0) - #else -- R8_MAIN(0); -+ R8_MAIN(0) - #if STEP_MAIN == 16 -- R8_MAIN(8); -+ R8_MAIN(8) - #endif - #endif - - #else - -- R1_MAIN(0); -+ R1_MAIN(0) - #if STEP_MAIN >= 2 -- R1_MAIN(1); -+ R1_MAIN(1) - #if STEP_MAIN >= 4 -- R2_MAIN(2); -+ R2_MAIN(2) - #if STEP_MAIN >= 8 -- R2_MAIN(4); -- R2_MAIN(6); -+ R2_MAIN(4) -+ R2_MAIN(6) - #if STEP_MAIN >= 16 -- R2_MAIN(8); -- R2_MAIN(10); -- R2_MAIN(12); -- R2_MAIN(14); -+ R2_MAIN(8) -+ R2_MAIN(10) -+ R2_MAIN(12) -+ R2_MAIN(14) - #endif - #endif - #endif -@@ -367,7 +368,7 @@ void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t - #undef s1 - #undef K - --#define Sha256_UpdateBlock(p) UPDATE_BLOCKS(p)(p->state, p->buffer, 1) -+#define Sha256_UpdateBlock(p) SHA256_UPDATE_BLOCKS(p)(p->state, p->buffer, 1) - - void Sha256_Update(CSha256 *p, const Byte *data, size_t size) - { -@@ -397,7 +398,7 @@ void Sha256_Update(CSha256 *p, const Byte *data, size_t size) - } - { - size_t numBlocks = size >> 6; -- UPDATE_BLOCKS(p)(p->state, data, numBlocks); -+ SHA256_UPDATE_BLOCKS(p)(p->state, data, numBlocks); - size &= 0x3F; - if (size == 0) - return; -@@ -441,8 +442,8 @@ void Sha256_Final(CSha256 *p, Byte *digest) - - { - UInt64 numBits = (p->count << 3); -- SetBe32(p->buffer + 64 - 8, (UInt32)(numBits >> 32)); -- SetBe32(p->buffer + 64 - 4, (UInt32)(numBits)); -+ SetBe32(p->buffer + 64 - 8, (UInt32)(numBits >> 32)) -+ SetBe32(p->buffer + 64 - 4, (UInt32)(numBits)) - } - - Sha256_UpdateBlock(p); -@@ -451,21 +452,21 @@ void Sha256_Final(CSha256 *p, Byte *digest) - { - UInt32 v0 = p->state[i]; - UInt32 v1 = p->state[(size_t)i + 1]; -- SetBe32(digest , v0); -- SetBe32(digest + 4, v1); -+ SetBe32(digest , v0) -+ SetBe32(digest + 4, v1) - digest += 8; - } - - Sha256_InitState(p); - } - --#ifdef _SHA_SUPPORTED --#undef _SHA_SUPPORTED -+#ifdef Z7_COMPILER_SHA256_SUPPORTED -+#undef Z7_COMPILER_SHA256_SUPPORTED - #endif - --void Sha256Prepare() -+void Sha256Prepare(void) - { -- #ifdef _SHA_SUPPORTED -+ #ifdef Z7_COMPILER_SHA256_SUPPORTED - SHA256_FUNC_UPDATE_BLOCKS f, f_hw; - f = Sha256_UpdateBlocks; - f_hw = NULL; -@@ -483,7 +484,36 @@ void Sha256Prepare() - // printf("\n========== HW SHA256 ======== \n"); - f = f_hw = Sha256_UpdateBlocks_HW; - } -- g_FUNC_UPDATE_BLOCKS = f; -- g_FUNC_UPDATE_BLOCKS_HW = f_hw; -+ g_SHA256_FUNC_UPDATE_BLOCKS = f; -+ g_SHA256_FUNC_UPDATE_BLOCKS_HW = f_hw; - #endif - } -+ -+#undef S0 -+#undef S1 -+#undef s0 -+#undef s1 -+#undef Ch -+#undef Maj -+#undef W_MAIN -+#undef W_PRE -+#undef w -+#undef blk2_main -+#undef blk2 -+#undef T1 -+#undef T4 -+#undef T8 -+#undef R1_PRE -+#undef R1_MAIN -+#undef R2_MAIN -+#undef R4 -+#undef R4_PRE -+#undef R4_MAIN -+#undef R8 -+#undef R8_PRE -+#undef R8_MAIN -+#undef STEP_PRE -+#undef STEP_MAIN -+#undef Z7_SHA256_BIG_W -+#undef Z7_SHA256_UNROLL -+#undef Z7_COMPILER_SHA256_SUPPORTED -diff --git a/src/lzma/Sha256.h b/src/lzma/Sha256.h -index aa38501e5..9e0422320 100644 ---- a/src/lzma/Sha256.h -+++ b/src/lzma/Sha256.h -@@ -1,8 +1,8 @@ - /* Sha256.h -- SHA-256 Hash --2021-01-01 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - --#ifndef __7Z_SHA256_H --#define __7Z_SHA256_H -+#ifndef ZIP7_INC_SHA256_H -+#define ZIP7_INC_SHA256_H - - #include "7zTypes.h" - -@@ -14,7 +14,7 @@ EXTERN_C_BEGIN - #define SHA256_BLOCK_SIZE (SHA256_NUM_BLOCK_WORDS * 4) - #define SHA256_DIGEST_SIZE (SHA256_NUM_DIGEST_WORDS * 4) - --typedef void (MY_FAST_CALL *SHA256_FUNC_UPDATE_BLOCKS)(UInt32 state[8], const Byte *data, size_t numBlocks); -+typedef void (Z7_FASTCALL *SHA256_FUNC_UPDATE_BLOCKS)(UInt32 state[8], const Byte *data, size_t numBlocks); - - /* - if (the system supports different SHA256 code implementations) -@@ -34,7 +34,7 @@ typedef struct - { - SHA256_FUNC_UPDATE_BLOCKS func_UpdateBlocks; - UInt64 count; -- UInt64 __pad_2[2]; -+ UInt64 _pad_2[2]; - UInt32 state[SHA256_NUM_DIGEST_WORDS]; - - Byte buffer[SHA256_BLOCK_SIZE]; -@@ -62,7 +62,7 @@ void Sha256_Final(CSha256 *p, Byte *digest); - - - --// void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); -+// void Z7_FASTCALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); - - /* - call Sha256Prepare() once at program start. -diff --git a/src/lzma/Sha256Opt.c b/src/lzma/Sha256Opt.c -index decc1382c..e4465e3e7 100644 ---- a/src/lzma/Sha256Opt.c -+++ b/src/lzma/Sha256Opt.c -@@ -1,7 +1,9 @@ - /* Sha256Opt.c -- SHA-256 optimized code for SHA-256 hardware instructions --2021-04-01 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" -+#include "Compiler.h" -+#include "CpuArch.h" - - #if defined(_MSC_VER) - #if (_MSC_VER < 1900) && (_MSC_VER >= 1200) -@@ -9,41 +11,26 @@ - #endif - #endif - --#include "CpuArch.h" -- - #ifdef MY_CPU_X86_OR_AMD64 -- #if defined(__clang__) -- #if (__clang_major__ >= 8) // fix that check -+ #if defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1600) // fix that check - #define USE_HW_SHA -- #ifndef __SHA__ -- #define ATTRIB_SHA __attribute__((__target__("sha,ssse3"))) -- #if defined(_MSC_VER) -- // SSSE3: for clang-cl: -- #include -- #define __SHA__ -- #endif -- #endif -- -- #endif -- #elif defined(__GNUC__) -- #if (__GNUC__ >= 8) // fix that check -+ #elif defined(Z7_LLVM_CLANG_VERSION) && (Z7_LLVM_CLANG_VERSION >= 30800) \ -+ || defined(Z7_APPLE_CLANG_VERSION) && (Z7_APPLE_CLANG_VERSION >= 50100) \ -+ || defined(Z7_GCC_VERSION) && (Z7_GCC_VERSION >= 40900) - #define USE_HW_SHA -- #ifndef __SHA__ -+ #if !defined(_INTEL_COMPILER) -+ // icc defines __GNUC__, but icc doesn't support __attribute__(__target__) -+ #if !defined(__SHA__) || !defined(__SSSE3__) - #define ATTRIB_SHA __attribute__((__target__("sha,ssse3"))) -- // #pragma GCC target("sha,ssse3") - #endif -- #endif -- #elif defined(__INTEL_COMPILER) -- #if (__INTEL_COMPILER >= 1800) // fix that check -- #define USE_HW_SHA -- #endif -+ #endif - #elif defined(_MSC_VER) - #ifdef USE_MY_MM - #define USE_VER_MIN 1300 - #else -- #define USE_VER_MIN 1910 -+ #define USE_VER_MIN 1900 - #endif -- #if _MSC_VER >= USE_VER_MIN -+ #if (_MSC_VER >= USE_VER_MIN) - #define USE_HW_SHA - #endif - #endif -@@ -52,16 +39,19 @@ - #ifdef USE_HW_SHA - - // #pragma message("Sha256 HW") --// #include - --#if !defined(_MSC_VER) || (_MSC_VER >= 1900) -+// sse/sse2/ssse3: -+#include -+// sha*: - #include --#else --#include - --#if defined(_MSC_VER) && (_MSC_VER >= 1600) --// #include --#endif -+#if defined (__clang__) && defined(_MSC_VER) -+ // #if !defined(__SSSE3__) -+ // #endif -+ #if !defined(__SHA__) -+ #include -+ #endif -+#else - - #ifdef USE_MY_MM - #include "My_mm.h" -@@ -98,9 +88,9 @@ const UInt32 SHA256_K_ARRAY[64]; - #define K SHA256_K_ARRAY - - --#define ADD_EPI32(dest, src) dest = _mm_add_epi32(dest, src); --#define SHA256_MSG1(dest, src) dest = _mm_sha256msg1_epu32(dest, src); --#define SHA25G_MSG2(dest, src) dest = _mm_sha256msg2_epu32(dest, src); -+#define ADD_EPI32(dest, src) dest = _mm_add_epi32(dest, src); -+#define SHA256_MSG1(dest, src) dest = _mm_sha256msg1_epu32(dest, src); -+#define SHA25G_MSG2(dest, src) dest = _mm_sha256msg2_epu32(dest, src); - - - #define LOAD_SHUFFLE(m, k) \ -@@ -112,7 +102,7 @@ const UInt32 SHA256_K_ARRAY[64]; - - #define SM2(g0, g1, g2, g3) \ - tmp = _mm_alignr_epi8(g1, g0, 4); \ -- ADD_EPI32(g2, tmp); \ -+ ADD_EPI32(g2, tmp) \ - SHA25G_MSG2(g2, g1); \ - - // #define LS0(k, g0, g1, g2, g3) LOAD_SHUFFLE(g0, k) -@@ -138,16 +128,16 @@ const UInt32 SHA256_K_ARRAY[64]; - // We use scheme with 3 rounds ahead for SHA256_MSG1 / 2 rounds ahead for SHA256_MSG2 - - #define R4(k, g0, g1, g2, g3, OP0, OP1) \ -- RND2_0(g0, k); \ -- OP0(g0, g1, g2, g3); \ -- RND2_1; \ -- OP1(g0, g1, g2, g3); \ -+ RND2_0(g0, k) \ -+ OP0(g0, g1, g2, g3) \ -+ RND2_1 \ -+ OP1(g0, g1, g2, g3) \ - - #define R16(k, OP0, OP1, OP2, OP3, OP4, OP5, OP6, OP7) \ -- R4 ( (k)*4+0, m0, m1, m2, m3, OP0, OP1 ) \ -- R4 ( (k)*4+1, m1, m2, m3, m0, OP2, OP3 ) \ -- R4 ( (k)*4+2, m2, m3, m0, m1, OP4, OP5 ) \ -- R4 ( (k)*4+3, m3, m0, m1, m2, OP6, OP7 ) \ -+ R4 ( (k)*4+0, m0,m1,m2,m3, OP0, OP1 ) \ -+ R4 ( (k)*4+1, m1,m2,m3,m0, OP2, OP3 ) \ -+ R4 ( (k)*4+2, m2,m3,m0,m1, OP4, OP5 ) \ -+ R4 ( (k)*4+3, m3,m0,m1,m2, OP6, OP7 ) \ - - #define PREPARE_STATE \ - tmp = _mm_shuffle_epi32(state0, 0x1B); /* abcd */ \ -@@ -157,11 +147,11 @@ const UInt32 SHA256_K_ARRAY[64]; - state1 = _mm_unpackhi_epi64(state1, tmp); /* abef */ \ - - --void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); -+void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); - #ifdef ATTRIB_SHA - ATTRIB_SHA - #endif --void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) -+void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) - { - const __m128i mask = _mm_set_epi32(0x0c0d0e0f, 0x08090a0b, 0x04050607, 0x00010203); - __m128i tmp; -@@ -192,13 +182,13 @@ void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size - - - -- R16 ( 0, NNN, NNN, SM1, NNN, SM1, SM2, SM1, SM2 ); -- R16 ( 1, SM1, SM2, SM1, SM2, SM1, SM2, SM1, SM2 ); -- R16 ( 2, SM1, SM2, SM1, SM2, SM1, SM2, SM1, SM2 ); -- R16 ( 3, SM1, SM2, NNN, SM2, NNN, NNN, NNN, NNN ); -+ R16 ( 0, NNN, NNN, SM1, NNN, SM1, SM2, SM1, SM2 ) -+ R16 ( 1, SM1, SM2, SM1, SM2, SM1, SM2, SM1, SM2 ) -+ R16 ( 2, SM1, SM2, SM1, SM2, SM1, SM2, SM1, SM2 ) -+ R16 ( 3, SM1, SM2, NNN, SM2, NNN, NNN, NNN, NNN ) - -- ADD_EPI32(state0, state0_save); -- ADD_EPI32(state1, state1_save); -+ ADD_EPI32(state0, state0_save) -+ ADD_EPI32(state1, state1_save) - - data += 64; - } -@@ -298,11 +288,11 @@ const UInt32 SHA256_K_ARRAY[64]; - R4 ( (k)*4+3, m3, m0, m1, m2, OP6, OP7 ) \ - - --void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); -+void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); - #ifdef ATTRIB_SHA - ATTRIB_SHA - #endif --void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) -+void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) - { - v128 state0, state1; - -@@ -353,12 +343,12 @@ void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size - // #include - - // #include "Sha256.h" --void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); -+void Z7_FASTCALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); - - #pragma message("Sha256 HW-SW stub was used") - --void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); --void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) -+void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); -+void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) - { - Sha256_UpdateBlocks(state, data, numBlocks); - /* -@@ -371,3 +361,26 @@ void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size - } - - #endif -+ -+ -+ -+#undef K -+#undef RND2 -+#undef RND2_0 -+#undef RND2_1 -+ -+#undef MY_rev32_for_LE -+#undef NNN -+#undef LOAD_128 -+#undef STORE_128 -+#undef LOAD_SHUFFLE -+#undef SM1 -+#undef SM2 -+ -+#undef NNN -+#undef R4 -+#undef R16 -+#undef PREPARE_STATE -+#undef USE_HW_SHA -+#undef ATTRIB_SHA -+#undef USE_VER_MIN -diff --git a/src/lzma/Sort.h b/src/lzma/Sort.h -index 2e2963a23..1817b652f 100644 ---- a/src/lzma/Sort.h -+++ b/src/lzma/Sort.h -@@ -1,8 +1,8 @@ - /* Sort.h -- Sort functions --2014-04-05 : Igor Pavlov : Public domain */ -+2023-03-05 : Igor Pavlov : Public domain */ - --#ifndef __7Z_SORT_H --#define __7Z_SORT_H -+#ifndef ZIP7_INC_SORT_H -+#define ZIP7_INC_SORT_H - - #include "7zTypes.h" - -diff --git a/src/lzma/Threads.c b/src/lzma/Threads.c -index 05bcc55ad..1a9f2bbb1 100644 ---- a/src/lzma/Threads.c -+++ b/src/lzma/Threads.c -@@ -1,5 +1,5 @@ - /* Threads.c -- multithreading library --2021-12-21 : Igor Pavlov : Public domain */ -+2023-03-04 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -11,9 +11,9 @@ - - #include "Threads.h" - --static WRes GetError() -+static WRes GetError(void) - { -- DWORD res = GetLastError(); -+ const DWORD res = GetLastError(); - return res ? (WRes)res : 1; - } - -@@ -173,6 +173,9 @@ WRes CriticalSection_Init(CCriticalSection *p) - Windows XP, 2003 : can raise a STATUS_NO_MEMORY exception - Windows Vista+ : no exceptions */ - #ifdef _MSC_VER -+ #ifdef __clang__ -+ #pragma GCC diagnostic ignored "-Wlanguage-extension-token" -+ #endif - __try - #endif - { -@@ -193,18 +196,26 @@ WRes CriticalSection_Init(CCriticalSection *p) - // ---------- POSIX ---------- - - #ifndef __APPLE__ --#ifndef _7ZIP_AFFINITY_DISABLE -+#ifndef Z7_AFFINITY_DISABLE - // _GNU_SOURCE can be required for pthread_setaffinity_np() / CPU_ZERO / CPU_SET -+// clang < 3.6 : unknown warning group '-Wreserved-id-macro' -+// clang 3.6 - 12.01 : gives warning "macro name is a reserved identifier" -+// clang >= 13 : do not give warning -+#if !defined(_GNU_SOURCE) -+ #if defined(__clang__) && (__clang_major__ >= 4) && (__clang_major__ <= 12) -+ #pragma GCC diagnostic ignored "-Wreserved-id-macro" -+ #endif - #define _GNU_SOURCE --#endif --#endif -+#endif // !defined(_GNU_SOURCE) -+#endif // Z7_AFFINITY_DISABLE -+#endif // __APPLE__ - - #include "Threads.h" - - #include - #include - #include --#ifdef _7ZIP_AFFINITY_SUPPORTED -+#ifdef Z7_AFFINITY_SUPPORTED - // #include - #endif - -@@ -212,15 +223,12 @@ WRes CriticalSection_Init(CCriticalSection *p) - // #include - // #define PRF(p) p - #define PRF(p) -- --#define Print(s) PRF(printf("\n%s\n", s)) -- --// #include -+#define Print(s) PRF(printf("\n%s\n", s);) - - WRes Thread_Create_With_CpuSet(CThread *p, THREAD_FUNC_TYPE func, LPVOID param, const CCpuSet *cpuSet) - { - // new thread in Posix probably inherits affinity from parrent thread -- Print("Thread_Create_With_CpuSet"); -+ Print("Thread_Create_With_CpuSet") - - pthread_attr_t attr; - int ret; -@@ -228,7 +236,7 @@ WRes Thread_Create_With_CpuSet(CThread *p, THREAD_FUNC_TYPE func, LPVOID param, - - p->_created = 0; - -- RINOK(pthread_attr_init(&attr)); -+ RINOK(pthread_attr_init(&attr)) - - ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); - -@@ -236,7 +244,7 @@ WRes Thread_Create_With_CpuSet(CThread *p, THREAD_FUNC_TYPE func, LPVOID param, - { - if (cpuSet) - { -- #ifdef _7ZIP_AFFINITY_SUPPORTED -+ #ifdef Z7_AFFINITY_SUPPORTED - - /* - printf("\n affinity :"); -@@ -292,7 +300,7 @@ WRes Thread_Create(CThread *p, THREAD_FUNC_TYPE func, LPVOID param) - - WRes Thread_Create_With_Affinity(CThread *p, THREAD_FUNC_TYPE func, LPVOID param, CAffinityMask affinity) - { -- Print("Thread_Create_WithAffinity"); -+ Print("Thread_Create_WithAffinity") - CCpuSet cs; - unsigned i; - CpuSet_Zero(&cs); -@@ -312,7 +320,7 @@ WRes Thread_Create_With_Affinity(CThread *p, THREAD_FUNC_TYPE func, LPVOID param - - WRes Thread_Close(CThread *p) - { -- // Print("Thread_Close"); -+ // Print("Thread_Close") - int ret; - if (!p->_created) - return 0; -@@ -326,7 +334,7 @@ WRes Thread_Close(CThread *p) - - WRes Thread_Wait_Close(CThread *p) - { -- // Print("Thread_Wait_Close"); -+ // Print("Thread_Wait_Close") - void *thread_return; - int ret; - if (!p->_created) -@@ -343,8 +351,8 @@ WRes Thread_Wait_Close(CThread *p) - - static WRes Event_Create(CEvent *p, int manualReset, int signaled) - { -- RINOK(pthread_mutex_init(&p->_mutex, NULL)); -- RINOK(pthread_cond_init(&p->_cond, NULL)); -+ RINOK(pthread_mutex_init(&p->_mutex, NULL)) -+ RINOK(pthread_cond_init(&p->_cond, NULL)) - p->_manual_reset = manualReset; - p->_state = (signaled ? True7z : False7z); - p->_created = 1; -@@ -363,7 +371,7 @@ WRes AutoResetEvent_CreateNotSignaled(CAutoResetEvent *p) - - WRes Event_Set(CEvent *p) - { -- RINOK(pthread_mutex_lock(&p->_mutex)); -+ RINOK(pthread_mutex_lock(&p->_mutex)) - p->_state = True7z; - int res1 = pthread_cond_broadcast(&p->_cond); - int res2 = pthread_mutex_unlock(&p->_mutex); -@@ -372,14 +380,14 @@ WRes Event_Set(CEvent *p) - - WRes Event_Reset(CEvent *p) - { -- RINOK(pthread_mutex_lock(&p->_mutex)); -+ RINOK(pthread_mutex_lock(&p->_mutex)) - p->_state = False7z; - return pthread_mutex_unlock(&p->_mutex); - } - - WRes Event_Wait(CEvent *p) - { -- RINOK(pthread_mutex_lock(&p->_mutex)); -+ RINOK(pthread_mutex_lock(&p->_mutex)) - while (p->_state == False7z) - { - // ETIMEDOUT -@@ -411,8 +419,8 @@ WRes Semaphore_Create(CSemaphore *p, UInt32 initCount, UInt32 maxCount) - { - if (initCount > maxCount || maxCount < 1) - return EINVAL; -- RINOK(pthread_mutex_init(&p->_mutex, NULL)); -- RINOK(pthread_cond_init(&p->_cond, NULL)); -+ RINOK(pthread_mutex_init(&p->_mutex, NULL)) -+ RINOK(pthread_cond_init(&p->_cond, NULL)) - p->_count = initCount; - p->_maxCount = maxCount; - p->_created = 1; -@@ -448,7 +456,7 @@ WRes Semaphore_ReleaseN(CSemaphore *p, UInt32 releaseCount) - if (releaseCount < 1) - return EINVAL; - -- RINOK(pthread_mutex_lock(&p->_mutex)); -+ RINOK(pthread_mutex_lock(&p->_mutex)) - - newCount = p->_count + releaseCount; - if (newCount > p->_maxCount) -@@ -458,13 +466,13 @@ WRes Semaphore_ReleaseN(CSemaphore *p, UInt32 releaseCount) - p->_count = newCount; - ret = pthread_cond_broadcast(&p->_cond); - } -- RINOK(pthread_mutex_unlock(&p->_mutex)); -+ RINOK(pthread_mutex_unlock(&p->_mutex)) - return ret; - } - - WRes Semaphore_Wait(CSemaphore *p) - { -- RINOK(pthread_mutex_lock(&p->_mutex)); -+ RINOK(pthread_mutex_lock(&p->_mutex)) - while (p->_count < 1) - { - pthread_cond_wait(&p->_cond, &p->_mutex); -@@ -489,7 +497,7 @@ WRes Semaphore_Close(CSemaphore *p) - - WRes CriticalSection_Init(CCriticalSection *p) - { -- // Print("CriticalSection_Init"); -+ // Print("CriticalSection_Init") - if (!p) - return EINTR; - return pthread_mutex_init(&p->_mutex, NULL); -@@ -497,7 +505,7 @@ WRes CriticalSection_Init(CCriticalSection *p) - - void CriticalSection_Enter(CCriticalSection *p) - { -- // Print("CriticalSection_Enter"); -+ // Print("CriticalSection_Enter") - if (p) - { - // int ret = -@@ -507,7 +515,7 @@ void CriticalSection_Enter(CCriticalSection *p) - - void CriticalSection_Leave(CCriticalSection *p) - { -- // Print("CriticalSection_Leave"); -+ // Print("CriticalSection_Leave") - if (p) - { - // int ret = -@@ -517,7 +525,7 @@ void CriticalSection_Leave(CCriticalSection *p) - - void CriticalSection_Delete(CCriticalSection *p) - { -- // Print("CriticalSection_Delete"); -+ // Print("CriticalSection_Delete") - if (p) - { - // int ret = -@@ -527,14 +535,28 @@ void CriticalSection_Delete(CCriticalSection *p) - - LONG InterlockedIncrement(LONG volatile *addend) - { -- // Print("InterlockedIncrement"); -+ // Print("InterlockedIncrement") - #ifdef USE_HACK_UNSAFE_ATOMIC - LONG val = *addend + 1; - *addend = val; - return val; - #else -+ -+ #if defined(__clang__) && (__clang_major__ >= 8) -+ #pragma GCC diagnostic ignored "-Watomic-implicit-seq-cst" -+ #endif - return __sync_add_and_fetch(addend, 1); - #endif - } - - #endif // _WIN32 -+ -+WRes AutoResetEvent_OptCreate_And_Reset(CAutoResetEvent *p) -+{ -+ if (Event_IsCreated(p)) -+ return Event_Reset(p); -+ return AutoResetEvent_CreateNotSignaled(p); -+} -+ -+#undef PRF -+#undef Print -diff --git a/src/lzma/Threads.h b/src/lzma/Threads.h -index 89ecb92be..4028464a3 100644 ---- a/src/lzma/Threads.h -+++ b/src/lzma/Threads.h -@@ -1,18 +1,19 @@ - /* Threads.h -- multithreading library --2021-12-21 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - --#ifndef __7Z_THREADS_H --#define __7Z_THREADS_H -+#ifndef ZIP7_INC_THREADS_H -+#define ZIP7_INC_THREADS_H - - #ifdef _WIN32 --#include -+#include "7zWindows.h" -+ - #else - - #if defined(__linux__) - #if !defined(__APPLE__) && !defined(_AIX) && !defined(__ANDROID__) --#ifndef _7ZIP_AFFINITY_DISABLE --#define _7ZIP_AFFINITY_SUPPORTED --// #pragma message(" ==== _7ZIP_AFFINITY_SUPPORTED") -+#ifndef Z7_AFFINITY_DISABLE -+#define Z7_AFFINITY_SUPPORTED -+// #pragma message(" ==== Z7_AFFINITY_SUPPORTED") - // #define _GNU_SOURCE - #endif - #endif -@@ -33,7 +34,7 @@ WRes Handle_WaitObject(HANDLE h); - - typedef HANDLE CThread; - --#define Thread_Construct(p) { *(p) = NULL; } -+#define Thread_CONSTRUCT(p) { *(p) = NULL; } - #define Thread_WasCreated(p) (*(p) != NULL) - #define Thread_Close(p) HandlePtr_Close(p) - // #define Thread_Wait(p) Handle_WaitObject(*(p)) -@@ -52,42 +53,46 @@ typedef - #endif - THREAD_FUNC_RET_TYPE; - -+#define THREAD_FUNC_RET_ZERO 0 -+ - typedef DWORD_PTR CAffinityMask; - typedef DWORD_PTR CCpuSet; - --#define CpuSet_Zero(p) { *(p) = 0; } --#define CpuSet_Set(p, cpu) { *(p) |= ((DWORD_PTR)1 << (cpu)); } -+#define CpuSet_Zero(p) *(p) = (0) -+#define CpuSet_Set(p, cpu) *(p) |= ((DWORD_PTR)1 << (cpu)) - - #else // _WIN32 - --typedef struct _CThread -+typedef struct - { - pthread_t _tid; - int _created; - } CThread; - --#define Thread_Construct(p) { (p)->_tid = 0; (p)->_created = 0; } --#define Thread_WasCreated(p) ((p)->_created != 0) -+#define Thread_CONSTRUCT(p) { (p)->_tid = 0; (p)->_created = 0; } -+#define Thread_WasCreated(p) ((p)->_created != 0) - WRes Thread_Close(CThread *p); - // #define Thread_Wait Thread_Wait_Close - - typedef void * THREAD_FUNC_RET_TYPE; -+#define THREAD_FUNC_RET_ZERO NULL -+ - - typedef UInt64 CAffinityMask; - --#ifdef _7ZIP_AFFINITY_SUPPORTED -+#ifdef Z7_AFFINITY_SUPPORTED - - typedef cpu_set_t CCpuSet; --#define CpuSet_Zero(p) CPU_ZERO(p) --#define CpuSet_Set(p, cpu) CPU_SET(cpu, p) --#define CpuSet_IsSet(p, cpu) CPU_ISSET(cpu, p) -+#define CpuSet_Zero(p) CPU_ZERO(p) -+#define CpuSet_Set(p, cpu) CPU_SET(cpu, p) -+#define CpuSet_IsSet(p, cpu) CPU_ISSET(cpu, p) - - #else - - typedef UInt64 CCpuSet; --#define CpuSet_Zero(p) { *(p) = 0; } --#define CpuSet_Set(p, cpu) { *(p) |= ((UInt64)1 << (cpu)); } --#define CpuSet_IsSet(p, cpu) ((*(p) & ((UInt64)1 << (cpu))) != 0) -+#define CpuSet_Zero(p) *(p) = (0) -+#define CpuSet_Set(p, cpu) *(p) |= ((UInt64)1 << (cpu)) -+#define CpuSet_IsSet(p, cpu) ((*(p) & ((UInt64)1 << (cpu))) != 0) - - #endif - -@@ -95,7 +100,7 @@ typedef UInt64 CCpuSet; - #endif // _WIN32 - - --#define THREAD_FUNC_CALL_TYPE MY_STD_CALL -+#define THREAD_FUNC_CALL_TYPE Z7_STDCALL - - #if defined(_WIN32) && defined(__GNUC__) - /* GCC compiler for x86 32-bit uses the rule: -@@ -187,6 +192,7 @@ WRes ManualResetEvent_Create(CManualResetEvent *p, int signaled); - WRes ManualResetEvent_CreateNotSignaled(CManualResetEvent *p); - WRes AutoResetEvent_Create(CAutoResetEvent *p, int signaled); - WRes AutoResetEvent_CreateNotSignaled(CAutoResetEvent *p); -+ - WRes Event_Set(CEvent *p); - WRes Event_Reset(CEvent *p); - WRes Event_Wait(CEvent *p); -@@ -227,6 +233,8 @@ LONG InterlockedIncrement(LONG volatile *addend); - - #endif // _WIN32 - -+WRes AutoResetEvent_OptCreate_And_Reset(CAutoResetEvent *p); -+ - EXTERN_C_END - - #endif -diff --git a/src/lzma/Xz.c b/src/lzma/Xz.c -index 7c53b6007..4ad071060 100644 ---- a/src/lzma/Xz.c -+++ b/src/lzma/Xz.c -@@ -1,5 +1,5 @@ - /* Xz.c - Xz --2021-02-09 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -70,7 +70,7 @@ int XzCheck_Final(CXzCheck *p, Byte *digest) - switch (p->mode) - { - case XZ_CHECK_CRC32: -- SetUi32(digest, CRC_GET_DIGEST(p->crc)); -+ SetUi32(digest, CRC_GET_DIGEST(p->crc)) - break; - case XZ_CHECK_CRC64: - { -diff --git a/src/lzma/Xz.h b/src/lzma/Xz.h -index 849b944bf..d5001f6ca 100644 ---- a/src/lzma/Xz.h -+++ b/src/lzma/Xz.h -@@ -1,21 +1,23 @@ - /* Xz.h - Xz interface --2021-04-01 : Igor Pavlov : Public domain */ -+2023-04-13 : Igor Pavlov : Public domain */ - --#ifndef __XZ_H --#define __XZ_H -+#ifndef ZIP7_INC_XZ_H -+#define ZIP7_INC_XZ_H - - #include "Sha256.h" -+#include "Delta.h" - - EXTERN_C_BEGIN - - #define XZ_ID_Subblock 1 - #define XZ_ID_Delta 3 --#define XZ_ID_X86 4 --#define XZ_ID_PPC 5 --#define XZ_ID_IA64 6 --#define XZ_ID_ARM 7 --#define XZ_ID_ARMT 8 -+#define XZ_ID_X86 4 -+#define XZ_ID_PPC 5 -+#define XZ_ID_IA64 6 -+#define XZ_ID_ARM 7 -+#define XZ_ID_ARMT 8 - #define XZ_ID_SPARC 9 -+#define XZ_ID_ARM64 0xa - #define XZ_ID_LZMA2 0x21 - - unsigned Xz_ReadVarInt(const Byte *p, size_t maxSize, UInt64 *value); -@@ -53,7 +55,7 @@ typedef struct - #define XzBlock_HasUnsupportedFlags(p) (((p)->flags & ~(XZ_BF_NUM_FILTERS_MASK | XZ_BF_PACK_SIZE | XZ_BF_UNPACK_SIZE)) != 0) - - SRes XzBlock_Parse(CXzBlock *p, const Byte *header); --SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStream *inStream, BoolInt *isIndex, UInt32 *headerSizeRes); -+SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStreamPtr inStream, BoolInt *isIndex, UInt32 *headerSizeRes); - - /* ---------- xz stream ---------- */ - -@@ -101,7 +103,7 @@ typedef UInt16 CXzStreamFlags; - unsigned XzFlags_GetCheckSize(CXzStreamFlags f); - - SRes Xz_ParseHeader(CXzStreamFlags *p, const Byte *buf); --SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStream *inStream); -+SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStreamPtr inStream); - - typedef struct - { -@@ -112,6 +114,7 @@ typedef struct - typedef struct - { - CXzStreamFlags flags; -+ // Byte _pad[6]; - size_t numBlocks; - CXzBlockSizes *blocks; - UInt64 startOffset; -@@ -134,7 +137,7 @@ typedef struct - - void Xzs_Construct(CXzs *p); - void Xzs_Free(CXzs *p, ISzAllocPtr alloc); --SRes Xzs_ReadBackward(CXzs *p, ILookInStream *inStream, Int64 *startOffset, ICompressProgress *progress, ISzAllocPtr alloc); -+SRes Xzs_ReadBackward(CXzs *p, ILookInStreamPtr inStream, Int64 *startOffset, ICompressProgressPtr progress, ISzAllocPtr alloc); - - UInt64 Xzs_GetNumBlocks(const CXzs *p); - UInt64 Xzs_GetUnpackSize(const CXzs *p); -@@ -160,9 +163,9 @@ typedef enum - } ECoderFinishMode; - - --typedef struct _IStateCoder -+typedef struct - { -- void *p; -+ void *p; // state object; - void (*Free)(void *p, ISzAllocPtr alloc); - SRes (*SetProps)(void *p, const Byte *props, size_t propSize, ISzAllocPtr alloc); - void (*Init)(void *p); -@@ -174,6 +177,20 @@ typedef struct _IStateCoder - } IStateCoder; - - -+typedef struct -+{ -+ UInt32 methodId; -+ UInt32 delta; -+ UInt32 ip; -+ UInt32 X86_State; -+ Byte delta_State[DELTA_STATE_SIZE]; -+} CXzBcFilterStateBase; -+ -+typedef SizeT (*Xz_Func_BcFilterStateBase_Filter)(CXzBcFilterStateBase *p, Byte *data, SizeT size); -+ -+SRes Xz_StateCoder_Bc_SetFromMethod_Func(IStateCoder *p, UInt64 id, -+ Xz_Func_BcFilterStateBase_Filter func, ISzAllocPtr alloc); -+ - - #define MIXCODER_NUM_FILTERS_MAX 4 - -@@ -422,7 +439,7 @@ typedef struct - size_t outStep_ST; // size of output buffer for Single-Thread decoding - BoolInt ignoreErrors; // if set to 1, the decoder can ignore some errors and it skips broken parts of data. - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - unsigned numThreads; // the number of threads for Multi-Thread decoding. if (umThreads == 1) it will use Single-thread decoding - size_t inBufSize_MT; // size of small input data buffers for Multi-Thread decoding. Big number of such small buffers can be created - size_t memUseMax; // the limit of total memory usage for Multi-Thread decoding. -@@ -432,8 +449,9 @@ typedef struct - - void XzDecMtProps_Init(CXzDecMtProps *p); - -- --typedef void * CXzDecMtHandle; -+typedef struct CXzDecMt CXzDecMt; -+typedef CXzDecMt * CXzDecMtHandle; -+// Z7_DECLARE_HANDLE(CXzDecMtHandle) - - /* - alloc : XzDecMt uses CAlignOffsetAlloc internally for addresses allocated by (alloc). -@@ -503,14 +521,14 @@ SRes XzDecMt_Decode(CXzDecMtHandle p, - const CXzDecMtProps *props, - const UInt64 *outDataSize, // NULL means undefined - int finishMode, // 0 - partial unpacking is allowed, 1 - xz stream(s) must be finished -- ISeqOutStream *outStream, -+ ISeqOutStreamPtr outStream, - // Byte *outBuf, size_t *outBufSize, -- ISeqInStream *inStream, -+ ISeqInStreamPtr inStream, - // const Byte *inData, size_t inDataSize, - CXzStatInfo *stat, // out: decoding results and statistics - int *isMT, // out: 0 means that ST (Single-Thread) version was used - // 1 means that MT (Multi-Thread) version was used -- ICompressProgress *progress); -+ ICompressProgressPtr progress); - - EXTERN_C_END - -diff --git a/src/lzma/XzCrc64.c b/src/lzma/XzCrc64.c -index b6d02cbeb..c2fad6cda 100644 ---- a/src/lzma/XzCrc64.c -+++ b/src/lzma/XzCrc64.c -@@ -1,5 +1,5 @@ - /* XzCrc64.c -- CRC64 calculation --2017-05-23 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -12,39 +12,30 @@ - #define CRC64_NUM_TABLES 4 - #else - #define CRC64_NUM_TABLES 5 -- #define CRC_UINT64_SWAP(v) \ -- ((v >> 56) \ -- | ((v >> 40) & ((UInt64)0xFF << 8)) \ -- | ((v >> 24) & ((UInt64)0xFF << 16)) \ -- | ((v >> 8) & ((UInt64)0xFF << 24)) \ -- | ((v << 8) & ((UInt64)0xFF << 32)) \ -- | ((v << 24) & ((UInt64)0xFF << 40)) \ -- | ((v << 40) & ((UInt64)0xFF << 48)) \ -- | ((v << 56))) - -- UInt64 MY_FAST_CALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table); -+ UInt64 Z7_FASTCALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table); - #endif - - #ifndef MY_CPU_BE -- UInt64 MY_FAST_CALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table); -+ UInt64 Z7_FASTCALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table); - #endif - --typedef UInt64 (MY_FAST_CALL *CRC64_FUNC)(UInt64 v, const void *data, size_t size, const UInt64 *table); -+typedef UInt64 (Z7_FASTCALL *CRC64_FUNC)(UInt64 v, const void *data, size_t size, const UInt64 *table); - - static CRC64_FUNC g_Crc64Update; - UInt64 g_Crc64Table[256 * CRC64_NUM_TABLES]; - --UInt64 MY_FAST_CALL Crc64Update(UInt64 v, const void *data, size_t size) -+UInt64 Z7_FASTCALL Crc64Update(UInt64 v, const void *data, size_t size) - { - return g_Crc64Update(v, data, size, g_Crc64Table); - } - --UInt64 MY_FAST_CALL Crc64Calc(const void *data, size_t size) -+UInt64 Z7_FASTCALL Crc64Calc(const void *data, size_t size) - { - return g_Crc64Update(CRC64_INIT_VAL, data, size, g_Crc64Table) ^ CRC64_INIT_VAL; - } - --void MY_FAST_CALL Crc64GenerateTable() -+void Z7_FASTCALL Crc64GenerateTable(void) - { - UInt32 i; - for (i = 0; i < 256; i++) -@@ -57,7 +48,7 @@ void MY_FAST_CALL Crc64GenerateTable() - } - for (i = 256; i < 256 * CRC64_NUM_TABLES; i++) - { -- UInt64 r = g_Crc64Table[(size_t)i - 256]; -+ const UInt64 r = g_Crc64Table[(size_t)i - 256]; - g_Crc64Table[i] = g_Crc64Table[r & 0xFF] ^ (r >> 8); - } - -@@ -76,11 +67,14 @@ void MY_FAST_CALL Crc64GenerateTable() - { - for (i = 256 * CRC64_NUM_TABLES - 1; i >= 256; i--) - { -- UInt64 x = g_Crc64Table[(size_t)i - 256]; -- g_Crc64Table[i] = CRC_UINT64_SWAP(x); -+ const UInt64 x = g_Crc64Table[(size_t)i - 256]; -+ g_Crc64Table[i] = Z7_BSWAP64(x); - } - g_Crc64Update = XzCrc64UpdateT1_BeT4; - } - } - #endif - } -+ -+#undef kCrc64Poly -+#undef CRC64_NUM_TABLES -diff --git a/src/lzma/XzCrc64.h b/src/lzma/XzCrc64.h -index 08dbc330c..ca46869a6 100644 ---- a/src/lzma/XzCrc64.h -+++ b/src/lzma/XzCrc64.h -@@ -1,8 +1,8 @@ - /* XzCrc64.h -- CRC64 calculation --2013-01-18 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - --#ifndef __XZ_CRC64_H --#define __XZ_CRC64_H -+#ifndef ZIP7_INC_XZ_CRC64_H -+#define ZIP7_INC_XZ_CRC64_H - - #include - -@@ -12,14 +12,14 @@ EXTERN_C_BEGIN - - extern UInt64 g_Crc64Table[]; - --void MY_FAST_CALL Crc64GenerateTable(void); -+void Z7_FASTCALL Crc64GenerateTable(void); - - #define CRC64_INIT_VAL UINT64_CONST(0xFFFFFFFFFFFFFFFF) - #define CRC64_GET_DIGEST(crc) ((crc) ^ CRC64_INIT_VAL) - #define CRC64_UPDATE_BYTE(crc, b) (g_Crc64Table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) - --UInt64 MY_FAST_CALL Crc64Update(UInt64 crc, const void *data, size_t size); --UInt64 MY_FAST_CALL Crc64Calc(const void *data, size_t size); -+UInt64 Z7_FASTCALL Crc64Update(UInt64 crc, const void *data, size_t size); -+UInt64 Z7_FASTCALL Crc64Calc(const void *data, size_t size); - - EXTERN_C_END - -diff --git a/src/lzma/XzCrc64Opt.c b/src/lzma/XzCrc64Opt.c -index 93a9ffff5..d03374c00 100644 ---- a/src/lzma/XzCrc64Opt.c -+++ b/src/lzma/XzCrc64Opt.c -@@ -1,5 +1,5 @@ - /* XzCrc64Opt.c -- CRC64 calculation --2021-02-09 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -9,15 +9,15 @@ - - #define CRC64_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) - --UInt64 MY_FAST_CALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table); --UInt64 MY_FAST_CALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table) -+UInt64 Z7_FASTCALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table); -+UInt64 Z7_FASTCALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table) - { - const Byte *p = (const Byte *)data; - for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++) - v = CRC64_UPDATE_BYTE_2(v, *p); - for (; size >= 4; size -= 4, p += 4) - { -- UInt32 d = (UInt32)v ^ *(const UInt32 *)(const void *)p; -+ const UInt32 d = (UInt32)v ^ *(const UInt32 *)(const void *)p; - v = (v >> 32) - ^ (table + 0x300)[((d ) & 0xFF)] - ^ (table + 0x200)[((d >> 8) & 0xFF)] -@@ -34,29 +34,19 @@ UInt64 MY_FAST_CALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, con - - #ifndef MY_CPU_LE - --#define CRC_UINT64_SWAP(v) \ -- ((v >> 56) \ -- | ((v >> 40) & ((UInt64)0xFF << 8)) \ -- | ((v >> 24) & ((UInt64)0xFF << 16)) \ -- | ((v >> 8) & ((UInt64)0xFF << 24)) \ -- | ((v << 8) & ((UInt64)0xFF << 32)) \ -- | ((v << 24) & ((UInt64)0xFF << 40)) \ -- | ((v << 40) & ((UInt64)0xFF << 48)) \ -- | ((v << 56))) -- - #define CRC64_UPDATE_BYTE_2_BE(crc, b) (table[(Byte)((crc) >> 56) ^ (b)] ^ ((crc) << 8)) - --UInt64 MY_FAST_CALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table); --UInt64 MY_FAST_CALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table) -+UInt64 Z7_FASTCALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table); -+UInt64 Z7_FASTCALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table) - { - const Byte *p = (const Byte *)data; - table += 0x100; -- v = CRC_UINT64_SWAP(v); -+ v = Z7_BSWAP64(v); - for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++) - v = CRC64_UPDATE_BYTE_2_BE(v, *p); - for (; size >= 4; size -= 4, p += 4) - { -- UInt32 d = (UInt32)(v >> 32) ^ *(const UInt32 *)(const void *)p; -+ const UInt32 d = (UInt32)(v >> 32) ^ *(const UInt32 *)(const void *)p; - v = (v << 32) - ^ (table + 0x000)[((d ) & 0xFF)] - ^ (table + 0x100)[((d >> 8) & 0xFF)] -@@ -65,7 +55,7 @@ UInt64 MY_FAST_CALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size - } - for (; size > 0; size--, p++) - v = CRC64_UPDATE_BYTE_2_BE(v, *p); -- return CRC_UINT64_SWAP(v); -+ return Z7_BSWAP64(v); - } - - #endif -diff --git a/src/lzma/XzDec.c b/src/lzma/XzDec.c -index f8c299411..15b1d82b4 100644 ---- a/src/lzma/XzDec.c -+++ b/src/lzma/XzDec.c -@@ -1,5 +1,5 @@ - /* XzDec.c -- Xz Decode --2021-09-04 : Igor Pavlov : Public domain */ -+2023-04-13 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -67,7 +67,8 @@ unsigned Xz_ReadVarInt(const Byte *p, size_t maxSize, UInt64 *value) - return 0; - } - --/* ---------- BraState ---------- */ -+ -+/* ---------- XzBcFilterState ---------- */ - - #define BRA_BUF_SIZE (1 << 14) - -@@ -76,27 +77,29 @@ typedef struct - size_t bufPos; - size_t bufConv; - size_t bufTotal; -+ Byte *buf; // must be aligned for 4 bytes -+ Xz_Func_BcFilterStateBase_Filter filter_func; -+ // int encodeMode; -+ CXzBcFilterStateBase base; -+ // Byte buf[BRA_BUF_SIZE]; -+} CXzBcFilterState; - -- int encodeMode; -- -- UInt32 methodId; -- UInt32 delta; -- UInt32 ip; -- UInt32 x86State; -- Byte deltaState[DELTA_STATE_SIZE]; - -- Byte buf[BRA_BUF_SIZE]; --} CBraState; -- --static void BraState_Free(void *pp, ISzAllocPtr alloc) -+static void XzBcFilterState_Free(void *pp, ISzAllocPtr alloc) - { -- ISzAlloc_Free(alloc, pp); -+ if (pp) -+ { -+ CXzBcFilterState *p = ((CXzBcFilterState *)pp); -+ ISzAlloc_Free(alloc, p->buf); -+ ISzAlloc_Free(alloc, pp); -+ } - } - --static SRes BraState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAllocPtr alloc) -+ -+static SRes XzBcFilterState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAllocPtr alloc) - { -- CBraState *p = ((CBraState *)pp); -- UNUSED_VAR(alloc); -+ CXzBcFilterStateBase *p = &((CXzBcFilterState *)pp)->base; -+ UNUSED_VAR(alloc) - p->ip = 0; - if (p->methodId == XZ_ID_Delta) - { -@@ -114,6 +117,7 @@ static SRes BraState_SetProps(void *pp, const Byte *props, size_t propSize, ISzA - case XZ_ID_PPC: - case XZ_ID_ARM: - case XZ_ID_SPARC: -+ case XZ_ID_ARM64: - if ((v & 3) != 0) - return SZ_ERROR_UNSUPPORTED; - break; -@@ -134,73 +138,90 @@ static SRes BraState_SetProps(void *pp, const Byte *props, size_t propSize, ISzA - return SZ_OK; - } - --static void BraState_Init(void *pp) -+ -+static void XzBcFilterState_Init(void *pp) - { -- CBraState *p = ((CBraState *)pp); -+ CXzBcFilterState *p = ((CXzBcFilterState *)pp); - p->bufPos = p->bufConv = p->bufTotal = 0; -- x86_Convert_Init(p->x86State); -- if (p->methodId == XZ_ID_Delta) -- Delta_Init(p->deltaState); -+ p->base.X86_State = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL; -+ if (p->base.methodId == XZ_ID_Delta) -+ Delta_Init(p->base.delta_State); - } - - --#define CASE_BRA_CONV(isa) case XZ_ID_ ## isa: size = isa ## _Convert(data, size, p->ip, p->encodeMode); break; -- --static SizeT BraState_Filter(void *pp, Byte *data, SizeT size) -+static const z7_Func_BranchConv g_Funcs_BranchConv_RISC_Dec[] = -+{ -+ Z7_BRANCH_CONV_DEC(PPC), -+ Z7_BRANCH_CONV_DEC(IA64), -+ Z7_BRANCH_CONV_DEC(ARM), -+ Z7_BRANCH_CONV_DEC(ARMT), -+ Z7_BRANCH_CONV_DEC(SPARC), -+ Z7_BRANCH_CONV_DEC(ARM64) -+}; -+ -+static SizeT XzBcFilterStateBase_Filter_Dec(CXzBcFilterStateBase *p, Byte *data, SizeT size) - { -- CBraState *p = ((CBraState *)pp); - switch (p->methodId) - { - case XZ_ID_Delta: -- if (p->encodeMode) -- Delta_Encode(p->deltaState, p->delta, data, size); -- else -- Delta_Decode(p->deltaState, p->delta, data, size); -+ Delta_Decode(p->delta_State, p->delta, data, size); - break; - case XZ_ID_X86: -- size = x86_Convert(data, size, p->ip, &p->x86State, p->encodeMode); -+ size = (SizeT)(z7_BranchConvSt_X86_Dec(data, size, p->ip, &p->X86_State) - data); -+ break; -+ default: -+ if (p->methodId >= XZ_ID_PPC) -+ { -+ const UInt32 i = p->methodId - XZ_ID_PPC; -+ if (i < Z7_ARRAY_SIZE(g_Funcs_BranchConv_RISC_Dec)) -+ size = (SizeT)(g_Funcs_BranchConv_RISC_Dec[i](data, size, p->ip) - data); -+ } - break; -- CASE_BRA_CONV(PPC) -- CASE_BRA_CONV(IA64) -- CASE_BRA_CONV(ARM) -- CASE_BRA_CONV(ARMT) -- CASE_BRA_CONV(SPARC) - } - p->ip += (UInt32)size; - return size; - } - - --static SRes BraState_Code2(void *pp, -+static SizeT XzBcFilterState_Filter(void *pp, Byte *data, SizeT size) -+{ -+ CXzBcFilterState *p = ((CXzBcFilterState *)pp); -+ return p->filter_func(&p->base, data, size); -+} -+ -+ -+static SRes XzBcFilterState_Code2(void *pp, - Byte *dest, SizeT *destLen, - const Byte *src, SizeT *srcLen, int srcWasFinished, - ECoderFinishMode finishMode, - // int *wasFinished - ECoderStatus *status) - { -- CBraState *p = ((CBraState *)pp); -+ CXzBcFilterState *p = ((CXzBcFilterState *)pp); - SizeT destRem = *destLen; - SizeT srcRem = *srcLen; -- UNUSED_VAR(finishMode); -+ UNUSED_VAR(finishMode) - - *destLen = 0; - *srcLen = 0; - // *wasFinished = False7z; - *status = CODER_STATUS_NOT_FINISHED; - -- while (destRem > 0) -+ while (destRem != 0) - { -- if (p->bufPos != p->bufConv) - { - size_t size = p->bufConv - p->bufPos; -- if (size > destRem) -- size = destRem; -- memcpy(dest, p->buf + p->bufPos, size); -- p->bufPos += size; -- *destLen += size; -- dest += size; -- destRem -= size; -- continue; -+ if (size) -+ { -+ if (size > destRem) -+ size = destRem; -+ memcpy(dest, p->buf + p->bufPos, size); -+ p->bufPos += size; -+ *destLen += size; -+ dest += size; -+ destRem -= size; -+ continue; -+ } - } - - p->bufTotal -= p->bufPos; -@@ -220,7 +241,7 @@ static SRes BraState_Code2(void *pp, - if (p->bufTotal == 0) - break; - -- p->bufConv = BraState_Filter(pp, p->buf, p->bufTotal); -+ p->bufConv = p->filter_func(&p->base, p->buf, p->bufTotal); - - if (p->bufConv == 0) - { -@@ -240,27 +261,37 @@ static SRes BraState_Code2(void *pp, - } - - --SRes BraState_SetFromMethod(IStateCoder *p, UInt64 id, int encodeMode, ISzAllocPtr alloc); --SRes BraState_SetFromMethod(IStateCoder *p, UInt64 id, int encodeMode, ISzAllocPtr alloc) -+#define XZ_IS_SUPPORTED_FILTER_ID(id) \ -+ ((id) >= XZ_ID_Delta && (id) <= XZ_ID_ARM64) -+ -+SRes Xz_StateCoder_Bc_SetFromMethod_Func(IStateCoder *p, UInt64 id, -+ Xz_Func_BcFilterStateBase_Filter func, ISzAllocPtr alloc) - { -- CBraState *decoder; -- if (id < XZ_ID_Delta || id > XZ_ID_SPARC) -+ CXzBcFilterState *decoder; -+ if (!XZ_IS_SUPPORTED_FILTER_ID(id)) - return SZ_ERROR_UNSUPPORTED; -- decoder = (CBraState *)p->p; -+ decoder = (CXzBcFilterState *)p->p; - if (!decoder) - { -- decoder = (CBraState *)ISzAlloc_Alloc(alloc, sizeof(CBraState)); -+ decoder = (CXzBcFilterState *)ISzAlloc_Alloc(alloc, sizeof(CXzBcFilterState)); - if (!decoder) - return SZ_ERROR_MEM; -+ decoder->buf = ISzAlloc_Alloc(alloc, BRA_BUF_SIZE); -+ if (!decoder->buf) -+ { -+ ISzAlloc_Free(alloc, decoder); -+ return SZ_ERROR_MEM; -+ } - p->p = decoder; -- p->Free = BraState_Free; -- p->SetProps = BraState_SetProps; -- p->Init = BraState_Init; -- p->Code2 = BraState_Code2; -- p->Filter = BraState_Filter; -+ p->Free = XzBcFilterState_Free; -+ p->SetProps = XzBcFilterState_SetProps; -+ p->Init = XzBcFilterState_Init; -+ p->Code2 = XzBcFilterState_Code2; -+ p->Filter = XzBcFilterState_Filter; -+ decoder->filter_func = func; - } -- decoder->methodId = (UInt32)id; -- decoder->encodeMode = encodeMode; -+ decoder->base.methodId = (UInt32)id; -+ // decoder->encodeMode = encodeMode; - return SZ_OK; - } - -@@ -279,9 +310,9 @@ static void SbState_Free(void *pp, ISzAllocPtr alloc) - - static SRes SbState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAllocPtr alloc) - { -- UNUSED_VAR(pp); -- UNUSED_VAR(props); -- UNUSED_VAR(alloc); -+ UNUSED_VAR(pp) -+ UNUSED_VAR(props) -+ UNUSED_VAR(alloc) - return (propSize == 0) ? SZ_OK : SZ_ERROR_UNSUPPORTED; - } - -@@ -297,7 +328,7 @@ static SRes SbState_Code2(void *pp, Byte *dest, SizeT *destLen, const Byte *src, - { - CSbDec *p = (CSbDec *)pp; - SRes res; -- UNUSED_VAR(srcWasFinished); -+ UNUSED_VAR(srcWasFinished) - p->dest = dest; - p->destLen = *destLen; - p->src = src; -@@ -389,7 +420,7 @@ static SRes Lzma2State_Code2(void *pp, Byte *dest, SizeT *destLen, const Byte *s - ELzmaStatus status2; - /* ELzmaFinishMode fm = (finishMode == LZMA_FINISH_ANY) ? LZMA_FINISH_ANY : LZMA_FINISH_END; */ - SRes res; -- UNUSED_VAR(srcWasFinished); -+ UNUSED_VAR(srcWasFinished) - if (spec->outBufMode) - { - SizeT dicPos = spec->decoder.decoder.dicPos; -@@ -420,7 +451,7 @@ static SRes Lzma2State_SetFromMethod(IStateCoder *p, Byte *outBuf, size_t outBuf - p->Init = Lzma2State_Init; - p->Code2 = Lzma2State_Code2; - p->Filter = NULL; -- Lzma2Dec_Construct(&spec->decoder); -+ Lzma2Dec_CONSTRUCT(&spec->decoder) - } - spec->outBufMode = False7z; - if (outBuf) -@@ -519,7 +550,8 @@ static SRes MixCoder_SetFromMethod(CMixCoder *p, unsigned coderIndex, UInt64 met - } - if (coderIndex == 0) - return SZ_ERROR_UNSUPPORTED; -- return BraState_SetFromMethod(sc, methodId, 0, p->alloc); -+ return Xz_StateCoder_Bc_SetFromMethod_Func(sc, methodId, -+ XzBcFilterStateBase_Filter_Dec, p->alloc); - } - - -@@ -568,7 +600,7 @@ static SRes MixCoder_Code(CMixCoder *p, - SizeT destLen2, srcLen2; - int wasFinished; - -- PRF_STR("------- MixCoder Single ----------"); -+ PRF_STR("------- MixCoder Single ----------") - - srcLen2 = srcLenOrig; - destLen2 = destLenOrig; -@@ -615,14 +647,14 @@ static SRes MixCoder_Code(CMixCoder *p, - processed = coder->Filter(coder->p, p->outBuf, processed); - if (wasFinished || (destFinish && p->outWritten == destLenOrig)) - processed = p->outWritten; -- PRF_STR_INT("filter", i); -+ PRF_STR_INT("filter", i) - } - *destLen = processed; - } - return res; - } - -- PRF_STR("standard mix"); -+ PRF_STR("standard mix") - - if (p->numCoders != 1) - { -@@ -779,7 +811,7 @@ static BoolInt Xz_CheckFooter(CXzStreamFlags flags, UInt64 indexSize, const Byte - - static BoolInt XzBlock_AreSupportedFilters(const CXzBlock *p) - { -- unsigned numFilters = XzBlock_GetNumFilters(p) - 1; -+ const unsigned numFilters = XzBlock_GetNumFilters(p) - 1; - unsigned i; - { - const CXzFilter *f = &p->filters[numFilters]; -@@ -795,8 +827,7 @@ static BoolInt XzBlock_AreSupportedFilters(const CXzBlock *p) - if (f->propsSize != 1) - return False7z; - } -- else if (f->id < XZ_ID_Delta -- || f->id > XZ_ID_SPARC -+ else if (!XZ_IS_SUPPORTED_FILTER_ID(f->id) - || (f->propsSize != 0 && f->propsSize != 4)) - return False7z; - } -@@ -821,22 +852,24 @@ SRes XzBlock_Parse(CXzBlock *p, const Byte *header) - p->packSize = (UInt64)(Int64)-1; - if (XzBlock_HasPackSize(p)) - { -- READ_VARINT_AND_CHECK(header, pos, headerSize, &p->packSize); -+ READ_VARINT_AND_CHECK(header, pos, headerSize, &p->packSize) - if (p->packSize == 0 || p->packSize + headerSize >= (UInt64)1 << 63) - return SZ_ERROR_ARCHIVE; - } - - p->unpackSize = (UInt64)(Int64)-1; - if (XzBlock_HasUnpackSize(p)) -- READ_VARINT_AND_CHECK(header, pos, headerSize, &p->unpackSize); -+ { -+ READ_VARINT_AND_CHECK(header, pos, headerSize, &p->unpackSize) -+ } - - numFilters = XzBlock_GetNumFilters(p); - for (i = 0; i < numFilters; i++) - { - CXzFilter *filter = p->filters + i; - UInt64 size; -- READ_VARINT_AND_CHECK(header, pos, headerSize, &filter->id); -- READ_VARINT_AND_CHECK(header, pos, headerSize, &size); -+ READ_VARINT_AND_CHECK(header, pos, headerSize, &filter->id) -+ READ_VARINT_AND_CHECK(header, pos, headerSize, &size) - if (size > headerSize - pos || size > XZ_FILTER_PROPS_SIZE_MAX) - return SZ_ERROR_ARCHIVE; - filter->propsSize = (UInt32)size; -@@ -894,20 +927,20 @@ static SRes XzDecMix_Init(CMixCoder *p, const CXzBlock *block, Byte *outBuf, siz - MixCoder_Free(p); - for (i = 0; i < numFilters; i++) - { -- RINOK(MixCoder_SetFromMethod(p, i, block->filters[numFilters - 1 - i].id, outBuf, outBufSize)); -+ RINOK(MixCoder_SetFromMethod(p, i, block->filters[numFilters - 1 - i].id, outBuf, outBufSize)) - } - p->numCoders = numFilters; - } - else - { -- RINOK(MixCoder_ResetFromMethod(p, 0, block->filters[numFilters - 1].id, outBuf, outBufSize)); -+ RINOK(MixCoder_ResetFromMethod(p, 0, block->filters[numFilters - 1].id, outBuf, outBufSize)) - } - - for (i = 0; i < numFilters; i++) - { - const CXzFilter *f = &block->filters[numFilters - 1 - i]; - IStateCoder *sc = &p->coders[i]; -- RINOK(sc->SetProps(sc->p, f->props, f->propsSize, p->alloc)); -+ RINOK(sc->SetProps(sc->p, f->props, f->propsSize, p->alloc)) - } - - MixCoder_Init(p); -@@ -1054,14 +1087,14 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen, - (*destLen) += destLen2; - p->unpackSize += destLen2; - -- RINOK(res); -+ RINOK(res) - - if (*status != CODER_STATUS_FINISHED_WITH_MARK) - { - if (p->block.packSize == p->packSize - && *status == CODER_STATUS_NEEDS_MORE_INPUT) - { -- PRF_STR("CODER_STATUS_NEEDS_MORE_INPUT"); -+ PRF_STR("CODER_STATUS_NEEDS_MORE_INPUT") - *status = CODER_STATUS_NOT_SPECIFIED; - return SZ_ERROR_DATA; - } -@@ -1078,7 +1111,7 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen, - if ((p->block.packSize != (UInt64)(Int64)-1 && p->block.packSize != p->packSize) - || (p->block.unpackSize != (UInt64)(Int64)-1 && p->block.unpackSize != p->unpackSize)) - { -- PRF_STR("ERROR: block.size mismatch"); -+ PRF_STR("ERROR: block.size mismatch") - return SZ_ERROR_DATA; - } - } -@@ -1109,7 +1142,7 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen, - } - else - { -- RINOK(Xz_ParseHeader(&p->streamFlags, p->buf)); -+ RINOK(Xz_ParseHeader(&p->streamFlags, p->buf)) - p->numStartedStreams++; - p->indexSize = 0; - p->numBlocks = 0; -@@ -1155,7 +1188,7 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen, - } - else - { -- RINOK(XzBlock_Parse(&p->block, p->buf)); -+ RINOK(XzBlock_Parse(&p->block, p->buf)) - if (!XzBlock_AreSupportedFilters(&p->block)) - return SZ_ERROR_UNSUPPORTED; - p->numTotalBlocks++; -@@ -1168,7 +1201,7 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen, - p->headerParsedOk = True7z; - return SZ_OK; - } -- RINOK(XzDecMix_Init(&p->decoder, &p->block, p->outBuf, p->outBufSize)); -+ RINOK(XzDecMix_Init(&p->decoder, &p->block, p->outBuf, p->outBufSize)) - } - break; - } -@@ -1389,7 +1422,7 @@ UInt64 XzUnpacker_GetExtraSize(const CXzUnpacker *p) - - - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - #include "MtDec.h" - #endif - -@@ -1400,7 +1433,7 @@ void XzDecMtProps_Init(CXzDecMtProps *p) - p->outStep_ST = 1 << 20; - p->ignoreErrors = False7z; - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - p->numThreads = 1; - p->inBufSize_MT = 1 << 18; - p->memUseMax = sizeof(size_t) << 28; -@@ -1409,7 +1442,7 @@ void XzDecMtProps_Init(CXzDecMtProps *p) - - - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - - /* ---------- CXzDecMtThread ---------- */ - -@@ -1448,7 +1481,7 @@ typedef struct - - /* ---------- CXzDecMt ---------- */ - --typedef struct -+struct CXzDecMt - { - CAlignOffsetAlloc alignOffsetAlloc; - ISzAllocPtr allocMid; -@@ -1456,9 +1489,9 @@ typedef struct - CXzDecMtProps props; - size_t unpackBlockMaxSize; - -- ISeqInStream *inStream; -- ISeqOutStream *outStream; -- ICompressProgress *progress; -+ ISeqInStreamPtr inStream; -+ ISeqOutStreamPtr outStream; -+ ICompressProgressPtr progress; - - BoolInt finishMode; - BoolInt outSize_Defined; -@@ -1481,7 +1514,7 @@ typedef struct - ECoderStatus status; - SRes codeRes; - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - BoolInt mainDecoderWasCalled; - // int statErrorDefined; - int finishedDecoderIndex; -@@ -1504,10 +1537,9 @@ typedef struct - - BoolInt mtc_WasConstructed; - CMtDec mtc; -- CXzDecMtThread coders[MTDEC__THREADS_MAX]; -+ CXzDecMtThread coders[MTDEC_THREADS_MAX]; - #endif -- --} CXzDecMt; -+}; - - - -@@ -1535,11 +1567,11 @@ CXzDecMtHandle XzDecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid) - - XzDecMtProps_Init(&p->props); - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - p->mtc_WasConstructed = False7z; - { - unsigned i; -- for (i = 0; i < MTDEC__THREADS_MAX; i++) -+ for (i = 0; i < MTDEC_THREADS_MAX; i++) - { - CXzDecMtThread *coder = &p->coders[i]; - coder->dec_created = False7z; -@@ -1549,16 +1581,16 @@ CXzDecMtHandle XzDecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid) - } - #endif - -- return p; -+ return (CXzDecMtHandle)p; - } - - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - - static void XzDecMt_FreeOutBufs(CXzDecMt *p) - { - unsigned i; -- for (i = 0; i < MTDEC__THREADS_MAX; i++) -+ for (i = 0; i < MTDEC_THREADS_MAX; i++) - { - CXzDecMtThread *coder = &p->coders[i]; - if (coder->outBuf) -@@ -1595,13 +1627,15 @@ static void XzDecMt_FreeSt(CXzDecMt *p) - } - - --void XzDecMt_Destroy(CXzDecMtHandle pp) -+// #define GET_CXzDecMt_p CXzDecMt *p = pp; -+ -+void XzDecMt_Destroy(CXzDecMtHandle p) - { -- CXzDecMt *p = (CXzDecMt *)pp; -+ // GET_CXzDecMt_p - - XzDecMt_FreeSt(p); - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - - if (p->mtc_WasConstructed) - { -@@ -1610,7 +1644,7 @@ void XzDecMt_Destroy(CXzDecMtHandle pp) - } - { - unsigned i; -- for (i = 0; i < MTDEC__THREADS_MAX; i++) -+ for (i = 0; i < MTDEC_THREADS_MAX; i++) - { - CXzDecMtThread *t = &p->coders[i]; - if (t->dec_created) -@@ -1625,12 +1659,12 @@ void XzDecMt_Destroy(CXzDecMtHandle pp) - - #endif - -- ISzAlloc_Free(p->alignOffsetAlloc.baseAlloc, pp); -+ ISzAlloc_Free(p->alignOffsetAlloc.baseAlloc, p); - } - - - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - - static void XzDecMt_Callback_Parse(void *obj, unsigned coderIndex, CMtDecCallbackInfo *cc) - { -@@ -1696,7 +1730,7 @@ static void XzDecMt_Callback_Parse(void *obj, unsigned coderIndex, CMtDecCallbac - coder->dec.parseMode = True7z; - coder->dec.headerParsedOk = False7z; - -- PRF_STR_INT("Parse", srcSize2); -+ PRF_STR_INT("Parse", srcSize2) - - res = XzUnpacker_Code(&coder->dec, - NULL, &destSize, -@@ -2071,7 +2105,7 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex, - } - data += cur; - size -= cur; -- // PRF_STR_INT("Written size =", size); -+ // PRF_STR_INT("Written size =", size) - if (size == 0) - break; - res = MtProgress_ProgressAdd(&me->mtc.mtProgress, 0, 0); -@@ -2087,7 +2121,7 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex, - return res; - } - -- RINOK(res); -+ RINOK(res) - - if (coder->inPreSize != coder->inCodeSize - || coder->blockPackTotal != coder->inCodeSize) -@@ -2106,13 +2140,13 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex, - // (coder->state == MTDEC_PARSE_END) means that there are no other working threads - // so we can use mtc variables without lock - -- PRF_STR_INT("Write MTDEC_PARSE_END", me->mtc.inProcessed); -+ PRF_STR_INT("Write MTDEC_PARSE_END", me->mtc.inProcessed) - - me->mtc.mtProgress.totalInSize = me->mtc.inProcessed; - { - CXzUnpacker *dec = &me->dec; - -- PRF_STR_INT("PostSingle", srcSize); -+ PRF_STR_INT("PostSingle", srcSize) - - { - size_t srcProcessed = srcSize; -@@ -2186,7 +2220,7 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex, - me->mtc.crossEnd = srcSize; - } - -- PRF_STR_INT("XZ_STATE_STREAM_HEADER crossEnd = ", (unsigned)me->mtc.crossEnd); -+ PRF_STR_INT("XZ_STATE_STREAM_HEADER crossEnd = ", (unsigned)me->mtc.crossEnd) - - return SZ_OK; - } -@@ -2277,7 +2311,7 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex, - UInt64 inDelta = me->mtc.inProcessed - inProgressPrev; - if (inDelta >= (1 << 22)) - { -- RINOK(MtProgress_Progress_ST(&me->mtc.mtProgress)); -+ RINOK(MtProgress_Progress_ST(&me->mtc.mtProgress)) - inProgressPrev = me->mtc.inProcessed; - } - } -@@ -2331,7 +2365,7 @@ void XzStatInfo_Clear(CXzStatInfo *p) - */ - - static SRes XzDecMt_Decode_ST(CXzDecMt *p -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - , BoolInt tMode - #endif - , CXzStatInfo *stat) -@@ -2343,7 +2377,7 @@ static SRes XzDecMt_Decode_ST(CXzDecMt *p - - CXzUnpacker *dec; - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - if (tMode) - { - XzDecMt_FreeOutBufs(p); -@@ -2400,7 +2434,7 @@ static SRes XzDecMt_Decode_ST(CXzDecMt *p - - if (inPos == inLim) - { -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - if (tMode) - { - inData = MtDec_Read(&p->mtc, &inLim); -@@ -2577,19 +2611,19 @@ static void XzStatInfo_SetStat(const CXzUnpacker *dec, - - - --SRes XzDecMt_Decode(CXzDecMtHandle pp, -+SRes XzDecMt_Decode(CXzDecMtHandle p, - const CXzDecMtProps *props, - const UInt64 *outDataSize, int finishMode, -- ISeqOutStream *outStream, -+ ISeqOutStreamPtr outStream, - // Byte *outBuf, size_t *outBufSize, -- ISeqInStream *inStream, -+ ISeqInStreamPtr inStream, - // const Byte *inData, size_t inDataSize, - CXzStatInfo *stat, - int *isMT, -- ICompressProgress *progress) -+ ICompressProgressPtr progress) - { -- CXzDecMt *p = (CXzDecMt *)pp; -- #ifndef _7ZIP_ST -+ // GET_CXzDecMt_p -+ #ifndef Z7_ST - BoolInt tMode; - #endif - -@@ -2640,7 +2674,7 @@ SRes XzDecMt_Decode(CXzDecMtHandle pp, - */ - - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - - p->isBlockHeaderState_Parse = False7z; - p->isBlockHeaderState_Write = False7z; -@@ -2782,7 +2816,7 @@ SRes XzDecMt_Decode(CXzDecMtHandle pp, - return res; - } - -- PRF_STR("----- decoding ST -----"); -+ PRF_STR("----- decoding ST -----") - } - - #endif -@@ -2792,13 +2826,13 @@ SRes XzDecMt_Decode(CXzDecMtHandle pp, - - { - SRes res = XzDecMt_Decode_ST(p -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - , tMode - #endif - , stat - ); - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - // we must set error code from MT decoding at first - if (p->mainErrorCode != SZ_OK) - stat->DecodeRes = p->mainErrorCode; -@@ -2835,3 +2869,7 @@ SRes XzDecMt_Decode(CXzDecMtHandle pp, - return res; - } - } -+ -+#undef PRF -+#undef PRF_STR -+#undef PRF_STR_INT_2 -diff --git a/src/lzma/XzEnc.c b/src/lzma/XzEnc.c -index 4c77ccaef..a715609d8 100644 ---- a/src/lzma/XzEnc.c -+++ b/src/lzma/XzEnc.c -@@ -1,5 +1,5 @@ - /* XzEnc.c -- Xz Encode --2021-04-01 : Igor Pavlov : Public domain */ -+2023-04-13 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -18,13 +18,13 @@ - - #include "XzEnc.h" - --// #define _7ZIP_ST -+// #define Z7_ST - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - #include "MtCoder.h" - #else --#define MTCODER__THREADS_MAX 1 --#define MTCODER__BLOCKS_MAX 1 -+#define MTCODER_THREADS_MAX 1 -+#define MTCODER_BLOCKS_MAX 1 - #endif - - #define XZ_GET_PAD_SIZE(dataSize) ((4 - ((unsigned)(dataSize) & 3)) & 3) -@@ -35,25 +35,25 @@ - #define XZ_GET_ESTIMATED_BLOCK_TOTAL_PACK_SIZE(unpackSize) (XZ_BLOCK_HEADER_SIZE_MAX + XZ_GET_MAX_BLOCK_PACK_SIZE(unpackSize)) - - --#define XzBlock_ClearFlags(p) (p)->flags = 0; --#define XzBlock_SetNumFilters(p, n) (p)->flags = (Byte)((p)->flags | ((n) - 1)); -+// #define XzBlock_ClearFlags(p) (p)->flags = 0; -+#define XzBlock_ClearFlags_SetNumFilters(p, n) (p)->flags = (Byte)((n) - 1); - #define XzBlock_SetHasPackSize(p) (p)->flags |= XZ_BF_PACK_SIZE; - #define XzBlock_SetHasUnpackSize(p) (p)->flags |= XZ_BF_UNPACK_SIZE; - - --static SRes WriteBytes(ISeqOutStream *s, const void *buf, size_t size) -+static SRes WriteBytes(ISeqOutStreamPtr s, const void *buf, size_t size) - { - return (ISeqOutStream_Write(s, buf, size) == size) ? SZ_OK : SZ_ERROR_WRITE; - } - --static SRes WriteBytesUpdateCrc(ISeqOutStream *s, const void *buf, size_t size, UInt32 *crc) -+static SRes WriteBytes_UpdateCrc(ISeqOutStreamPtr s, const void *buf, size_t size, UInt32 *crc) - { - *crc = CrcUpdate(*crc, buf, size); - return WriteBytes(s, buf, size); - } - - --static SRes Xz_WriteHeader(CXzStreamFlags f, ISeqOutStream *s) -+static SRes Xz_WriteHeader(CXzStreamFlags f, ISeqOutStreamPtr s) - { - UInt32 crc; - Byte header[XZ_STREAM_HEADER_SIZE]; -@@ -61,12 +61,12 @@ static SRes Xz_WriteHeader(CXzStreamFlags f, ISeqOutStream *s) - header[XZ_SIG_SIZE] = (Byte)(f >> 8); - header[XZ_SIG_SIZE + 1] = (Byte)(f & 0xFF); - crc = CrcCalc(header + XZ_SIG_SIZE, XZ_STREAM_FLAGS_SIZE); -- SetUi32(header + XZ_SIG_SIZE + XZ_STREAM_FLAGS_SIZE, crc); -+ SetUi32(header + XZ_SIG_SIZE + XZ_STREAM_FLAGS_SIZE, crc) - return WriteBytes(s, header, XZ_STREAM_HEADER_SIZE); - } - - --static SRes XzBlock_WriteHeader(const CXzBlock *p, ISeqOutStream *s) -+static SRes XzBlock_WriteHeader(const CXzBlock *p, ISeqOutStreamPtr s) - { - Byte header[XZ_BLOCK_HEADER_SIZE_MAX]; - -@@ -91,7 +91,7 @@ static SRes XzBlock_WriteHeader(const CXzBlock *p, ISeqOutStream *s) - header[pos++] = 0; - - header[0] = (Byte)(pos >> 2); -- SetUi32(header + pos, CrcCalc(header, pos)); -+ SetUi32(header + pos, CrcCalc(header, pos)) - return WriteBytes(s, header, pos + 4); - } - -@@ -182,7 +182,7 @@ static SRes XzEncIndex_AddIndexRecord(CXzEncIndex *p, UInt64 unpackSize, UInt64 - size_t newSize = p->allocated * 2 + 16 * 2; - if (newSize < p->size + pos) - return SZ_ERROR_MEM; -- RINOK(XzEncIndex_ReAlloc(p, newSize, alloc)); -+ RINOK(XzEncIndex_ReAlloc(p, newSize, alloc)) - } - memcpy(p->blocks + p->size, buf, pos); - p->size += pos; -@@ -191,7 +191,7 @@ static SRes XzEncIndex_AddIndexRecord(CXzEncIndex *p, UInt64 unpackSize, UInt64 - } - - --static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, ISeqOutStream *s) -+static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, ISeqOutStreamPtr s) - { - Byte buf[32]; - UInt64 globalPos; -@@ -200,8 +200,8 @@ static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, I - - globalPos = pos; - buf[0] = 0; -- RINOK(WriteBytesUpdateCrc(s, buf, pos, &crc)); -- RINOK(WriteBytesUpdateCrc(s, p->blocks, p->size, &crc)); -+ RINOK(WriteBytes_UpdateCrc(s, buf, pos, &crc)) -+ RINOK(WriteBytes_UpdateCrc(s, p->blocks, p->size, &crc)) - globalPos += p->size; - - pos = XZ_GET_PAD_SIZE(globalPos); -@@ -211,12 +211,12 @@ static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, I - globalPos += pos; - - crc = CrcUpdate(crc, buf + 4 - pos, pos); -- SetUi32(buf + 4, CRC_GET_DIGEST(crc)); -+ SetUi32(buf + 4, CRC_GET_DIGEST(crc)) - -- SetUi32(buf + 8 + 4, (UInt32)(globalPos >> 2)); -+ SetUi32(buf + 8 + 4, (UInt32)(globalPos >> 2)) - buf[8 + 8] = (Byte)(flags >> 8); - buf[8 + 9] = (Byte)(flags & 0xFF); -- SetUi32(buf + 8, CrcCalc(buf + 8 + 4, 6)); -+ SetUi32(buf + 8, CrcCalc(buf + 8 + 4, 6)) - buf[8 + 10] = XZ_FOOTER_SIG_0; - buf[8 + 11] = XZ_FOOTER_SIG_1; - -@@ -230,7 +230,7 @@ static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, I - typedef struct - { - ISeqInStream vt; -- ISeqInStream *realStream; -+ ISeqInStreamPtr realStream; - const Byte *data; - UInt64 limit; - UInt64 processed; -@@ -251,9 +251,9 @@ static void SeqCheckInStream_GetDigest(CSeqCheckInStream *p, Byte *digest) - XzCheck_Final(&p->check, digest); - } - --static SRes SeqCheckInStream_Read(const ISeqInStream *pp, void *data, size_t *size) -+static SRes SeqCheckInStream_Read(ISeqInStreamPtr pp, void *data, size_t *size) - { -- CSeqCheckInStream *p = CONTAINER_FROM_VTBL(pp, CSeqCheckInStream, vt); -+ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeqCheckInStream) - size_t size2 = *size; - SRes res = SZ_OK; - -@@ -285,15 +285,15 @@ static SRes SeqCheckInStream_Read(const ISeqInStream *pp, void *data, size_t *si - typedef struct - { - ISeqOutStream vt; -- ISeqOutStream *realStream; -+ ISeqOutStreamPtr realStream; - Byte *outBuf; - size_t outBufLimit; - UInt64 processed; - } CSeqSizeOutStream; - --static size_t SeqSizeOutStream_Write(const ISeqOutStream *pp, const void *data, size_t size) -+static size_t SeqSizeOutStream_Write(ISeqOutStreamPtr pp, const void *data, size_t size) - { -- CSeqSizeOutStream *p = CONTAINER_FROM_VTBL(pp, CSeqSizeOutStream, vt); -+ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeqSizeOutStream) - if (p->realStream) - size = ISeqOutStream_Write(p->realStream, data, size); - else -@@ -313,8 +313,8 @@ static size_t SeqSizeOutStream_Write(const ISeqOutStream *pp, const void *data, - - typedef struct - { -- ISeqInStream p; -- ISeqInStream *realStream; -+ ISeqInStream vt; -+ ISeqInStreamPtr realStream; - IStateCoder StateCoder; - Byte *buf; - size_t curPos; -@@ -323,7 +323,39 @@ typedef struct - } CSeqInFilter; - - --SRes BraState_SetFromMethod(IStateCoder *p, UInt64 id, int encodeMode, ISzAllocPtr alloc); -+static const z7_Func_BranchConv g_Funcs_BranchConv_RISC_Enc[] = -+{ -+ Z7_BRANCH_CONV_ENC(PPC), -+ Z7_BRANCH_CONV_ENC(IA64), -+ Z7_BRANCH_CONV_ENC(ARM), -+ Z7_BRANCH_CONV_ENC(ARMT), -+ Z7_BRANCH_CONV_ENC(SPARC), -+ Z7_BRANCH_CONV_ENC(ARM64) -+}; -+ -+static SizeT XzBcFilterStateBase_Filter_Enc(CXzBcFilterStateBase *p, Byte *data, SizeT size) -+{ -+ switch (p->methodId) -+ { -+ case XZ_ID_Delta: -+ Delta_Encode(p->delta_State, p->delta, data, size); -+ break; -+ case XZ_ID_X86: -+ size = (SizeT)(z7_BranchConvSt_X86_Enc(data, size, p->ip, &p->X86_State) - data); -+ break; -+ default: -+ if (p->methodId >= XZ_ID_PPC) -+ { -+ const UInt32 i = p->methodId - XZ_ID_PPC; -+ if (i < Z7_ARRAY_SIZE(g_Funcs_BranchConv_RISC_Enc)) -+ size = (SizeT)(g_Funcs_BranchConv_RISC_Enc[i](data, size, p->ip) - data); -+ } -+ break; -+ } -+ p->ip += (UInt32)size; -+ return size; -+} -+ - - static SRes SeqInFilter_Init(CSeqInFilter *p, const CXzFilter *props, ISzAllocPtr alloc) - { -@@ -335,17 +367,17 @@ static SRes SeqInFilter_Init(CSeqInFilter *p, const CXzFilter *props, ISzAllocPt - } - p->curPos = p->endPos = 0; - p->srcWasFinished = 0; -- RINOK(BraState_SetFromMethod(&p->StateCoder, props->id, 1, alloc)); -- RINOK(p->StateCoder.SetProps(p->StateCoder.p, props->props, props->propsSize, alloc)); -+ RINOK(Xz_StateCoder_Bc_SetFromMethod_Func(&p->StateCoder, props->id, XzBcFilterStateBase_Filter_Enc, alloc)) -+ RINOK(p->StateCoder.SetProps(p->StateCoder.p, props->props, props->propsSize, alloc)) - p->StateCoder.Init(p->StateCoder.p); - return SZ_OK; - } - - --static SRes SeqInFilter_Read(const ISeqInStream *pp, void *data, size_t *size) -+static SRes SeqInFilter_Read(ISeqInStreamPtr pp, void *data, size_t *size) - { -- CSeqInFilter *p = CONTAINER_FROM_VTBL(pp, CSeqInFilter, p); -- size_t sizeOriginal = *size; -+ Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeqInFilter) -+ const size_t sizeOriginal = *size; - if (sizeOriginal == 0) - return SZ_OK; - *size = 0; -@@ -356,7 +388,7 @@ static SRes SeqInFilter_Read(const ISeqInStream *pp, void *data, size_t *size) - { - p->curPos = 0; - p->endPos = FILTER_BUF_SIZE; -- RINOK(ISeqInStream_Read(p->realStream, p->buf, &p->endPos)); -+ RINOK(ISeqInStream_Read(p->realStream, p->buf, &p->endPos)) - if (p->endPos == 0) - p->srcWasFinished = 1; - } -@@ -381,7 +413,7 @@ static void SeqInFilter_Construct(CSeqInFilter *p) - { - p->buf = NULL; - p->StateCoder.p = NULL; -- p->p.Read = SeqInFilter_Read; -+ p->vt.Read = SeqInFilter_Read; - } - - static void SeqInFilter_Free(CSeqInFilter *p, ISzAllocPtr alloc) -@@ -406,13 +438,13 @@ static void SeqInFilter_Free(CSeqInFilter *p, ISzAllocPtr alloc) - typedef struct - { - ISeqInStream vt; -- ISeqInStream *inStream; -+ ISeqInStreamPtr inStream; - CSbEnc enc; - } CSbEncInStream; - --static SRes SbEncInStream_Read(const ISeqInStream *pp, void *data, size_t *size) -+static SRes SbEncInStream_Read(ISeqInStreamPtr pp, void *data, size_t *size) - { -- CSbEncInStream *p = CONTAINER_FROM_VTBL(pp, CSbEncInStream, vt); -+ CSbEncInStream *p = Z7_CONTAINER_FROM_VTBL(pp, CSbEncInStream, vt); - size_t sizeOriginal = *size; - if (sizeOriginal == 0) - return SZ_OK; -@@ -422,7 +454,7 @@ static SRes SbEncInStream_Read(const ISeqInStream *pp, void *data, size_t *size) - if (p->enc.needRead && !p->enc.readWasFinished) - { - size_t processed = p->enc.needReadSizeMax; -- RINOK(p->inStream->Read(p->inStream, p->enc.buf + p->enc.readPos, &processed)); -+ RINOK(p->inStream->Read(p->inStream, p->enc.buf + p->enc.readPos, &processed)) - p->enc.readPos += processed; - if (processed == 0) - { -@@ -433,7 +465,7 @@ static SRes SbEncInStream_Read(const ISeqInStream *pp, void *data, size_t *size) - } - - *size = sizeOriginal; -- RINOK(SbEnc_Read(&p->enc, data, size)); -+ RINOK(SbEnc_Read(&p->enc, data, size)) - if (*size != 0 || !p->enc.needRead) - return SZ_OK; - } -@@ -473,7 +505,7 @@ void XzFilterProps_Init(CXzFilterProps *p) - void XzProps_Init(CXzProps *p) - { - p->checkId = XZ_CHECK_CRC32; -- p->blockSize = XZ_PROPS__BLOCK_SIZE__AUTO; -+ p->blockSize = XZ_PROPS_BLOCK_SIZE_AUTO; - p->numBlockThreads_Reduced = -1; - p->numBlockThreads_Max = -1; - p->numTotalThreads = -1; -@@ -502,8 +534,8 @@ static void XzEncProps_Normalize_Fixed(CXzProps *p) - t2 = p->numBlockThreads_Max; - t3 = p->numTotalThreads; - -- if (t2 > MTCODER__THREADS_MAX) -- t2 = MTCODER__THREADS_MAX; -+ if (t2 > MTCODER_THREADS_MAX) -+ t2 = MTCODER_THREADS_MAX; - - if (t3 <= 0) - { -@@ -519,8 +551,8 @@ static void XzEncProps_Normalize_Fixed(CXzProps *p) - t1 = 1; - t2 = t3; - } -- if (t2 > MTCODER__THREADS_MAX) -- t2 = MTCODER__THREADS_MAX; -+ if (t2 > MTCODER_THREADS_MAX) -+ t2 = MTCODER_THREADS_MAX; - } - else if (t1 <= 0) - { -@@ -571,7 +603,7 @@ static void XzProps_Normalize(CXzProps *p) - /* we normalize xzProps properties, but we normalize only some of CXzProps::lzma2Props properties. - Lzma2Enc_SetProps() will normalize lzma2Props later. */ - -- if (p->blockSize == XZ_PROPS__BLOCK_SIZE__SOLID) -+ if (p->blockSize == XZ_PROPS_BLOCK_SIZE_SOLID) - { - p->lzma2Props.lzmaProps.reduceSize = p->reduceSize; - p->numBlockThreads_Reduced = 1; -@@ -583,15 +615,15 @@ static void XzProps_Normalize(CXzProps *p) - else - { - CLzma2EncProps *lzma2 = &p->lzma2Props; -- if (p->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO) -+ if (p->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO) - { - // xz-auto - p->lzma2Props.lzmaProps.reduceSize = p->reduceSize; - -- if (lzma2->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID) -+ if (lzma2->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID) - { - // if (xz-auto && lzma2-solid) - we use solid for both -- p->blockSize = XZ_PROPS__BLOCK_SIZE__SOLID; -+ p->blockSize = XZ_PROPS_BLOCK_SIZE_SOLID; - p->numBlockThreads_Reduced = 1; - p->numBlockThreads_Max = 1; - if (p->lzma2Props.numTotalThreads <= 0) -@@ -610,9 +642,9 @@ static void XzProps_Normalize(CXzProps *p) - p->blockSize = tp.blockSize; // fixed or solid - p->numBlockThreads_Reduced = tp.numBlockThreads_Reduced; - p->numBlockThreads_Max = tp.numBlockThreads_Max; -- if (lzma2->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO) -- lzma2->blockSize = tp.blockSize; // fixed or solid, LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID -- if (lzma2->lzmaProps.reduceSize > tp.blockSize && tp.blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID) -+ if (lzma2->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO) -+ lzma2->blockSize = tp.blockSize; // fixed or solid, LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID -+ if (lzma2->lzmaProps.reduceSize > tp.blockSize && tp.blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID) - lzma2->lzmaProps.reduceSize = tp.blockSize; - lzma2->numBlockThreads_Reduced = 1; - lzma2->numBlockThreads_Max = 1; -@@ -631,9 +663,9 @@ static void XzProps_Normalize(CXzProps *p) - r = p->blockSize; - lzma2->lzmaProps.reduceSize = r; - } -- if (lzma2->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO) -- lzma2->blockSize = LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID; -- else if (lzma2->blockSize > p->blockSize && lzma2->blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID) -+ if (lzma2->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO) -+ lzma2->blockSize = LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID; -+ else if (lzma2->blockSize > p->blockSize && lzma2->blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID) - lzma2->blockSize = p->blockSize; - - XzEncProps_Normalize_Fixed(p); -@@ -704,17 +736,17 @@ typedef struct - static SRes Xz_CompressBlock( - CLzma2WithFilters *lzmaf, - -- ISeqOutStream *outStream, -+ ISeqOutStreamPtr outStream, - Byte *outBufHeader, - Byte *outBufData, size_t outBufDataLimit, - -- ISeqInStream *inStream, -+ ISeqInStreamPtr inStream, - // UInt64 expectedSize, - const Byte *inBuf, // used if (!inStream) - size_t inBufSize, // used if (!inStream), it's block size, props->blockSize is ignored - - const CXzProps *props, -- ICompressProgress *progress, -+ ICompressProgressPtr progress, - int *inStreamFinished, /* only for inStream version */ - CXzEncBlockInfo *blockSizes, - ISzAllocPtr alloc, -@@ -731,12 +763,12 @@ static SRes Xz_CompressBlock( - - *inStreamFinished = False7z; - -- RINOK(Lzma2WithFilters_Create(lzmaf, alloc, allocBig)); -+ RINOK(Lzma2WithFilters_Create(lzmaf, alloc, allocBig)) - -- RINOK(Lzma2Enc_SetProps(lzmaf->lzma2, &props->lzma2Props)); -+ RINOK(Lzma2Enc_SetProps(lzmaf->lzma2, &props->lzma2Props)) - -- XzBlock_ClearFlags(&block); -- XzBlock_SetNumFilters(&block, 1 + (fp ? 1 : 0)); -+ // XzBlock_ClearFlags(&block) -+ XzBlock_ClearFlags_SetNumFilters(&block, 1 + (fp ? 1 : 0)) - - if (fp) - { -@@ -752,7 +784,7 @@ static SRes Xz_CompressBlock( - else if (fp->ipDefined) - { - Byte *ptr = filter->props; -- SetUi32(ptr, fp->ip); -+ SetUi32(ptr, fp->ip) - filter->propsSize = 4; - } - } -@@ -777,13 +809,13 @@ static SRes Xz_CompressBlock( - if (props->blockSize != (UInt64)(Int64)-1) - if (expectedSize > props->blockSize) - block.unpackSize = props->blockSize; -- XzBlock_SetHasUnpackSize(&block); -+ XzBlock_SetHasUnpackSize(&block) - } - */ - - if (outStream) - { -- RINOK(XzBlock_WriteHeader(&block, &seqSizeOutStream.vt)); -+ RINOK(XzBlock_WriteHeader(&block, &seqSizeOutStream.vt)) - } - - checkInStream.vt.Read = SeqCheckInStream_Read; -@@ -801,13 +833,13 @@ static SRes Xz_CompressBlock( - if (fp->id == XZ_ID_Subblock) - { - lzmaf->sb.inStream = &checkInStream.vt; -- RINOK(SbEncInStream_Init(&lzmaf->sb)); -+ RINOK(SbEncInStream_Init(&lzmaf->sb)) - } - else - #endif - { - lzmaf->filter.realStream = &checkInStream.vt; -- RINOK(SeqInFilter_Init(&lzmaf->filter, filter, alloc)); -+ RINOK(SeqInFilter_Init(&lzmaf->filter, filter, alloc)) - } - } - -@@ -841,7 +873,7 @@ static SRes Xz_CompressBlock( - #ifdef USE_SUBBLOCK - (fp->id == XZ_ID_Subblock) ? &lzmaf->sb.vt: - #endif -- &lzmaf->filter.p) : -+ &lzmaf->filter.vt) : - &checkInStream.vt) : NULL, - - useStream ? NULL : inBuf, -@@ -852,7 +884,7 @@ static SRes Xz_CompressBlock( - if (outBuf) - seqSizeOutStream.processed += outSize; - -- RINOK(res); -+ RINOK(res) - blockSizes->unpackSize = checkInStream.processed; - } - { -@@ -866,7 +898,7 @@ static SRes Xz_CompressBlock( - buf[3] = 0; - - SeqCheckInStream_GetDigest(&checkInStream, buf + 4); -- RINOK(WriteBytes(&seqSizeOutStream.vt, buf + (4 - padSize), padSize + XzFlags_GetCheckSize((CXzStreamFlags)props->checkId))); -+ RINOK(WriteBytes(&seqSizeOutStream.vt, buf + (4 - padSize), padSize + XzFlags_GetCheckSize((CXzStreamFlags)props->checkId))) - - blockSizes->totalSize = seqSizeOutStream.processed - padSize; - -@@ -877,12 +909,12 @@ static SRes Xz_CompressBlock( - seqSizeOutStream.processed = 0; - - block.unpackSize = blockSizes->unpackSize; -- XzBlock_SetHasUnpackSize(&block); -+ XzBlock_SetHasUnpackSize(&block) - - block.packSize = packSize; -- XzBlock_SetHasPackSize(&block); -+ XzBlock_SetHasPackSize(&block) - -- RINOK(XzBlock_WriteHeader(&block, &seqSizeOutStream.vt)); -+ RINOK(XzBlock_WriteHeader(&block, &seqSizeOutStream.vt)) - - blockSizes->headerSize = (size_t)seqSizeOutStream.processed; - blockSizes->totalSize += seqSizeOutStream.processed; -@@ -906,15 +938,15 @@ static SRes Xz_CompressBlock( - typedef struct - { - ICompressProgress vt; -- ICompressProgress *progress; -+ ICompressProgressPtr progress; - UInt64 inOffset; - UInt64 outOffset; - } CCompressProgress_XzEncOffset; - - --static SRes CompressProgress_XzEncOffset_Progress(const ICompressProgress *pp, UInt64 inSize, UInt64 outSize) -+static SRes CompressProgress_XzEncOffset_Progress(ICompressProgressPtr pp, UInt64 inSize, UInt64 outSize) - { -- const CCompressProgress_XzEncOffset *p = CONTAINER_FROM_VTBL(pp, CCompressProgress_XzEncOffset, vt); -+ const CCompressProgress_XzEncOffset *p = Z7_CONTAINER_FROM_VTBL_CONST(pp, CCompressProgress_XzEncOffset, vt); - inSize += p->inOffset; - outSize += p->outOffset; - return ICompressProgress_Progress(p->progress, inSize, outSize); -@@ -923,7 +955,7 @@ static SRes CompressProgress_XzEncOffset_Progress(const ICompressProgress *pp, U - - - --typedef struct -+struct CXzEnc - { - ISzAllocPtr alloc; - ISzAllocPtr allocBig; -@@ -933,20 +965,19 @@ typedef struct - - CXzEncIndex xzIndex; - -- CLzma2WithFilters lzmaf_Items[MTCODER__THREADS_MAX]; -+ CLzma2WithFilters lzmaf_Items[MTCODER_THREADS_MAX]; - - size_t outBufSize; /* size of allocated outBufs[i] */ -- Byte *outBufs[MTCODER__BLOCKS_MAX]; -+ Byte *outBufs[MTCODER_BLOCKS_MAX]; - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - unsigned checkType; -- ISeqOutStream *outStream; -+ ISeqOutStreamPtr outStream; - BoolInt mtCoder_WasConstructed; - CMtCoder mtCoder; -- CXzEncBlockInfo EncBlocks[MTCODER__BLOCKS_MAX]; -+ CXzEncBlockInfo EncBlocks[MTCODER_BLOCKS_MAX]; - #endif -- --} CXzEnc; -+}; - - - static void XzEnc_Construct(CXzEnc *p) -@@ -955,13 +986,13 @@ static void XzEnc_Construct(CXzEnc *p) - - XzEncIndex_Construct(&p->xzIndex); - -- for (i = 0; i < MTCODER__THREADS_MAX; i++) -+ for (i = 0; i < MTCODER_THREADS_MAX; i++) - Lzma2WithFilters_Construct(&p->lzmaf_Items[i]); - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - p->mtCoder_WasConstructed = False7z; - { -- for (i = 0; i < MTCODER__BLOCKS_MAX; i++) -+ for (i = 0; i < MTCODER_BLOCKS_MAX; i++) - p->outBufs[i] = NULL; - p->outBufSize = 0; - } -@@ -972,7 +1003,7 @@ static void XzEnc_Construct(CXzEnc *p) - static void XzEnc_FreeOutBufs(CXzEnc *p) - { - unsigned i; -- for (i = 0; i < MTCODER__BLOCKS_MAX; i++) -+ for (i = 0; i < MTCODER_BLOCKS_MAX; i++) - if (p->outBufs[i]) - { - ISzAlloc_Free(p->alloc, p->outBufs[i]); -@@ -988,10 +1019,10 @@ static void XzEnc_Free(CXzEnc *p, ISzAllocPtr alloc) - - XzEncIndex_Free(&p->xzIndex, alloc); - -- for (i = 0; i < MTCODER__THREADS_MAX; i++) -+ for (i = 0; i < MTCODER_THREADS_MAX; i++) - Lzma2WithFilters_Free(&p->lzmaf_Items[i], alloc); - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - if (p->mtCoder_WasConstructed) - { - MtCoder_Destruct(&p->mtCoder); -@@ -1013,37 +1044,38 @@ CXzEncHandle XzEnc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig) - p->expectedDataSize = (UInt64)(Int64)-1; - p->alloc = alloc; - p->allocBig = allocBig; -- return p; -+ return (CXzEncHandle)p; - } - -+// #define GET_CXzEnc_p CXzEnc *p = (CXzEnc *)(void *)pp; - --void XzEnc_Destroy(CXzEncHandle pp) -+void XzEnc_Destroy(CXzEncHandle p) - { -- CXzEnc *p = (CXzEnc *)pp; -+ // GET_CXzEnc_p - XzEnc_Free(p, p->alloc); - ISzAlloc_Free(p->alloc, p); - } - - --SRes XzEnc_SetProps(CXzEncHandle pp, const CXzProps *props) -+SRes XzEnc_SetProps(CXzEncHandle p, const CXzProps *props) - { -- CXzEnc *p = (CXzEnc *)pp; -+ // GET_CXzEnc_p - p->xzProps = *props; - XzProps_Normalize(&p->xzProps); - return SZ_OK; - } - - --void XzEnc_SetDataSize(CXzEncHandle pp, UInt64 expectedDataSiize) -+void XzEnc_SetDataSize(CXzEncHandle p, UInt64 expectedDataSiize) - { -- CXzEnc *p = (CXzEnc *)pp; -+ // GET_CXzEnc_p - p->expectedDataSize = expectedDataSiize; - } - - - - --#ifndef _7ZIP_ST -+#ifndef Z7_ST - - static SRes XzEnc_MtCallback_Code(void *pp, unsigned coderIndex, unsigned outBufIndex, - const Byte *src, size_t srcSize, int finished) -@@ -1073,7 +1105,7 @@ static SRes XzEnc_MtCallback_Code(void *pp, unsigned coderIndex, unsigned outBuf - - MtProgressThunk_CreateVTable(&progressThunk); - progressThunk.mtProgress = &me->mtCoder.mtProgress; -- MtProgressThunk_Init(&progressThunk); -+ MtProgressThunk_INIT(&progressThunk) - - { - CXzEncBlockInfo blockSizes; -@@ -1112,11 +1144,11 @@ static SRes XzEnc_MtCallback_Write(void *pp, unsigned outBufIndex) - const CXzEncBlockInfo *bInfo = &me->EncBlocks[outBufIndex]; - const Byte *data = me->outBufs[outBufIndex]; - -- RINOK(WriteBytes(me->outStream, data, bInfo->headerSize)); -+ RINOK(WriteBytes(me->outStream, data, bInfo->headerSize)) - - { - UInt64 totalPackFull = bInfo->totalSize + XZ_GET_PAD_SIZE(bInfo->totalSize); -- RINOK(WriteBytes(me->outStream, data + XZ_BLOCK_HEADER_SIZE_MAX, (size_t)totalPackFull - bInfo->headerSize)); -+ RINOK(WriteBytes(me->outStream, data + XZ_BLOCK_HEADER_SIZE_MAX, (size_t)totalPackFull - bInfo->headerSize)) - } - - return XzEncIndex_AddIndexRecord(&me->xzIndex, bInfo->unpackSize, bInfo->totalSize, me->alloc); -@@ -1126,9 +1158,9 @@ static SRes XzEnc_MtCallback_Write(void *pp, unsigned outBufIndex) - - - --SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress) -+SRes XzEnc_Encode(CXzEncHandle p, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, ICompressProgressPtr progress) - { -- CXzEnc *p = (CXzEnc *)pp; -+ // GET_CXzEnc_p - - const CXzProps *props = &p->xzProps; - -@@ -1137,7 +1169,7 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr - UInt64 numBlocks = 1; - UInt64 blockSize = props->blockSize; - -- if (blockSize != XZ_PROPS__BLOCK_SIZE__SOLID -+ if (blockSize != XZ_PROPS_BLOCK_SIZE_SOLID - && props->reduceSize != (UInt64)(Int64)-1) - { - numBlocks = props->reduceSize / blockSize; -@@ -1147,13 +1179,13 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr - else - blockSize = (UInt64)1 << 62; - -- RINOK(XzEncIndex_PreAlloc(&p->xzIndex, numBlocks, blockSize, XZ_GET_ESTIMATED_BLOCK_TOTAL_PACK_SIZE(blockSize), p->alloc)); -+ RINOK(XzEncIndex_PreAlloc(&p->xzIndex, numBlocks, blockSize, XZ_GET_ESTIMATED_BLOCK_TOTAL_PACK_SIZE(blockSize), p->alloc)) - } - -- RINOK(Xz_WriteHeader((CXzStreamFlags)props->checkId, outStream)); -+ RINOK(Xz_WriteHeader((CXzStreamFlags)props->checkId, outStream)) - - -- #ifndef _7ZIP_ST -+ #ifndef Z7_ST - if (props->numBlockThreads_Reduced > 1) - { - IMtCoderCallback2 vt; -@@ -1180,8 +1212,8 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr - p->mtCoder.mtCallback = &vt; - p->mtCoder.mtCallbackObject = p; - -- if ( props->blockSize == XZ_PROPS__BLOCK_SIZE__SOLID -- || props->blockSize == XZ_PROPS__BLOCK_SIZE__AUTO) -+ if ( props->blockSize == XZ_PROPS_BLOCK_SIZE_SOLID -+ || props->blockSize == XZ_PROPS_BLOCK_SIZE_AUTO) - return SZ_ERROR_FAIL; - - p->mtCoder.blockSize = (size_t)props->blockSize; -@@ -1200,7 +1232,7 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr - p->mtCoder.numThreadsMax = (unsigned)props->numBlockThreads_Max; - p->mtCoder.expectedDataSize = p->expectedDataSize; - -- RINOK(MtCoder_Code(&p->mtCoder)); -+ RINOK(MtCoder_Code(&p->mtCoder)) - } - else - #endif -@@ -1217,7 +1249,7 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr - - writeStartSizes = 0; - -- if (props->blockSize != XZ_PROPS__BLOCK_SIZE__SOLID) -+ if (props->blockSize != XZ_PROPS_BLOCK_SIZE_SOLID) - { - writeStartSizes = (props->forceWriteSizesInHeader > 0); - -@@ -1274,18 +1306,18 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr - &inStreamFinished, - &blockSizes, - p->alloc, -- p->allocBig)); -+ p->allocBig)) - - { - UInt64 totalPackFull = blockSizes.totalSize + XZ_GET_PAD_SIZE(blockSizes.totalSize); - - if (writeStartSizes) - { -- RINOK(WriteBytes(outStream, p->outBufs[0], blockSizes.headerSize)); -- RINOK(WriteBytes(outStream, bufData, (size_t)totalPackFull - blockSizes.headerSize)); -+ RINOK(WriteBytes(outStream, p->outBufs[0], blockSizes.headerSize)) -+ RINOK(WriteBytes(outStream, bufData, (size_t)totalPackFull - blockSizes.headerSize)) - } - -- RINOK(XzEncIndex_AddIndexRecord(&p->xzIndex, blockSizes.unpackSize, blockSizes.totalSize, p->alloc)); -+ RINOK(XzEncIndex_AddIndexRecord(&p->xzIndex, blockSizes.unpackSize, blockSizes.totalSize, p->alloc)) - - progress2.inOffset += blockSizes.unpackSize; - progress2.outOffset += totalPackFull; -@@ -1302,8 +1334,8 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr - - #include "Alloc.h" - --SRes Xz_Encode(ISeqOutStream *outStream, ISeqInStream *inStream, -- const CXzProps *props, ICompressProgress *progress) -+SRes Xz_Encode(ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, -+ const CXzProps *props, ICompressProgressPtr progress) - { - SRes res; - CXzEncHandle xz = XzEnc_Create(&g_Alloc, &g_BigAlloc); -@@ -1317,7 +1349,7 @@ SRes Xz_Encode(ISeqOutStream *outStream, ISeqInStream *inStream, - } - - --SRes Xz_EncodeEmpty(ISeqOutStream *outStream) -+SRes Xz_EncodeEmpty(ISeqOutStreamPtr outStream) - { - SRes res; - CXzEncIndex xzIndex; -diff --git a/src/lzma/XzEnc.h b/src/lzma/XzEnc.h -index 0c29e7e1e..77b78c014 100644 ---- a/src/lzma/XzEnc.h -+++ b/src/lzma/XzEnc.h -@@ -1,8 +1,8 @@ - /* XzEnc.h -- Xz Encode --2017-06-27 : Igor Pavlov : Public domain */ -+2023-04-13 : Igor Pavlov : Public domain */ - --#ifndef __XZ_ENC_H --#define __XZ_ENC_H -+#ifndef ZIP7_INC_XZ_ENC_H -+#define ZIP7_INC_XZ_ENC_H - - #include "Lzma2Enc.h" - -@@ -11,8 +11,8 @@ - EXTERN_C_BEGIN - - --#define XZ_PROPS__BLOCK_SIZE__AUTO LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO --#define XZ_PROPS__BLOCK_SIZE__SOLID LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID -+#define XZ_PROPS_BLOCK_SIZE_AUTO LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO -+#define XZ_PROPS_BLOCK_SIZE_SOLID LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID - - - typedef struct -@@ -41,19 +41,20 @@ typedef struct - - void XzProps_Init(CXzProps *p); - -- --typedef void * CXzEncHandle; -+typedef struct CXzEnc CXzEnc; -+typedef CXzEnc * CXzEncHandle; -+// Z7_DECLARE_HANDLE(CXzEncHandle) - - CXzEncHandle XzEnc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig); - void XzEnc_Destroy(CXzEncHandle p); - SRes XzEnc_SetProps(CXzEncHandle p, const CXzProps *props); - void XzEnc_SetDataSize(CXzEncHandle p, UInt64 expectedDataSiize); --SRes XzEnc_Encode(CXzEncHandle p, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress); -+SRes XzEnc_Encode(CXzEncHandle p, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, ICompressProgressPtr progress); - --SRes Xz_Encode(ISeqOutStream *outStream, ISeqInStream *inStream, -- const CXzProps *props, ICompressProgress *progress); -+SRes Xz_Encode(ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, -+ const CXzProps *props, ICompressProgressPtr progress); - --SRes Xz_EncodeEmpty(ISeqOutStream *outStream); -+SRes Xz_EncodeEmpty(ISeqOutStreamPtr outStream); - - EXTERN_C_END - -diff --git a/src/lzma/XzIn.c b/src/lzma/XzIn.c -index a293d6bdd..9261bcb09 100644 ---- a/src/lzma/XzIn.c -+++ b/src/lzma/XzIn.c -@@ -1,5 +1,5 @@ - /* XzIn.c - Xz input --2021-09-04 : Igor Pavlov : Public domain */ -+2023-04-02 : Igor Pavlov : Public domain */ - - #include "Precomp.h" - -@@ -15,11 +15,13 @@ - #define XZ_FOOTER_SIG_CHECK(p) ((p)[0] == XZ_FOOTER_SIG_0 && (p)[1] == XZ_FOOTER_SIG_1) - - --SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStream *inStream) -+SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStreamPtr inStream) - { - Byte sig[XZ_STREAM_HEADER_SIZE]; -- RINOK(SeqInStream_Read2(inStream, sig, XZ_STREAM_HEADER_SIZE, SZ_ERROR_NO_ARCHIVE)); -- if (memcmp(sig, XZ_SIG, XZ_SIG_SIZE) != 0) -+ size_t processedSize = XZ_STREAM_HEADER_SIZE; -+ RINOK(SeqInStream_ReadMax(inStream, sig, &processedSize)) -+ if (processedSize != XZ_STREAM_HEADER_SIZE -+ || memcmp(sig, XZ_SIG, XZ_SIG_SIZE) != 0) - return SZ_ERROR_NO_ARCHIVE; - return Xz_ParseHeader(p, sig); - } -@@ -29,12 +31,12 @@ SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStream *inStream) - if (s == 0) return SZ_ERROR_ARCHIVE; \ - pos += s; } - --SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStream *inStream, BoolInt *isIndex, UInt32 *headerSizeRes) -+SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStreamPtr inStream, BoolInt *isIndex, UInt32 *headerSizeRes) - { - Byte header[XZ_BLOCK_HEADER_SIZE_MAX]; - unsigned headerSize; - *headerSizeRes = 0; -- RINOK(SeqInStream_ReadByte(inStream, &header[0])); -+ RINOK(SeqInStream_ReadByte(inStream, &header[0])) - headerSize = (unsigned)header[0]; - if (headerSize == 0) - { -@@ -46,7 +48,12 @@ SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStream *inStream, BoolInt *isIndex, U - *isIndex = False7z; - headerSize = (headerSize << 2) + 4; - *headerSizeRes = headerSize; -- RINOK(SeqInStream_Read(inStream, header + 1, headerSize - 1)); -+ { -+ size_t processedSize = headerSize - 1; -+ RINOK(SeqInStream_ReadMax(inStream, header + 1, &processedSize)) -+ if (processedSize != headerSize - 1) -+ return SZ_ERROR_INPUT_EOF; -+ } - return XzBlock_Parse(p, header); - } - -@@ -58,7 +65,9 @@ UInt64 Xz_GetUnpackSize(const CXzStream *p) - UInt64 size = 0; - size_t i; - for (i = 0; i < p->numBlocks; i++) -- ADD_SIZE_CHECK(size, p->blocks[i].unpackSize); -+ { -+ ADD_SIZE_CHECK(size, p->blocks[i].unpackSize) -+ } - return size; - } - -@@ -67,12 +76,14 @@ UInt64 Xz_GetPackSize(const CXzStream *p) - UInt64 size = 0; - size_t i; - for (i = 0; i < p->numBlocks; i++) -- ADD_SIZE_CHECK(size, (p->blocks[i].totalSize + 3) & ~(UInt64)3); -+ { -+ ADD_SIZE_CHECK(size, (p->blocks[i].totalSize + 3) & ~(UInt64)3) -+ } - return size; - } - - /* --SRes XzBlock_ReadFooter(CXzBlock *p, CXzStreamFlags f, ISeqInStream *inStream) -+SRes XzBlock_ReadFooter(CXzBlock *p, CXzStreamFlags f, ISeqInStreamPtr inStream) - { - return SeqInStream_Read(inStream, p->check, XzFlags_GetCheckSize(f)); - } -@@ -93,7 +104,7 @@ static SRes Xz_ReadIndex2(CXzStream *p, const Byte *buf, size_t size, ISzAllocPt - - { - UInt64 numBlocks64; -- READ_VARINT_AND_CHECK(buf, pos, size, &numBlocks64); -+ READ_VARINT_AND_CHECK(buf, pos, size, &numBlocks64) - numBlocks = (size_t)numBlocks64; - if (numBlocks != numBlocks64 || numBlocks * 2 > size) - return SZ_ERROR_ARCHIVE; -@@ -110,8 +121,8 @@ static SRes Xz_ReadIndex2(CXzStream *p, const Byte *buf, size_t size, ISzAllocPt - for (i = 0; i < numBlocks; i++) - { - CXzBlockSizes *block = &p->blocks[i]; -- READ_VARINT_AND_CHECK(buf, pos, size, &block->totalSize); -- READ_VARINT_AND_CHECK(buf, pos, size, &block->unpackSize); -+ READ_VARINT_AND_CHECK(buf, pos, size, &block->totalSize) -+ READ_VARINT_AND_CHECK(buf, pos, size, &block->unpackSize) - if (block->totalSize == 0) - return SZ_ERROR_ARCHIVE; - } -@@ -122,7 +133,7 @@ static SRes Xz_ReadIndex2(CXzStream *p, const Byte *buf, size_t size, ISzAllocPt - return (pos == size) ? SZ_OK : SZ_ERROR_ARCHIVE; - } - --static SRes Xz_ReadIndex(CXzStream *p, ILookInStream *stream, UInt64 indexSize, ISzAllocPtr alloc) -+static SRes Xz_ReadIndex(CXzStream *p, ILookInStreamPtr stream, UInt64 indexSize, ISzAllocPtr alloc) - { - SRes res; - size_t size; -@@ -142,14 +153,14 @@ static SRes Xz_ReadIndex(CXzStream *p, ILookInStream *stream, UInt64 indexSize, - return res; - } - --static SRes LookInStream_SeekRead_ForArc(ILookInStream *stream, UInt64 offset, void *buf, size_t size) -+static SRes LookInStream_SeekRead_ForArc(ILookInStreamPtr stream, UInt64 offset, void *buf, size_t size) - { -- RINOK(LookInStream_SeekTo(stream, offset)); -+ RINOK(LookInStream_SeekTo(stream, offset)) - return LookInStream_Read(stream, buf, size); - /* return LookInStream_Read2(stream, buf, size, SZ_ERROR_NO_ARCHIVE); */ - } - --static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOffset, ISzAllocPtr alloc) -+static SRes Xz_ReadBackward(CXzStream *p, ILookInStreamPtr stream, Int64 *startOffset, ISzAllocPtr alloc) - { - UInt64 indexSize; - Byte buf[XZ_STREAM_FOOTER_SIZE]; -@@ -159,7 +170,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff - return SZ_ERROR_NO_ARCHIVE; - - pos -= XZ_STREAM_FOOTER_SIZE; -- RINOK(LookInStream_SeekRead_ForArc(stream, pos, buf, XZ_STREAM_FOOTER_SIZE)); -+ RINOK(LookInStream_SeekRead_ForArc(stream, pos, buf, XZ_STREAM_FOOTER_SIZE)) - - if (!XZ_FOOTER_SIG_CHECK(buf + 10)) - { -@@ -174,7 +185,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff - - i = (pos > TEMP_BUF_SIZE) ? TEMP_BUF_SIZE : (size_t)pos; - pos -= i; -- RINOK(LookInStream_SeekRead_ForArc(stream, pos, temp, i)); -+ RINOK(LookInStream_SeekRead_ForArc(stream, pos, temp, i)) - total += (UInt32)i; - for (; i != 0; i--) - if (temp[i - 1] != 0) -@@ -193,7 +204,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff - if (pos < XZ_STREAM_FOOTER_SIZE) - return SZ_ERROR_NO_ARCHIVE; - pos -= XZ_STREAM_FOOTER_SIZE; -- RINOK(LookInStream_SeekRead_ForArc(stream, pos, buf, XZ_STREAM_FOOTER_SIZE)); -+ RINOK(LookInStream_SeekRead_ForArc(stream, pos, buf, XZ_STREAM_FOOTER_SIZE)) - if (!XZ_FOOTER_SIG_CHECK(buf + 10)) - return SZ_ERROR_NO_ARCHIVE; - } -@@ -217,8 +228,8 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff - return SZ_ERROR_ARCHIVE; - - pos -= indexSize; -- RINOK(LookInStream_SeekTo(stream, pos)); -- RINOK(Xz_ReadIndex(p, stream, indexSize, alloc)); -+ RINOK(LookInStream_SeekTo(stream, pos)) -+ RINOK(Xz_ReadIndex(p, stream, indexSize, alloc)) - - { - UInt64 totalSize = Xz_GetPackSize(p); -@@ -227,7 +238,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff - || pos < totalSize + XZ_STREAM_HEADER_SIZE) - return SZ_ERROR_ARCHIVE; - pos -= (totalSize + XZ_STREAM_HEADER_SIZE); -- RINOK(LookInStream_SeekTo(stream, pos)); -+ RINOK(LookInStream_SeekTo(stream, pos)) - *startOffset = (Int64)pos; - } - { -@@ -236,7 +247,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff - SecToRead_CreateVTable(&secToRead); - secToRead.realStream = stream; - -- RINOK(Xz_ReadHeader(&headerFlags, &secToRead.vt)); -+ RINOK(Xz_ReadHeader(&headerFlags, &secToRead.vt)) - return (p->flags == headerFlags) ? SZ_OK : SZ_ERROR_ARCHIVE; - } - } -@@ -274,7 +285,9 @@ UInt64 Xzs_GetUnpackSize(const CXzs *p) - UInt64 size = 0; - size_t i; - for (i = 0; i < p->num; i++) -- ADD_SIZE_CHECK(size, Xz_GetUnpackSize(&p->streams[i])); -+ { -+ ADD_SIZE_CHECK(size, Xz_GetUnpackSize(&p->streams[i])) -+ } - return size; - } - -@@ -284,15 +297,17 @@ UInt64 Xzs_GetPackSize(const CXzs *p) - UInt64 size = 0; - size_t i; - for (i = 0; i < p->num; i++) -- ADD_SIZE_CHECK(size, Xz_GetTotalSize(&p->streams[i])); -+ { -+ ADD_SIZE_CHECK(size, Xz_GetTotalSize(&p->streams[i])) -+ } - return size; - } - */ - --SRes Xzs_ReadBackward(CXzs *p, ILookInStream *stream, Int64 *startOffset, ICompressProgress *progress, ISzAllocPtr alloc) -+SRes Xzs_ReadBackward(CXzs *p, ILookInStreamPtr stream, Int64 *startOffset, ICompressProgressPtr progress, ISzAllocPtr alloc) - { - Int64 endOffset = 0; -- RINOK(ILookInStream_Seek(stream, &endOffset, SZ_SEEK_END)); -+ RINOK(ILookInStream_Seek(stream, &endOffset, SZ_SEEK_END)) - *startOffset = endOffset; - for (;;) - { -@@ -301,7 +316,7 @@ SRes Xzs_ReadBackward(CXzs *p, ILookInStream *stream, Int64 *startOffset, ICompr - Xz_Construct(&st); - res = Xz_ReadBackward(&st, stream, startOffset, alloc); - st.startOffset = (UInt64)*startOffset; -- RINOK(res); -+ RINOK(res) - if (p->num == p->numAllocated) - { - const size_t newNum = p->num + p->num / 4 + 1; -@@ -317,7 +332,7 @@ SRes Xzs_ReadBackward(CXzs *p, ILookInStream *stream, Int64 *startOffset, ICompr - p->streams[p->num++] = st; - if (*startOffset == 0) - break; -- RINOK(LookInStream_SeekTo(stream, (UInt64)*startOffset)); -+ RINOK(LookInStream_SeekTo(stream, (UInt64)*startOffset)) - if (progress && ICompressProgress_Progress(progress, (UInt64)(endOffset - *startOffset), (UInt64)(Int64)-1) != SZ_OK) - return SZ_ERROR_PROGRESS; - } -diff --git a/src/lzma/lzma-sdk.txt b/src/lzma/lzma-sdk.txt -index 9621c8d5d..141b0fd4e 100644 ---- a/src/lzma/lzma-sdk.txt -+++ b/src/lzma/lzma-sdk.txt -@@ -1,4 +1,4 @@ --LZMA SDK 21.07 -+LZMA SDK 23.01 - -------------- - - LZMA SDK provides the documentation, samples, header files, -diff --git a/src/sevenzipfile.cpp b/src/sevenzipfile.cpp -index 7a539a5b3..e65dd3378 100644 ---- a/src/sevenzipfile.cpp -+++ b/src/sevenzipfile.cpp -@@ -283,7 +283,7 @@ bool SevenZipFile::open(QString fileName) - } - m_lookStream.bufSize = kInputBufSize; - m_lookStream.realStream = &m_archiveStream.vt; -- LookToRead2_Init(&m_lookStream); -+ LookToRead2_INIT(&m_lookStream); - CrcGenerateTable(); - SzArEx_Init(db()); - - -From 8b20ee8349cb7e1c8b69c23d28a960caa746e96d Mon Sep 17 00:00:00 2001 -From: Julian Sikorski -Date: Wed, 21 Feb 2024 23:46:52 +0100 -Subject: [PATCH 3/4] imp: updated bundled minizip to 3.0.10 - ---- - src/minizip/README.minizip | 2 +- - src/minizip/mz.h | 45 +++--- - src/minizip/mz_compat.c | 254 +++++++++++++++---------------- - src/minizip/mz_compat.h | 4 +- - src/minizip/mz_crypt.c | 13 +- - src/minizip/mz_crypt.h | 4 +- - src/minizip/mz_os.c | 27 ++-- - src/minizip/mz_os.h | 5 +- - src/minizip/mz_os_posix.c | 88 +++++------ - src/minizip/mz_os_win32.c | 142 ++++++++--------- - src/minizip/mz_strm.c | 58 ++++--- - src/minizip/mz_strm.h | 2 +- - src/minizip/mz_strm_mem.c | 33 ++-- - src/minizip/mz_strm_mem.h | 2 +- - src/minizip/mz_strm_os.h | 2 +- - src/minizip/mz_strm_os_posix.c | 39 +++-- - src/minizip/mz_strm_os_win32.c | 41 ++--- - src/minizip/mz_strm_zlib.c | 25 ++- - src/minizip/mz_strm_zlib.h | 2 +- - src/minizip/mz_zip.c | 269 +++++++++++++++++---------------- - src/minizip/mz_zip.h | 5 +- - 21 files changed, 506 insertions(+), 556 deletions(-) - -diff --git a/src/minizip/README.minizip b/src/minizip/README.minizip -index 4940a1e15..22a0f58b6 100644 ---- a/src/minizip/README.minizip -+++ b/src/minizip/README.minizip -@@ -1 +1 @@ --This code has been taken from https://github.com/zlib-ng/minizip-ng/releases/tag/3.0.5 -+This code has been taken from https://github.com/zlib-ng/minizip-ng/releases/tag/3.0.10 -diff --git a/src/minizip/mz.h b/src/minizip/mz.h -index bcebe08a2..769a7b65a 100644 ---- a/src/minizip/mz.h -+++ b/src/minizip/mz.h -@@ -1,7 +1,7 @@ - /* mz.h -- Errors codes, zip flags and magic - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - - This program is distributed under the terms of the same license as zlib. -@@ -14,8 +14,8 @@ - /***************************************************************************/ - - /* MZ_VERSION */ --#define MZ_VERSION ("3.0.5") --#define MZ_VERSION_BUILD (030005) -+#define MZ_VERSION ("3.0.10") -+#define MZ_VERSION_BUILD (03000a) - - /* MZ_ERROR */ - #define MZ_OK (0) /* zlib */ -@@ -146,13 +146,6 @@ - /* MZ_UTILITY */ - #define MZ_UNUSED(SYMBOL) ((void)SYMBOL) - --#ifndef MZ_CUSTOM_ALLOC --#define MZ_ALLOC(SIZE) (malloc((SIZE))) --#endif --#ifndef MZ_CUSTOM_FREE --#define MZ_FREE(PTR) (free(PTR)) --#endif -- - #if defined(_WIN32) && defined(MZ_EXPORTS) - #define MZ_EXPORT __declspec(dllexport) - #else -@@ -175,25 +168,25 @@ - #endif - - #ifndef INT8_MAX --typedef signed char int8_t; -+typedef signed char int8_t; - #endif - #ifndef INT16_MAX --typedef short int16_t; -+typedef short int16_t; - #endif - #ifndef INT32_MAX --typedef int int32_t; -+typedef int int32_t; - #endif - #ifndef INT64_MAX --typedef long long int64_t; -+typedef long long int64_t; - #endif - #ifndef UINT8_MAX --typedef unsigned char uint8_t; -+typedef unsigned char uint8_t; - #endif - #ifndef UINT16_MAX --typedef unsigned short uint16_t; -+typedef unsigned short uint16_t; - #endif - #ifndef UINT32_MAX --typedef unsigned int uint32_t; -+typedef unsigned int uint32_t; - #endif - #ifndef UINT64_MAX - typedef unsigned long long uint64_t; -@@ -208,13 +201,13 @@ typedef unsigned long long uint64_t; - #endif - - #ifndef PRId8 --# define PRId8 "hhd" -+# define PRId8 "hhd" - #endif - #ifndef PRIu8 --# define PRIu8 "hhu" -+# define PRIu8 "hhu" - #endif - #ifndef PRIx8 --# define PRIx8 "hhx" -+# define PRIx8 "hhx" - #endif - #ifndef PRId16 - # define PRId16 "hd" -@@ -257,22 +250,22 @@ typedef unsigned long long uint64_t; - #endif - - #ifndef INT16_MAX --# define INT16_MAX 32767 -+# define INT16_MAX 32767 - #endif - #ifndef INT32_MAX --# define INT32_MAX 2147483647L -+# define INT32_MAX 2147483647L - #endif - #ifndef INT64_MAX --# define INT64_MAX 9223372036854775807LL -+# define INT64_MAX 9223372036854775807LL - #endif - #ifndef UINT16_MAX --# define UINT16_MAX 65535U -+# define UINT16_MAX 65535U - #endif - #ifndef UINT32_MAX --# define UINT32_MAX 4294967295UL -+# define UINT32_MAX 4294967295UL - #endif - #ifndef UINT64_MAX --# define UINT64_MAX 18446744073709551615ULL -+# define UINT64_MAX 18446744073709551615ULL - #endif - - /***************************************************************************/ -diff --git a/src/minizip/mz_compat.c b/src/minizip/mz_compat.c -index 5a08046a7..fab6bf046 100644 ---- a/src/minizip/mz_compat.c -+++ b/src/minizip/mz_compat.c -@@ -1,7 +1,7 @@ - /* mz_compat.c -- Backwards compatible interface for older versions - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - Copyright (C) 1998-2010 Gilles Vollant - https://www.winimage.com/zLibDll/minizip.html -@@ -10,7 +10,6 @@ - See the accompanying LICENSE file for the full text of the license. - */ - -- - #include "mz.h" - #include "mz_os.h" - #include "mz_strm.h" -@@ -87,12 +86,12 @@ static int32_t mz_stream_ioapi_open(void *stream, const char *path, int32_t mode - else - return MZ_OPEN_ERROR; - -- if (ioapi->filefunc64.zopen64_file != NULL) -+ if (ioapi->filefunc64.zopen64_file) - ioapi->handle = ioapi->filefunc64.zopen64_file(ioapi->filefunc64.opaque, path, ioapi_mode); -- else if (ioapi->filefunc.zopen_file != NULL) -+ else if (ioapi->filefunc.zopen_file) - ioapi->handle = ioapi->filefunc.zopen_file(ioapi->filefunc.opaque, path, ioapi_mode); - -- if (ioapi->handle == NULL) -+ if (!ioapi->handle) - return MZ_PARAM_ERROR; - - return MZ_OK; -@@ -100,7 +99,7 @@ static int32_t mz_stream_ioapi_open(void *stream, const char *path, int32_t mode - - static int32_t mz_stream_ioapi_is_open(void *stream) { - mz_stream_ioapi *ioapi = (mz_stream_ioapi *)stream; -- if (ioapi->handle == NULL) -+ if (!ioapi->handle) - return MZ_OPEN_ERROR; - return MZ_OK; - } -@@ -113,10 +112,10 @@ static int32_t mz_stream_ioapi_read(void *stream, void *buf, int32_t size) { - if (mz_stream_ioapi_is_open(stream) != MZ_OK) - return MZ_OPEN_ERROR; - -- if (ioapi->filefunc64.zread_file != NULL) { -+ if (ioapi->filefunc64.zread_file) { - zread = ioapi->filefunc64.zread_file; - opaque = ioapi->filefunc64.opaque; -- } else if (ioapi->filefunc.zread_file != NULL) { -+ } else if (ioapi->filefunc.zread_file) { - zread = ioapi->filefunc.zread_file; - opaque = ioapi->filefunc.opaque; - } else -@@ -134,10 +133,10 @@ static int32_t mz_stream_ioapi_write(void *stream, const void *buf, int32_t size - if (mz_stream_ioapi_is_open(stream) != MZ_OK) - return MZ_OPEN_ERROR; - -- if (ioapi->filefunc64.zwrite_file != NULL) { -+ if (ioapi->filefunc64.zwrite_file) { - zwrite = ioapi->filefunc64.zwrite_file; - opaque = ioapi->filefunc64.opaque; -- } else if (ioapi->filefunc.zwrite_file != NULL) { -+ } else if (ioapi->filefunc.zwrite_file) { - zwrite = ioapi->filefunc.zwrite_file; - opaque = ioapi->filefunc.opaque; - } else -@@ -153,9 +152,9 @@ static int64_t mz_stream_ioapi_tell(void *stream) { - if (mz_stream_ioapi_is_open(stream) != MZ_OK) - return MZ_OPEN_ERROR; - -- if (ioapi->filefunc64.ztell64_file != NULL) -+ if (ioapi->filefunc64.ztell64_file) - return ioapi->filefunc64.ztell64_file(ioapi->filefunc64.opaque, ioapi->handle); -- else if (ioapi->filefunc.ztell_file != NULL) -+ else if (ioapi->filefunc.ztell_file) - return ioapi->filefunc.ztell_file(ioapi->filefunc.opaque, ioapi->handle); - - return MZ_INTERNAL_ERROR; -@@ -163,16 +162,14 @@ static int64_t mz_stream_ioapi_tell(void *stream) { - - static int32_t mz_stream_ioapi_seek(void *stream, int64_t offset, int32_t origin) { - mz_stream_ioapi *ioapi = (mz_stream_ioapi *)stream; -- int32_t written = 0; -- void *opaque = NULL; - - if (mz_stream_ioapi_is_open(stream) != MZ_OK) - return MZ_OPEN_ERROR; - -- if (ioapi->filefunc64.zseek64_file != NULL) { -+ if (ioapi->filefunc64.zseek64_file) { - if (ioapi->filefunc64.zseek64_file(ioapi->filefunc64.opaque, ioapi->handle, offset, origin) != 0) - return MZ_INTERNAL_ERROR; -- } else if (ioapi->filefunc.zseek_file != NULL) { -+ } else if (ioapi->filefunc.zseek_file) { - if (ioapi->filefunc.zseek_file(ioapi->filefunc.opaque, ioapi->handle, (int32_t)offset, origin) != 0) - return MZ_INTERNAL_ERROR; - } else -@@ -189,10 +186,10 @@ static int32_t mz_stream_ioapi_close(void *stream) { - if (mz_stream_ioapi_is_open(stream) != MZ_OK) - return MZ_OPEN_ERROR; - -- if (ioapi->filefunc.zclose_file != NULL) { -+ if (ioapi->filefunc.zclose_file) { - zclose = ioapi->filefunc.zclose_file; - opaque = ioapi->filefunc.opaque; -- } else if (ioapi->filefunc64.zclose_file != NULL) { -+ } else if (ioapi->filefunc64.zclose_file) { - zclose = ioapi->filefunc64.zclose_file; - opaque = ioapi->filefunc64.opaque; - } else -@@ -212,10 +209,10 @@ static int32_t mz_stream_ioapi_error(void *stream) { - if (mz_stream_ioapi_is_open(stream) != MZ_OK) - return MZ_OPEN_ERROR; - -- if (ioapi->filefunc.zerror_file != NULL) { -+ if (ioapi->filefunc.zerror_file) { - zerror = ioapi->filefunc.zerror_file; - opaque = ioapi->filefunc.opaque; -- } else if (ioapi->filefunc64.zerror_file != NULL) { -+ } else if (ioapi->filefunc64.zerror_file) { - zerror = ioapi->filefunc64.zerror_file; - opaque = ioapi->filefunc64.opaque; - } else -@@ -239,12 +236,10 @@ static int32_t mz_stream_ioapi_set_filefunc64(void *stream, zlib_filefunc64_def - static void *mz_stream_ioapi_create(void **stream) { - mz_stream_ioapi *ioapi = NULL; - -- ioapi = (mz_stream_ioapi *)MZ_ALLOC(sizeof(mz_stream_ioapi)); -- if (ioapi != NULL) { -- memset(ioapi, 0, sizeof(mz_stream_ioapi)); -+ ioapi = (mz_stream_ioapi *)calloc(1, sizeof(mz_stream_ioapi)); -+ if (ioapi) - ioapi->stream.vtbl = &mz_stream_ioapi_vtbl; -- } -- if (stream != NULL) -+ if (stream) - *stream = ioapi; - - return ioapi; -@@ -252,11 +247,11 @@ static void *mz_stream_ioapi_create(void **stream) { - - static void mz_stream_ioapi_delete(void **stream) { - mz_stream_ioapi *ioapi = NULL; -- if (stream == NULL) -+ if (!stream) - return; - ioapi = (mz_stream_ioapi *)*stream; -- if (ioapi != NULL) -- MZ_FREE(ioapi); -+ if (ioapi) -+ free(ioapi); - *stream = NULL; - } - -@@ -264,41 +259,41 @@ static void mz_stream_ioapi_delete(void **stream) { - - void fill_fopen_filefunc(zlib_filefunc_def *pzlib_filefunc_def) { - /* For 32-bit file support only, compile with MZ_FILE32_API */ -- if (pzlib_filefunc_def != NULL) -+ if (pzlib_filefunc_def) - memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc_def)); - } - - void fill_fopen64_filefunc(zlib_filefunc64_def *pzlib_filefunc_def) { - /* All mz_stream_os_* support large files if compilation supports it */ -- if (pzlib_filefunc_def != NULL) -+ if (pzlib_filefunc_def) - memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc64_def)); - } - - void fill_win32_filefunc(zlib_filefunc_def *pzlib_filefunc_def) { - /* Handled by mz_stream_os_win32 */ -- if (pzlib_filefunc_def != NULL) -+ if (pzlib_filefunc_def) - memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc_def)); - } - - void fill_win32_filefunc64(zlib_filefunc64_def *pzlib_filefunc_def) { - /* Automatically supported in mz_stream_os_win32 */ -- if (pzlib_filefunc_def != NULL) -+ if (pzlib_filefunc_def) - memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc64_def)); - } - - void fill_win32_filefunc64A(zlib_filefunc64_def *pzlib_filefunc_def) { - /* Automatically supported in mz_stream_os_win32 */ -- if (pzlib_filefunc_def != NULL) -+ if (pzlib_filefunc_def) - memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc64_def)); - } - --/* NOTE: fill_win32_filefunc64W is no longer necessary since wide-character -- support is automatically handled by the underlying os stream. Do not -+/* NOTE: fill_win32_filefunc64W is no longer necessary since wide-character -+ support is automatically handled by the underlying os stream. Do not - pass wide-characters to zipOpen or unzOpen. */ - - void fill_memory_filefunc(zlib_filefunc_def *pzlib_filefunc_def) { - /* Use opaque to indicate which stream interface to create */ -- if (pzlib_filefunc_def != NULL) { -+ if (pzlib_filefunc_def) { - memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc_def)); - pzlib_filefunc_def->opaque = mz_stream_mem_get_interface(); - } -@@ -330,25 +325,25 @@ zipFile zipOpen64(const void *path, int append) { - return zipOpen2(path, append, NULL, NULL); - } - --zipFile zipOpen2(const char *path, int append, const char **globalcomment, -+zipFile zipOpen2(const char *path, int append, const char **globalcomment, - zlib_filefunc_def *pzlib_filefunc_def) { - zipFile zip = NULL; - int32_t mode = zipConvertAppendToStreamMode(append); - void *stream = NULL; - - if (pzlib_filefunc_def) { -- if (pzlib_filefunc_def->zopen_file != NULL) { -- if (mz_stream_ioapi_create(&stream) == NULL) -+ if (pzlib_filefunc_def->zopen_file) { -+ if (!mz_stream_ioapi_create(&stream)) - return NULL; - mz_stream_ioapi_set_filefunc(stream, pzlib_filefunc_def); -- } else if (pzlib_filefunc_def->opaque != NULL) { -- if (mz_stream_create(&stream, (mz_stream_vtbl *)pzlib_filefunc_def->opaque) == NULL) -+ } else if (pzlib_filefunc_def->opaque) { -+ if (!mz_stream_create(&stream, (mz_stream_vtbl *)pzlib_filefunc_def->opaque)) - return NULL; - } - } - -- if (stream == NULL) { -- if (mz_stream_os_create(&stream) == NULL) -+ if (!stream) { -+ if (!mz_stream_os_create(&stream)) - return NULL; - } - -@@ -359,7 +354,7 @@ zipFile zipOpen2(const char *path, int append, const char **globalcomment, - - zip = zipOpen_MZ(stream, append, globalcomment); - -- if (zip == NULL) { -+ if (!zip) { - mz_stream_delete(&stream); - return NULL; - } -@@ -367,25 +362,25 @@ zipFile zipOpen2(const char *path, int append, const char **globalcomment, - return zip; - } - --zipFile zipOpen2_64(const void *path, int append, const char **globalcomment, -+zipFile zipOpen2_64(const void *path, int append, const char **globalcomment, - zlib_filefunc64_def *pzlib_filefunc_def) { - zipFile zip = NULL; - int32_t mode = zipConvertAppendToStreamMode(append); - void *stream = NULL; - - if (pzlib_filefunc_def) { -- if (pzlib_filefunc_def->zopen64_file != NULL) { -- if (mz_stream_ioapi_create(&stream) == NULL) -+ if (pzlib_filefunc_def->zopen64_file) { -+ if (!mz_stream_ioapi_create(&stream)) - return NULL; - mz_stream_ioapi_set_filefunc64(stream, pzlib_filefunc_def); -- } else if (pzlib_filefunc_def->opaque != NULL) { -- if (mz_stream_create(&stream, (mz_stream_vtbl *)pzlib_filefunc_def->opaque) == NULL) -+ } else if (pzlib_filefunc_def->opaque) { -+ if (!mz_stream_create(&stream, (mz_stream_vtbl *)pzlib_filefunc_def->opaque)) - return NULL; - } - } - -- if (stream == NULL) { -- if (mz_stream_os_create(&stream) == NULL) -+ if (!stream) { -+ if (!mz_stream_os_create(&stream)) - return NULL; - } - -@@ -396,7 +391,7 @@ zipFile zipOpen2_64(const void *path, int append, const char **globalcomment, - - zip = zipOpen_MZ(stream, append, globalcomment); - -- if (zip == NULL) { -+ if (!zip) { - mz_stream_delete(&stream); - return NULL; - } -@@ -418,11 +413,11 @@ zipFile zipOpen_MZ(void *stream, int append, const char **globalcomment) { - return NULL; - } - -- if (globalcomment != NULL) -+ if (globalcomment) - mz_zip_get_comment(handle, globalcomment); - -- compat = (mz_compat *)MZ_ALLOC(sizeof(mz_compat)); -- if (compat != NULL) { -+ compat = (mz_compat *)calloc(1, sizeof(mz_compat)); -+ if (compat) { - compat->handle = handle; - compat->stream = stream; - } else { -@@ -434,14 +429,14 @@ zipFile zipOpen_MZ(void *stream, int append, const char **globalcomment) { - - void* zipGetHandle_MZ(zipFile file) { - mz_compat *compat = (mz_compat *)file; -- if (compat == NULL) -+ if (!compat) - return NULL; - return compat->handle; - } - - void* zipGetStream_MZ(zipFile file) { - mz_compat *compat = (mz_compat *)file; -- if (compat == NULL) -+ if (!compat) - return NULL; - return (void *)compat->stream; - } -@@ -461,12 +456,12 @@ int zipOpenNewFileInZip5(zipFile file, const char *filename, const zip_fileinfo - MZ_UNUSED(extrafield_local); - MZ_UNUSED(crc_for_crypting); - -- if (compat == NULL) -+ if (!compat) - return ZIP_PARAMERROR; - - memset(&file_info, 0, sizeof(file_info)); - -- if (zipfi != NULL) { -+ if (zipfi) { - uint64_t dos_date = 0; - - if (zipfi->mz_dos_date != 0) -@@ -479,7 +474,7 @@ int zipOpenNewFileInZip5(zipFile file, const char *filename, const zip_fileinfo - file_info.internal_fa = zipfi->internal_fa; - } - -- if (filename == NULL) -+ if (!filename) - filename = "-"; - - file_info.compression_method = (uint16_t)compression_method; -@@ -490,7 +485,7 @@ int zipOpenNewFileInZip5(zipFile file, const char *filename, const zip_fileinfo - file_info.extrafield_size = size_extrafield_global; - file_info.version_madeby = (uint16_t)version_madeby; - file_info.comment = comment; -- if (file_info.comment != NULL) -+ if (file_info.comment) - file_info.comment_size = (uint16_t)strlen(file_info.comment); - file_info.flag = (uint16_t)flag_base; - if (zip64) -@@ -498,7 +493,7 @@ int zipOpenNewFileInZip5(zipFile file, const char *filename, const zip_fileinfo - else - file_info.zip64 = MZ_ZIP64_DISABLE; - #ifdef HAVE_WZAES -- if ((password != NULL) || (raw && (file_info.flag & MZ_ZIP_FLAG_ENCRYPTED))) -+ if (password || (raw && (file_info.flag & MZ_ZIP_FLAG_ENCRYPTED))) - file_info.aes_version = MZ_AES_VERSION; - #endif - -@@ -581,7 +576,7 @@ int zipOpenNewFileInZip_64(zipFile file, const char *filename, const zip_fileinf - int zipWriteInFileInZip(zipFile file, const void *buf, uint32_t len) { - mz_compat *compat = (mz_compat *)file; - int32_t written = 0; -- if (compat == NULL || len >= INT32_MAX) -+ if (!compat || len >= INT32_MAX) - return ZIP_PARAMERROR; - written = mz_zip_entry_write(compat->handle, buf, (int32_t)len); - if ((written < 0) || ((uint32_t)written != len)) -@@ -595,7 +590,7 @@ int zipCloseFileInZipRaw(zipFile file, unsigned long uncompressed_size, unsigned - - int zipCloseFileInZipRaw64(zipFile file, uint64_t uncompressed_size, unsigned long crc32) { - mz_compat *compat = (mz_compat *)file; -- if (compat == NULL) -+ if (!compat) - return ZIP_PARAMERROR; - return mz_zip_entry_close_raw(compat->handle, (int64_t)uncompressed_size, crc32); - } -@@ -606,7 +601,7 @@ int zipCloseFileInZip(zipFile file) { - - int zipCloseFileInZip64(zipFile file) { - mz_compat *compat = (mz_compat *)file; -- if (compat == NULL) -+ if (!compat) - return ZIP_PARAMERROR; - return mz_zip_entry_close(compat->handle); - } -@@ -623,15 +618,15 @@ int zipClose2_64(zipFile file, const char *global_comment, uint16_t version_made - mz_compat *compat = (mz_compat *)file; - int32_t err = MZ_OK; - -- if (compat->handle != NULL) -+ if (compat->handle) - err = zipClose2_MZ(file, global_comment, version_madeby); - -- if (compat->stream != NULL) { -+ if (compat->stream) { - mz_stream_close(compat->stream); - mz_stream_delete(&compat->stream); - } - -- MZ_FREE(compat); -+ free(compat); - - return err; - } -@@ -646,12 +641,12 @@ int zipClose2_MZ(zipFile file, const char *global_comment, uint16_t version_made - mz_compat *compat = (mz_compat *)file; - int32_t err = MZ_OK; - -- if (compat == NULL) -+ if (!compat) - return ZIP_PARAMERROR; -- if (compat->handle == NULL) -+ if (!compat->handle) - return err; - -- if (global_comment != NULL) -+ if (global_comment) - mz_zip_set_comment(compat->handle, global_comment); - - mz_zip_set_version_madeby(compat->handle, version_madeby); -@@ -676,18 +671,18 @@ unzFile unzOpen2(const char *path, zlib_filefunc_def *pzlib_filefunc_def) { - void *stream = NULL; - - if (pzlib_filefunc_def) { -- if (pzlib_filefunc_def->zopen_file != NULL) { -- if (mz_stream_ioapi_create(&stream) == NULL) -+ if (pzlib_filefunc_def->zopen_file) { -+ if (!mz_stream_ioapi_create(&stream)) - return NULL; - mz_stream_ioapi_set_filefunc(stream, pzlib_filefunc_def); -- } else if (pzlib_filefunc_def->opaque != NULL) { -- if (mz_stream_create(&stream, (mz_stream_vtbl *)pzlib_filefunc_def->opaque) == NULL) -+ } else if (pzlib_filefunc_def->opaque) { -+ if (!mz_stream_create(&stream, (mz_stream_vtbl *)pzlib_filefunc_def->opaque)) - return NULL; - } - } - -- if (stream == NULL) { -- if (mz_stream_os_create(&stream) == NULL) -+ if (!stream) { -+ if (!mz_stream_os_create(&stream)) - return NULL; - } - -@@ -697,7 +692,7 @@ unzFile unzOpen2(const char *path, zlib_filefunc_def *pzlib_filefunc_def) { - } - - unz = unzOpen_MZ(stream); -- if (unz == NULL) { -+ if (!unz) { - mz_stream_close(stream); - mz_stream_delete(&stream); - return NULL; -@@ -710,18 +705,18 @@ unzFile unzOpen2_64(const void *path, zlib_filefunc64_def *pzlib_filefunc_def) { - void *stream = NULL; - - if (pzlib_filefunc_def) { -- if (pzlib_filefunc_def->zopen64_file != NULL) { -- if (mz_stream_ioapi_create(&stream) == NULL) -+ if (pzlib_filefunc_def->zopen64_file) { -+ if (!mz_stream_ioapi_create(&stream)) - return NULL; - mz_stream_ioapi_set_filefunc64(stream, pzlib_filefunc_def); -- } else if (pzlib_filefunc_def->opaque != NULL) { -- if (mz_stream_create(&stream, (mz_stream_vtbl *)pzlib_filefunc_def->opaque) == NULL) -+ } else if (pzlib_filefunc_def->opaque) { -+ if (!mz_stream_create(&stream, (mz_stream_vtbl *)pzlib_filefunc_def->opaque)) - return NULL; - } - } - -- if (stream == NULL) { -- if (mz_stream_os_create(&stream) == NULL) -+ if (!stream) { -+ if (!mz_stream_os_create(&stream)) - return NULL; - } - -@@ -731,7 +726,7 @@ unzFile unzOpen2_64(const void *path, zlib_filefunc64_def *pzlib_filefunc_def) { - } - - unz = unzOpen_MZ(stream); -- if (unz == NULL) { -+ if (!unz) { - mz_stream_close(stream); - mz_stream_delete(&stream); - return NULL; -@@ -741,14 +736,14 @@ unzFile unzOpen2_64(const void *path, zlib_filefunc64_def *pzlib_filefunc_def) { - - void* unzGetHandle_MZ(unzFile file) { - mz_compat *compat = (mz_compat *)file; -- if (compat == NULL) -+ if (!compat) - return NULL; - return compat->handle; - } - - void* unzGetStream_MZ(unzFile file) { - mz_compat *compat = (mz_compat *)file; -- if (compat == NULL) -+ if (!compat) - return NULL; - return compat->stream; - } -@@ -766,8 +761,8 @@ unzFile unzOpen_MZ(void *stream) { - return NULL; - } - -- compat = (mz_compat *)MZ_ALLOC(sizeof(mz_compat)); -- if (compat != NULL) { -+ compat = (mz_compat *)calloc(1, sizeof(mz_compat)); -+ if (compat) { - compat->handle = handle; - compat->stream = stream; - -@@ -783,18 +778,18 @@ int unzClose(unzFile file) { - mz_compat *compat = (mz_compat *)file; - int32_t err = MZ_OK; - -- if (compat == NULL) -+ if (!compat) - return UNZ_PARAMERROR; - -- if (compat->handle != NULL) -+ if (compat->handle) - err = unzClose_MZ(file); - -- if (compat->stream != NULL) { -+ if (compat->stream) { - mz_stream_close(compat->stream); - mz_stream_delete(&compat->stream); - } - -- MZ_FREE(compat); -+ free(compat); - - return err; - } -@@ -804,7 +799,7 @@ int unzClose_MZ(unzFile file) { - mz_compat *compat = (mz_compat *)file; - int32_t err = MZ_OK; - -- if (compat == NULL) -+ if (!compat) - return UNZ_PARAMERROR; - - err = mz_zip_close(compat->handle); -@@ -819,7 +814,7 @@ int unzGetGlobalInfo(unzFile file, unz_global_info* pglobal_info32) { - int32_t err = MZ_OK; - - memset(pglobal_info32, 0, sizeof(unz_global_info)); -- if (compat == NULL) -+ if (!compat) - return UNZ_PARAMERROR; - - err = unzGetGlobalInfo64(file, &global_info64); -@@ -837,7 +832,7 @@ int unzGetGlobalInfo64(unzFile file, unz_global_info64 *pglobal_info) { - int32_t err = MZ_OK; - - memset(pglobal_info, 0, sizeof(unz_global_info64)); -- if (compat == NULL) -+ if (!compat) - return UNZ_PARAMERROR; - err = mz_zip_get_comment(compat->handle, &comment_ptr); - if (err == MZ_OK) -@@ -854,7 +849,7 @@ int unzGetGlobalComment(unzFile file, char *comment, unsigned long comment_size) - const char *comment_ptr = NULL; - int32_t err = MZ_OK; - -- if (comment == NULL || comment_size == 0) -+ if (!comment || !comment_size) - return UNZ_PARAMERROR; - err = mz_zip_get_comment(compat->handle, &comment_ptr); - if (err == MZ_OK) { -@@ -870,23 +865,28 @@ int unzOpenCurrentFile3(unzFile file, int *method, int *level, int raw, const ch - int32_t err = MZ_OK; - void *stream = NULL; - -- if (compat == NULL) -+ if (!compat) - return UNZ_PARAMERROR; -- if (method != NULL) -+ if (method) - *method = 0; -- if (level != NULL) -+ if (level) - *level = 0; - -+ if (mz_zip_entry_is_open(compat->handle) == MZ_OK) { -+ /* zlib minizip does not error out here if close returns errors */ -+ unzCloseCurrentFile(file); -+ } -+ - compat->total_out = 0; - err = mz_zip_entry_read_open(compat->handle, (uint8_t)raw, password); - if (err == MZ_OK) - err = mz_zip_entry_get_info(compat->handle, &file_info); - if (err == MZ_OK) { -- if (method != NULL) { -+ if (method) { - *method = file_info->compression_method; - } - -- if (level != NULL) { -+ if (level) { - *level = 6; - switch (file_info->flag & 0x06) { - case MZ_ZIP_FLAG_DEFLATE_SUPER_FAST: -@@ -923,7 +923,7 @@ int unzOpenCurrentFile2(unzFile file, int *method, int *level, int raw) { - int unzReadCurrentFile(unzFile file, void *buf, uint32_t len) { - mz_compat *compat = (mz_compat *)file; - int32_t err = MZ_OK; -- if (compat == NULL || len >= INT32_MAX) -+ if (!compat || len >= INT32_MAX) - return UNZ_PARAMERROR; - err = mz_zip_entry_read(compat->handle, buf, (int32_t)len); - if (err > 0) -@@ -934,7 +934,7 @@ int unzReadCurrentFile(unzFile file, void *buf, uint32_t len) { - int unzCloseCurrentFile(unzFile file) { - mz_compat *compat = (mz_compat *)file; - int32_t err = MZ_OK; -- if (compat == NULL) -+ if (!compat) - return UNZ_PARAMERROR; - err = mz_zip_entry_close(compat->handle); - return err; -@@ -948,14 +948,14 @@ int unzGetCurrentFileInfo(unzFile file, unz_file_info *pfile_info, char *filenam - uint16_t bytes_to_copy = 0; - int32_t err = MZ_OK; - -- if (compat == NULL) -+ if (!compat) - return UNZ_PARAMERROR; - - err = mz_zip_entry_get_info(compat->handle, &file_info); - if (err != MZ_OK) - return err; - -- if (pfile_info != NULL) { -+ if (pfile_info) { - pfile_info->version = file_info->version_madeby; - pfile_info->version_needed = file_info->version_needed; - pfile_info->flag = file_info->flag; -@@ -976,7 +976,7 @@ int unzGetCurrentFileInfo(unzFile file, unz_file_info *pfile_info, char *filenam - pfile_info->compressed_size = (uint32_t)file_info->compressed_size; - pfile_info->uncompressed_size = (uint32_t)file_info->uncompressed_size; - } -- if (filename_size > 0 && filename != NULL && file_info->filename != NULL) { -+ if (filename_size > 0 && filename && file_info->filename) { - bytes_to_copy = (uint16_t)filename_size; - if (bytes_to_copy > file_info->filename_size) - bytes_to_copy = file_info->filename_size; -@@ -984,13 +984,13 @@ int unzGetCurrentFileInfo(unzFile file, unz_file_info *pfile_info, char *filenam - if (bytes_to_copy < filename_size) - filename[bytes_to_copy] = 0; - } -- if (extrafield_size > 0 && extrafield != NULL) { -+ if (extrafield_size > 0 && extrafield) { - bytes_to_copy = (uint16_t)extrafield_size; - if (bytes_to_copy > file_info->extrafield_size) - bytes_to_copy = file_info->extrafield_size; - memcpy(extrafield, file_info->extrafield, bytes_to_copy); - } -- if (comment_size > 0 && comment != NULL && file_info->comment != NULL) { -+ if (comment_size > 0 && comment && file_info->comment) { - bytes_to_copy = (uint16_t)comment_size; - if (bytes_to_copy > file_info->comment_size) - bytes_to_copy = file_info->comment_size; -@@ -1009,14 +1009,14 @@ int unzGetCurrentFileInfo64(unzFile file, unz_file_info64 * pfile_info, char *fi - uint16_t bytes_to_copy = 0; - int32_t err = MZ_OK; - -- if (compat == NULL) -+ if (!compat) - return UNZ_PARAMERROR; - - err = mz_zip_entry_get_info(compat->handle, &file_info); - if (err != MZ_OK) - return err; - -- if (pfile_info != NULL) { -+ if (pfile_info) { - pfile_info->version = file_info->version_madeby; - pfile_info->version_needed = file_info->version_needed; - pfile_info->flag = file_info->flag; -@@ -1037,7 +1037,7 @@ int unzGetCurrentFileInfo64(unzFile file, unz_file_info64 * pfile_info, char *fi - pfile_info->compressed_size = (uint64_t)file_info->compressed_size; - pfile_info->uncompressed_size = (uint64_t)file_info->uncompressed_size; - } -- if (filename_size > 0 && filename != NULL && file_info->filename != NULL) { -+ if (filename_size > 0 && filename && file_info->filename) { - bytes_to_copy = (uint16_t)filename_size; - if (bytes_to_copy > file_info->filename_size) - bytes_to_copy = file_info->filename_size; -@@ -1045,13 +1045,13 @@ int unzGetCurrentFileInfo64(unzFile file, unz_file_info64 * pfile_info, char *fi - if (bytes_to_copy < filename_size) - filename[bytes_to_copy] = 0; - } -- if (extrafield_size > 0 && extrafield != NULL) { -+ if (extrafield_size > 0 && extrafield) { - bytes_to_copy = (uint16_t)extrafield_size; - if (bytes_to_copy > file_info->extrafield_size) - bytes_to_copy = file_info->extrafield_size; - memcpy(extrafield, file_info->extrafield, bytes_to_copy); - } -- if (comment_size > 0 && comment != NULL && file_info->comment != NULL) { -+ if (comment_size > 0 && comment && file_info->comment) { - bytes_to_copy = (uint16_t)comment_size; - if (bytes_to_copy > file_info->comment_size) - bytes_to_copy = file_info->comment_size; -@@ -1064,7 +1064,7 @@ int unzGetCurrentFileInfo64(unzFile file, unz_file_info64 * pfile_info, char *fi - - int unzGoToFirstFile(unzFile file) { - mz_compat *compat = (mz_compat *)file; -- if (compat == NULL) -+ if (!compat) - return UNZ_PARAMERROR; - compat->entry_index = 0; - return mz_zip_goto_first_entry(compat->handle); -@@ -1073,7 +1073,7 @@ int unzGoToFirstFile(unzFile file) { - int unzGoToNextFile(unzFile file) { - mz_compat *compat = (mz_compat *)file; - int32_t err = MZ_OK; -- if (compat == NULL) -+ if (!compat) - return UNZ_PARAMERROR; - err = mz_zip_goto_next_entry(compat->handle); - if (err != MZ_END_OF_LIST) -@@ -1088,7 +1088,7 @@ int unzLocateFile(unzFile file, const char *filename, unzFileNameComparer filena - int32_t err = MZ_OK; - int32_t result = 0; - -- if (compat == NULL) -+ if (!compat) - return UNZ_PARAMERROR; - - preserve_index = compat->entry_index; -@@ -1135,7 +1135,7 @@ int unzGoToFilePos(unzFile file, unz_file_pos *file_pos) { - mz_compat *compat = (mz_compat *)file; - unz64_file_pos file_pos64; - -- if (compat == NULL || file_pos == NULL) -+ if (!compat || !file_pos) - return UNZ_PARAMERROR; - - file_pos64.pos_in_zip_directory = file_pos->pos_in_zip_directory; -@@ -1148,7 +1148,7 @@ int unzGetFilePos64(unzFile file, unz64_file_pos *file_pos) { - mz_compat *compat = (mz_compat *)file; - int64_t offset = 0; - -- if (compat == NULL || file_pos == NULL) -+ if (!compat || !file_pos) - return UNZ_PARAMERROR; - - offset = unzGetOffset64(file); -@@ -1164,7 +1164,7 @@ int unzGoToFilePos64(unzFile file, const unz64_file_pos *file_pos) { - mz_compat *compat = (mz_compat *)file; - int32_t err = MZ_OK; - -- if (compat == NULL || file_pos == NULL) -+ if (!compat || !file_pos) - return UNZ_PARAMERROR; - - err = mz_zip_goto_entry(compat->handle, file_pos->pos_in_zip_directory); -@@ -1179,7 +1179,7 @@ unsigned long unzGetOffset(unzFile file) { - - int64_t unzGetOffset64(unzFile file) { - mz_compat *compat = (mz_compat *)file; -- if (compat == NULL) -+ if (!compat) - return UNZ_PARAMERROR; - return mz_zip_get_entry(compat->handle); - } -@@ -1190,7 +1190,7 @@ int unzSetOffset(unzFile file, unsigned long pos) { - - int unzSetOffset64(unzFile file, int64_t pos) { - mz_compat *compat = (mz_compat *)file; -- if (compat == NULL) -+ if (!compat) - return UNZ_PARAMERROR; - return (int)mz_zip_goto_entry(compat->handle, pos); - } -@@ -1201,7 +1201,7 @@ int unzGetLocalExtrafield(unzFile file, void *buf, unsigned int len) { - int32_t err = MZ_OK; - int32_t bytes_to_copy = 0; - -- if (compat == NULL || buf == NULL || len >= INT32_MAX) -+ if (!compat || !buf || len >= INT32_MAX) - return UNZ_PARAMERROR; - - err = mz_zip_entry_get_local_info(compat->handle, &file_info); -@@ -1230,7 +1230,7 @@ uint64_t unzTell64(unzFile file) { - - uint64_t unztell64(unzFile file) { - mz_compat *compat = (mz_compat *)file; -- if (compat == NULL) -+ if (!compat) - return UNZ_PARAMERROR; - return compat->total_out; - } -@@ -1246,7 +1246,7 @@ int unzSeek64(unzFile file, int64_t offset, int origin) { - int32_t err = MZ_OK; - void *stream = NULL; - -- if (compat == NULL) -+ if (!compat) - return UNZ_PARAMERROR; - err = mz_zip_entry_get_info(compat->handle, &file_info); - if (err != MZ_OK) -@@ -1283,7 +1283,7 @@ int unzeof(unzFile file) { - mz_zip_file *file_info = NULL; - int32_t err = MZ_OK; - -- if (compat == NULL) -+ if (!compat) - return UNZ_PARAMERROR; - err = mz_zip_entry_get_info(compat->handle, &file_info); - if (err != MZ_OK) -@@ -1295,7 +1295,7 @@ int unzeof(unzFile file) { - - void* unzGetStream(unzFile file) { - mz_compat *compat = (mz_compat *)file; -- if (compat == NULL) -+ if (!compat) - return NULL; - return (void *)compat->stream; - } -diff --git a/src/minizip/mz_compat.h b/src/minizip/mz_compat.h -index 808cc74e1..6e6a916ff 100644 ---- a/src/minizip/mz_compat.h -+++ b/src/minizip/mz_compat.h -@@ -1,7 +1,7 @@ - /* mz_compat.h -- Backwards compatible interface for older versions - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - Copyright (C) 1998-2010 Gilles Vollant - https://www.winimage.com/zLibDll/minizip.html -@@ -63,7 +63,7 @@ typedef uint64_t ZPOS64_T; - typedef void* (ZCALLBACK *open_file_func) (void *opaque, const char *filename, int mode); - typedef void* (ZCALLBACK *open64_file_func) (void *opaque, const void *filename, int mode); - typedef unsigned long (ZCALLBACK *read_file_func) (void *opaque, void *stream, void* buf, unsigned long size); --typedef unsigned long (ZCALLBACK *write_file_func) (void *opaque, void *stream, const void* buf, -+typedef unsigned long (ZCALLBACK *write_file_func) (void *opaque, void *stream, const void* buf, - unsigned long size); - typedef int (ZCALLBACK *close_file_func) (void *opaque, void *stream); - typedef int (ZCALLBACK *testerror_file_func)(void *opaque, void *stream); -diff --git a/src/minizip/mz_crypt.c b/src/minizip/mz_crypt.c -index f21b3a1ab..0f3f28433 100644 ---- a/src/minizip/mz_crypt.c -+++ b/src/minizip/mz_crypt.c -@@ -1,14 +1,13 @@ - /* mz_crypt.c -- Crypto/hash functions - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - - This program is distributed under the terms of the same license as zlib. - See the accompanying LICENSE file for the full text of the license. - */ - -- - #include "mz.h" - #include "mz_os.h" - #include "mz_crypt.h" -@@ -16,7 +15,7 @@ - #if defined(HAVE_ZLIB) - # if !defined(ZLIB_COMPAT) - # include "zlib-ng.h" --# define ZLIB_PREFIX(x) zng_ ## x -+# define ZLIB_PREFIX(x) zng_##x - # else - # include "zlib.h" - # define ZLIB_PREFIX(x) x -@@ -105,19 +104,19 @@ uint32_t mz_crypt_crc32_update(uint32_t value, const uint8_t *buf, int32_t size) - - #if defined(HAVE_WZAES) - int32_t mz_crypt_pbkdf2(uint8_t *password, int32_t password_length, uint8_t *salt, -- int32_t salt_length, int32_t iteration_count, uint8_t *key, int32_t key_length) { -+ int32_t salt_length, uint32_t iteration_count, uint8_t *key, uint16_t key_length) { - void *hmac1 = NULL; - void *hmac2 = NULL; - void *hmac3 = NULL; - int32_t err = MZ_OK; - uint16_t i = 0; -- uint16_t j = 0; -+ uint32_t j = 0; - uint16_t k = 0; - uint16_t block_count = 0; - uint8_t uu[MZ_HASH_SHA1_SIZE]; - uint8_t ux[MZ_HASH_SHA1_SIZE]; - -- if (password == NULL || salt == NULL || key == NULL) -+ if (!password || !salt || !key) - return MZ_PARAM_ERROR; - - memset(key, 0, key_length); -@@ -157,7 +156,7 @@ int32_t mz_crypt_pbkdf2(uint8_t *password, int32_t password_length, uint8_t *sa - if (err != MZ_OK) - break; - -- for(k = 0; k < MZ_HASH_SHA1_SIZE; k += 1) -+ for (k = 0; k < MZ_HASH_SHA1_SIZE; k += 1) - ux[k] ^= uu[k]; - - err = mz_crypt_hmac_copy(hmac1, hmac3); -diff --git a/src/minizip/mz_crypt.h b/src/minizip/mz_crypt.h -index 59a193c02..9a341fc61 100644 ---- a/src/minizip/mz_crypt.h -+++ b/src/minizip/mz_crypt.h -@@ -1,7 +1,7 @@ - /* mz_crypt.h -- Crypto/hash functions - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - - This program is distributed under the terms of the same license as zlib. -@@ -20,7 +20,7 @@ extern "C" { - uint32_t mz_crypt_crc32_update(uint32_t value, const uint8_t *buf, int32_t size); - - int32_t mz_crypt_pbkdf2(uint8_t *password, int32_t password_length, uint8_t *salt, -- int32_t salt_length, int32_t iteration_count, uint8_t *key, int32_t key_length); -+ int32_t salt_length, uint32_t iteration_count, uint8_t *key, uint16_t key_length); - - /***************************************************************************/ - -diff --git a/src/minizip/mz_os.c b/src/minizip/mz_os.c -index c93ed0475..6a3706086 100644 ---- a/src/minizip/mz_os.c -+++ b/src/minizip/mz_os.c -@@ -1,7 +1,7 @@ - /* mz_os.c -- System functions - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - Copyright (C) 1998-2010 Gilles Vollant - https://www.winimage.com/zLibDll/minizip.html -@@ -17,13 +17,14 @@ - #include "mz_strm_os.h" - - #include /* tolower */ -+#include - - /***************************************************************************/ - - int32_t mz_path_combine(char *path, const char *join, int32_t max_path) { - int32_t path_len = 0; - -- if (path == NULL || join == NULL || max_path == 0) -+ if (!path || !join || !max_path) - return MZ_PARAM_ERROR; - - path_len = (int32_t)strlen(path); -@@ -130,7 +131,6 @@ int32_t mz_path_resolve(const char *path, char *output, int32_t max_output) { - const char *check = output; - char *target = output; - -- - if (max_output <= 0) - return MZ_PARAM_ERROR; - -@@ -213,7 +213,7 @@ int32_t mz_path_resolve(const char *path, char *output, int32_t max_output) { - int32_t mz_path_remove_filename(char *path) { - char *path_ptr = NULL; - -- if (path == NULL) -+ if (!path) - return MZ_PARAM_ERROR; - - path_ptr = path + strlen(path) - 1; -@@ -236,7 +236,7 @@ int32_t mz_path_remove_filename(char *path) { - int32_t mz_path_remove_extension(char *path) { - char *path_ptr = NULL; - -- if (path == NULL) -+ if (!path) - return MZ_PARAM_ERROR; - - path_ptr = path + strlen(path) - 1; -@@ -261,7 +261,7 @@ int32_t mz_path_remove_extension(char *path) { - int32_t mz_path_get_filename(const char *path, const char **filename) { - const char *match = NULL; - -- if (path == NULL || filename == NULL) -+ if (!path || !filename) - return MZ_PARAM_ERROR; - - *filename = NULL; -@@ -271,7 +271,7 @@ int32_t mz_path_get_filename(const char *path, const char **filename) { - *filename = match + 1; - } - -- if (*filename == NULL) -+ if (!*filename) - return MZ_EXIST_ERROR; - - return MZ_OK; -@@ -279,21 +279,14 @@ int32_t mz_path_get_filename(const char *path, const char **filename) { - - int32_t mz_dir_make(const char *path) { - int32_t err = MZ_OK; -- size_t len = 0; - char *current_dir = NULL; - char *match = NULL; - char hold = 0; - -- -- len = strlen(path); -- if (len <= 0 || len > INT16_MAX) -- return 0; -- -- current_dir = (char *)MZ_ALLOC(len + 1); -- if (current_dir == NULL) -+ current_dir = strdup(path); -+ if (!current_dir) - return MZ_MEM_ERROR; - -- strcpy(current_dir, path); - mz_path_remove_slash(current_dir); - - err = mz_os_make_dir(current_dir); -@@ -316,7 +309,7 @@ int32_t mz_dir_make(const char *path) { - } - } - -- MZ_FREE(current_dir); -+ free(current_dir); - return err; - } - -diff --git a/src/minizip/mz_os.h b/src/minizip/mz_os.h -index b3e2a58c1..4505bc393 100644 ---- a/src/minizip/mz_os.h -+++ b/src/minizip/mz_os.h -@@ -1,7 +1,7 @@ - /* mz_os.h -- System functions - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - - This program is distributed under the terms of the same license as zlib. -@@ -41,8 +41,9 @@ extern "C" { - (MZ_VERSION_MADEBY_ZIP_VERSION)) - - #define MZ_PATH_SLASH_UNIX ('/') -+#define MZ_PATH_SLASH_WINDOWS ('\\') - #if defined(_WIN32) --# define MZ_PATH_SLASH_PLATFORM ('\\') -+# define MZ_PATH_SLASH_PLATFORM (MZ_PATH_SLASH_WINDOWS) - #else - # define MZ_PATH_SLASH_PLATFORM (MZ_PATH_SLASH_UNIX) - #endif -diff --git a/src/minizip/mz_os_posix.c b/src/minizip/mz_os_posix.c -index 85615ac0c..b4eb1937e 100644 ---- a/src/minizip/mz_os_posix.c -+++ b/src/minizip/mz_os_posix.c -@@ -1,7 +1,7 @@ - /* mz_os_posix.c -- System functions for posix - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - - This program is distributed under the terms of the same license as zlib. -@@ -17,7 +17,7 @@ - #if defined(HAVE_ICONV) - #include - #endif -- -+#include - #include - #include - -@@ -34,11 +34,7 @@ - # include - #endif - #if defined(HAVE_LIBBSD) --# include --# ifndef __u_char_defined -- typedef unsigned char u_char; --# endif --# include /* arc4random_buf */ -+# include /* arc4random_buf */ - #endif - - /***************************************************************************/ -@@ -53,7 +49,7 @@ uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { - uint8_t *string_utf8 = NULL; - uint8_t *string_utf8_ptr = NULL; - -- if (string == NULL) -+ if (!string) - return NULL; - - if (encoding == MZ_ENCODING_CODEPAGE_437) -@@ -75,12 +71,10 @@ uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { - - string_length = strlen(string); - string_utf8_size = string_length * 2; -- string_utf8 = (uint8_t *)MZ_ALLOC((int32_t)(string_utf8_size + 1)); -+ string_utf8 = (uint8_t *)calloc((int32_t)(string_utf8_size + 1), sizeof(char)); - string_utf8_ptr = string_utf8; - - if (string_utf8) { -- memset(string_utf8, 0, string_utf8_size + 1); -- - result = iconv(cd, (char **)&string, &string_length, - (char **)&string_utf8_ptr, &string_utf8_size); - } -@@ -88,7 +82,7 @@ uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { - iconv_close(cd); - - if (result == (size_t)-1) { -- MZ_FREE(string_utf8); -+ free(string_utf8); - string_utf8 = NULL; - } - -@@ -96,28 +90,35 @@ uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { - } - #else - uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { -- size_t string_length = 0; -- uint8_t *string_copy = NULL; -- -- string_length = strlen(string); -- string_copy = (uint8_t *)MZ_ALLOC((int32_t)(string_length + 1)); -- strncpy((char *)string_copy, string, string_length); -- string_copy[string_length] = 0; -- -- return string_copy; -+ return strdup(string); - } - #endif - - void mz_os_utf8_string_delete(uint8_t **string) { -- if (string != NULL) { -- MZ_FREE(*string); -+ if (string) { -+ free(*string); - *string = NULL; - } - } - - /***************************************************************************/ - --#if defined(HAVE_ARC4RANDOM_BUF) -+#if defined(HAVE_GETRANDOM) -+int32_t mz_os_rand(uint8_t *buf, int32_t size) { -+ int32_t left = size; -+ int32_t written = 0; -+ -+ while (left > 0) { -+ written = getrandom(buf, left, 0); -+ if (written < 0) -+ return MZ_INTERNAL_ERROR; -+ -+ buf += written; -+ left -= written; -+ } -+ return size - left; -+} -+#elif defined(HAVE_ARC4RANDOM_BUF) - int32_t mz_os_rand(uint8_t *buf, int32_t size) { - if (size < 0) - return 0; -@@ -139,21 +140,6 @@ int32_t mz_os_rand(uint8_t *buf, int32_t size) { - } - return size - left; - } --#elif defined(HAVE_GETRANDOM) --int32_t mz_os_rand(uint8_t *buf, int32_t size) { -- int32_t left = size; -- int32_t written = 0; -- -- while (left > 0) { -- written = getrandom(buf, left, 0); -- if (written < 0) -- return MZ_INTERNAL_ERROR; -- -- buf += written; -- left -= written; -- } -- return size - left; --} - #else - int32_t mz_os_rand(uint8_t *buf, int32_t size) { - static unsigned calls = 0; -@@ -220,19 +206,16 @@ int32_t mz_os_get_file_date(const char *path, time_t *modified_date, time_t *acc - - if (strcmp(path, "-") != 0) { - /* Not all systems allow stat'ing a file with / appended */ -- len = strlen(path); -- name = (char *)malloc(len + 1); -- strncpy(name, path, len); -- name[len - 1] = 0; -+ name = strdup(path); - mz_path_remove_slash(name); - - if (stat(name, &path_stat) == 0) { -- if (modified_date != NULL) -+ if (modified_date) - *modified_date = path_stat.st_mtime; -- if (accessed_date != NULL) -+ if (accessed_date) - *accessed_date = path_stat.st_atime; - /* Creation date not supported */ -- if (creation_date != NULL) -+ if (creation_date) - *creation_date = 0; - - err = MZ_OK; -@@ -295,13 +278,13 @@ DIR* mz_os_open_dir(const char *path) { - } - - struct dirent* mz_os_read_dir(DIR *dir) { -- if (dir == NULL) -+ if (!dir) - return NULL; - return readdir(dir); - } - - int32_t mz_os_close_dir(DIR *dir) { -- if (dir == NULL) -+ if (!dir) - return MZ_PARAM_ERROR; - if (closedir(dir) == -1) - return MZ_INTERNAL_ERROR; -@@ -360,8 +343,15 @@ uint64_t mz_os_ms_time(void) { - - ts.tv_sec = mts.tv_sec; - ts.tv_nsec = mts.tv_nsec; --#else -+#elif !defined(_POSIX_MONOTONIC_CLOCK) || _POSIX_MONOTONIC_CLOCK < 0 -+ clock_gettime(CLOCK_REALTIME, &ts); -+#elif _POSIX_MONOTONIC_CLOCK > 0 - clock_gettime(CLOCK_MONOTONIC, &ts); -+#else -+ if (sysconf(_SC_MONOTONIC_CLOCK) > 0) -+ clock_gettime(CLOCK_MONOTONIC, &ts); -+ else -+ clock_gettime(CLOCK_REALTIME, &ts); - #endif - - return ((uint64_t)ts.tv_sec * 1000) + ((uint64_t)ts.tv_nsec / 1000000); -diff --git a/src/minizip/mz_os_win32.c b/src/minizip/mz_os_win32.c -index 7effef731..85c7b3a24 100644 ---- a/src/minizip/mz_os_win32.c -+++ b/src/minizip/mz_os_win32.c -@@ -1,28 +1,22 @@ - /* mz_os_win32.c -- System functions for Windows - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - - This program is distributed under the terms of the same license as zlib. - See the accompanying LICENSE file for the full text of the license. - */ - -- - #include "mz.h" - #include "mz_os.h" - #include "mz_strm_os.h" - - #include -+#include - - /***************************************************************************/ - --#if defined(WINAPI_FAMILY_PARTITION) && (!(defined(MZ_WINRT_API))) --# if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) --# define MZ_WINRT_API 1 --# endif --#endif -- - #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY - # define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1 - #endif -@@ -45,19 +39,17 @@ wchar_t *mz_os_unicode_string_create(const char *string, int32_t encoding) { - string_wide_size = MultiByteToWideChar(encoding, 0, string, -1, NULL, 0); - if (string_wide_size == 0) - return NULL; -- string_wide = (wchar_t *)MZ_ALLOC((string_wide_size + 1) * sizeof(wchar_t)); -- if (string_wide == NULL) -+ string_wide = (wchar_t *)calloc(string_wide_size + 1, sizeof(wchar_t)); -+ if (!string_wide) - return NULL; - -- memset(string_wide, 0, sizeof(wchar_t) * (string_wide_size + 1)); - MultiByteToWideChar(encoding, 0, string, -1, string_wide, string_wide_size); -- - return string_wide; - } - - void mz_os_unicode_string_delete(wchar_t **string) { -- if (string != NULL) { -- MZ_FREE(*string); -+ if (string) { -+ free(*string); - *string = NULL; - } - } -@@ -70,12 +62,10 @@ uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { - string_wide = mz_os_unicode_string_create(string, encoding); - if (string_wide) { - string_utf8_size = WideCharToMultiByte(CP_UTF8, 0, string_wide, -1, NULL, 0, NULL, NULL); -- string_utf8 = (uint8_t *)MZ_ALLOC((string_utf8_size + 1) * sizeof(wchar_t)); -+ string_utf8 = (uint8_t *)calloc(string_utf8_size + 1, sizeof(wchar_t)); - -- if (string_utf8) { -- memset(string_utf8, 0, string_utf8_size + 1); -+ if (string_utf8) - WideCharToMultiByte(CP_UTF8, 0, string_wide, -1, (char *)string_utf8, string_utf8_size, NULL, NULL); -- } - - mz_os_unicode_string_delete(&string_wide); - } -@@ -90,19 +80,17 @@ uint8_t *mz_os_utf8_string_create_from_unicode(const wchar_t *string, int32_t en - MZ_UNUSED(encoding); - - string_utf8_size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL); -- string_utf8 = (uint8_t *)MZ_ALLOC((string_utf8_size + 1) * sizeof(wchar_t)); -+ string_utf8 = (uint8_t *)calloc(string_utf8_size + 1, sizeof(wchar_t)); - -- if (string_utf8) { -- memset(string_utf8, 0, string_utf8_size + 1); -+ if (string_utf8) - WideCharToMultiByte(CP_UTF8, 0, string, -1, (char *)string_utf8, string_utf8_size, NULL, NULL); -- } - - return string_utf8; - } - - void mz_os_utf8_string_delete(uint8_t **string) { -- if (string != NULL) { -- MZ_FREE(*string); -+ if (string) { -+ free(*string); - *string = NULL; - } - } -@@ -116,7 +104,7 @@ int32_t mz_os_rand(uint8_t *buf, int32_t size) { - for (len = 0; len < (int)size; len += 1) { - if (len % 8 == 0) - QueryPerformanceCounter((LARGE_INTEGER *)pentium_tsc); -- buf[len] = ((unsigned char*)pentium_tsc)[len % 8]; -+ buf[len] = ((unsigned char *)pentium_tsc)[len % 8]; - } - - return len; -@@ -128,20 +116,20 @@ int32_t mz_os_rename(const char *source_path, const char *target_path) { - int32_t result = 0; - int32_t err = MZ_OK; - -- if (source_path == NULL || target_path == NULL) -+ if (!source_path || !target_path) - return MZ_PARAM_ERROR; - - source_path_wide = mz_os_unicode_string_create(source_path, MZ_ENCODING_UTF8); -- if (source_path_wide == NULL) { -+ if (!source_path_wide) { - err = MZ_PARAM_ERROR; - } else { - target_path_wide = mz_os_unicode_string_create(target_path, MZ_ENCODING_UTF8); -- if (target_path_wide == NULL) -+ if (!target_path_wide) - err = MZ_PARAM_ERROR; - } - - if (err == MZ_OK) { --#ifdef MZ_WINRT_API -+#if _WIN32_WINNT >= _WIN32_WINNT_WINXP - result = MoveFileExW(source_path_wide, target_path_wide, MOVEFILE_WRITE_THROUGH); - #else - result = MoveFileW(source_path_wide, target_path_wide); -@@ -162,10 +150,10 @@ int32_t mz_os_unlink(const char *path) { - wchar_t *path_wide = NULL; - int32_t result = 0; - -- if (path == NULL) -+ if (!path) - return MZ_PARAM_ERROR; - path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); -- if (path_wide == NULL) -+ if (!path_wide) - return MZ_PARAM_ERROR; - - if (mz_os_is_dir(path) == MZ_OK) -@@ -185,10 +173,10 @@ int32_t mz_os_file_exists(const char *path) { - wchar_t *path_wide = NULL; - DWORD attribs = 0; - -- if (path == NULL) -+ if (!path) - return MZ_PARAM_ERROR; - path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); -- if (path_wide == NULL) -+ if (!path_wide) - return MZ_PARAM_ERROR; - - attribs = GetFileAttributesW(path_wide); -@@ -205,12 +193,12 @@ int64_t mz_os_get_file_size(const char *path) { - LARGE_INTEGER large_size; - wchar_t *path_wide = NULL; - -- if (path == NULL) -+ if (!path) - return MZ_PARAM_ERROR; - path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); -- if (path_wide == NULL) -+ if (!path_wide) - return MZ_PARAM_ERROR; --#ifdef MZ_WINRT_API -+#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 - handle = CreateFile2(path_wide, GENERIC_READ, 0, OPEN_EXISTING, NULL); - #else - handle = CreateFileW(path_wide, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); -@@ -247,21 +235,21 @@ int32_t mz_os_get_file_date(const char *path, time_t *modified_date, time_t *acc - wchar_t *path_wide = NULL; - int32_t err = MZ_INTERNAL_ERROR; - -- if (path == NULL) -+ if (!path) - return MZ_PARAM_ERROR; - path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); -- if (path_wide == NULL) -+ if (!path_wide) - return MZ_PARAM_ERROR; - - handle = FindFirstFileW(path_wide, &ff32); -- MZ_FREE(path_wide); -+ free(path_wide); - - if (handle != INVALID_HANDLE_VALUE) { -- if (modified_date != NULL) -+ if (modified_date) - mz_os_file_to_unix_time(ff32.ftLastWriteTime, modified_date); -- if (accessed_date != NULL) -+ if (accessed_date) - mz_os_file_to_unix_time(ff32.ftLastAccessTime, accessed_date); -- if (creation_date != NULL) -+ if (creation_date) - mz_os_file_to_unix_time(ff32.ftCreationTime, creation_date); - - FindClose(handle); -@@ -277,13 +265,13 @@ int32_t mz_os_set_file_date(const char *path, time_t modified_date, time_t acces - wchar_t *path_wide = NULL; - int32_t err = MZ_OK; - -- if (path == NULL) -+ if (!path) - return MZ_PARAM_ERROR; - path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); -- if (path_wide == NULL) -+ if (!path_wide) - return MZ_PARAM_ERROR; - --#ifdef MZ_WINRT_API -+#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 - handle = CreateFile2(path_wide, GENERIC_READ | GENERIC_WRITE, 0, OPEN_EXISTING, NULL); - #else - handle = CreateFileW(path_wide, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); -@@ -313,10 +301,10 @@ int32_t mz_os_get_file_attribs(const char *path, uint32_t *attributes) { - wchar_t *path_wide = NULL; - int32_t err = MZ_OK; - -- if (path == NULL || attributes == NULL) -+ if (!path || !attributes) - return MZ_PARAM_ERROR; - path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); -- if (path_wide == NULL) -+ if (!path_wide) - return MZ_PARAM_ERROR; - - *attributes = GetFileAttributesW(path_wide); -@@ -332,10 +320,10 @@ int32_t mz_os_set_file_attribs(const char *path, uint32_t attributes) { - wchar_t *path_wide = NULL; - int32_t err = MZ_OK; - -- if (path == NULL) -+ if (!path) - return MZ_PARAM_ERROR; - path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); -- if (path_wide == NULL) -+ if (!path_wide) - return MZ_PARAM_ERROR; - - if (SetFileAttributesW(path_wide, attributes) == 0) -@@ -349,7 +337,7 @@ int32_t mz_os_make_dir(const char *path) { - wchar_t *path_wide = NULL; - int32_t err = MZ_OK; - -- if (path == NULL) -+ if (!path) - return MZ_PARAM_ERROR; - - /* Don't try to create a drive letter */ -@@ -357,7 +345,7 @@ int32_t mz_os_make_dir(const char *path) { - return mz_os_is_dir(path); - - path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); -- if (path_wide == NULL) -+ if (!path_wide) - return MZ_PARAM_ERROR; - - if (CreateDirectoryW(path_wide, NULL) == 0) { -@@ -377,8 +365,7 @@ DIR *mz_os_open_dir(const char *path) { - char fixed_path[320]; - void *handle = NULL; - -- -- if (path == NULL) -+ if (!path) - return NULL; - - strncpy(fixed_path, path, sizeof(fixed_path) - 1); -@@ -388,7 +375,7 @@ DIR *mz_os_open_dir(const char *path) { - mz_path_combine(fixed_path, "*", sizeof(fixed_path)); - - path_wide = mz_os_unicode_string_create(fixed_path, MZ_ENCODING_UTF8); -- if (path_wide == NULL) -+ if (!path_wide) - return NULL; - - handle = FindFirstFileW(path_wide, &find_data); -@@ -397,9 +384,11 @@ DIR *mz_os_open_dir(const char *path) { - if (handle == INVALID_HANDLE_VALUE) - return NULL; - -- dir_int = (DIR_int *)MZ_ALLOC(sizeof(DIR_int)); -- if (dir_int == NULL) -+ dir_int = (DIR_int *)malloc(sizeof(DIR_int)); -+ if (!dir_int) { -+ FindClose(handle); - return NULL; -+ } - dir_int->find_handle = handle; - dir_int->end = 0; - -@@ -411,7 +400,7 @@ DIR *mz_os_open_dir(const char *path) { - struct dirent* mz_os_read_dir(DIR *dir) { - DIR_int *dir_int; - -- if (dir == NULL) -+ if (!dir) - return NULL; - - dir_int = (DIR_int *)dir; -@@ -434,13 +423,13 @@ struct dirent* mz_os_read_dir(DIR *dir) { - int32_t mz_os_close_dir(DIR *dir) { - DIR_int *dir_int; - -- if (dir == NULL) -+ if (!dir) - return MZ_PARAM_ERROR; - - dir_int = (DIR_int *)dir; - if (dir_int->find_handle != INVALID_HANDLE_VALUE) - FindClose(dir_int->find_handle); -- MZ_FREE(dir_int); -+ free(dir_int); - return MZ_OK; - } - -@@ -448,10 +437,10 @@ int32_t mz_os_is_dir(const char *path) { - wchar_t *path_wide = NULL; - uint32_t attribs = 0; - -- if (path == NULL) -+ if (!path) - return MZ_PARAM_ERROR; - path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); -- if (path_wide == NULL) -+ if (!path_wide) - return MZ_PARAM_ERROR; - - attribs = GetFileAttributesW(path_wide); -@@ -469,10 +458,10 @@ int32_t mz_os_is_symlink(const char *path) { - wchar_t *path_wide = NULL; - uint32_t attribs = 0; - -- if (path == NULL) -+ if (!path) - return MZ_PARAM_ERROR; - path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); -- if (path_wide == NULL) -+ if (!path_wide) - return MZ_PARAM_ERROR; - - attribs = GetFileAttributesW(path_wide); -@@ -488,6 +477,7 @@ int32_t mz_os_is_symlink(const char *path) { - - int32_t mz_os_make_symlink(const char *path, const char *target_path) { - typedef BOOLEAN (WINAPI *LPCREATESYMBOLICLINKW)(LPCWSTR, LPCWSTR, DWORD); -+ MEMORY_BASIC_INFORMATION mbi; - LPCREATESYMBOLICLINKW create_symbolic_link_w = NULL; - HMODULE kernel32_mod = NULL; - wchar_t *path_wide = NULL; -@@ -495,33 +485,29 @@ int32_t mz_os_make_symlink(const char *path, const char *target_path) { - int32_t err = MZ_OK; - int32_t flags = 0; - -- if (path == NULL) -+ if (!path) - return MZ_PARAM_ERROR; - --#ifdef MZ_WINRT_API -- MEMORY_BASIC_INFORMATION mbi; -+ // Use VirtualQuery instead of GetModuleHandleW for UWP - memset(&mbi, 0, sizeof(mbi)); - VirtualQuery(VirtualQuery, &mbi, sizeof(mbi)); - kernel32_mod = (HMODULE)mbi.AllocationBase; --#else -- kernel32_mod = GetModuleHandleW(L"kernel32.dll"); --#endif - -- if (kernel32_mod == NULL) -+ if (!kernel32_mod) - return MZ_SUPPORT_ERROR; - - create_symbolic_link_w = (LPCREATESYMBOLICLINKW)GetProcAddress(kernel32_mod, "CreateSymbolicLinkW"); -- if (create_symbolic_link_w == NULL) { -+ if (!create_symbolic_link_w) { - return MZ_SUPPORT_ERROR; - } - - path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); -- if (path_wide == NULL) { -+ if (!path_wide) { - return MZ_PARAM_ERROR; - } - - target_path_wide = mz_os_unicode_string_create(target_path, MZ_ENCODING_UTF8); -- if (target_path_wide != NULL) { -+ if (target_path_wide) { - if (mz_path_has_slash(target_path) == MZ_OK) - flags |= SYMBOLIC_LINK_FLAG_DIRECTORY; - -@@ -575,13 +561,13 @@ int32_t mz_os_read_symlink(const char *path, char *target_path, int32_t max_targ - int32_t err = MZ_OK; - uint8_t *target_path_utf8 = NULL; - -- if (path == NULL) -+ if (!path) - return MZ_PARAM_ERROR; - path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); -- if (path_wide == NULL) -+ if (!path_wide) - return MZ_PARAM_ERROR; - --#ifdef MZ_WINRT_API -+#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 - CREATEFILE2_EXTENDED_PARAMETERS extended_params; - memset(&extended_params, 0, sizeof(extended_params)); - extended_params.dwSize = sizeof(extended_params); -@@ -609,7 +595,7 @@ int32_t mz_os_read_symlink(const char *path, char *target_path, int32_t max_targ - if (target_path_len > reparse_data->SymbolicLinkReparseBuffer.PrintNameLength) - target_path_len = reparse_data->SymbolicLinkReparseBuffer.PrintNameLength; - -- target_path_wide = (wchar_t *)MZ_ALLOC(target_path_len + sizeof(wchar_t)); -+ target_path_wide = (wchar_t *)malloc(target_path_len + sizeof(wchar_t)); - if (target_path_wide) { - target_path_idx = reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset / sizeof(wchar_t); - memcpy(target_path_wide, &reparse_data->SymbolicLinkReparseBuffer.PathBuffer[target_path_idx], -@@ -629,7 +615,7 @@ int32_t mz_os_read_symlink(const char *path, char *target_path, int32_t max_targ - err = MZ_MEM_ERROR; - } - -- MZ_FREE(target_path_wide); -+ free(target_path_wide); - } else { - err = MZ_MEM_ERROR; - } -diff --git a/src/minizip/mz_strm.c b/src/minizip/mz_strm.c -index da7d5872d..35d4c62fd 100644 ---- a/src/minizip/mz_strm.c -+++ b/src/minizip/mz_strm.c -@@ -1,7 +1,7 @@ - /* mz_strm.c -- Stream interface - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - - This program is distributed under the terms of the same license as zlib. -@@ -19,21 +19,21 @@ - - int32_t mz_stream_open(void *stream, const char *path, int32_t mode) { - mz_stream *strm = (mz_stream *)stream; -- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->open == NULL) -+ if (!strm || !strm->vtbl || !strm->vtbl->open) - return MZ_STREAM_ERROR; - return strm->vtbl->open(strm, path, mode); - } - - int32_t mz_stream_is_open(void *stream) { - mz_stream *strm = (mz_stream *)stream; -- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->is_open == NULL) -+ if (!strm || !strm->vtbl || !strm->vtbl->is_open) - return MZ_STREAM_ERROR; - return strm->vtbl->is_open(strm); - } - - int32_t mz_stream_read(void *stream, void *buf, int32_t size) { - mz_stream *strm = (mz_stream *)stream; -- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->read == NULL) -+ if (!strm || !strm->vtbl || !strm->vtbl->read) - return MZ_PARAM_ERROR; - if (mz_stream_is_open(stream) != MZ_OK) - return MZ_STREAM_ERROR; -@@ -102,7 +102,7 @@ int32_t mz_stream_write(void *stream, const void *buf, int32_t size) { - mz_stream *strm = (mz_stream *)stream; - if (size == 0) - return size; -- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->write == NULL) -+ if (!strm || !strm->vtbl || !strm->vtbl->write) - return MZ_PARAM_ERROR; - if (mz_stream_is_open(stream) != MZ_OK) - return MZ_STREAM_ERROR; -@@ -165,9 +165,9 @@ int32_t mz_stream_copy_stream(void *target, mz_stream_write_cb write_cb, void *s - int32_t read = 0; - int32_t written = 0; - -- if (write_cb == NULL) -+ if (!write_cb) - write_cb = mz_stream_write; -- if (read_cb == NULL) -+ if (!read_cb) - read_cb = mz_stream_read; - - while (len > 0) { -@@ -192,9 +192,9 @@ int32_t mz_stream_copy_stream_to_end(void *target, mz_stream_write_cb write_cb, - int32_t read = 0; - int32_t written = 0; - -- if (write_cb == NULL) -+ if (!write_cb) - write_cb = mz_stream_write; -- if (read_cb == NULL) -+ if (!read_cb) - read_cb = mz_stream_read; - - read = read_cb(source, buf, sizeof(buf)); -@@ -213,7 +213,7 @@ int32_t mz_stream_copy_stream_to_end(void *target, mz_stream_write_cb write_cb, - - int64_t mz_stream_tell(void *stream) { - mz_stream *strm = (mz_stream *)stream; -- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->tell == NULL) -+ if (!strm || !strm->vtbl || !strm->vtbl->tell) - return MZ_PARAM_ERROR; - if (mz_stream_is_open(stream) != MZ_OK) - return MZ_STREAM_ERROR; -@@ -222,7 +222,7 @@ int64_t mz_stream_tell(void *stream) { - - int32_t mz_stream_seek(void *stream, int64_t offset, int32_t origin) { - mz_stream *strm = (mz_stream *)stream; -- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->seek == NULL) -+ if (!strm || !strm->vtbl || !strm->vtbl->seek) - return MZ_PARAM_ERROR; - if (mz_stream_is_open(stream) != MZ_OK) - return MZ_STREAM_ERROR; -@@ -243,7 +243,7 @@ int32_t mz_stream_find(void *stream, const void *find, int32_t find_size, int64_ - uint8_t first = 1; - int32_t err = MZ_OK; - -- if (stream == NULL || find == NULL || position == NULL) -+ if (!stream || !find || !position) - return MZ_PARAM_ERROR; - if (find_size < 0 || find_size >= (int32_t)sizeof(buf)) - return MZ_PARAM_ERROR; -@@ -301,7 +301,7 @@ int32_t mz_stream_find_reverse(void *stream, const void *find, int32_t find_size - int32_t i = 0; - int32_t err = MZ_OK; - -- if (stream == NULL || find == NULL || position == NULL) -+ if (!stream || !find || !position) - return MZ_PARAM_ERROR; - if (find_size < 0 || find_size >= (int32_t)sizeof(buf)) - return MZ_PARAM_ERROR; -@@ -356,7 +356,7 @@ int32_t mz_stream_find_reverse(void *stream, const void *find, int32_t find_size - - int32_t mz_stream_close(void *stream) { - mz_stream *strm = (mz_stream *)stream; -- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->close == NULL) -+ if (!strm || !strm->vtbl || !strm->vtbl->close) - return MZ_PARAM_ERROR; - if (mz_stream_is_open(stream) != MZ_OK) - return MZ_STREAM_ERROR; -@@ -365,7 +365,7 @@ int32_t mz_stream_close(void *stream) { - - int32_t mz_stream_error(void *stream) { - mz_stream *strm = (mz_stream *)stream; -- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->error == NULL) -+ if (!strm || !strm->vtbl || !strm->vtbl->error) - return MZ_PARAM_ERROR; - return strm->vtbl->error(strm); - } -@@ -378,39 +378,37 @@ int32_t mz_stream_set_base(void *stream, void *base) { - - void* mz_stream_get_interface(void *stream) { - mz_stream *strm = (mz_stream *)stream; -- if (strm == NULL || strm->vtbl == NULL) -+ if (!strm || !strm->vtbl) - return NULL; - return (void *)strm->vtbl; - } - - int32_t mz_stream_get_prop_int64(void *stream, int32_t prop, int64_t *value) { - mz_stream *strm = (mz_stream *)stream; -- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->get_prop_int64 == NULL) -+ if (!strm || !strm->vtbl || !strm->vtbl->get_prop_int64) - return MZ_PARAM_ERROR; - return strm->vtbl->get_prop_int64(stream, prop, value); - } - - int32_t mz_stream_set_prop_int64(void *stream, int32_t prop, int64_t value) { - mz_stream *strm = (mz_stream *)stream; -- if (strm == NULL || strm->vtbl == NULL || strm->vtbl->set_prop_int64 == NULL) -+ if (!strm || !strm->vtbl || !strm->vtbl->set_prop_int64) - return MZ_PARAM_ERROR; - return strm->vtbl->set_prop_int64(stream, prop, value); - } - - void *mz_stream_create(void **stream, mz_stream_vtbl *vtbl) { -- if (stream == NULL) -- return NULL; -- if (vtbl == NULL || vtbl->create == NULL) -+ if (!stream || !vtbl || !vtbl->create) - return NULL; - return vtbl->create(stream); - } - - void mz_stream_delete(void **stream) { - mz_stream *strm = NULL; -- if (stream == NULL) -+ if (!stream) - return; - strm = (mz_stream *)*stream; -- if (strm != NULL && strm->vtbl != NULL && strm->vtbl->destroy != NULL) -+ if (strm && strm->vtbl && strm->vtbl->destroy) - strm->vtbl->destroy(stream); - *stream = NULL; - } -@@ -538,12 +536,10 @@ static mz_stream_vtbl mz_stream_raw_vtbl = { - void *mz_stream_raw_create(void **stream) { - mz_stream_raw *raw = NULL; - -- raw = (mz_stream_raw *)MZ_ALLOC(sizeof(mz_stream_raw)); -- if (raw != NULL) { -- memset(raw, 0, sizeof(mz_stream_raw)); -+ raw = (mz_stream_raw *)calloc(1, sizeof(mz_stream_raw)); -+ if (raw) - raw->stream.vtbl = &mz_stream_raw_vtbl; -- } -- if (stream != NULL) -+ if (stream) - *stream = raw; - - return raw; -@@ -551,10 +547,10 @@ void *mz_stream_raw_create(void **stream) { - - void mz_stream_raw_delete(void **stream) { - mz_stream_raw *raw = NULL; -- if (stream == NULL) -+ if (!stream) - return; - raw = (mz_stream_raw *)*stream; -- if (raw != NULL) -- MZ_FREE(raw); -+ if (raw) -+ free(raw); - *stream = NULL; - } -diff --git a/src/minizip/mz_strm.h b/src/minizip/mz_strm.h -index 8b0027cf5..5f88015d0 100644 ---- a/src/minizip/mz_strm.h -+++ b/src/minizip/mz_strm.h -@@ -1,7 +1,7 @@ - /* mz_strm.h -- Stream interface - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - - This program is distributed under the terms of the same license as zlib. -diff --git a/src/minizip/mz_strm_mem.c b/src/minizip/mz_strm_mem.c -index f4a882d92..9a78dc1bd 100644 ---- a/src/minizip/mz_strm_mem.c -+++ b/src/minizip/mz_strm_mem.c -@@ -6,7 +6,7 @@ - - Based on Unzip ioapi.c version 0.22, May 19th, 2003 - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - Copyright (C) 2003 Justin Fletcher - Copyright (C) 1998-2003 Gilles Vollant -@@ -16,7 +16,6 @@ - See the accompanying LICENSE file for the full text of the license. - */ - -- - #include "mz.h" - #include "mz_strm.h" - #include "mz_strm_mem.h" -@@ -57,14 +56,13 @@ static int32_t mz_stream_mem_set_size(void *stream, int32_t size) { - int32_t new_size = size; - uint8_t *new_buf = NULL; - -- -- new_buf = (uint8_t *)MZ_ALLOC((uint32_t)new_size); -- if (new_buf == NULL) -+ new_buf = (uint8_t *)malloc((uint32_t)new_size); -+ if (!new_buf) - return MZ_BUF_ERROR; - - if (mem->buffer) { - memcpy(new_buf, mem->buffer, mem->size); -- MZ_FREE(mem->buffer); -+ free(mem->buffer); - } - - mem->buffer = new_buf; -@@ -92,7 +90,7 @@ int32_t mz_stream_mem_open(void *stream, const char *path, int32_t mode) { - - int32_t mz_stream_mem_is_open(void *stream) { - mz_stream_mem *mem = (mz_stream_mem *)stream; -- if (mem->buffer == NULL) -+ if (!mem->buffer) - return MZ_OPEN_ERROR; - return MZ_OK; - } -@@ -119,7 +117,7 @@ int32_t mz_stream_mem_write(void *stream, const void *buf, int32_t size) { - int32_t new_size = 0; - int32_t err = MZ_OK; - -- if (size == 0) -+ if (!size) - return size; - - if (size > mem->size - mem->position) { -@@ -213,7 +211,7 @@ int32_t mz_stream_mem_get_buffer(void *stream, const void **buf) { - - int32_t mz_stream_mem_get_buffer_at(void *stream, int64_t position, const void **buf) { - mz_stream_mem *mem = (mz_stream_mem *)stream; -- if (buf == NULL || position < 0 || mem->size < position || mem->buffer == NULL) -+ if (!buf || position < 0 || !mem->buffer|| mem->size < position) - return MZ_SEEK_ERROR; - *buf = mem->buffer + position; - return MZ_OK; -@@ -242,13 +240,12 @@ void mz_stream_mem_set_grow_size(void *stream, int32_t grow_size) { - void *mz_stream_mem_create(void **stream) { - mz_stream_mem *mem = NULL; - -- mem = (mz_stream_mem *)MZ_ALLOC(sizeof(mz_stream_mem)); -- if (mem != NULL) { -- memset(mem, 0, sizeof(mz_stream_mem)); -+ mem = (mz_stream_mem *)calloc(1, sizeof(mz_stream_mem)); -+ if (mem) { - mem->stream.vtbl = &mz_stream_mem_vtbl; - mem->grow_size = 4096; - } -- if (stream != NULL) -+ if (stream) - *stream = mem; - - return mem; -@@ -256,13 +253,13 @@ void *mz_stream_mem_create(void **stream) { - - void mz_stream_mem_delete(void **stream) { - mz_stream_mem *mem = NULL; -- if (stream == NULL) -+ if (!stream) - return; - mem = (mz_stream_mem *)*stream; -- if (mem != NULL) { -- if ((mem->mode & MZ_OPEN_MODE_CREATE) && (mem->buffer != NULL)) -- MZ_FREE(mem->buffer); -- MZ_FREE(mem); -+ if (mem) { -+ if ((mem->mode & MZ_OPEN_MODE_CREATE) && (mem->buffer)) -+ free(mem->buffer); -+ free(mem); - } - *stream = NULL; - } -diff --git a/src/minizip/mz_strm_mem.h b/src/minizip/mz_strm_mem.h -index 5bfa13d8a..22a12deae 100644 ---- a/src/minizip/mz_strm_mem.h -+++ b/src/minizip/mz_strm_mem.h -@@ -1,7 +1,7 @@ - /* mz_strm_mem.h -- Stream for memory access - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - - This program is distributed under the terms of the same license as zlib. -diff --git a/src/minizip/mz_strm_os.h b/src/minizip/mz_strm_os.h -index 614e25520..83d292b95 100644 ---- a/src/minizip/mz_strm_os.h -+++ b/src/minizip/mz_strm_os.h -@@ -1,7 +1,7 @@ - /* mz_sstrm_os.h -- Stream for filesystem access - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - - This program is distributed under the terms of the same license as zlib. -diff --git a/src/minizip/mz_strm_os_posix.c b/src/minizip/mz_strm_os_posix.c -index f0b5bd335..60ff502de 100644 ---- a/src/minizip/mz_strm_os_posix.c -+++ b/src/minizip/mz_strm_os_posix.c -@@ -1,7 +1,7 @@ - /* mz_strm_posix.c -- Stream for filesystem access for posix/linux - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - Modifications for Zip64 support - Copyright (C) 2009-2010 Mathias Svensson -@@ -13,7 +13,6 @@ - See the accompanying LICENSE file for the full text of the license. - */ - -- - #include "mz.h" - #include "mz_strm.h" - #include "mz_strm_os.h" -@@ -71,7 +70,7 @@ int32_t mz_stream_os_open(void *stream, const char *path, int32_t mode) { - mz_stream_posix *posix = (mz_stream_posix *)stream; - const char *mode_fopen = NULL; - -- if (path == NULL) -+ if (!path) - return MZ_PARAM_ERROR; - - if ((mode & MZ_OPEN_MODE_READWRITE) == MZ_OPEN_MODE_READ) -@@ -84,7 +83,7 @@ int32_t mz_stream_os_open(void *stream, const char *path, int32_t mode) { - return MZ_OPEN_ERROR; - - posix->handle = fopen64(path, mode_fopen); -- if (posix->handle == NULL) { -+ if (!posix->handle) { - posix->error = errno; - return MZ_OPEN_ERROR; - } -@@ -96,14 +95,14 @@ int32_t mz_stream_os_open(void *stream, const char *path, int32_t mode) { - } - - int32_t mz_stream_os_is_open(void *stream) { -- mz_stream_posix *posix = (mz_stream_posix*)stream; -- if (posix->handle == NULL) -+ mz_stream_posix *posix = (mz_stream_posix *)stream; -+ if (!posix->handle) - return MZ_OPEN_ERROR; - return MZ_OK; - } - - int32_t mz_stream_os_read(void *stream, void *buf, int32_t size) { -- mz_stream_posix *posix = (mz_stream_posix*)stream; -+ mz_stream_posix *posix = (mz_stream_posix *)stream; - int32_t read = (int32_t)fread(buf, 1, (size_t)size, posix->handle); - if (read < size && ferror(posix->handle)) { - posix->error = errno; -@@ -113,7 +112,7 @@ int32_t mz_stream_os_read(void *stream, void *buf, int32_t size) { - } - - int32_t mz_stream_os_write(void *stream, const void *buf, int32_t size) { -- mz_stream_posix *posix = (mz_stream_posix*)stream; -+ mz_stream_posix *posix = (mz_stream_posix *)stream; - int32_t written = (int32_t)fwrite(buf, 1, (size_t)size, posix->handle); - if (written < size && ferror(posix->handle)) { - posix->error = errno; -@@ -123,7 +122,7 @@ int32_t mz_stream_os_write(void *stream, const void *buf, int32_t size) { - } - - int64_t mz_stream_os_tell(void *stream) { -- mz_stream_posix *posix = (mz_stream_posix*)stream; -+ mz_stream_posix *posix = (mz_stream_posix *)stream; - int64_t position = ftello64(posix->handle); - if (position == -1) { - posix->error = errno; -@@ -133,7 +132,7 @@ int64_t mz_stream_os_tell(void *stream) { - } - - int32_t mz_stream_os_seek(void *stream, int64_t offset, int32_t origin) { -- mz_stream_posix *posix = (mz_stream_posix*)stream; -+ mz_stream_posix *posix = (mz_stream_posix *)stream; - int32_t fseek_origin = 0; - - switch (origin) { -@@ -159,9 +158,9 @@ int32_t mz_stream_os_seek(void *stream, int64_t offset, int32_t origin) { - } - - int32_t mz_stream_os_close(void *stream) { -- mz_stream_posix *posix = (mz_stream_posix*)stream; -+ mz_stream_posix *posix = (mz_stream_posix *)stream; - int32_t closed = 0; -- if (posix->handle != NULL) { -+ if (posix->handle) { - closed = fclose(posix->handle); - posix->handle = NULL; - } -@@ -173,19 +172,17 @@ int32_t mz_stream_os_close(void *stream) { - } - - int32_t mz_stream_os_error(void *stream) { -- mz_stream_posix *posix = (mz_stream_posix*)stream; -+ mz_stream_posix *posix = (mz_stream_posix *)stream; - return posix->error; - } - - void *mz_stream_os_create(void **stream) { - mz_stream_posix *posix = NULL; - -- posix = (mz_stream_posix *)MZ_ALLOC(sizeof(mz_stream_posix)); -- if (posix != NULL) { -- memset(posix, 0, sizeof(mz_stream_posix)); -+ posix = (mz_stream_posix *)calloc(1, sizeof(mz_stream_posix)); -+ if (posix) - posix->stream.vtbl = &mz_stream_os_vtbl; -- } -- if (stream != NULL) -+ if (stream) - *stream = posix; - - return posix; -@@ -193,11 +190,11 @@ void *mz_stream_os_create(void **stream) { - - void mz_stream_os_delete(void **stream) { - mz_stream_posix *posix = NULL; -- if (stream == NULL) -+ if (!stream) - return; - posix = (mz_stream_posix *)*stream; -- if (posix != NULL) -- MZ_FREE(posix); -+ if (posix) -+ free(posix); - *stream = NULL; - } - -diff --git a/src/minizip/mz_strm_os_win32.c b/src/minizip/mz_strm_os_win32.c -index 893df5418..80d03ea11 100644 ---- a/src/minizip/mz_strm_os_win32.c -+++ b/src/minizip/mz_strm_os_win32.c -@@ -1,7 +1,7 @@ - /* mz_strm_win32.c -- Stream for filesystem access for windows - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - Copyright (C) 2009-2010 Mathias Svensson - Modifications for Zip64 support -@@ -13,7 +13,6 @@ - See the accompanying LICENSE file for the full text of the license. - */ - -- - #include "mz.h" - #include "mz_os.h" - #include "mz_strm.h" -@@ -31,12 +30,6 @@ - # define INVALID_SET_FILE_POINTER ((DWORD)-1) - #endif - --#if defined(WINAPI_FAMILY_ONE_PARTITION) && !defined(MZ_WINRT_API) --# if WINAPI_FAMILY_ONE_PARTITION(WINAPI_FAMILY, WINAPI_PARTITION_APP) --# define MZ_WINRT_API 1 --# endif --#endif -- - /***************************************************************************/ - - static mz_stream_vtbl mz_stream_os_vtbl = { -@@ -67,7 +60,7 @@ typedef struct mz_stream_win32_s { - #if 0 - # define mz_stream_os_print printf - #else --# define mz_stream_os_print(fmt,...) -+# define mz_stream_os_print(fmt, ...) - #endif - - /***************************************************************************/ -@@ -80,8 +73,7 @@ int32_t mz_stream_os_open(void *stream, const char *path, int32_t mode) { - uint32_t flags_attribs = FILE_ATTRIBUTE_NORMAL; - wchar_t *path_wide = NULL; - -- -- if (path == NULL) -+ if (!path) - return MZ_PARAM_ERROR; - - /* Some use cases require write sharing as well */ -@@ -103,10 +95,10 @@ int32_t mz_stream_os_open(void *stream, const char *path, int32_t mode) { - mz_stream_os_print("Win32 - Open - %s (mode %" PRId32 ")\n", path); - - path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); -- if (path_wide == NULL) -+ if (!path_wide) - return MZ_PARAM_ERROR; - --#ifdef MZ_WINRT_API -+#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 - win32->handle = CreateFile2(path_wide, desired_access, share_mode, - creation_disposition, NULL); - #else -@@ -129,7 +121,7 @@ int32_t mz_stream_os_open(void *stream, const char *path, int32_t mode) { - - int32_t mz_stream_os_is_open(void *stream) { - mz_stream_win32 *win32 = (mz_stream_win32 *)stream; -- if (win32->handle == NULL || win32->handle == INVALID_HANDLE_VALUE) -+ if (!win32->handle || win32->handle == INVALID_HANDLE_VALUE) - return MZ_OPEN_ERROR; - return MZ_OK; - } -@@ -172,7 +164,7 @@ int32_t mz_stream_os_write(void *stream, const void *buf, int32_t size) { - - static int32_t mz_stream_os_seekinternal(HANDLE handle, LARGE_INTEGER large_pos, - LARGE_INTEGER *new_pos, uint32_t move_method) { --#ifdef MZ_WINRT_API -+#if _WIN32_WINNT >= _WIN32_WINNT_WINXP - BOOL success = FALSE; - success = SetFilePointerEx(handle, large_pos, new_pos, move_method); - if ((success == FALSE) && (GetLastError() != NO_ERROR)) -@@ -189,7 +181,7 @@ static int32_t mz_stream_os_seekinternal(HANDLE handle, LARGE_INTEGER large_pos, - if ((pos == INVALID_SET_FILE_POINTER) && (GetLastError() != NO_ERROR)) - return MZ_SEEK_ERROR; - -- if (new_pos != NULL) { -+ if (new_pos) { - new_pos->LowPart = pos; - new_pos->HighPart = high_part; - } -@@ -221,7 +213,6 @@ int32_t mz_stream_os_seek(void *stream, int64_t offset, int32_t origin) { - int32_t err = MZ_OK; - LARGE_INTEGER large_pos; - -- - if (mz_stream_os_is_open(stream) != MZ_OK) - return MZ_OPEN_ERROR; - -@@ -255,7 +246,7 @@ int32_t mz_stream_os_seek(void *stream, int64_t offset, int32_t origin) { - int32_t mz_stream_os_close(void *stream) { - mz_stream_win32 *win32 = (mz_stream_win32 *)stream; - -- if (win32->handle != NULL) -+ if (win32->handle) - CloseHandle(win32->handle); - mz_stream_os_print("Win32 - Close\n"); - win32->handle = NULL; -@@ -270,12 +261,10 @@ int32_t mz_stream_os_error(void *stream) { - void *mz_stream_os_create(void **stream) { - mz_stream_win32 *win32 = NULL; - -- win32 = (mz_stream_win32 *)MZ_ALLOC(sizeof(mz_stream_win32)); -- if (win32 != NULL) { -- memset(win32, 0, sizeof(mz_stream_win32)); -+ win32 = (mz_stream_win32 *)calloc(1, sizeof(mz_stream_win32)); -+ if (win32) - win32->stream.vtbl = &mz_stream_os_vtbl; -- } -- if (stream != NULL) -+ if (stream) - *stream = win32; - - return win32; -@@ -283,11 +272,11 @@ void *mz_stream_os_create(void **stream) { - - void mz_stream_os_delete(void **stream) { - mz_stream_win32 *win32 = NULL; -- if (stream == NULL) -+ if (!stream) - return; - win32 = (mz_stream_win32 *)*stream; -- if (win32 != NULL) -- MZ_FREE(win32); -+ if (win32) -+ free(win32); - *stream = NULL; - } - -diff --git a/src/minizip/mz_strm_zlib.c b/src/minizip/mz_strm_zlib.c -index f76d7ffc4..b7ac4d1a6 100644 ---- a/src/minizip/mz_strm_zlib.c -+++ b/src/minizip/mz_strm_zlib.c -@@ -1,14 +1,13 @@ - /* mz_strm_zlib.c -- Stream for zlib inflate/deflate - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - - This program is distributed under the terms of the same license as zlib. - See the accompanying LICENSE file for the full text of the license. - */ - -- - #include "mz.h" - #include "mz_strm.h" - #include "mz_strm_zlib.h" -@@ -144,8 +143,7 @@ int32_t mz_stream_zlib_read(void *stream, void *buf, int32_t size) { - int32_t read = 0; - int32_t err = Z_OK; - -- -- zlib->zstream.next_out = (Bytef*)buf; -+ zlib->zstream.next_out = (Bytef *)buf; - zlib->zstream.avail_out = (uInt)size; - - do { -@@ -168,7 +166,7 @@ int32_t mz_stream_zlib_read(void *stream, void *buf, int32_t size) { - total_out_before = zlib->zstream.total_out; - - err = ZLIB_PREFIX(inflate)(&zlib->zstream, Z_SYNC_FLUSH); -- if ((err >= Z_OK) && (zlib->zstream.msg != NULL)) { -+ if ((err >= Z_OK) && (zlib->zstream.msg)) { - zlib->error = Z_DATA_ERROR; - break; - } -@@ -217,7 +215,6 @@ static int32_t mz_stream_zlib_deflate(void *stream, int flush) { - int32_t out_bytes = 0; - int32_t err = Z_OK; - -- - do { - if (zlib->zstream.avail_out == 0) { - err = mz_stream_zlib_flush(zlib); -@@ -261,7 +258,7 @@ int32_t mz_stream_zlib_write(void *stream, const void *buf, int32_t size) { - mz_stream_zlib *zlib = (mz_stream_zlib *)stream; - int32_t err = MZ_OK; - -- zlib->zstream.next_in = (Bytef*)(intptr_t)buf; -+ zlib->zstream.next_in = (Bytef *)(intptr_t)buf; - zlib->zstream.avail_in = (uInt)size; - - err = mz_stream_zlib_deflate(stream, Z_NO_FLUSH); -@@ -291,7 +288,6 @@ int32_t mz_stream_zlib_seek(void *stream, int64_t offset, int32_t origin) { - int32_t mz_stream_zlib_close(void *stream) { - mz_stream_zlib *zlib = (mz_stream_zlib *)stream; - -- - if (zlib->mode & MZ_OPEN_MODE_WRITE) { - #ifdef MZ_ZIP_NO_COMPRESSION - return MZ_SUPPORT_ERROR; -@@ -366,14 +362,13 @@ int32_t mz_stream_zlib_set_prop_int64(void *stream, int32_t prop, int64_t value) - void *mz_stream_zlib_create(void **stream) { - mz_stream_zlib *zlib = NULL; - -- zlib = (mz_stream_zlib *)MZ_ALLOC(sizeof(mz_stream_zlib)); -- if (zlib != NULL) { -- memset(zlib, 0, sizeof(mz_stream_zlib)); -+ zlib = (mz_stream_zlib *)calloc(1, sizeof(mz_stream_zlib)); -+ if (zlib) { - zlib->stream.vtbl = &mz_stream_zlib_vtbl; - zlib->level = Z_DEFAULT_COMPRESSION; - zlib->window_bits = -MAX_WBITS; - } -- if (stream != NULL) -+ if (stream) - *stream = zlib; - - return zlib; -@@ -381,11 +376,11 @@ void *mz_stream_zlib_create(void **stream) { - - void mz_stream_zlib_delete(void **stream) { - mz_stream_zlib *zlib = NULL; -- if (stream == NULL) -+ if (!stream) - return; - zlib = (mz_stream_zlib *)*stream; -- if (zlib != NULL) -- MZ_FREE(zlib); -+ if (zlib) -+ free(zlib); - *stream = NULL; - } - -diff --git a/src/minizip/mz_strm_zlib.h b/src/minizip/mz_strm_zlib.h -index 47f74804f..4bdcdf813 100644 ---- a/src/minizip/mz_strm_zlib.h -+++ b/src/minizip/mz_strm_zlib.h -@@ -1,7 +1,7 @@ - /* mz_strm_zlib.h -- Stream for zlib inflate/deflate - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - - This program is distributed under the terms of the same license as zlib. -diff --git a/src/minizip/mz_zip.c b/src/minizip/mz_zip.c -index cc4f57d0b..e80550f0e 100644 ---- a/src/minizip/mz_zip.c -+++ b/src/minizip/mz_zip.c -@@ -1,7 +1,7 @@ - /* zip.c -- Zip manipulation - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - Copyright (C) 2009-2010 Mathias Svensson - Modifications for Zip64 support -@@ -15,7 +15,6 @@ - See the accompanying LICENSE file for the full text of the license. - */ - -- - #include "mz.h" - #include "mz_crypt.h" - #include "mz_strm.h" -@@ -48,7 +47,7 @@ - #include /* snprintf */ - - #if defined(_MSC_VER) || defined(__MINGW32__) --# define localtime_r(t1,t2) (localtime_s(t2,t1) == 0 ? t1 : NULL) -+# define localtime_r(t1, t2) (localtime_s(t2, t1) == 0 ? t1 : NULL) - #endif - #if defined(_MSC_VER) && (_MSC_VER < 1900) - # define snprintf _snprintf -@@ -122,7 +121,7 @@ typedef struct mz_zip_s { - #if 0 - # define mz_zip_print printf - #else --# define mz_zip_print(fmt,...) -+# define mz_zip_print(fmt, ...) - #endif - - /***************************************************************************/ -@@ -152,7 +151,6 @@ static int32_t mz_zip_search_zip64_eocd(void *stream, const int64_t end_central_ - uint32_t value32 = 0; - int32_t err = MZ_OK; - -- - *central_pos = 0; - - /* Zip64 end of central directory locator */ -@@ -188,6 +186,7 @@ static int32_t mz_zip_search_zip64_eocd(void *stream, const int64_t end_central_ - return err; - } - -+#ifdef HAVE_PKCRYPT - /* Get PKWARE traditional encryption verifier */ - static uint16_t mz_zip_get_pk_verify(uint32_t dos_date, uint64_t crc, uint16_t flag) - { -@@ -197,6 +196,7 @@ static uint16_t mz_zip_get_pk_verify(uint32_t dos_date, uint64_t crc, uint16_t f - return ((dos_date >> 16) & 0xff) << 8 | ((dos_date >> 8) & 0xff); - return ((crc >> 16) & 0xff) << 8 | ((crc >> 24) & 0xff); - } -+#endif - - /* Get info about the current file in the zip file */ - static int32_t mz_zip_entry_read_header(void *stream, uint8_t local, mz_zip_file *file_info, void *file_extra_stream) { -@@ -220,7 +220,6 @@ static int32_t mz_zip_entry_read_header(void *stream, uint8_t local, mz_zip_file - int32_t err = MZ_OK; - char *linkname = NULL; - -- - memset(file_info, 0, sizeof(mz_zip_file)); - - /* Check the magic */ -@@ -394,8 +393,8 @@ static int32_t mz_zip_entry_read_header(void *stream, uint8_t local, mz_zip_file - terminated string */ - linkname_size = field_length - 12; - if ((err == MZ_OK) && (linkname_size > 0)) { -- linkname = (char *)MZ_ALLOC(linkname_size); -- if (linkname != NULL) { -+ linkname = (char *)malloc(linkname_size); -+ if (linkname) { - if (mz_stream_read(file_extra_stream, linkname, linkname_size) != linkname_size) - err = MZ_READ_ERROR; - if (err == MZ_OK) { -@@ -407,7 +406,7 @@ static int32_t mz_zip_entry_read_header(void *stream, uint8_t local, mz_zip_file - - mz_stream_seek(file_extra_stream, saved_pos, MZ_SEEK_SET); - } -- MZ_FREE(linkname); -+ free(linkname); - } - } - } -@@ -455,13 +454,13 @@ static int32_t mz_zip_entry_read_header(void *stream, uint8_t local, mz_zip_file - mz_stream_mem_get_buffer_at(file_extra_stream, linkname_pos, (const void **)&file_info->linkname); - - /* Set to empty string just in-case */ -- if (file_info->filename == NULL) -+ if (!file_info->filename) - file_info->filename = ""; -- if (file_info->extrafield == NULL) -+ if (!file_info->extrafield) - file_info->extrafield_size = 0; -- if (file_info->comment == NULL) -+ if (!file_info->comment) - file_info->comment = ""; -- if (file_info->linkname == NULL) -+ if (!file_info->linkname) - file_info->linkname = ""; - - if (err == MZ_OK) { -@@ -485,13 +484,12 @@ static int32_t mz_zip_entry_read_descriptor(void *stream, uint8_t zip64, uint32_ - int64_t value64 = 0; - int32_t err = MZ_OK; - -- - err = mz_stream_read_uint32(stream, &value32); - if (value32 != MZ_ZIP_MAGIC_DATADESCRIPTOR) - err = MZ_FORMAT_ERROR; - if (err == MZ_OK) - err = mz_stream_read_uint32(stream, &value32); -- if ((err == MZ_OK) && (crc32 != NULL)) -+ if (err == MZ_OK && crc32) - *crc32 = value32; - if (err == MZ_OK) { - /* If zip 64 extension is enabled then read as 8 byte */ -@@ -503,7 +501,7 @@ static int32_t mz_zip_entry_read_descriptor(void *stream, uint8_t zip64, uint32_ - if (value64 < 0) - err = MZ_FORMAT_ERROR; - } -- if ((err == MZ_OK) && (compressed_size != NULL)) -+ if (err == MZ_OK && compressed_size) - *compressed_size = value64; - } - if (err == MZ_OK) { -@@ -515,7 +513,7 @@ static int32_t mz_zip_entry_read_descriptor(void *stream, uint8_t zip64, uint32_ - if (value64 < 0) - err = MZ_FORMAT_ERROR; - } -- if ((err == MZ_OK) && (uncompressed_size != NULL)) -+ if (err == MZ_OK && uncompressed_size) - *uncompressed_size = value64; - } - -@@ -554,7 +552,7 @@ static int32_t mz_zip_entry_needs_zip64(mz_zip_file *file_info, uint8_t local, u - uint32_t max_uncompressed_size = UINT32_MAX; - uint8_t needs_zip64 = 0; - -- if (zip64 == NULL) -+ if (!zip64) - return MZ_PARAM_ERROR; - - *zip64 = 0; -@@ -621,7 +619,7 @@ static int32_t mz_zip_entry_write_header(void *stream, uint8_t local, mz_zip_fil - char masked_name[64]; - void *file_extra_stream = NULL; - -- if (file_info == NULL) -+ if (!file_info) - return MZ_PARAM_ERROR; - - if ((local) && (file_info->flag & MZ_ZIP_FLAG_MASK_LOCAL_INFO)) -@@ -690,7 +688,7 @@ static int32_t mz_zip_entry_write_header(void *stream, uint8_t local, mz_zip_fil - } - - /* Unix1 symbolic links */ -- if (file_info->linkname != NULL && *file_info->linkname != 0) { -+ if (file_info->linkname && *file_info->linkname != 0) { - linkname_size = (uint16_t)strlen(file_info->linkname); - field_length_unix1 = 12 + linkname_size; - extrafield_size += 4 + field_length_unix1; -@@ -765,7 +763,7 @@ static int32_t mz_zip_entry_write_header(void *stream, uint8_t local, mz_zip_fil - err = mz_stream_write_uint16(stream, extrafield_size); - - if (!local) { -- if (file_info->comment != NULL) { -+ if (file_info->comment) { - comment_size = (int32_t)strlen(file_info->comment); - if (comment_size > UINT16_MAX) - comment_size = UINT16_MAX; -@@ -787,8 +785,26 @@ static int32_t mz_zip_entry_write_header(void *stream, uint8_t local, mz_zip_fil - } - - if (err == MZ_OK) { -- if (mz_stream_write(stream, filename, filename_length) != filename_length) -- err = MZ_WRITE_ERROR; -+ const char *backslash = NULL; -+ const char *next = filename; -+ int32_t left = filename_length; -+ -+ /* Ensure all slashes are written as forward slashes according to 4.4.17.1 */ -+ while ((err == MZ_OK) && (backslash = strrchr(next, '\\'))) { -+ int32_t part_length = (int32_t)(backslash - next); -+ -+ if (mz_stream_write(stream, next, part_length) != part_length || -+ mz_stream_write(stream, "/", 1) != 1) -+ err = MZ_WRITE_ERROR; -+ -+ left -= part_length + 1; -+ next = backslash + 1; -+ } -+ -+ if (err == MZ_OK && left > 0) { -+ if (mz_stream_write(stream, next, left) != left) -+ err = MZ_WRITE_ERROR; -+ } - - /* Ensure that directories have a slash appended to them for compatibility */ - if (err == MZ_OK && write_end_slash) -@@ -892,7 +908,7 @@ static int32_t mz_zip_entry_write_header(void *stream, uint8_t local, mz_zip_fil - mz_stream_mem_delete(&file_extra_stream); - } - -- if ((err == MZ_OK) && (!local) && (file_info->comment != NULL)) { -+ if (err == MZ_OK && !local && file_info->comment) { - if (mz_stream_write(stream, file_info->comment, file_info->comment_size) != file_info->comment_size) - err = MZ_WRITE_ERROR; - } -@@ -939,8 +955,7 @@ static int32_t mz_zip_read_cd(void *handle) { - int32_t comment_read = 0; - int32_t err = MZ_OK; - -- -- if (zip == NULL) -+ if (!zip) - return MZ_PARAM_ERROR; - - /* Read and cache central directory records */ -@@ -979,8 +994,8 @@ static int32_t mz_zip_read_cd(void *handle) { - if (err == MZ_OK) - err = mz_stream_read_uint16(zip->stream, &comment_size); - if ((err == MZ_OK) && (comment_size > 0)) { -- zip->comment = (char *)MZ_ALLOC(comment_size + 1); -- if (zip->comment != NULL) { -+ zip->comment = (char *)malloc(comment_size + 1); -+ if (zip->comment) { - comment_read = mz_stream_read(zip->stream, zip->comment, comment_size); - /* Don't fail if incorrect comment length read, not critical */ - if (comment_read < 0) -@@ -1058,7 +1073,6 @@ static int32_t mz_zip_read_cd(void *handle) { - if (err == MZ_OK) - err = mz_stream_read_uint32(zip->stream, &zip->cd_signature); - if ((err == MZ_OK) && (zip->cd_signature == MZ_ZIP_MAGIC_CENTRALHEADER)) { -- - /* If found compensate for incorrect locations */ - value64i = zip->cd_offset; - zip->cd_offset = eocd_pos - zip->cd_size; -@@ -1089,8 +1103,7 @@ static int32_t mz_zip_write_cd(void *handle) { - int32_t comment_size = 0; - int32_t err = MZ_OK; - -- -- if (zip == NULL) -+ if (!zip) - return MZ_PARAM_ERROR; - - if (mz_stream_get_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, &disk_number) == MZ_OK) -@@ -1202,7 +1215,7 @@ static int32_t mz_zip_write_cd(void *handle) { - } - - /* Write global comment */ -- if (zip->comment != NULL) { -+ if (zip->comment) { - comment_size = (int32_t)strlen(zip->comment); - if (comment_size > UINT16_MAX) - comment_size = UINT16_MAX; -@@ -1239,7 +1252,6 @@ static int32_t mz_zip_recover_cd(void *handle) { - uint8_t zip64 = 0; - uint8_t eof = 0; - -- - mz_zip_print("Zip - Recover - Start\n"); - - mz_zip_get_cd_mem_stream(handle, &cd_mem_stream); -@@ -1388,12 +1400,10 @@ static int32_t mz_zip_recover_cd(void *handle) { - void *mz_zip_create(void **handle) { - mz_zip *zip = NULL; - -- zip = (mz_zip *)MZ_ALLOC(sizeof(mz_zip)); -- if (zip != NULL) { -- memset(zip, 0, sizeof(mz_zip)); -+ zip = (mz_zip *)calloc(1, sizeof(mz_zip)); -+ if (zip) - zip->data_descriptor = 1; -- } -- if (handle != NULL) -+ if (handle) - *handle = zip; - - return zip; -@@ -1401,11 +1411,11 @@ void *mz_zip_create(void **handle) { - - void mz_zip_delete(void **handle) { - mz_zip *zip = NULL; -- if (handle == NULL) -+ if (!handle) - return; - zip = (mz_zip *)*handle; -- if (zip != NULL) { -- MZ_FREE(zip); -+ if (zip) { -+ free(zip); - } - *handle = NULL; - } -@@ -1414,8 +1424,7 @@ int32_t mz_zip_open(void *handle, void *stream, int32_t mode) { - mz_zip *zip = (mz_zip *)handle; - int32_t err = MZ_OK; - -- -- if (zip == NULL) -+ if (!zip) - return MZ_PARAM_ERROR; - - mz_zip_print("Zip - Open\n"); -@@ -1489,7 +1498,7 @@ int32_t mz_zip_close(void *handle) { - mz_zip *zip = (mz_zip *)handle; - int32_t err = MZ_OK; - -- if (zip == NULL) -+ if (!zip) - return MZ_PARAM_ERROR; - - mz_zip_print("Zip - Close\n"); -@@ -1500,22 +1509,22 @@ int32_t mz_zip_close(void *handle) { - if ((err == MZ_OK) && (zip->open_mode & MZ_OPEN_MODE_WRITE)) - err = mz_zip_write_cd(handle); - -- if (zip->cd_mem_stream != NULL) { -+ if (zip->cd_mem_stream) { - mz_stream_close(zip->cd_mem_stream); - mz_stream_delete(&zip->cd_mem_stream); - } - -- if (zip->file_info_stream != NULL) { -+ if (zip->file_info_stream) { - mz_stream_mem_close(zip->file_info_stream); - mz_stream_mem_delete(&zip->file_info_stream); - } -- if (zip->local_file_info_stream != NULL) { -+ if (zip->local_file_info_stream) { - mz_stream_mem_close(zip->local_file_info_stream); - mz_stream_mem_delete(&zip->local_file_info_stream); - } - - if (zip->comment) { -- MZ_FREE(zip->comment); -+ free(zip->comment); - zip->comment = NULL; - } - -@@ -1527,9 +1536,9 @@ int32_t mz_zip_close(void *handle) { - - int32_t mz_zip_get_comment(void *handle, const char **comment) { - mz_zip *zip = (mz_zip *)handle; -- if (zip == NULL || comment == NULL) -+ if (!zip || !comment) - return MZ_PARAM_ERROR; -- if (zip->comment == NULL) -+ if (!zip->comment) - return MZ_EXIST_ERROR; - *comment = zip->comment; - return MZ_OK; -@@ -1538,24 +1547,23 @@ int32_t mz_zip_get_comment(void *handle, const char **comment) { - int32_t mz_zip_set_comment(void *handle, const char *comment) { - mz_zip *zip = (mz_zip *)handle; - int32_t comment_size = 0; -- if (zip == NULL || comment == NULL) -+ if (!zip || !comment) - return MZ_PARAM_ERROR; -- if (zip->comment != NULL) -- MZ_FREE(zip->comment); -+ if (zip->comment) -+ free(zip->comment); - comment_size = (int32_t)strlen(comment); - if (comment_size > UINT16_MAX) - return MZ_PARAM_ERROR; -- zip->comment = (char *)MZ_ALLOC(comment_size+1); -- if (zip->comment == NULL) -+ zip->comment = (char *)calloc(comment_size + 1, sizeof(char)); -+ if (!zip->comment) - return MZ_MEM_ERROR; -- memset(zip->comment, 0, comment_size+1); - strncpy(zip->comment, comment, comment_size); - return MZ_OK; - } - - int32_t mz_zip_get_version_madeby(void *handle, uint16_t *version_madeby) { - mz_zip *zip = (mz_zip *)handle; -- if (zip == NULL || version_madeby == NULL) -+ if (!zip || !version_madeby) - return MZ_PARAM_ERROR; - *version_madeby = zip->version_madeby; - return MZ_OK; -@@ -1563,7 +1571,7 @@ int32_t mz_zip_get_version_madeby(void *handle, uint16_t *version_madeby) { - - int32_t mz_zip_set_version_madeby(void *handle, uint16_t version_madeby) { - mz_zip *zip = (mz_zip *)handle; -- if (zip == NULL) -+ if (!zip) - return MZ_PARAM_ERROR; - zip->version_madeby = version_madeby; - return MZ_OK; -@@ -1571,7 +1579,7 @@ int32_t mz_zip_set_version_madeby(void *handle, uint16_t version_madeby) { - - int32_t mz_zip_set_recover(void *handle, uint8_t recover) { - mz_zip *zip = (mz_zip *)handle; -- if (zip == NULL) -+ if (!zip) - return MZ_PARAM_ERROR; - zip->recover = recover; - return MZ_OK; -@@ -1579,7 +1587,7 @@ int32_t mz_zip_set_recover(void *handle, uint8_t recover) { - - int32_t mz_zip_set_data_descriptor(void *handle, uint8_t data_descriptor) { - mz_zip *zip = (mz_zip *)handle; -- if (zip == NULL) -+ if (!zip) - return MZ_PARAM_ERROR; - zip->data_descriptor = data_descriptor; - return MZ_OK; -@@ -1587,17 +1595,17 @@ int32_t mz_zip_set_data_descriptor(void *handle, uint8_t data_descriptor) { - - int32_t mz_zip_get_stream(void *handle, void **stream) { - mz_zip *zip = (mz_zip *)handle; -- if (zip == NULL || stream == NULL) -+ if (!zip || !stream) - return MZ_PARAM_ERROR; - *stream = zip->stream; -- if (*stream == NULL) -+ if (!*stream) - return MZ_EXIST_ERROR; - return MZ_OK; - } - - int32_t mz_zip_set_cd_stream(void *handle, int64_t cd_start_pos, void *cd_stream) { - mz_zip *zip = (mz_zip *)handle; -- if (zip == NULL || cd_stream == NULL) -+ if (!zip || !cd_stream) - return MZ_PARAM_ERROR; - zip->cd_offset = 0; - zip->cd_stream = cd_stream; -@@ -1607,17 +1615,17 @@ int32_t mz_zip_set_cd_stream(void *handle, int64_t cd_start_pos, void *cd_stream - - int32_t mz_zip_get_cd_mem_stream(void *handle, void **cd_mem_stream) { - mz_zip *zip = (mz_zip *)handle; -- if (zip == NULL || cd_mem_stream == NULL) -+ if (!zip || !cd_mem_stream) - return MZ_PARAM_ERROR; - *cd_mem_stream = zip->cd_mem_stream; -- if (*cd_mem_stream == NULL) -+ if (!*cd_mem_stream) - return MZ_EXIST_ERROR; - return MZ_OK; - } - - int32_t mz_zip_set_number_entry(void *handle, uint64_t number_entry) { - mz_zip *zip = (mz_zip *)handle; -- if (zip == NULL) -+ if (!zip) - return MZ_PARAM_ERROR; - zip->number_entry = number_entry; - return MZ_OK; -@@ -1625,7 +1633,7 @@ int32_t mz_zip_set_number_entry(void *handle, uint64_t number_entry) { - - int32_t mz_zip_get_number_entry(void *handle, uint64_t *number_entry) { - mz_zip *zip = (mz_zip *)handle; -- if (zip == NULL || number_entry == NULL) -+ if (!zip || !number_entry) - return MZ_PARAM_ERROR; - *number_entry = zip->number_entry; - return MZ_OK; -@@ -1633,7 +1641,7 @@ int32_t mz_zip_get_number_entry(void *handle, uint64_t *number_entry) { - - int32_t mz_zip_set_disk_number_with_cd(void *handle, uint32_t disk_number_with_cd) { - mz_zip *zip = (mz_zip *)handle; -- if (zip == NULL) -+ if (!zip) - return MZ_PARAM_ERROR; - zip->disk_number_with_cd = disk_number_with_cd; - return MZ_OK; -@@ -1641,7 +1649,7 @@ int32_t mz_zip_set_disk_number_with_cd(void *handle, uint32_t disk_number_with_c - - int32_t mz_zip_get_disk_number_with_cd(void *handle, uint32_t *disk_number_with_cd) { - mz_zip *zip = (mz_zip *)handle; -- if (zip == NULL || disk_number_with_cd == NULL) -+ if (!zip || !disk_number_with_cd) - return MZ_PARAM_ERROR; - *disk_number_with_cd = zip->disk_number_with_cd; - return MZ_OK; -@@ -1650,10 +1658,10 @@ int32_t mz_zip_get_disk_number_with_cd(void *handle, uint32_t *disk_number_with_ - static int32_t mz_zip_entry_close_int(void *handle) { - mz_zip *zip = (mz_zip *)handle; - -- if (zip->crypt_stream != NULL) -+ if (zip->crypt_stream) - mz_stream_delete(&zip->crypt_stream); - zip->crypt_stream = NULL; -- if (zip->compress_stream != NULL) -+ if (zip->compress_stream) - mz_stream_delete(&zip->compress_stream); - zip->compress_stream = NULL; - -@@ -1670,7 +1678,7 @@ static int32_t mz_zip_entry_open_int(void *handle, uint8_t raw, int16_t compress - int32_t err = MZ_OK; - uint8_t use_crypt = 0; - -- if (zip == NULL) -+ if (!zip) - return MZ_PARAM_ERROR; - - switch (zip->file_info.compression_method) { -@@ -1701,7 +1709,7 @@ static int32_t mz_zip_entry_open_int(void *handle, uint8_t raw, int16_t compress - - zip->entry_raw = raw; - -- if ((zip->file_info.flag & MZ_ZIP_FLAG_ENCRYPTED) && (password != NULL)) { -+ if ((zip->file_info.flag & MZ_ZIP_FLAG_ENCRYPTED) && (password)) { - if (zip->open_mode & MZ_OPEN_MODE_WRITE) { - /* Encrypt only when we are not trying to write raw and password is supplied. */ - if (!zip->entry_raw) -@@ -1734,7 +1742,7 @@ static int32_t mz_zip_entry_open_int(void *handle, uint8_t raw, int16_t compress - } - - if (err == MZ_OK) { -- if (zip->crypt_stream == NULL) -+ if (!zip->crypt_stream) - mz_stream_raw_create(&zip->crypt_stream); - - mz_stream_set_base(zip->crypt_stream, zip->stream); -@@ -1833,7 +1841,7 @@ static int32_t mz_zip_entry_open_int(void *handle, uint8_t raw, int16_t compress - - int32_t mz_zip_entry_is_open(void *handle) { - mz_zip *zip = (mz_zip *)handle; -- if (zip == NULL) -+ if (!zip) - return MZ_PARAM_ERROR; - if (zip->entry_opened == 0) - return MZ_EXIST_ERROR; -@@ -1846,15 +1854,13 @@ int32_t mz_zip_entry_read_open(void *handle, uint8_t raw, const char *password) - int32_t err_shift = MZ_OK; - - #if defined(MZ_ZIP_NO_ENCRYPTION) -- if (password != NULL) -+ if (password) - return MZ_SUPPORT_ERROR; - #endif -- if (zip == NULL) -+ if (!zip || !zip->entry_scanned) - return MZ_PARAM_ERROR; - if ((zip->open_mode & MZ_OPEN_MODE_READ) == 0) - return MZ_PARAM_ERROR; -- if (zip->entry_scanned == 0) -- return MZ_PARAM_ERROR; - - mz_zip_print("Zip - Entry - Read open (raw %" PRId32 ")\n", raw); - -@@ -1894,10 +1900,10 @@ int32_t mz_zip_entry_write_open(void *handle, const mz_zip_file *file_info, int1 - int32_t err = MZ_OK; - - #if defined(MZ_ZIP_NO_ENCRYPTION) -- if (password != NULL) -+ if (password) - return MZ_SUPPORT_ERROR; - #endif -- if (zip == NULL || file_info == NULL || file_info->filename == NULL) -+ if (!zip || !file_info || !file_info->filename) - return MZ_PARAM_ERROR; - - if (mz_zip_entry_is_open(handle) == MZ_OK) { -@@ -1916,22 +1922,22 @@ int32_t mz_zip_entry_write_open(void *handle, const mz_zip_file *file_info, int1 - - /* Copy filename, extrafield, and comment internally */ - filename_pos = mz_stream_tell(zip->file_info_stream); -- if (file_info->filename != NULL) -+ if (file_info->filename) - mz_stream_write(zip->file_info_stream, file_info->filename, (int32_t)strlen(file_info->filename)); - mz_stream_write_uint8(zip->file_info_stream, 0); - - extrafield_pos = mz_stream_tell(zip->file_info_stream); -- if (file_info->extrafield != NULL) -+ if (file_info->extrafield) - mz_stream_write(zip->file_info_stream, file_info->extrafield, file_info->extrafield_size); - mz_stream_write_uint8(zip->file_info_stream, 0); - - comment_pos = mz_stream_tell(zip->file_info_stream); -- if (file_info->comment != NULL) -+ if (file_info->comment) - mz_stream_write(zip->file_info_stream, file_info->comment, file_info->comment_size); - mz_stream_write_uint8(zip->file_info_stream, 0); - - linkname_pos = mz_stream_tell(zip->file_info_stream); -- if (file_info->linkname != NULL) -+ if (file_info->linkname) - mz_stream_write(zip->file_info_stream, file_info->linkname, (int32_t)strlen(file_info->linkname)); - mz_stream_write_uint8(zip->file_info_stream, 0); - -@@ -1960,7 +1966,7 @@ int32_t mz_zip_entry_write_open(void *handle, const mz_zip_file *file_info, int1 - if (!is_dir) { - if (zip->data_descriptor) - zip->file_info.flag |= MZ_ZIP_FLAG_DATA_DESCRIPTOR; -- if (password != NULL) -+ if (password) - zip->file_info.flag |= MZ_ZIP_FLAG_ENCRYPTED; - } - -@@ -2002,7 +2008,7 @@ int32_t mz_zip_entry_read(void *handle, void *buf, int32_t len) { - mz_zip *zip = (mz_zip *)handle; - int32_t read = 0; - -- if (zip == NULL || mz_zip_entry_is_open(handle) != MZ_OK) -+ if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) - return MZ_PARAM_ERROR; - if (UINT_MAX == UINT16_MAX && len > UINT16_MAX) /* zlib limitation */ - return MZ_PARAM_ERROR; -@@ -2027,7 +2033,7 @@ int32_t mz_zip_entry_write(void *handle, const void *buf, int32_t len) { - mz_zip *zip = (mz_zip *)handle; - int32_t written = 0; - -- if (zip == NULL || mz_zip_entry_is_open(handle) != MZ_OK) -+ if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) - return MZ_PARAM_ERROR; - written = mz_stream_write(zip->compress_stream, buf, len); - if (written > 0) -@@ -2045,25 +2051,25 @@ int32_t mz_zip_entry_read_close(void *handle, uint32_t *crc32, int64_t *compress - int32_t err = MZ_OK; - uint8_t zip64 = 0; - -- if (zip == NULL || mz_zip_entry_is_open(handle) != MZ_OK) -+ if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) - return MZ_PARAM_ERROR; - - mz_stream_close(zip->compress_stream); - - mz_zip_print("Zip - Entry - Read Close\n"); - -- if (crc32 != NULL) -+ if (crc32) - *crc32 = zip->file_info.crc; -- if (compressed_size != NULL) -+ if (compressed_size) - *compressed_size = zip->file_info.compressed_size; -- if (uncompressed_size != NULL) -+ if (uncompressed_size) - *uncompressed_size = zip->file_info.uncompressed_size; - - mz_stream_get_prop_int64(zip->compress_stream, MZ_STREAM_PROP_TOTAL_IN, &total_in); - - if ((zip->file_info.flag & MZ_ZIP_FLAG_DATA_DESCRIPTOR) && - ((zip->file_info.flag & MZ_ZIP_FLAG_MASK_LOCAL_INFO) == 0) && -- (crc32 != NULL || compressed_size != NULL || uncompressed_size != NULL)) { -+ (crc32 || compressed_size || uncompressed_size)) { - /* Check to see if data descriptor is zip64 bit format or not */ - if (mz_zip_extrafield_contains(zip->local_file_info.extrafield, - zip->local_file_info.extrafield_size, MZ_ZIP_EXTENSION_ZIP64, NULL) == MZ_OK) -@@ -2085,7 +2091,7 @@ int32_t mz_zip_entry_read_close(void *handle, uint32_t *crc32, int64_t *compress - } - - /* If entire entry was not read verification will fail */ -- if ((err == MZ_OK) && (total_in > 0) && (!zip->entry_raw)) { -+ if ((err == MZ_OK) && (total_in == zip->file_info.compressed_size) && (!zip->entry_raw)) { - #ifdef HAVE_WZAES - /* AES zip version AE-1 will expect a valid crc as well */ - if (zip->file_info.aes_version <= 0x0001) -@@ -2112,7 +2118,7 @@ int32_t mz_zip_entry_write_close(void *handle, uint32_t crc32, int64_t compresse - int32_t err = MZ_OK; - uint8_t zip64 = 0; - -- if (zip == NULL || mz_zip_entry_is_open(handle) != MZ_OK) -+ if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) - return MZ_PARAM_ERROR; - - mz_stream_close(zip->compress_stream); -@@ -2173,7 +2179,9 @@ int32_t mz_zip_entry_write_close(void *handle, uint32_t crc32, int64_t compresse - - if (err == MZ_OK) { - /* Seek to crc32 and sizes offset in local header */ -- err = mz_stream_seek(zip->stream, MZ_ZIP_OFFSET_CRC_SIZES, MZ_SEEK_CUR); -+ err = mz_stream_set_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, zip->file_info.disk_number); -+ if (err == MZ_OK) -+ err = mz_stream_seek(zip->stream, zip->file_info.disk_offset + MZ_ZIP_OFFSET_CRC_SIZES, MZ_SEEK_SET); - } - - if (err == MZ_OK) -@@ -2230,6 +2238,16 @@ int32_t mz_zip_entry_seek_local_header(void *handle) { - return mz_stream_seek(zip->stream, zip->file_info.disk_offset + zip->disk_offset_shift, MZ_SEEK_SET); - } - -+int32_t mz_zip_entry_get_compress_stream(void *handle, void **compress_stream) { -+ mz_zip *zip = (mz_zip *)handle; -+ if (!zip || !compress_stream) -+ return MZ_PARAM_ERROR; -+ *compress_stream = zip->compress_stream; -+ if (!*compress_stream) -+ return MZ_EXIST_ERROR; -+ return MZ_OK; -+} -+ - int32_t mz_zip_entry_close(void *handle) { - return mz_zip_entry_close_raw(handle, UINT64_MAX, 0); - } -@@ -2238,7 +2256,7 @@ int32_t mz_zip_entry_close_raw(void *handle, int64_t uncompressed_size, uint32_t - mz_zip *zip = (mz_zip *)handle; - int32_t err = MZ_OK; - -- if (zip == NULL || mz_zip_entry_is_open(handle) != MZ_OK) -+ if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) - return MZ_PARAM_ERROR; - - if (zip->open_mode & MZ_OPEN_MODE_WRITE) -@@ -2253,9 +2271,7 @@ int32_t mz_zip_entry_is_dir(void *handle) { - mz_zip *zip = (mz_zip *)handle; - int32_t filename_length = 0; - -- if (zip == NULL) -- return MZ_PARAM_ERROR; -- if (zip->entry_scanned == 0) -+ if (!zip || !zip->entry_scanned) - return MZ_PARAM_ERROR; - if (mz_zip_attrib_is_dir(zip->file_info.external_fa, zip->file_info.version_madeby) == MZ_OK) - return MZ_OK; -@@ -2272,14 +2288,10 @@ int32_t mz_zip_entry_is_dir(void *handle) { - int32_t mz_zip_entry_is_symlink(void *handle) { - mz_zip *zip = (mz_zip *)handle; - -- if (zip == NULL) -- return MZ_PARAM_ERROR; -- if (zip->entry_scanned == 0) -+ if (!zip || !zip->entry_scanned) - return MZ_PARAM_ERROR; - if (mz_zip_attrib_is_symlink(zip->file_info.external_fa, zip->file_info.version_madeby) != MZ_OK) - return MZ_EXIST_ERROR; -- if (zip->file_info.linkname == NULL || *zip->file_info.linkname == 0) -- return MZ_EXIST_ERROR; - - return MZ_OK; - } -@@ -2287,7 +2299,7 @@ int32_t mz_zip_entry_is_symlink(void *handle) { - int32_t mz_zip_entry_get_info(void *handle, mz_zip_file **file_info) { - mz_zip *zip = (mz_zip *)handle; - -- if (zip == NULL) -+ if (!zip) - return MZ_PARAM_ERROR; - - if ((zip->open_mode & MZ_OPEN_MODE_WRITE) == 0) { -@@ -2301,7 +2313,7 @@ int32_t mz_zip_entry_get_info(void *handle, mz_zip_file **file_info) { - - int32_t mz_zip_entry_get_local_info(void *handle, mz_zip_file **local_file_info) { - mz_zip *zip = (mz_zip *)handle; -- if (zip == NULL || mz_zip_entry_is_open(handle) != MZ_OK) -+ if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) - return MZ_PARAM_ERROR; - *local_file_info = &zip->local_file_info; - return MZ_OK; -@@ -2310,7 +2322,7 @@ int32_t mz_zip_entry_get_local_info(void *handle, mz_zip_file **local_file_info) - int32_t mz_zip_entry_set_extrafield(void *handle, const uint8_t *extrafield, uint16_t extrafield_size) { - mz_zip *zip = (mz_zip *)handle; - -- if (zip == NULL || mz_zip_entry_is_open(handle) != MZ_OK) -+ if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) - return MZ_PARAM_ERROR; - - zip->file_info.extrafield = extrafield; -@@ -2322,7 +2334,7 @@ static int32_t mz_zip_goto_next_entry_int(void *handle) { - mz_zip *zip = (mz_zip *)handle; - int32_t err = MZ_OK; - -- if (zip == NULL) -+ if (!zip) - return MZ_PARAM_ERROR; - - zip->entry_scanned = 0; -@@ -2340,7 +2352,7 @@ static int32_t mz_zip_goto_next_entry_int(void *handle) { - int64_t mz_zip_get_entry(void *handle) { - mz_zip *zip = (mz_zip *)handle; - -- if (zip == NULL) -+ if (!zip) - return MZ_PARAM_ERROR; - - return zip->cd_current_pos; -@@ -2349,7 +2361,7 @@ int64_t mz_zip_get_entry(void *handle) { - int32_t mz_zip_goto_entry(void *handle, int64_t cd_pos) { - mz_zip *zip = (mz_zip *)handle; - -- if (zip == NULL) -+ if (!zip) - return MZ_PARAM_ERROR; - - if (cd_pos < zip->cd_start_pos || cd_pos > zip->cd_start_pos + zip->cd_size) -@@ -2363,7 +2375,7 @@ int32_t mz_zip_goto_entry(void *handle, int64_t cd_pos) { - int32_t mz_zip_goto_first_entry(void *handle) { - mz_zip *zip = (mz_zip *)handle; - -- if (zip == NULL) -+ if (!zip) - return MZ_PARAM_ERROR; - - zip->cd_current_pos = zip->cd_start_pos; -@@ -2374,7 +2386,7 @@ int32_t mz_zip_goto_first_entry(void *handle) { - int32_t mz_zip_goto_next_entry(void *handle) { - mz_zip *zip = (mz_zip *)handle; - -- if (zip == NULL) -+ if (!zip) - return MZ_PARAM_ERROR; - - zip->cd_current_pos += (int64_t)MZ_ZIP_SIZE_CD_ITEM + zip->file_info.filename_size + -@@ -2388,11 +2400,11 @@ int32_t mz_zip_locate_entry(void *handle, const char *filename, uint8_t ignore_c - int32_t err = MZ_OK; - int32_t result = 0; - -- if (zip == NULL || filename == NULL) -+ if (!zip || !filename) - return MZ_PARAM_ERROR; - - /* If we are already on the current entry, no need to search */ -- if ((zip->entry_scanned) && (zip->file_info.filename != NULL)) { -+ if (zip->entry_scanned && zip->file_info.filename) { - result = mz_zip_path_compare(zip->file_info.filename, filename, ignore_case); - if (result == 0) - return MZ_OK; -@@ -2477,7 +2489,7 @@ int32_t mz_zip_attrib_is_symlink(uint32_t attrib, int32_t version_madeby) { - } - - int32_t mz_zip_attrib_convert(uint8_t src_sys, uint32_t src_attrib, uint8_t target_sys, uint32_t *target_attrib) { -- if (target_attrib == NULL) -+ if (!target_attrib) - return MZ_PARAM_ERROR; - - *target_attrib = 0; -@@ -2490,11 +2502,11 @@ int32_t mz_zip_attrib_convert(uint8_t src_sys, uint32_t src_attrib, uint8_t targ - if ((target_sys == MZ_HOST_SYSTEM_UNIX) || (target_sys == MZ_HOST_SYSTEM_OSX_DARWIN) || (target_sys == MZ_HOST_SYSTEM_RISCOS)) - return mz_zip_attrib_win32_to_posix(src_attrib, target_attrib); - } else if ((src_sys == MZ_HOST_SYSTEM_UNIX) || (src_sys == MZ_HOST_SYSTEM_OSX_DARWIN) || (src_sys == MZ_HOST_SYSTEM_RISCOS)) { -- if ((target_sys == MZ_HOST_SYSTEM_UNIX) || (target_sys == MZ_HOST_SYSTEM_OSX_DARWIN) || (target_sys == MZ_HOST_SYSTEM_RISCOS)) { -- /* If high bytes are set, it contains unix specific attributes */ -- if ((src_attrib >> 16) != 0) -- src_attrib >>= 16; -+ /* If high bytes are set, it contains unix specific attributes */ -+ if ((src_attrib >> 16) != 0) -+ src_attrib >>= 16; - -+ if ((target_sys == MZ_HOST_SYSTEM_UNIX) || (target_sys == MZ_HOST_SYSTEM_OSX_DARWIN) || (target_sys == MZ_HOST_SYSTEM_RISCOS)) { - *target_attrib = src_attrib; - return MZ_OK; - } -@@ -2506,7 +2518,7 @@ int32_t mz_zip_attrib_convert(uint8_t src_sys, uint32_t src_attrib, uint8_t targ - } - - int32_t mz_zip_attrib_posix_to_win32(uint32_t posix_attrib, uint32_t *win32_attrib) { -- if (win32_attrib == NULL) -+ if (!win32_attrib) - return MZ_PARAM_ERROR; - - *win32_attrib = 0; -@@ -2528,7 +2540,7 @@ int32_t mz_zip_attrib_posix_to_win32(uint32_t posix_attrib, uint32_t *win32_attr - } - - int32_t mz_zip_attrib_win32_to_posix(uint32_t win32_attrib, uint32_t *posix_attrib) { -- if (posix_attrib == NULL) -+ if (!posix_attrib) - return MZ_PARAM_ERROR; - - *posix_attrib = 0000444; /* S_IRUSR | S_IRGRP | S_IROTH */ -@@ -2554,7 +2566,6 @@ int32_t mz_zip_extrafield_find(void *stream, uint16_t type, int32_t max_seek, ui - uint16_t field_type = 0; - uint16_t field_length = 0; - -- - if (max_seek < 4) - return MZ_EXIST_ERROR; - -@@ -2566,7 +2577,7 @@ int32_t mz_zip_extrafield_find(void *stream, uint16_t type, int32_t max_seek, ui - break; - - if (type == field_type) { -- if (length != NULL) -+ if (length) - *length = field_length; - return MZ_OK; - } -@@ -2586,7 +2597,7 @@ int32_t mz_zip_extrafield_contains(const uint8_t *extrafield, int32_t extrafield - void *file_extra_stream = NULL; - int32_t err = MZ_OK; - -- if (extrafield == NULL || extrafield_size == 0) -+ if (!extrafield || !extrafield_size) - return MZ_PARAM_ERROR; - - mz_stream_mem_create(&file_extra_stream); -@@ -2601,7 +2612,7 @@ int32_t mz_zip_extrafield_contains(const uint8_t *extrafield, int32_t extrafield - - int32_t mz_zip_extrafield_read(void *stream, uint16_t *type, uint16_t *length) { - int32_t err = MZ_OK; -- if (type == NULL || length == NULL) -+ if (!type || !length) - return MZ_PARAM_ERROR; - err = mz_stream_read_uint16(stream, type); - if (err == MZ_OK) -@@ -2643,7 +2654,7 @@ static void mz_zip_dosdate_to_raw_tm(uint64_t dos_date, struct tm *ptm) { - } - - int32_t mz_zip_dosdate_to_tm(uint64_t dos_date, struct tm *ptm) { -- if (ptm == NULL) -+ if (!ptm) - return MZ_PARAM_ERROR; - - mz_zip_dosdate_to_raw_tm(dos_date, ptm); -@@ -2664,9 +2675,9 @@ time_t mz_zip_dosdate_to_time_t(uint64_t dos_date) { - - int32_t mz_zip_time_t_to_tm(time_t unix_time, struct tm *ptm) { - struct tm ltm; -- if (ptm == NULL) -+ if (!ptm) - return MZ_PARAM_ERROR; -- if (localtime_r(&unix_time, <m) == NULL) { /* Returns a 1900-based year */ -+ if (!localtime_r(&unix_time, <m)) { /* Returns a 1900-based year */ - /* Invalid date stored, so don't return it */ - memset(ptm, 0, sizeof(struct tm)); - return MZ_INTERNAL_ERROR; -diff --git a/src/minizip/mz_zip.h b/src/minizip/mz_zip.h -index e3d1fbd52..65be301af 100644 ---- a/src/minizip/mz_zip.h -+++ b/src/minizip/mz_zip.h -@@ -1,7 +1,7 @@ - /* mz_zip.h -- Zip manipulation - part of the minizip-ng project - -- Copyright (C) 2010-2021 Nathan Moinvaziri -+ Copyright (C) Nathan Moinvaziri - https://github.com/zlib-ng/minizip-ng - Copyright (C) 2009-2010 Mathias Svensson - Modifications for Zip64 support -@@ -139,6 +139,9 @@ int32_t mz_zip_entry_write_close(void *handle, uint32_t crc32, int64_t compresse - int32_t mz_zip_entry_seek_local_header(void *handle); - /* Seeks to the local header for the entry */ - -+int32_t mz_zip_entry_get_compress_stream(void *handle, void **compress_stream); -+/* Get a pointer to the compression stream used for the current entry */ -+ - int32_t mz_zip_entry_close_raw(void *handle, int64_t uncompressed_size, uint32_t crc32); - /* Close the current file in the zip file where raw is compressed data */ - - -From 5b5a0a5973eaa6204a5663a68d59a5307b0ff55a Mon Sep 17 00:00:00 2001 -From: Julian Sikorski -Date: Wed, 21 Feb 2024 23:49:52 +0100 -Subject: [PATCH 4/4] imp: updated bundled minizip to 4.0.4 - ---- - src/minizip/README.minizip | 2 +- - src/minizip/mz.h | 15 ++-- - src/minizip/mz_compat.c | 126 +++++++++++++++++++++++++-------- - src/minizip/mz_compat.h | 97 ++++++++++++++----------- - src/minizip/mz_crypt.c | 12 +++- - src/minizip/mz_crypt.h | 24 +++---- - src/minizip/mz_os.c | 14 ++-- - src/minizip/mz_os.h | 4 +- - src/minizip/mz_os_posix.c | 13 ++-- - src/minizip/mz_os_win32.c | 30 ++++---- - src/minizip/mz_strm.c | 15 ++-- - src/minizip/mz_strm.h | 6 +- - src/minizip/mz_strm_mem.c | 9 +-- - src/minizip/mz_strm_mem.h | 2 +- - src/minizip/mz_strm_os.h | 2 +- - src/minizip/mz_strm_os_posix.c | 9 +-- - src/minizip/mz_strm_os_win32.c | 17 +++-- - src/minizip/mz_strm_zlib.c | 16 ++--- - src/minizip/mz_strm_zlib.h | 2 +- - src/minizip/mz_zip.c | 101 +++++++++++++++----------- - src/minizip/mz_zip.h | 4 +- - 21 files changed, 308 insertions(+), 212 deletions(-) - -diff --git a/src/minizip/README.minizip b/src/minizip/README.minizip -index 22a0f58b6..7634a8511 100644 ---- a/src/minizip/README.minizip -+++ b/src/minizip/README.minizip -@@ -1 +1 @@ --This code has been taken from https://github.com/zlib-ng/minizip-ng/releases/tag/3.0.10 -+This code has been taken from https://github.com/zlib-ng/minizip-ng/releases/tag/4.0.4 -diff --git a/src/minizip/mz.h b/src/minizip/mz.h -index 769a7b65a..675cec297 100644 ---- a/src/minizip/mz.h -+++ b/src/minizip/mz.h -@@ -14,8 +14,8 @@ - /***************************************************************************/ - - /* MZ_VERSION */ --#define MZ_VERSION ("3.0.10") --#define MZ_VERSION_BUILD (03000a) -+#define MZ_VERSION ("4.0.4") -+#define MZ_VERSION_BUILD (040004) - - /* MZ_ERROR */ - #define MZ_OK (0) /* zlib */ -@@ -112,13 +112,14 @@ - - /* MZ_AES */ - #define MZ_AES_VERSION (1) --#define MZ_AES_ENCRYPTION_MODE_128 (0x01) --#define MZ_AES_ENCRYPTION_MODE_192 (0x02) --#define MZ_AES_ENCRYPTION_MODE_256 (0x03) --#define MZ_AES_KEY_LENGTH(MODE) (8 * (MODE & 3) + 8) -+#define MZ_AES_MODE_ECB (0) -+#define MZ_AES_MODE_CBC (1) -+#define MZ_AES_MODE_GCM (2) -+#define MZ_AES_STRENGTH_128 (1) -+#define MZ_AES_STRENGTH_192 (2) -+#define MZ_AES_STRENGTH_256 (3) - #define MZ_AES_KEY_LENGTH_MAX (32) - #define MZ_AES_BLOCK_SIZE (16) --#define MZ_AES_HEADER_SIZE(MODE) ((4 * (MODE & 3) + 4) + 2) - #define MZ_AES_FOOTER_SIZE (10) - - /* MZ_HASH */ -diff --git a/src/minizip/mz_compat.c b/src/minizip/mz_compat.c -index fab6bf046..872dab8f3 100644 ---- a/src/minizip/mz_compat.c -+++ b/src/minizip/mz_compat.c -@@ -51,7 +51,7 @@ static int64_t mz_stream_ioapi_tell(void *stream); - static int32_t mz_stream_ioapi_seek(void *stream, int64_t offset, int32_t origin); - static int32_t mz_stream_ioapi_close(void *stream); - static int32_t mz_stream_ioapi_error(void *stream); --static void *mz_stream_ioapi_create(void **stream); -+static void *mz_stream_ioapi_create(void); - static void mz_stream_ioapi_delete(void **stream); - - /***************************************************************************/ -@@ -121,7 +121,7 @@ static int32_t mz_stream_ioapi_read(void *stream, void *buf, int32_t size) { - } else - return MZ_PARAM_ERROR; - -- return zread(opaque, ioapi->handle, buf, size); -+ return (int32_t)zread(opaque, ioapi->handle, buf, size); - } - - static int32_t mz_stream_ioapi_write(void *stream, const void *buf, int32_t size) { -@@ -142,7 +142,7 @@ static int32_t mz_stream_ioapi_write(void *stream, const void *buf, int32_t size - } else - return MZ_PARAM_ERROR; - -- written = zwrite(opaque, ioapi->handle, buf, size); -+ written = (int32_t)zwrite(opaque, ioapi->handle, buf, size); - return written; - } - -@@ -233,15 +233,10 @@ static int32_t mz_stream_ioapi_set_filefunc64(void *stream, zlib_filefunc64_def - return MZ_OK; - } - --static void *mz_stream_ioapi_create(void **stream) { -- mz_stream_ioapi *ioapi = NULL; -- -- ioapi = (mz_stream_ioapi *)calloc(1, sizeof(mz_stream_ioapi)); -+static void *mz_stream_ioapi_create(void) { -+ mz_stream_ioapi *ioapi = (mz_stream_ioapi *)calloc(1, sizeof(mz_stream_ioapi)); - if (ioapi) - ioapi->stream.vtbl = &mz_stream_ioapi_vtbl; -- if (stream) -- *stream = ioapi; -- - return ioapi; - } - -@@ -333,17 +328,20 @@ zipFile zipOpen2(const char *path, int append, const char **globalcomment, - - if (pzlib_filefunc_def) { - if (pzlib_filefunc_def->zopen_file) { -- if (!mz_stream_ioapi_create(&stream)) -+ stream = mz_stream_ioapi_create(); -+ if (!stream) - return NULL; - mz_stream_ioapi_set_filefunc(stream, pzlib_filefunc_def); - } else if (pzlib_filefunc_def->opaque) { -- if (!mz_stream_create(&stream, (mz_stream_vtbl *)pzlib_filefunc_def->opaque)) -+ stream = mz_stream_create((mz_stream_vtbl *)pzlib_filefunc_def->opaque); -+ if (!stream) - return NULL; - } - } - - if (!stream) { -- if (!mz_stream_os_create(&stream)) -+ stream = mz_stream_os_create(); -+ if (!stream) - return NULL; - } - -@@ -370,17 +368,20 @@ zipFile zipOpen2_64(const void *path, int append, const char **globalcomment, - - if (pzlib_filefunc_def) { - if (pzlib_filefunc_def->zopen64_file) { -- if (!mz_stream_ioapi_create(&stream)) -+ stream = mz_stream_ioapi_create(); -+ if (!stream) - return NULL; - mz_stream_ioapi_set_filefunc64(stream, pzlib_filefunc_def); - } else if (pzlib_filefunc_def->opaque) { -- if (!mz_stream_create(&stream, (mz_stream_vtbl *)pzlib_filefunc_def->opaque)) -+ stream = mz_stream_create((mz_stream_vtbl *)pzlib_filefunc_def->opaque); -+ if (!stream) - return NULL; - } - } - - if (!stream) { -- if (!mz_stream_os_create(&stream)) -+ stream = mz_stream_os_create(); -+ if (!stream) - return NULL; - } - -@@ -405,7 +406,10 @@ zipFile zipOpen_MZ(void *stream, int append, const char **globalcomment) { - int32_t mode = zipConvertAppendToStreamMode(append); - void *handle = NULL; - -- mz_zip_create(&handle); -+ handle = mz_zip_create(); -+ if (!handle) -+ return NULL; -+ - err = mz_zip_open(handle, stream, mode); - - if (err != MZ_OK) { -@@ -459,6 +463,12 @@ int zipOpenNewFileInZip5(zipFile file, const char *filename, const zip_fileinfo - if (!compat) - return ZIP_PARAMERROR; - -+ /* The filename and comment length must fit in 16 bits. */ -+ if (filename && strlen(filename) > 0xffff) -+ return ZIP_PARAMERROR; -+ if (comment && strlen(comment) > 0xffff) -+ return ZIP_PARAMERROR; -+ - memset(&file_info, 0, sizeof(file_info)); - - if (zipfi) { -@@ -470,8 +480,8 @@ int zipOpenNewFileInZip5(zipFile file, const char *filename, const zip_fileinfo - dos_date = mz_zip_tm_to_dosdate(&zipfi->tmz_date); - - file_info.modified_date = mz_zip_dosdate_to_time_t(dos_date); -- file_info.external_fa = zipfi->external_fa; -- file_info.internal_fa = zipfi->internal_fa; -+ file_info.external_fa = (uint32_t)zipfi->external_fa; -+ file_info.internal_fa = (uint16_t)zipfi->internal_fa; - } - - if (!filename) -@@ -534,7 +544,7 @@ int zipOpenNewFileInZip3_64(zipFile file, const char *filename, const zip_filein - const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, - uint16_t size_extrafield_global, const char *comment, int compression_method, int level, - int raw, int windowBits, int memLevel, int strategy, const char *password, -- uint32_t crc_for_crypting, int zip64) { -+ unsigned long crc_for_crypting, int zip64) { - return zipOpenNewFileInZip4_64(file, filename, zipfi, extrafield_local, size_extrafield_local, - extrafield_global, size_extrafield_global, comment, compression_method, level, raw, windowBits, - memLevel, strategy, password, crc_for_crypting, MZ_VERSION_MADEBY, 0, zip64); -@@ -592,7 +602,7 @@ int zipCloseFileInZipRaw64(zipFile file, uint64_t uncompressed_size, unsigned lo - mz_compat *compat = (mz_compat *)file; - if (!compat) - return ZIP_PARAMERROR; -- return mz_zip_entry_close_raw(compat->handle, (int64_t)uncompressed_size, crc32); -+ return mz_zip_entry_close_raw(compat->handle, (int64_t)uncompressed_size, (uint32_t)crc32); - } - - int zipCloseFileInZip(zipFile file) { -@@ -672,17 +682,20 @@ unzFile unzOpen2(const char *path, zlib_filefunc_def *pzlib_filefunc_def) { - - if (pzlib_filefunc_def) { - if (pzlib_filefunc_def->zopen_file) { -- if (!mz_stream_ioapi_create(&stream)) -+ stream = mz_stream_ioapi_create(); -+ if (!stream) - return NULL; - mz_stream_ioapi_set_filefunc(stream, pzlib_filefunc_def); - } else if (pzlib_filefunc_def->opaque) { -- if (!mz_stream_create(&stream, (mz_stream_vtbl *)pzlib_filefunc_def->opaque)) -+ stream = mz_stream_create((mz_stream_vtbl *)pzlib_filefunc_def->opaque); -+ if (!stream) - return NULL; - } - } - - if (!stream) { -- if (!mz_stream_os_create(&stream)) -+ stream = mz_stream_os_create(); -+ if (!stream) - return NULL; - } - -@@ -706,17 +719,20 @@ unzFile unzOpen2_64(const void *path, zlib_filefunc64_def *pzlib_filefunc_def) { - - if (pzlib_filefunc_def) { - if (pzlib_filefunc_def->zopen64_file) { -- if (!mz_stream_ioapi_create(&stream)) -+ stream = mz_stream_ioapi_create(); -+ if (!stream) - return NULL; - mz_stream_ioapi_set_filefunc64(stream, pzlib_filefunc_def); - } else if (pzlib_filefunc_def->opaque) { -- if (!mz_stream_create(&stream, (mz_stream_vtbl *)pzlib_filefunc_def->opaque)) -+ stream = mz_stream_create((mz_stream_vtbl *)pzlib_filefunc_def->opaque); -+ if (!stream) - return NULL; - } - } - - if (!stream) { -- if (!mz_stream_os_create(&stream)) -+ stream = mz_stream_os_create(); -+ if (!stream) - return NULL; - } - -@@ -753,9 +769,11 @@ unzFile unzOpen_MZ(void *stream) { - int32_t err = MZ_OK; - void *handle = NULL; - -- mz_zip_create(&handle); -- err = mz_zip_open(handle, stream, MZ_OPEN_MODE_READ); -+ handle = mz_zip_create(); -+ if (!handle) -+ return NULL; - -+ err = mz_zip_open(handle, stream, MZ_OPEN_MODE_READ); - if (err != MZ_OK) { - mz_zip_delete(&handle); - return NULL; -@@ -1081,12 +1099,56 @@ int unzGoToNextFile(unzFile file) { - return err; - } - --int unzLocateFile(unzFile file, const char *filename, unzFileNameComparer filename_compare_func) { -+#if !defined(MZ_COMPAT_VERSION) || MZ_COMPAT_VERSION < 110 -+#ifdef WIN32 -+# define UNZ_DEFAULT_IGNORE_CASE 1 -+#else -+# define UNZ_DEFAULT_IGNORE_CASE 0 -+#endif -+ -+int unzLocateFile(unzFile file, const char *filename, unzFileNameCase filename_case) { - mz_compat *compat = (mz_compat *)file; - mz_zip_file *file_info = NULL; - uint64_t preserve_index = 0; - int32_t err = MZ_OK; - int32_t result = 0; -+ uint8_t ignore_case = UNZ_DEFAULT_IGNORE_CASE; -+ -+ if (!compat) -+ return UNZ_PARAMERROR; -+ -+ if (filename_case == 1) { -+ ignore_case = 0; -+ } else if (filename_case > 1) { -+ ignore_case = 1; -+ } -+ -+ preserve_index = compat->entry_index; -+ -+ err = mz_zip_goto_first_entry(compat->handle); -+ while (err == MZ_OK) { -+ err = mz_zip_entry_get_info(compat->handle, &file_info); -+ if (err != MZ_OK) -+ break; -+ -+ result = mz_path_compare_wc(filename, file_info->filename, !ignore_case); -+ -+ if (result == 0) -+ return MZ_OK; -+ -+ err = mz_zip_goto_next_entry(compat->handle); -+ } -+ -+ compat->entry_index = preserve_index; -+ return err; -+} -+#else -+int unzLocateFile(unzFile file, const char* filename, unzFileNameComparer filename_compare_func) { -+ mz_compat* compat = (mz_compat*)file; -+ mz_zip_file* file_info = NULL; -+ uint64_t preserve_index = 0; -+ int32_t err = MZ_OK; -+ int32_t result = 0; - - if (!compat) - return UNZ_PARAMERROR; -@@ -1101,7 +1163,8 @@ int unzLocateFile(unzFile file, const char *filename, unzFileNameComparer filena - - if ((intptr_t)filename_compare_func > 2) { - result = filename_compare_func(file, filename, file_info->filename); -- } else { -+ } -+ else { - int32_t case_sensitive = (int32_t)(intptr_t)filename_compare_func; - result = mz_path_compare_wc(filename, file_info->filename, !case_sensitive); - } -@@ -1115,6 +1178,7 @@ int unzLocateFile(unzFile file, const char *filename, unzFileNameComparer filena - compat->entry_index = preserve_index; - return err; - } -+#endif - - /***************************************************************************/ - -diff --git a/src/minizip/mz_compat.h b/src/minizip/mz_compat.h -index 6e6a916ff..47153ea24 100644 ---- a/src/minizip/mz_compat.h -+++ b/src/minizip/mz_compat.h -@@ -120,7 +120,7 @@ ZEXPORT void fill_memory_filefunc(zlib_filefunc_def *pzlib_filefunc_def); - - /***************************************************************************/ - --#if MZ_COMPAT_VERSION <= 110 -+#if !defined(MZ_COMPAT_VERSION) || MZ_COMPAT_VERSION <= 110 - #define mz_dos_date dosDate - #else - #define mz_dos_date dos_date -@@ -130,10 +130,10 @@ typedef struct tm tm_unz; - typedef struct tm tm_zip; - - typedef struct { -- uint32_t mz_dos_date; -- struct tm tmz_date; -- uint16_t internal_fa; /* internal file attributes 2 bytes */ -- uint32_t external_fa; /* external file attributes 4 bytes */ -+ struct tm tmz_date; /* date in understandable format */ -+ unsigned long mz_dos_date; /* if dos_date == 0, tmz_date is used */ -+ unsigned long internal_fa; /* internal file attributes 2 bytes */ -+ unsigned long external_fa; /* external file attributes 4 bytes */ - } zip_fileinfo; - - typedef const char *zipcharpc; -@@ -195,7 +195,7 @@ ZEXPORT int zipOpenNewFileInZip3_64(zipFile file, const char *filename, cons - const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, - uint16_t size_extrafield_global, const char *comment, int compression_method, int level, - int raw, int windowBits, int memLevel, int strategy, const char *password, -- uint32_t crc_for_crypting, int zip64); -+ unsigned long crc_for_crypting, int zip64); - ZEXPORT int zipOpenNewFileInZip4(zipFile file, const char *filename, const zip_fileinfo *zipfi, - const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, - uint16_t size_extrafield_global, const char *comment, int compression_method, int level, -@@ -252,33 +252,34 @@ typedef void *unzFile; - - typedef struct unz_global_info64_s { - uint64_t number_entry; /* total number of entries in the central dir on this disk */ -+ unsigned long size_comment; /* size of the global comment of the zipfile */ - uint32_t number_disk_with_CD; /* number the the disk with central dir, used for spanning ZIP */ -- uint16_t size_comment; /* size of the global comment of the zipfile */ - } unz_global_info64; - - typedef struct unz_global_info_s { -- uint32_t number_entry; /* total number of entries in the central dir on this disk */ -+ unsigned long number_entry; /* total number of entries in the central dir on this disk */ -+ unsigned long size_comment; /* size of the global comment of the zipfile */ - uint32_t number_disk_with_CD; /* number the the disk with central dir, used for spanning ZIP */ -- uint16_t size_comment; /* size of the global comment of the zipfile */ - } unz_global_info; - - typedef struct unz_file_info64_s { -- uint16_t version; /* version made by 2 bytes */ -- uint16_t version_needed; /* version needed to extract 2 bytes */ -- uint16_t flag; /* general purpose bit flag 2 bytes */ -- uint16_t compression_method; /* compression method 2 bytes */ -- uint32_t mz_dos_date; /* last mod file date in Dos fmt 4 bytes */ -- struct tm tmu_date; -- uint32_t crc; /* crc-32 4 bytes */ -- uint64_t compressed_size; /* compressed size 8 bytes */ -- uint64_t uncompressed_size; /* uncompressed size 8 bytes */ -- uint16_t size_filename; /* filename length 2 bytes */ -- uint16_t size_file_extra; /* extra field length 2 bytes */ -- uint16_t size_file_comment; /* file comment length 2 bytes */ -+ unsigned long version; /* version made by 2 bytes */ -+ unsigned long version_needed; /* version needed to extract 2 bytes */ -+ unsigned long flag; /* general purpose bit flag 2 bytes */ -+ unsigned long compression_method; /* compression method 2 bytes */ -+ unsigned long mz_dos_date; /* last mod file date in Dos fmt 4 bytes */ -+ unsigned long crc; /* crc-32 4 bytes */ -+ uint64_t compressed_size; /* compressed size 8 bytes */ -+ uint64_t uncompressed_size; /* uncompressed size 8 bytes */ -+ unsigned long size_filename; /* filename length 2 bytes */ -+ unsigned long size_file_extra; /* extra field length 2 bytes */ -+ unsigned long size_file_comment; /* file comment length 2 bytes */ -+ -+ unsigned long disk_num_start; /* disk number start 4 bytes */ -+ unsigned long internal_fa; /* internal file attributes 2 bytes */ -+ unsigned long external_fa; /* external file attributes 4 bytes */ - -- uint32_t disk_num_start; /* disk number start 4 bytes */ -- uint16_t internal_fa; /* internal file attributes 2 bytes */ -- uint32_t external_fa; /* external file attributes 4 bytes */ -+ struct tm tmu_date; - - uint64_t disk_offset; - -@@ -286,29 +287,39 @@ typedef struct unz_file_info64_s { - } unz_file_info64; - - typedef struct unz_file_info_s { -- uint16_t version; /* version made by 2 bytes */ -- uint16_t version_needed; /* version needed to extract 2 bytes */ -- uint16_t flag; /* general purpose bit flag 2 bytes */ -- uint16_t compression_method; /* compression method 2 bytes */ -- uint32_t mz_dos_date; /* last mod file date in Dos fmt 4 bytes */ -- struct tm tmu_date; -- uint32_t crc; /* crc-32 4 bytes */ -- uint32_t compressed_size; /* compressed size 4 bytes */ -- uint32_t uncompressed_size; /* uncompressed size 4 bytes */ -- uint16_t size_filename; /* filename length 2 bytes */ -- uint16_t size_file_extra; /* extra field length 2 bytes */ -- uint16_t size_file_comment; /* file comment length 2 bytes */ -+ unsigned long version; /* version made by 2 bytes */ -+ unsigned long version_needed; /* version needed to extract 2 bytes */ -+ unsigned long flag; /* general purpose bit flag 2 bytes */ -+ unsigned long compression_method; /* compression method 2 bytes */ -+ unsigned long mz_dos_date; /* last mod file date in Dos fmt 4 bytes */ -+ unsigned long crc; /* crc-32 4 bytes */ -+ unsigned long compressed_size; /* compressed size 4 bytes */ -+ unsigned long uncompressed_size; /* uncompressed size 4 bytes */ -+ unsigned long size_filename; /* filename length 2 bytes */ -+ unsigned long size_file_extra; /* extra field length 2 bytes */ -+ unsigned long size_file_comment; /* file comment length 2 bytes */ -+ -+ unsigned long disk_num_start; /* disk number start 2 bytes */ -+ unsigned long internal_fa; /* internal file attributes 2 bytes */ -+ unsigned long external_fa; /* external file attributes 4 bytes */ - -- uint16_t disk_num_start; /* disk number start 2 bytes */ -- uint16_t internal_fa; /* internal file attributes 2 bytes */ -- uint32_t external_fa; /* external file attributes 4 bytes */ -+ struct tm tmu_date; - - uint64_t disk_offset; - } unz_file_info; - - /***************************************************************************/ - --typedef int (*unzFileNameComparer)(unzFile file, const char *filename1, const char *filename2); -+#if !defined(MZ_COMPAT_VERSION) || MZ_COMPAT_VERSION < 110 -+/* Possible values: -+ 0 - Uses OS default, e.g. Windows ignores case. -+ 1 - Is case sensitive. -+ >= 2 - Ignore case. -+*/ -+typedef int unzFileNameCase; -+#else -+typedef int (*unzFileNameComparer)(unzFile file, const char* filename1, const char* filename2); -+#endif - typedef int (*unzIteratorFunction)(unzFile file); - typedef int (*unzIteratorFunction2)(unzFile file, unz_file_info64 *pfile_info, char *filename, - uint16_t filename_size, void *extrafield, uint16_t extrafield_size, char *comment, -@@ -349,7 +360,11 @@ ZEXPORT int unzGetCurrentFileInfo64(unzFile file, unz_file_info64 * pfile_in - - ZEXPORT int unzGoToFirstFile(unzFile file); - ZEXPORT int unzGoToNextFile(unzFile file); --ZEXPORT int unzLocateFile(unzFile file, const char *filename, unzFileNameComparer filename_compare_func); -+#if !defined(MZ_COMPAT_VERSION) || MZ_COMPAT_VERSION < 110 -+ZEXPORT int unzLocateFile(unzFile file, const char *filename, unzFileNameCase filename_case); -+#else -+ZEXPORT int unzLocateFile(unzFile file, const char* filename, unzFileNameComparer filename_compare_func); -+#endif - - ZEXPORT int unzGetLocalExtrafield(unzFile file, void *buf, unsigned int len); - -diff --git a/src/minizip/mz_crypt.c b/src/minizip/mz_crypt.c -index 0f3f28433..4c8d6596c 100644 ---- a/src/minizip/mz_crypt.c -+++ b/src/minizip/mz_crypt.c -@@ -121,9 +121,14 @@ int32_t mz_crypt_pbkdf2(uint8_t *password, int32_t password_length, uint8_t *sa - - memset(key, 0, key_length); - -- mz_crypt_hmac_create(&hmac1); -- mz_crypt_hmac_create(&hmac2); -- mz_crypt_hmac_create(&hmac3); -+ hmac1 = mz_crypt_hmac_create(); -+ hmac2 = mz_crypt_hmac_create(); -+ hmac3 = mz_crypt_hmac_create(); -+ -+ if (!hmac1 || !hmac2 || !hmac3) { -+ err = MZ_MEM_ERROR; -+ goto pbkdf2_cleanup; -+ } - - mz_crypt_hmac_set_algorithm(hmac1, MZ_HASH_SHA1); - mz_crypt_hmac_set_algorithm(hmac2, MZ_HASH_SHA1); -@@ -174,6 +179,7 @@ int32_t mz_crypt_pbkdf2(uint8_t *password, int32_t password_length, uint8_t *sa - key[k++] = ux[j++]; - } - -+pbkdf2_cleanup: - /* hmac3 uses the same provider as hmac2, so it must be deleted - before the context is destroyed. */ - mz_crypt_hmac_delete(&hmac3); -diff --git a/src/minizip/mz_crypt.h b/src/minizip/mz_crypt.h -index 9a341fc61..1837af800 100644 ---- a/src/minizip/mz_crypt.h -+++ b/src/minizip/mz_crypt.h -@@ -30,17 +30,21 @@ void mz_crypt_sha_reset(void *handle); - int32_t mz_crypt_sha_begin(void *handle); - int32_t mz_crypt_sha_update(void *handle, const void *buf, int32_t size); - int32_t mz_crypt_sha_end(void *handle, uint8_t *digest, int32_t digest_size); --void mz_crypt_sha_set_algorithm(void *handle, uint16_t algorithm); --void* mz_crypt_sha_create(void **handle); -+int32_t mz_crypt_sha_set_algorithm(void *handle, uint16_t algorithm); -+void* mz_crypt_sha_create(void); - void mz_crypt_sha_delete(void **handle); - - void mz_crypt_aes_reset(void *handle); --int32_t mz_crypt_aes_encrypt(void *handle, uint8_t *buf, int32_t size); --int32_t mz_crypt_aes_decrypt(void *handle, uint8_t *buf, int32_t size); --int32_t mz_crypt_aes_set_encrypt_key(void *handle, const void *key, int32_t key_length); --int32_t mz_crypt_aes_set_decrypt_key(void *handle, const void *key, int32_t key_length); -+int32_t mz_crypt_aes_encrypt(void *handle, const void *aad, int32_t aad_size, uint8_t *buf, int32_t size); -+int32_t mz_crypt_aes_encrypt_final(void *handle, uint8_t *buf, int32_t size, uint8_t *tag, int32_t tag_size); -+int32_t mz_crypt_aes_decrypt(void *handle, const void *aad, int32_t aad_size, uint8_t *buf, int32_t size); -+int32_t mz_crypt_aes_decrypt_final(void *handle, uint8_t *buf, int32_t size, const uint8_t *tag, int32_t tag_size); -+int32_t mz_crypt_aes_set_encrypt_key(void *handle, const void *key, int32_t key_length, -+ const void *iv, int32_t iv_length); -+int32_t mz_crypt_aes_set_decrypt_key(void *handle, const void *key, int32_t key_length, -+ const void *iv, int32_t iv_length); - void mz_crypt_aes_set_mode(void *handle, int32_t mode); --void* mz_crypt_aes_create(void **handle); -+void* mz_crypt_aes_create(void); - void mz_crypt_aes_delete(void **handle); - - void mz_crypt_hmac_reset(void *handle); -@@ -49,13 +53,9 @@ int32_t mz_crypt_hmac_update(void *handle, const void *buf, int32_t size); - int32_t mz_crypt_hmac_end(void *handle, uint8_t *digest, int32_t digest_size); - int32_t mz_crypt_hmac_copy(void *src_handle, void *target_handle); - void mz_crypt_hmac_set_algorithm(void *handle, uint16_t algorithm); --void* mz_crypt_hmac_create(void **handle); -+void* mz_crypt_hmac_create(void); - void mz_crypt_hmac_delete(void **handle); - --int32_t mz_crypt_sign(uint8_t *message, int32_t message_size, uint8_t *cert_data, int32_t cert_data_size, -- const char *cert_pwd, uint8_t **signature, int32_t *signature_size); --int32_t mz_crypt_sign_verify(uint8_t *message, int32_t message_size, uint8_t *signature, int32_t signature_size); -- - /***************************************************************************/ - - #ifdef __cplusplus -diff --git a/src/minizip/mz_os.c b/src/minizip/mz_os.c -index 6a3706086..57b1722fc 100644 ---- a/src/minizip/mz_os.c -+++ b/src/minizip/mz_os.c -@@ -68,7 +68,7 @@ int32_t mz_path_remove_slash(char *path) { - - int32_t mz_path_has_slash(const char *path) { - int32_t path_len = (int32_t)strlen(path); -- if (path[path_len - 1] != '\\' && path[path_len - 1] != '/') -+ if (path_len > 0 && path[path_len - 1] != '\\' && path[path_len - 1] != '/') - return MZ_EXIST_ERROR; - return MZ_OK; - } -@@ -171,11 +171,11 @@ int32_t mz_path_resolve(const char *path, char *output, int32_t max_output) { - if ((*check == 0) || (*check == '\\' || *check == '/')) { - source += (check - source); - -- /* Search backwards for previous slash */ -+ /* Search backwards for previous slash or the start of the output string */ - if (target != output) { - target -= 1; - do { -- if ((*target == '\\') || (*target == '/')) -+ if ((target == output) ||(*target == '\\') || (*target == '/')) - break; - - target -= 1; -@@ -283,6 +283,9 @@ int32_t mz_dir_make(const char *path) { - char *match = NULL; - char hold = 0; - -+ if (!*path) -+ return MZ_OK; -+ - current_dir = strdup(path); - if (!current_dir) - return MZ_MEM_ERROR; -@@ -320,10 +323,11 @@ int32_t mz_file_get_crc(const char *path, uint32_t *result_crc) { - int32_t err = MZ_OK; - uint8_t buf[16384]; - -- mz_stream_os_create(&stream); -+ stream = mz_stream_os_create(); -+ if (!stream) -+ return MZ_MEM_ERROR; - - err = mz_stream_os_open(stream, path, MZ_OPEN_MODE_READ); -- - if (err == MZ_OK) { - do { - read = mz_stream_os_read(stream, buf, sizeof(buf)); -diff --git a/src/minizip/mz_os.h b/src/minizip/mz_os.h -index 4505bc393..ad6ea4f11 100644 ---- a/src/minizip/mz_os.h -+++ b/src/minizip/mz_os.h -@@ -107,10 +107,10 @@ wchar_t *mz_os_unicode_string_create(const char *string, int32_t encoding); - void mz_os_unicode_string_delete(wchar_t **string); - /* Delete a unicode string that was created */ - --uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding); -+char *mz_os_utf8_string_create(const char *string, int32_t encoding); - /* Create a utf8 string from a string with another encoding */ - --void mz_os_utf8_string_delete(uint8_t **string); -+void mz_os_utf8_string_delete(char **string); - /* Delete a utf8 string that was created */ - - int32_t mz_os_rand(uint8_t *buf, int32_t size); -diff --git a/src/minizip/mz_os_posix.c b/src/minizip/mz_os_posix.c -index b4eb1937e..6736d0997 100644 ---- a/src/minizip/mz_os_posix.c -+++ b/src/minizip/mz_os_posix.c -@@ -40,14 +40,14 @@ - /***************************************************************************/ - - #if defined(HAVE_ICONV) --uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { -+char *mz_os_utf8_string_create(const char *string, int32_t encoding) { - iconv_t cd; - const char *from_encoding = NULL; - size_t result = 0; - size_t string_length = 0; - size_t string_utf8_size = 0; -- uint8_t *string_utf8 = NULL; -- uint8_t *string_utf8_ptr = NULL; -+ char *string_utf8 = NULL; -+ char *string_utf8_ptr = NULL; - - if (!string) - return NULL; -@@ -71,7 +71,7 @@ uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { - - string_length = strlen(string); - string_utf8_size = string_length * 2; -- string_utf8 = (uint8_t *)calloc((int32_t)(string_utf8_size + 1), sizeof(char)); -+ string_utf8 = (char *)calloc((int32_t)(string_utf8_size + 1), sizeof(char)); - string_utf8_ptr = string_utf8; - - if (string_utf8) { -@@ -89,12 +89,12 @@ uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { - return string_utf8; - } - #else --uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { -+char *mz_os_utf8_string_create(const char *string, int32_t encoding) { - return strdup(string); - } - #endif - --void mz_os_utf8_string_delete(uint8_t **string) { -+void mz_os_utf8_string_delete(char **string) { - if (string) { - free(*string); - *string = NULL; -@@ -199,7 +199,6 @@ int64_t mz_os_get_file_size(const char *path) { - int32_t mz_os_get_file_date(const char *path, time_t *modified_date, time_t *accessed_date, time_t *creation_date) { - struct stat path_stat; - char *name = NULL; -- size_t len = 0; - int32_t err = MZ_INTERNAL_ERROR; - - memset(&path_stat, 0, sizeof(path_stat)); -diff --git a/src/minizip/mz_os_win32.c b/src/minizip/mz_os_win32.c -index 85c7b3a24..808749b5d 100644 ---- a/src/minizip/mz_os_win32.c -+++ b/src/minizip/mz_os_win32.c -@@ -21,6 +21,10 @@ - # define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1 - #endif - -+#ifndef _WIN32_WINNT_WIN8 -+# define _WIN32_WINNT_WIN8 0x0602 -+#endif -+ - /***************************************************************************/ - - typedef struct DIR_int_s { -@@ -54,18 +58,18 @@ void mz_os_unicode_string_delete(wchar_t **string) { - } - } - --uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { -+char *mz_os_utf8_string_create(const char *string, int32_t encoding) { - wchar_t *string_wide = NULL; -- uint8_t *string_utf8 = NULL; -+ char *string_utf8 = NULL; - uint32_t string_utf8_size = 0; - - string_wide = mz_os_unicode_string_create(string, encoding); - if (string_wide) { - string_utf8_size = WideCharToMultiByte(CP_UTF8, 0, string_wide, -1, NULL, 0, NULL, NULL); -- string_utf8 = (uint8_t *)calloc(string_utf8_size + 1, sizeof(wchar_t)); -+ string_utf8 = (char *)calloc(string_utf8_size + 1, sizeof(char)); - - if (string_utf8) -- WideCharToMultiByte(CP_UTF8, 0, string_wide, -1, (char *)string_utf8, string_utf8_size, NULL, NULL); -+ WideCharToMultiByte(CP_UTF8, 0, string_wide, -1, string_utf8, string_utf8_size, NULL, NULL); - - mz_os_unicode_string_delete(&string_wide); - } -@@ -73,22 +77,22 @@ uint8_t *mz_os_utf8_string_create(const char *string, int32_t encoding) { - return string_utf8; - } - --uint8_t *mz_os_utf8_string_create_from_unicode(const wchar_t *string, int32_t encoding) { -- uint8_t *string_utf8 = NULL; -+char *mz_os_utf8_string_create_from_unicode(const wchar_t *string, int32_t encoding) { -+ char *string_utf8 = NULL; - uint32_t string_utf8_size = 0; - - MZ_UNUSED(encoding); - - string_utf8_size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL); -- string_utf8 = (uint8_t *)calloc(string_utf8_size + 1, sizeof(wchar_t)); -+ string_utf8 = (char *)calloc(string_utf8_size + 1, sizeof(char)); - - if (string_utf8) -- WideCharToMultiByte(CP_UTF8, 0, string, -1, (char *)string_utf8, string_utf8_size, NULL, NULL); -+ WideCharToMultiByte(CP_UTF8, 0, string, -1, string_utf8, string_utf8_size, NULL, NULL); - - return string_utf8; - } - --void mz_os_utf8_string_delete(uint8_t **string) { -+void mz_os_utf8_string_delete(char **string) { - if (string) { - free(*string); - *string = NULL; -@@ -488,7 +492,7 @@ int32_t mz_os_make_symlink(const char *path, const char *target_path) { - if (!path) - return MZ_PARAM_ERROR; - -- // Use VirtualQuery instead of GetModuleHandleW for UWP -+ /* Use VirtualQuery instead of GetModuleHandleW for UWP */ - memset(&mbi, 0, sizeof(mbi)); - VirtualQuery(VirtualQuery, &mbi, sizeof(mbi)); - kernel32_mod = (HMODULE)mbi.AllocationBase; -@@ -559,7 +563,7 @@ int32_t mz_os_read_symlink(const char *path, char *target_path, int32_t max_targ - int32_t target_path_len = 0; - int32_t target_path_idx = 0; - int32_t err = MZ_OK; -- uint8_t *target_path_utf8 = NULL; -+ char *target_path_utf8 = NULL; - - if (!path) - return MZ_PARAM_ERROR; -@@ -605,10 +609,10 @@ int32_t mz_os_read_symlink(const char *path, char *target_path, int32_t max_targ - target_path_utf8 = mz_os_utf8_string_create_from_unicode(target_path_wide, MZ_ENCODING_UTF8); - - if (target_path_utf8) { -- strncpy(target_path, (const char *)target_path_utf8, max_target_path - 1); -+ strncpy(target_path, target_path_utf8, max_target_path - 1); - target_path[max_target_path - 1] = 0; - /* Ensure directories have slash at the end so we can recreate them later */ -- if (mz_os_is_dir((const char *)target_path_utf8) == MZ_OK) -+ if (mz_os_is_dir(target_path_utf8) == MZ_OK) - mz_path_append_slash(target_path, max_target_path, MZ_PATH_SLASH_PLATFORM); - mz_os_utf8_string_delete(&target_path_utf8); - } else { -diff --git a/src/minizip/mz_strm.c b/src/minizip/mz_strm.c -index 35d4c62fd..edcbafa0c 100644 ---- a/src/minizip/mz_strm.c -+++ b/src/minizip/mz_strm.c -@@ -397,10 +397,10 @@ int32_t mz_stream_set_prop_int64(void *stream, int32_t prop, int64_t value) { - return strm->vtbl->set_prop_int64(stream, prop, value); - } - --void *mz_stream_create(void **stream, mz_stream_vtbl *vtbl) { -- if (!stream || !vtbl || !vtbl->create) -+void *mz_stream_create(mz_stream_vtbl *vtbl) { -+ if (!vtbl || !vtbl->create) - return NULL; -- return vtbl->create(stream); -+ return vtbl->create(); - } - - void mz_stream_delete(void **stream) { -@@ -533,15 +533,10 @@ static mz_stream_vtbl mz_stream_raw_vtbl = { - - /***************************************************************************/ - --void *mz_stream_raw_create(void **stream) { -- mz_stream_raw *raw = NULL; -- -- raw = (mz_stream_raw *)calloc(1, sizeof(mz_stream_raw)); -+void *mz_stream_raw_create(void) { -+ mz_stream_raw *raw = (mz_stream_raw *)calloc(1, sizeof(mz_stream_raw)); - if (raw) - raw->stream.vtbl = &mz_stream_raw_vtbl; -- if (stream) -- *stream = raw; -- - return raw; - } - -diff --git a/src/minizip/mz_strm.h b/src/minizip/mz_strm.h -index 5f88015d0..f65baabfb 100644 ---- a/src/minizip/mz_strm.h -+++ b/src/minizip/mz_strm.h -@@ -39,7 +39,7 @@ typedef int64_t (*mz_stream_tell_cb) (void *stream); - typedef int32_t (*mz_stream_seek_cb) (void *stream, int64_t offset, int32_t origin); - typedef int32_t (*mz_stream_close_cb) (void *stream); - typedef int32_t (*mz_stream_error_cb) (void *stream); --typedef void* (*mz_stream_create_cb) (void **stream); -+typedef void* (*mz_stream_create_cb) (void); - typedef void (*mz_stream_destroy_cb) (void **stream); - - typedef int32_t (*mz_stream_get_prop_int64_cb) (void *stream, int32_t prop, int64_t *value); -@@ -103,7 +103,7 @@ void* mz_stream_get_interface(void *stream); - int32_t mz_stream_get_prop_int64(void *stream, int32_t prop, int64_t *value); - int32_t mz_stream_set_prop_int64(void *stream, int32_t prop, int64_t value); - --void* mz_stream_create(void **stream, mz_stream_vtbl *vtbl); -+void* mz_stream_create(mz_stream_vtbl *vtbl); - void mz_stream_delete(void **stream); - - /***************************************************************************/ -@@ -120,7 +120,7 @@ int32_t mz_stream_raw_error(void *stream); - int32_t mz_stream_raw_get_prop_int64(void *stream, int32_t prop, int64_t *value); - int32_t mz_stream_raw_set_prop_int64(void *stream, int32_t prop, int64_t value); - --void* mz_stream_raw_create(void **stream); -+void* mz_stream_raw_create(void); - void mz_stream_raw_delete(void **stream); - - /***************************************************************************/ -diff --git a/src/minizip/mz_strm_mem.c b/src/minizip/mz_strm_mem.c -index 9a78dc1bd..45881b2ba 100644 ---- a/src/minizip/mz_strm_mem.c -+++ b/src/minizip/mz_strm_mem.c -@@ -237,17 +237,12 @@ void mz_stream_mem_set_grow_size(void *stream, int32_t grow_size) { - mem->grow_size = grow_size; - } - --void *mz_stream_mem_create(void **stream) { -- mz_stream_mem *mem = NULL; -- -- mem = (mz_stream_mem *)calloc(1, sizeof(mz_stream_mem)); -+void *mz_stream_mem_create(void) { -+ mz_stream_mem *mem = (mz_stream_mem *)calloc(1, sizeof(mz_stream_mem)); - if (mem) { - mem->stream.vtbl = &mz_stream_mem_vtbl; - mem->grow_size = 4096; - } -- if (stream) -- *stream = mem; -- - return mem; - } - -diff --git a/src/minizip/mz_strm_mem.h b/src/minizip/mz_strm_mem.h -index 22a12deae..ed6f9574e 100644 ---- a/src/minizip/mz_strm_mem.h -+++ b/src/minizip/mz_strm_mem.h -@@ -34,7 +34,7 @@ void mz_stream_mem_get_buffer_length(void *stream, int32_t *length); - void mz_stream_mem_set_buffer_limit(void *stream, int32_t limit); - void mz_stream_mem_set_grow_size(void *stream, int32_t grow_size); - --void* mz_stream_mem_create(void **stream); -+void* mz_stream_mem_create(void); - void mz_stream_mem_delete(void **stream); - - void* mz_stream_mem_get_interface(void); -diff --git a/src/minizip/mz_strm_os.h b/src/minizip/mz_strm_os.h -index 83d292b95..0ed279f5f 100644 ---- a/src/minizip/mz_strm_os.h -+++ b/src/minizip/mz_strm_os.h -@@ -26,7 +26,7 @@ int32_t mz_stream_os_seek(void *stream, int64_t offset, int32_t origin); - int32_t mz_stream_os_close(void *stream); - int32_t mz_stream_os_error(void *stream); - --void* mz_stream_os_create(void **stream); -+void* mz_stream_os_create(void); - void mz_stream_os_delete(void **stream); - - void* mz_stream_os_get_interface(void); -diff --git a/src/minizip/mz_strm_os_posix.c b/src/minizip/mz_strm_os_posix.c -index 60ff502de..b351ebb70 100644 ---- a/src/minizip/mz_strm_os_posix.c -+++ b/src/minizip/mz_strm_os_posix.c -@@ -176,15 +176,10 @@ int32_t mz_stream_os_error(void *stream) { - return posix->error; - } - --void *mz_stream_os_create(void **stream) { -- mz_stream_posix *posix = NULL; -- -- posix = (mz_stream_posix *)calloc(1, sizeof(mz_stream_posix)); -+void *mz_stream_os_create(void) { -+ mz_stream_posix *posix = (mz_stream_posix *)calloc(1, sizeof(mz_stream_posix)); - if (posix) - posix->stream.vtbl = &mz_stream_os_vtbl; -- if (stream) -- *stream = posix; -- - return posix; - } - -diff --git a/src/minizip/mz_strm_os_win32.c b/src/minizip/mz_strm_os_win32.c -index 80d03ea11..c4198ccf2 100644 ---- a/src/minizip/mz_strm_os_win32.c -+++ b/src/minizip/mz_strm_os_win32.c -@@ -23,11 +23,15 @@ - /***************************************************************************/ - - #ifndef INVALID_HANDLE_VALUE --# define INVALID_HANDLE_VALUE (0xFFFFFFFF) -+# define INVALID_HANDLE_VALUE 0xFFFFFFFF - #endif - - #ifndef INVALID_SET_FILE_POINTER --# define INVALID_SET_FILE_POINTER ((DWORD)-1) -+# define INVALID_SET_FILE_POINTER (DWORD)-1 -+#endif -+ -+#ifndef _WIN32_WINNT_WIN8 -+# define _WIN32_WINNT_WIN8 0x0602 - #endif - - /***************************************************************************/ -@@ -258,15 +262,10 @@ int32_t mz_stream_os_error(void *stream) { - return win32->error; - } - --void *mz_stream_os_create(void **stream) { -- mz_stream_win32 *win32 = NULL; -- -- win32 = (mz_stream_win32 *)calloc(1, sizeof(mz_stream_win32)); -+void *mz_stream_os_create(void) { -+ mz_stream_win32 *win32 = (mz_stream_win32 *)calloc(1, sizeof(mz_stream_win32)); - if (win32) - win32->stream.vtbl = &mz_stream_os_vtbl; -- if (stream) -- *stream = win32; -- - return win32; - } - -diff --git a/src/minizip/mz_strm_zlib.c b/src/minizip/mz_strm_zlib.c -index b7ac4d1a6..cba63fb2f 100644 ---- a/src/minizip/mz_strm_zlib.c -+++ b/src/minizip/mz_strm_zlib.c -@@ -191,6 +191,8 @@ int32_t mz_stream_zlib_read(void *stream, void *buf, int32_t size) { - } - } while (zlib->zstream.avail_out > 0); - -+ MZ_UNUSED(total_in); -+ - if (zlib->error != 0) { - /* Zlib errors are compatible with MZ */ - return zlib->error; -@@ -345,7 +347,10 @@ int32_t mz_stream_zlib_set_prop_int64(void *stream, int32_t prop, int64_t value) - mz_stream_zlib *zlib = (mz_stream_zlib *)stream; - switch (prop) { - case MZ_STREAM_PROP_COMPRESS_LEVEL: -- zlib->level = (int16_t)value; -+ if (value == MZ_COMPRESS_LEVEL_DEFAULT) -+ zlib->level = Z_DEFAULT_COMPRESSION; -+ else -+ zlib->level = (int16_t)value; - break; - case MZ_STREAM_PROP_TOTAL_IN_MAX: - zlib->max_total_in = value; -@@ -359,18 +364,13 @@ int32_t mz_stream_zlib_set_prop_int64(void *stream, int32_t prop, int64_t value) - return MZ_OK; - } - --void *mz_stream_zlib_create(void **stream) { -- mz_stream_zlib *zlib = NULL; -- -- zlib = (mz_stream_zlib *)calloc(1, sizeof(mz_stream_zlib)); -+void *mz_stream_zlib_create(void) { -+ mz_stream_zlib *zlib = zlib = (mz_stream_zlib *)calloc(1, sizeof(mz_stream_zlib)); - if (zlib) { - zlib->stream.vtbl = &mz_stream_zlib_vtbl; - zlib->level = Z_DEFAULT_COMPRESSION; - zlib->window_bits = -MAX_WBITS; - } -- if (stream) -- *stream = zlib; -- - return zlib; - } - -diff --git a/src/minizip/mz_strm_zlib.h b/src/minizip/mz_strm_zlib.h -index 4bdcdf813..bba0991ca 100644 ---- a/src/minizip/mz_strm_zlib.h -+++ b/src/minizip/mz_strm_zlib.h -@@ -29,7 +29,7 @@ int32_t mz_stream_zlib_error(void *stream); - int32_t mz_stream_zlib_get_prop_int64(void *stream, int32_t prop, int64_t *value); - int32_t mz_stream_zlib_set_prop_int64(void *stream, int32_t prop, int64_t value); - --void* mz_stream_zlib_create(void **stream); -+void* mz_stream_zlib_create(void); - void mz_stream_zlib_delete(void **stream); - - void* mz_stream_zlib_get_interface(void); -diff --git a/src/minizip/mz_zip.c b/src/minizip/mz_zip.c -index e80550f0e..019fcbf28 100644 ---- a/src/minizip/mz_zip.c -+++ b/src/minizip/mz_zip.c -@@ -431,7 +431,7 @@ static int32_t mz_zip_entry_read_header(void *stream, uint8_t local, mz_zip_file - /* Get AES encryption strength and actual compression method */ - if (err == MZ_OK) { - err = mz_stream_read_uint8(file_extra_stream, &value8); -- file_info->aes_encryption_mode = value8; -+ file_info->aes_strength = value8; - } - if (err == MZ_OK) { - err = mz_stream_read_uint16(file_extra_stream, &value16); -@@ -643,7 +643,9 @@ static int32_t mz_zip_entry_write_header(void *stream, uint8_t local, mz_zip_fil - - /* Calculate extra field size and check for duplicates */ - if (file_info->extrafield_size > 0) { -- mz_stream_mem_create(&file_extra_stream); -+ file_extra_stream = mz_stream_mem_create(); -+ if (!file_extra_stream) -+ return MZ_MEM_ERROR; - mz_stream_mem_set_buffer(file_extra_stream, (void *)file_info->extrafield, - file_info->extrafield_size); - -@@ -790,7 +792,7 @@ static int32_t mz_zip_entry_write_header(void *stream, uint8_t local, mz_zip_fil - int32_t left = filename_length; - - /* Ensure all slashes are written as forward slashes according to 4.4.17.1 */ -- while ((err == MZ_OK) && (backslash = strrchr(next, '\\'))) { -+ while ((err == MZ_OK) && (backslash = strchr(next, '\\'))) { - int32_t part_length = (int32_t)(backslash - next); - - if (mz_stream_write(stream, next, part_length) != part_length || -@@ -876,7 +878,7 @@ static int32_t mz_zip_entry_write_header(void *stream, uint8_t local, mz_zip_fil - if (err == MZ_OK) - err = mz_stream_write_uint8(stream, 'E'); - if (err == MZ_OK) -- err = mz_stream_write_uint8(stream, file_info->aes_encryption_mode); -+ err = mz_stream_write_uint8(stream, file_info->aes_strength); - if (err == MZ_OK) - err = mz_stream_write_uint16(stream, file_info->compression_method); - } -@@ -1112,7 +1114,7 @@ static int32_t mz_zip_write_cd(void *handle) { - zip->disk_number_with_cd += 1; - mz_stream_set_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, -1); - if ((zip->disk_number_with_cd > 0) && (zip->open_mode & MZ_OPEN_MODE_APPEND)) { -- // Overwrite existing central directory if using split disks -+ /* Overwrite existing central directory if using split disks */ - mz_stream_seek(zip->stream, 0, MZ_SEEK_SET); - } - -@@ -1127,7 +1129,7 @@ static int32_t mz_zip_write_cd(void *handle) { - zip->disk_number_with_cd, zip->number_entry, zip->cd_offset, zip->cd_size); - - if (zip->cd_size == 0 && zip->number_entry > 0) { -- // Zip does not contain central directory, open with recovery option -+ /* Zip does not contain central directory, open with recovery option */ - return MZ_FORMAT_ERROR; - } - -@@ -1264,10 +1266,13 @@ static int32_t mz_zip_recover_cd(void *handle) { - } else - disk_number_with_cd = 1; - -+ local_file_info_stream = mz_stream_mem_create(); -+ if (!local_file_info_stream) -+ return MZ_MEM_ERROR; -+ - if (mz_stream_is_open(cd_mem_stream) != MZ_OK) - err = mz_stream_mem_open(cd_mem_stream, NULL, MZ_OPEN_MODE_CREATE); - -- mz_stream_mem_create(&local_file_info_stream); - mz_stream_mem_open(local_file_info_stream, NULL, MZ_OPEN_MODE_CREATE); - - if (err == MZ_OK) { -@@ -1397,15 +1402,10 @@ static int32_t mz_zip_recover_cd(void *handle) { - return MZ_OK; - } - --void *mz_zip_create(void **handle) { -- mz_zip *zip = NULL; -- -- zip = (mz_zip *)calloc(1, sizeof(mz_zip)); -+void *mz_zip_create(void) { -+ mz_zip *zip = (mz_zip *)calloc(1, sizeof(mz_zip)); - if (zip) - zip->data_descriptor = 1; -- if (handle) -- *handle = zip; -- - return zip; - } - -@@ -1430,8 +1430,9 @@ int32_t mz_zip_open(void *handle, void *stream, int32_t mode) { - mz_zip_print("Zip - Open\n"); - - zip->stream = stream; -- -- mz_stream_mem_create(&zip->cd_mem_stream); -+ zip->cd_mem_stream = mz_stream_mem_create(); -+ if (!zip->cd_mem_stream) -+ return MZ_MEM_ERROR; - - if (mode & MZ_OPEN_MODE_WRITE) { - mz_stream_mem_open(zip->cd_mem_stream, NULL, MZ_OPEN_MODE_CREATE); -@@ -1483,10 +1484,18 @@ int32_t mz_zip_open(void *handle, void *stream, int32_t mode) { - } - - /* Memory streams used to store variable length file info data */ -- mz_stream_mem_create(&zip->file_info_stream); -+ zip->file_info_stream = mz_stream_mem_create(); -+ if (!zip->file_info_stream) -+ return MZ_MEM_ERROR; -+ - mz_stream_mem_open(zip->file_info_stream, NULL, MZ_OPEN_MODE_CREATE); - -- mz_stream_mem_create(&zip->local_file_info_stream); -+ zip->local_file_info_stream = mz_stream_mem_create(); -+ if (!zip->local_file_info_stream) { -+ mz_stream_delete(&zip->file_info_stream); -+ return MZ_MEM_ERROR; -+ } -+ - mz_stream_mem_open(zip->local_file_info_stream, NULL, MZ_OPEN_MODE_CREATE); - - zip->open_mode = mode; -@@ -1724,9 +1733,11 @@ static int32_t mz_zip_entry_open_int(void *handle, uint8_t raw, int16_t compress - if ((err == MZ_OK) && (use_crypt)) { - #ifdef HAVE_WZAES - if (zip->file_info.aes_version) { -- mz_stream_wzaes_create(&zip->crypt_stream); -+ zip->crypt_stream = mz_stream_wzaes_create(); -+ if (!zip->crypt_stream) -+ return MZ_MEM_ERROR; - mz_stream_wzaes_set_password(zip->crypt_stream, password); -- mz_stream_wzaes_set_encryption_mode(zip->crypt_stream, zip->file_info.aes_encryption_mode); -+ mz_stream_wzaes_set_strength(zip->crypt_stream, zip->file_info.aes_strength); - } else - #endif - { -@@ -1734,7 +1745,9 @@ static int32_t mz_zip_entry_open_int(void *handle, uint8_t raw, int16_t compress - uint8_t verify1 = (uint8_t)((zip->file_info.pk_verify >> 8) & 0xff); - uint8_t verify2 = (uint8_t)((zip->file_info.pk_verify) & 0xff); - -- mz_stream_pkcrypt_create(&zip->crypt_stream); -+ zip->crypt_stream = mz_stream_pkcrypt_create(); -+ if (!zip->crypt_stream) -+ return MZ_MEM_ERROR; - mz_stream_pkcrypt_set_password(zip->crypt_stream, password); - mz_stream_pkcrypt_set_verify(zip->crypt_stream, verify1, verify2); - #endif -@@ -1743,7 +1756,9 @@ static int32_t mz_zip_entry_open_int(void *handle, uint8_t raw, int16_t compress - - if (err == MZ_OK) { - if (!zip->crypt_stream) -- mz_stream_raw_create(&zip->crypt_stream); -+ zip->crypt_stream = mz_stream_raw_create(); -+ if (!zip->crypt_stream) -+ return MZ_MEM_ERROR; - - mz_stream_set_base(zip->crypt_stream, zip->stream); - -@@ -1752,39 +1767,44 @@ static int32_t mz_zip_entry_open_int(void *handle, uint8_t raw, int16_t compress - - if (err == MZ_OK) { - if (zip->entry_raw || zip->file_info.compression_method == MZ_COMPRESS_METHOD_STORE) -- mz_stream_raw_create(&zip->compress_stream); -+ zip->compress_stream = mz_stream_raw_create(); - #ifdef HAVE_ZLIB - else if (zip->file_info.compression_method == MZ_COMPRESS_METHOD_DEFLATE) -- mz_stream_zlib_create(&zip->compress_stream); -+ zip->compress_stream = mz_stream_zlib_create(); - #endif - #ifdef HAVE_BZIP2 - else if (zip->file_info.compression_method == MZ_COMPRESS_METHOD_BZIP2) -- mz_stream_bzip_create(&zip->compress_stream); -+ zip->compress_stream = mz_stream_bzip_create(); - #endif - #ifdef HAVE_LIBCOMP - else if (zip->file_info.compression_method == MZ_COMPRESS_METHOD_DEFLATE || - zip->file_info.compression_method == MZ_COMPRESS_METHOD_XZ) { -- mz_stream_libcomp_create(&zip->compress_stream); -- mz_stream_set_prop_int64(zip->compress_stream, MZ_STREAM_PROP_COMPRESS_METHOD, -- zip->file_info.compression_method); -+ zip->compress_stream = mz_stream_libcomp_create(); -+ if (zip->compress_stream) -+ mz_stream_set_prop_int64(zip->compress_stream, MZ_STREAM_PROP_COMPRESS_METHOD, -+ zip->file_info.compression_method); - } - #endif - #ifdef HAVE_LZMA - else if (zip->file_info.compression_method == MZ_COMPRESS_METHOD_LZMA || - zip->file_info.compression_method == MZ_COMPRESS_METHOD_XZ) { -- mz_stream_lzma_create(&zip->compress_stream); -- mz_stream_set_prop_int64(zip->compress_stream, MZ_STREAM_PROP_COMPRESS_METHOD, -- zip->file_info.compression_method); -+ zip->compress_stream = mz_stream_lzma_create(); -+ if (zip->compress_stream) -+ mz_stream_set_prop_int64(zip->compress_stream, MZ_STREAM_PROP_COMPRESS_METHOD, -+ zip->file_info.compression_method); - } - #endif - #ifdef HAVE_ZSTD - else if (zip->file_info.compression_method == MZ_COMPRESS_METHOD_ZSTD) -- mz_stream_zstd_create(&zip->compress_stream); -+ zip->compress_stream = mz_stream_zstd_create(); - #endif - else - err = MZ_PARAM_ERROR; - } - -+ if (err == MZ_OK && !zip->compress_stream) -+ err = MZ_MEM_ERROR; -+ - if (err == MZ_OK) { - if (zip->open_mode & MZ_OPEN_MODE_WRITE) { - mz_stream_set_prop_int64(zip->compress_stream, MZ_STREAM_PROP_COMPRESS_LEVEL, compress_level); -@@ -1981,8 +2001,8 @@ int32_t mz_zip_entry_write_open(void *handle, const mz_zip_file *file_info, int1 - zip->file_info.pk_verify = mz_zip_get_pk_verify(dos_date, zip->file_info.crc, zip->file_info.flag); - #endif - #ifdef HAVE_WZAES -- if (zip->file_info.aes_version && zip->file_info.aes_encryption_mode == 0) -- zip->file_info.aes_encryption_mode = MZ_AES_ENCRYPTION_MODE_256; -+ if (zip->file_info.aes_version && zip->file_info.aes_strength == 0) -+ zip->file_info.aes_strength = MZ_AES_STRENGTH_256; - #endif - } - -@@ -2179,9 +2199,8 @@ int32_t mz_zip_entry_write_close(void *handle, uint32_t crc32, int64_t compresse - - if (err == MZ_OK) { - /* Seek to crc32 and sizes offset in local header */ -- err = mz_stream_set_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, zip->file_info.disk_number); -- if (err == MZ_OK) -- err = mz_stream_seek(zip->stream, zip->file_info.disk_offset + MZ_ZIP_OFFSET_CRC_SIZES, MZ_SEEK_SET); -+ mz_stream_set_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, zip->file_info.disk_number); -+ err = mz_stream_seek(zip->stream, zip->file_info.disk_offset + MZ_ZIP_OFFSET_CRC_SIZES, MZ_SEEK_SET); - } - - if (err == MZ_OK) -@@ -2600,13 +2619,13 @@ int32_t mz_zip_extrafield_contains(const uint8_t *extrafield, int32_t extrafield - if (!extrafield || !extrafield_size) - return MZ_PARAM_ERROR; - -- mz_stream_mem_create(&file_extra_stream); -- mz_stream_mem_set_buffer(file_extra_stream, (void *)extrafield, extrafield_size); -+ file_extra_stream = mz_stream_mem_create(); -+ if (!file_extra_stream) -+ return MZ_MEM_ERROR; - -+ mz_stream_mem_set_buffer(file_extra_stream, (void *)extrafield, extrafield_size); - err = mz_zip_extrafield_find(file_extra_stream, type, extrafield_size, length); -- - mz_stream_mem_delete(&file_extra_stream); -- - return err; - } - -diff --git a/src/minizip/mz_zip.h b/src/minizip/mz_zip.h -index 65be301af..cc01ee5a0 100644 ---- a/src/minizip/mz_zip.h -+++ b/src/minizip/mz_zip.h -@@ -48,7 +48,7 @@ typedef struct mz_zip_file_s { - - uint16_t zip64; /* zip64 extension mode */ - uint16_t aes_version; /* winzip aes extension if not 0 */ -- uint8_t aes_encryption_mode; /* winzip aes encryption mode */ -+ uint8_t aes_strength; /* winzip aes encryption strength */ - uint16_t pk_verify; /* pkware encryption verifier */ - - } mz_zip_file, mz_zip_entry; -@@ -59,7 +59,7 @@ typedef int32_t (*mz_zip_locate_entry_cb)(void *handle, void *userdata, mz_zip_f - - /***************************************************************************/ - --void * mz_zip_create(void **handle); -+void * mz_zip_create(void); - /* Create zip instance for opening */ - - void mz_zip_delete(void **handle); diff --git a/42.patch b/42.patch deleted file mode 100644 index 4f2d46a..0000000 --- a/42.patch +++ /dev/null @@ -1,1174 +0,0 @@ -From cbfd360cd6404b32b0913fd451c31c80f71ef8ea Mon Sep 17 00:00:00 2001 -From: Julian Sikorski -Date: Wed, 7 Feb 2024 00:45:38 +0100 -Subject: [PATCH 1/5] imp: convert machinelist.{cpp,h} to QXmlStreamReader - ---- - src/machinelist.cpp | 642 ++++++++++++++++++++++---------------------- - src/machinelist.h | 6 +- - 2 files changed, 322 insertions(+), 326 deletions(-) - -diff --git a/src/machinelist.cpp b/src/machinelist.cpp -index 4ccdc3c4b..559e6ac65 100644 ---- a/src/machinelist.cpp -+++ b/src/machinelist.cpp -@@ -892,14 +892,11 @@ void MachineList::verify(bool currentOnly) - verifyProc->start(command, args, QIODevice::ReadOnly | QIODevice::Text); - } - --QString MachineList::value(QString element, QString attribute, bool translate) -+QString MachineList::value(QXmlStreamReader *element, QString attribute, bool translate) - { -- QString attributePattern(" " + attribute + "=\""); -- if ( element.contains(attributePattern) ) { -- QString valueString(element.remove(0, element.indexOf(attributePattern) + attributePattern.length())); -- valueString = valueString.remove(valueString.indexOf("\""), valueString.lastIndexOf(">")).replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'"); -- if ( valueString == ">" ) -- return QString(); -+ if ( element->attributes().hasAttribute(attribute) ) { -+ QString valueString(element->attributes().value(attribute).toString()); -+ valueString = valueString.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'"); - if ( translate ) - return tr(valueString.toUtf8().constData()); - else -@@ -908,7 +905,7 @@ QString MachineList::value(QString element, QString attribute, bool translate) - return QString(); - } - --void MachineList::insertAttributeItems(QTreeWidgetItem *parent, QString element, QStringList attributes, QStringList descriptions, bool translate) -+void MachineList::insertAttributeItems(QTreeWidgetItem *parent, QXmlStreamReader *element, QStringList attributes, QStringList descriptions, bool translate) - { - QList itemList; - for (int i = 0; i < attributes.count(); i++) { -@@ -923,7 +920,7 @@ void MachineList::insertAttributeItems(QTreeWidgetItem *parent, QString element, - parent->addChildren(itemList); - } - --void MachineList::insertAttributeItems(QList *itemList, QString element, QStringList attributes, QStringList descriptions, bool translate) -+void MachineList::insertAttributeItems(QList *itemList, QXmlStreamReader *element, QStringList attributes, QStringList descriptions, bool translate) - { - for (int i = 0; i < attributes.count(); i++) { - QString valueString(value(element, attributes.at(i), translate)); -@@ -939,12 +936,7 @@ void MachineList::insertAttributeItems(QList *itemList, QStri - void MachineList::parseMachineDetail(QTreeWidgetItem *item) - { - QString machineName(item->text(QMC2_MACHINELIST_COLUMN_NAME)); -- QStringList xmlLines(xmlDb()->xml(machineName).split("\n", QString::SkipEmptyParts)); -- if ( xmlLines.count() < 2 ) { -- qmc2MainWindow->log(QMC2_LOG_FRONTEND, tr("WARNING: couldn't find machine information for '%1'").arg(machineName)); -- return; -- } -- int gamePos = 1; -+ QXmlStreamReader xmlMachineEntry(xmlDb()->xml(machineName)); - item->child(0)->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Updating")); - qmc2MainWindow->treeWidgetMachineList->viewport()->repaint(); - qApp->processEvents(); -@@ -955,259 +947,264 @@ void MachineList::parseMachineDetail(QTreeWidgetItem *item) - - attributes << "name" << "sourcefile" << "isbios" << "isdevice" << "runnable" << "cloneof" << "romof" << "sampleof"; - descriptions << tr("Name") << tr("Source file") << tr("Is BIOS?") << tr("Is device?") << tr("Runnable") << tr("Clone of") << tr("ROM of") << tr("Sample of"); -- element = xmlLines.at(gamePos - 1).simplified(); -- insertAttributeItems(&itemList, element, attributes, descriptions, true); -- QString endMark(""); -- -- while ( !xmlLines.at(gamePos).contains(endMark) ) { -- childItem = 0; -- element = xmlLines.at(gamePos).simplified(); -- if ( element.contains("") ) { -- content = element.remove("").remove(""); -- childItem = new QTreeWidgetItem(); -- childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Year")); -- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, content); -- } -- if ( element.contains("") ) { -- content = element.remove("").remove(""); -- content.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'"); -- childItem = new QTreeWidgetItem(); -- childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Manufacturer")); -- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, content); -- } -- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("ROM")); -- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name")); -- attributes.clear(); -- attributes << "bios" << "size" << "crc" << "sha1" << "merge" << "region" << "offset" << "status" << "optional"; -- descriptions.clear(); -- descriptions << tr("BIOS") << tr("Size") << tr("CRC") << tr("SHA-1") << tr("Merge") << tr("Region") << tr("Offset") << tr("Status") << tr("Optional"); -- insertAttributeItems(childItem, element, attributes, descriptions, true); -- } -- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Device reference")); -- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name")); -- } -- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Chip")); -- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name")); -- attributes.clear(); -- attributes << "tag" << "type" << "clock"; -- descriptions.clear(); -- descriptions << tr("Tag") << tr("Type") << tr("Clock"); -- insertAttributeItems(childItem, element, attributes, descriptions, true); -- } -- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Display")); -- attributes.clear(); -- attributes << "type" << "rotate" << "flipx" << "width" << "height" << "refresh" << "pixclock" << "htotal" << "hbend" << "hbstart" << "vtotal" << "vbend" << "vbstart"; -- descriptions.clear(); -- descriptions << tr("Type") << tr("Rotate") << tr("Flip-X") << tr("Width") << tr("Height") << tr("Refresh") << tr("Pixel clock") << tr("H-Total") << tr("H-Bend") << tr("HB-Start") << tr("V-Total") << tr("V-Bend") << tr("VB-Start"); -- insertAttributeItems(childItem, element, attributes, descriptions, true); -- } -- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Sound")); -- attributes.clear(); -- attributes << "channels"; -- descriptions.clear(); -- descriptions << tr("Channels"); -- insertAttributeItems(childItem, element, attributes, descriptions, true); -- } -- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Input")); -- attributes.clear(); -- attributes << "service" << "tilt" << "players" << "buttons" << "coins"; -- descriptions.clear(); -- descriptions << tr("Service") << tr("Tilt") << tr("Players") << tr("Buttons") << tr("Coins"); -- insertAttributeItems(childItem, element, attributes, descriptions, true); -- gamePos++; -- while ( xmlLines.at(gamePos).contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Control")); -- nextChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(subElement, "type", true)); -- attributes.clear(); -- attributes << "minimum" << "maximum" << "sensitivity" << "keydelta" << "reverse" << "player" << "buttons" << "ways"; -- descriptions.clear(); -- descriptions << tr("Minimum") << tr("Maximum") << tr("Sensitivity") << tr("Key Delta") << tr("Reverse") << tr("Player") << tr("Buttons") << tr("Ways"); -- insertAttributeItems(nextChildItem, subElement, attributes, descriptions, true); -- gamePos++; -- } -- } -- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("DIP switch")); -- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name", true)); -- gamePos++; -- while ( xmlLines.at(gamePos).contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("DIP value")); -- secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(subElement, "name", true)); -- attributes.clear(); -- attributes << "default"; -- descriptions.clear(); -- descriptions << tr("Default"); -- insertAttributeItems(secondChildItem, subElement, attributes, descriptions, true); -- gamePos++; -- } -- } -- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Configuration")); -- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name", true)); -- attributes.clear(); -- attributes << "tag" << "mask"; -- descriptions.clear(); -- descriptions << tr("Tag") << tr("Mask"); -- insertAttributeItems(childItem, element, attributes, descriptions, true); -- gamePos++; -- while ( xmlLines.at(gamePos).contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Setting")); -- secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(subElement, "name", true)); -- attributes.clear(); -- attributes << "value" << "default"; -- descriptions.clear(); -- descriptions << tr("Value") << tr("Default"); -- insertAttributeItems(secondChildItem, subElement, attributes, descriptions, true); -- gamePos++; -- } -- } -- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Driver")); -- attributes.clear(); -- attributes << "status" << "emulation" << "color" << "sound" << "graphic" << "cocktail" << "protection" << "savestate" << "palettesize"; -- descriptions.clear(); -- descriptions << tr("Status") << tr("Emulation") << tr("Color") << tr("Sound") << tr("Graphic") << tr("Cocktail") << tr("Protection") << tr("Save state") << tr("Palette size"); -- insertAttributeItems(childItem, element, attributes, descriptions, true); -- } -- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("BIOS set")); -- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name")); -- attributes.clear(); -- attributes << "description" << "default"; -- descriptions.clear(); -- descriptions << tr("Description") << tr("Default"); -- insertAttributeItems(childItem, element, attributes, descriptions, true); -- } -- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Sample")); -- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name")); -- } -- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Disk")); -- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name")); -- attributes.clear(); -- attributes << "md5" << "sha1" << "merge" << "region" << "index" << "status" << "optional"; -- descriptions.clear(); -- descriptions << tr("MD5") << tr("SHA-1") << tr("Merge") << tr("Region") << tr("Index") << tr("Status") << tr("Optional"); -- insertAttributeItems(childItem, element, attributes, descriptions, true); -- } -- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Adjuster")); -- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name")); -- attributes.clear(); -- attributes << "default"; -- descriptions.clear(); -- descriptions << tr("Default"); -- insertAttributeItems(childItem, element, attributes, descriptions, true); -- } -- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Software list")); -- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name")); -- attributes.clear(); -- attributes << "status"; -- descriptions.clear(); -- descriptions << tr("Status"); -- insertAttributeItems(childItem, element, attributes, descriptions, true); -- } -- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Category")); -- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "name", true)); -- gamePos++; -- while ( xmlLines.at(gamePos).contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Item")); -- secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(subElement, "name", true)); -- attributes.clear(); -- attributes << "default"; -- descriptions.clear(); -- descriptions << tr("Default"); -- insertAttributeItems(secondChildItem, subElement, attributes, descriptions, true); -- gamePos++; -- } -- } -- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Device")); -- childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(element, "type", true)); -- attributes.clear(); -- attributes << "tag" << "mandatory" << "interface"; -- descriptions.clear(); -- descriptions << tr("Tag") << tr("Mandatory") << tr("Interface"); -- insertAttributeItems(childItem, element, attributes, descriptions, false); -- gamePos++; -- while ( xmlLines.at(gamePos).contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Instance")); -- secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(subElement, "name", false)); -- attributes.clear(); -- attributes << "briefname"; -- descriptions.clear(); -- descriptions << tr("Brief name"); -- insertAttributeItems(secondChildItem, element, attributes, descriptions, false); -- gamePos++; -- } -- while ( xmlLines.at(gamePos).contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Extension")); -- secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(subElement, "name", false)); -- gamePos++; -- } -- } -- if ( element.contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("RAM options")); -- while ( xmlLines.at(gamePos).contains("setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Option")); -- int fromIndex = subElement.indexOf('>') + 1; -- int toIndex = subElement.indexOf('<', fromIndex); -- QString ramOptionValue(subElement.mid(fromIndex, toIndex - fromIndex)); -- secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, ramOptionValue); -- attributes.clear(); -- attributes << "default"; -- descriptions.clear(); -- descriptions << tr("Default"); -- insertAttributeItems(secondChildItem, subElement, attributes, descriptions, false); -- gamePos++; -+ -+ if ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "machine" ) { -+ insertAttributeItems(&itemList, &xmlMachineEntry, attributes, descriptions, true); -+ while ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "year" ) { -+ content = xmlMachineEntry.readElementText(); -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Year")); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, content); -+ } else if ( xmlMachineEntry.name() =="manufacturer" ) { -+ content = xmlMachineEntry.readElementText(); -+ content.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'"); -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Manufacturer")); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, content); -+ } else if ( xmlMachineEntry.name() == "rom" ) { -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("ROM")); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "name")); -+ attributes.clear(); -+ attributes << "bios" << "size" << "crc" << "sha1" << "merge" << "region" << "offset" << "status" << "optional"; -+ descriptions.clear(); -+ descriptions << tr("BIOS") << tr("Size") << tr("CRC") << tr("SHA-1") << tr("Merge") << tr("Region") << tr("Offset") << tr("Status") << tr("Optional"); -+ insertAttributeItems(childItem, &xmlMachineEntry, attributes, descriptions, true); -+ xmlMachineEntry.skipCurrentElement(); -+ } else if ( xmlMachineEntry.name() == "device_ref" ) { -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Device reference")); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "name")); -+ xmlMachineEntry.skipCurrentElement(); -+ } else if ( xmlMachineEntry.name() == "chip") { -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Chip")); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "name")); -+ attributes.clear(); -+ attributes << "tag" << "type" << "clock"; -+ descriptions.clear(); -+ descriptions << tr("Tag") << tr("Type") << tr("Clock"); -+ insertAttributeItems(childItem, &xmlMachineEntry, attributes, descriptions, true); -+ xmlMachineEntry.skipCurrentElement(); -+ } else if ( xmlMachineEntry.name() == "display" ) { -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Display")); -+ attributes.clear(); -+ attributes << "type" << "rotate" << "flipx" << "width" << "height" << "refresh" << "pixclock" << "htotal" << "hbend" << "hbstart" << "vtotal" << "vbend" << "vbstart"; -+ descriptions.clear(); -+ descriptions << tr("Type") << tr("Rotate") << tr("Flip-X") << tr("Width") << tr("Height") << tr("Refresh") << tr("Pixel clock") << tr("H-Total") << tr("H-Bend") << tr("HB-Start") << tr("V-Total") << tr("V-Bend") << tr("VB-Start"); -+ insertAttributeItems(childItem, &xmlMachineEntry, attributes, descriptions, true); -+ xmlMachineEntry.skipCurrentElement(); -+ } else if ( xmlMachineEntry.name() == "sound" ) { -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Sound")); -+ attributes.clear(); -+ attributes << "channels"; -+ descriptions.clear(); -+ descriptions << tr("Channels"); -+ insertAttributeItems(childItem, &xmlMachineEntry, attributes, descriptions, true); -+ xmlMachineEntry.skipCurrentElement(); -+ } else if ( xmlMachineEntry.name() == "input" ) { -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Input")); -+ attributes.clear(); -+ attributes << "service" << "tilt" << "players" << "buttons" << "coins"; -+ descriptions.clear(); -+ descriptions << tr("Service") << tr("Tilt") << tr("Players") << tr("Buttons") << tr("Coins"); -+ insertAttributeItems(childItem, &xmlMachineEntry, attributes, descriptions, true); -+ while ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "control" ) { -+ QTreeWidgetItem *nextChildItem = new QTreeWidgetItem(childItem); -+ nextChildItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Control")); -+ nextChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "type", true)); -+ attributes.clear(); -+ attributes << "minimum" << "maximum" << "sensitivity" << "keydelta" << "reverse" << "player" << "buttons" << "ways"; -+ descriptions.clear(); -+ descriptions << tr("Minimum") << tr("Maximum") << tr("Sensitivity") << tr("Key Delta") << tr("Reverse") << tr("Player") << tr("Buttons") << tr("Ways"); -+ insertAttributeItems(nextChildItem, &xmlMachineEntry, attributes, descriptions, true); -+ xmlMachineEntry.skipCurrentElement(); -+ } else -+ xmlMachineEntry.skipCurrentElement(); -+ } -+ } else if ( xmlMachineEntry.name() == "dipswitch") { -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("DIP switch")); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "name", true)); -+ while ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "dipvalue") { -+ QTreeWidgetItem *secondChildItem = new QTreeWidgetItem(childItem); -+ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("DIP value")); -+ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "name", true)); -+ attributes.clear(); -+ attributes << "default"; -+ descriptions.clear(); -+ descriptions << tr("Default"); -+ insertAttributeItems(secondChildItem, &xmlMachineEntry, attributes, descriptions, true); -+ xmlMachineEntry.skipCurrentElement(); -+ } else -+ xmlMachineEntry.skipCurrentElement(); -+ } -+ } else if ( xmlMachineEntry.name() == "configuration" ) { -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Configuration")); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "name", true)); -+ attributes.clear(); -+ attributes << "tag" << "mask"; -+ descriptions.clear(); -+ descriptions << tr("Tag") << tr("Mask"); -+ insertAttributeItems(childItem, &xmlMachineEntry, attributes, descriptions, true); -+ while ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "confsetting" ) { -+ QTreeWidgetItem *secondChildItem = new QTreeWidgetItem(childItem); -+ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Setting")); -+ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "name", true)); -+ attributes.clear(); -+ attributes << "value" << "default"; -+ descriptions.clear(); -+ descriptions << tr("Value") << tr("Default"); -+ insertAttributeItems(secondChildItem, &xmlMachineEntry, attributes, descriptions, true); -+ xmlMachineEntry.skipCurrentElement(); -+ } else -+ xmlMachineEntry.skipCurrentElement(); -+ } -+ } else if ( xmlMachineEntry.name() == "driver" ) { -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Driver")); -+ attributes.clear(); -+ attributes << "status" << "emulation" << "color" << "sound" << "graphic" << "cocktail" << "protection" << "savestate" << "palettesize"; -+ descriptions.clear(); -+ descriptions << tr("Status") << tr("Emulation") << tr("Color") << tr("Sound") << tr("Graphic") << tr("Cocktail") << tr("Protection") << tr("Save state") << tr("Palette size"); -+ insertAttributeItems(childItem, &xmlMachineEntry, attributes, descriptions, true); -+ xmlMachineEntry.skipCurrentElement(); -+ } else if ( xmlMachineEntry.name() == "biosset" ) { -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("BIOS set")); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "name")); -+ attributes.clear(); -+ attributes << "description" << "default"; -+ descriptions.clear(); -+ descriptions << tr("Description") << tr("Default"); -+ insertAttributeItems(childItem, &xmlMachineEntry, attributes, descriptions, true); -+ xmlMachineEntry.skipCurrentElement(); -+ } else if ( xmlMachineEntry.name() == "sample" ) { -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Sample")); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "name")); -+ xmlMachineEntry.skipCurrentElement(); -+ } else if ( xmlMachineEntry.name() == "disk" ) { -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Disk")); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "name")); -+ attributes.clear(); -+ attributes << "md5" << "sha1" << "merge" << "region" << "index" << "status" << "optional"; -+ descriptions.clear(); -+ descriptions << tr("MD5") << tr("SHA-1") << tr("Merge") << tr("Region") << tr("Index") << tr("Status") << tr("Optional"); -+ insertAttributeItems(childItem, &xmlMachineEntry, attributes, descriptions, true); -+ xmlMachineEntry.skipCurrentElement(); -+ } else if ( xmlMachineEntry.name() == "adjuster" ) { -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Adjuster")); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "name")); -+ attributes.clear(); -+ attributes << "default"; -+ descriptions.clear(); -+ descriptions << tr("Default"); -+ insertAttributeItems(childItem, &xmlMachineEntry, attributes, descriptions, true); -+ xmlMachineEntry.skipCurrentElement(); -+ } else if ( xmlMachineEntry.name() == "softwarelist" ) { -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Software list")); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "name")); -+ attributes.clear(); -+ attributes << "status"; -+ descriptions.clear(); -+ descriptions << tr("Status"); -+ insertAttributeItems(childItem, &xmlMachineEntry, attributes, descriptions, true); -+ xmlMachineEntry.skipCurrentElement(); -+ } else if ( xmlMachineEntry.name() == "category" ) { -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Category")); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "name", true)); -+ while ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "item" ) { -+ QTreeWidgetItem *secondChildItem = new QTreeWidgetItem(childItem); -+ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Item")); -+ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "name", true)); -+ attributes.clear(); -+ attributes << "default"; -+ descriptions.clear(); -+ descriptions << tr("Default"); -+ insertAttributeItems(secondChildItem, &xmlMachineEntry, attributes, descriptions, true); -+ xmlMachineEntry.skipCurrentElement(); -+ } else -+ xmlMachineEntry.skipCurrentElement(); -+ } -+ } else if ( xmlMachineEntry.name() == "device" ) { -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Device")); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "type", true)); -+ attributes.clear(); -+ attributes << "tag" << "mandatory" << "interface"; -+ descriptions.clear(); -+ descriptions << tr("Tag") << tr("Mandatory") << tr("Interface"); -+ insertAttributeItems(childItem, &xmlMachineEntry, attributes, descriptions, false); -+ while ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "instance" ) { -+ QTreeWidgetItem *secondChildItem = new QTreeWidgetItem(childItem); -+ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Instance")); -+ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "name", false)); -+ attributes.clear(); -+ attributes << "briefname"; -+ descriptions.clear(); -+ descriptions << tr("Brief name"); -+ insertAttributeItems(secondChildItem, &xmlMachineEntry, attributes, descriptions, false); -+ xmlMachineEntry.skipCurrentElement(); -+ } else if ( xmlMachineEntry.name() == "extension" ) { -+ QTreeWidgetItem *secondChildItem = new QTreeWidgetItem(childItem); -+ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Extension")); -+ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, value(&xmlMachineEntry, "name", false)); -+ xmlMachineEntry.skipCurrentElement(); -+ } else -+ xmlMachineEntry.skipCurrentElement(); -+ } -+ } else if ( xmlMachineEntry.name() == "ramoption") { -+ childItem = new QTreeWidgetItem(); -+ childItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("RAM options")); -+ QTreeWidgetItem *secondChildItem = new QTreeWidgetItem(childItem); -+ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Option")); -+ attributes.clear(); -+ attributes << "default"; -+ descriptions.clear(); -+ descriptions << tr("Default"); -+ insertAttributeItems(secondChildItem, &xmlMachineEntry, attributes, descriptions, false); -+ QString ramOptionValue = xmlMachineEntry.readElementText(); -+ secondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, ramOptionValue); -+ while ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "ramoption" ) { -+ QTreeWidgetItem *anotherSecondChildItem = new QTreeWidgetItem(childItem); -+ anotherSecondChildItem->setText(QMC2_MACHINELIST_COLUMN_MACHINE, tr("Option")); -+ attributes.clear(); -+ attributes << "default"; -+ descriptions.clear(); -+ descriptions << tr("Default"); -+ insertAttributeItems(anotherSecondChildItem, &xmlMachineEntry, attributes, descriptions, false); -+ QString ramOptionValue = xmlMachineEntry.readElementText(); -+ anotherSecondChildItem->setText(QMC2_MACHINELIST_COLUMN_ICON, ramOptionValue); -+ } -+ } -+ } else -+ xmlMachineEntry.skipCurrentElement(); -+ if ( childItem ) -+ itemList.append(childItem); - } -- if ( xmlLines.at(gamePos).contains(endMark) ) -- gamePos--; -+ } else { -+ qmc2MainWindow->log(QMC2_LOG_FRONTEND, tr("WARNING: couldn't find machine information for '%1'").arg(machineName)); -+ return; - } -- gamePos++; -- if ( childItem ) -- itemList.append(childItem); - } -+ - qmc2MainWindow->treeWidgetMachineList->setUpdatesEnabled(false); - delete item->takeChild(0); - item->addChildren(itemList); -@@ -1548,26 +1545,21 @@ void MachineList::parse() - machineListDb()->beginTransaction(); - int pendingDbUpdates = 0; - for (qint64 rowCounter = 1; rowCounter <= xmlRowCount && !qmc2LoadingInterrupted; rowCounter++) { -- QStringList xmlLines(xmlDb()->xml(rowCounter).split(lineSplitChar, QString::SkipEmptyParts)); -- for (int lineCounter = 0; lineCounter < xmlLines.count() && !qmc2LoadingInterrupted; lineCounter++) { -- while ( lineCounter < xmlLines.count() && !xmlLines.at(lineCounter).contains("") ) -- lineCounter++; -- if ( !qmc2LoadingInterrupted && lineCounter < xmlLines.count() ) { -- QString machineElement(xmlLines.at(lineCounter - 1).simplified()); -- if ( !machineElement.contains(" name=\"") ) -- continue; -- bool isBIOS = value(machineElement, "isbios").compare("yes") == 0; -- bool isDev = value(machineElement, "isdevice").compare("yes") == 0; -- QString machineName(value(machineElement, "name")); -+ QXmlStreamReader xmlMachineEntry(xmlDb()->xml(rowCounter)); -+ if ( xmlMachineEntry.readNextStartElement() && !qmc2LoadingInterrupted ) { -+ if ( xmlMachineEntry.name() == "machine" ) { -+ bool isBIOS = value(&xmlMachineEntry, "isbios").compare("yes") == 0; -+ bool isDev = value(&xmlMachineEntry, "isdevice").compare("yes") == 0; -+ QString machineName(value(&xmlMachineEntry, "name")); - if ( machineName.isEmpty() ) { -- qmc2MainWindow->log(QMC2_LOG_FRONTEND, tr("WARNING: name attribute empty on XML line %1 (set will be ignored!) -- please inform MAME developers and include the offending output from -listxml").arg(lineCounter + 2)); -+ qmc2MainWindow->log(QMC2_LOG_FRONTEND, tr("WARNING: name attribute empty on XML line %1 (set will be ignored!) -- please inform MAME developers and include the offending output from -listxml").arg(xmlMachineEntry.lineNumber())); - qApp->processEvents(); - continue; - } -- QString machineSource(value(machineElement, "sourcefile")); -- QString machineCloneOf(value(machineElement, "cloneof")); -- QString descriptionElement(xmlLines.at(lineCounter).simplified()); -- QString machineDescription(descriptionElement.remove("").remove("").replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'")); -+ QString machineSource(value(&xmlMachineEntry, "sourcefile")); -+ QString machineCloneOf(value(&xmlMachineEntry, "cloneof")); -+ QString descriptionElement; -+ QString machineDescription; - MachineListItem *machineItem = new MachineListItem(); - qmc2MachineListItemHash.insert(machineName, machineItem); - machineItem->setFlags(MachineListItem::defaultItemFlags); -@@ -1576,37 +1568,40 @@ void MachineList::parse() - hiddenItemHash.insert(machineItem, true); - // find year & manufacturer and determine ROM/CHD requirements - bool endMachine = false; -- int i = lineCounter; -+ - QString machineYear(trQuestionMark), machineManufacturer(trQuestionMark), machinePlayers(trQuestionMark), machineDrvStat(trQuestionMark); - bool yearFound = false, manufacturerFound = false, hasROMs = false, hasCHDs = false, playersFound = false, statusFound = false; -- QString endMark(""); -- while ( !endMachine ) { -- QString xmlLine(xmlLines.at(i)); -- if ( xmlLine.contains("") ) { -- machineYear = xmlLine.simplified().remove("").remove(""); -+ while ( xmlMachineEntry.readNextStartElement() && !endMachine ) { -+ if ( xmlMachineEntry.name() == "description" ) { -+ descriptionElement = xmlMachineEntry.readElementText(); -+ machineDescription = descriptionElement.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'"); -+ } else if ( xmlMachineEntry.name() == "year" ) { -+ machineYear = xmlMachineEntry.readElementText(); - yearFound = true; -- } else if ( xmlLine.contains("") ) { -- machineManufacturer = xmlLine.simplified().remove("").remove("").replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'"); -+ } else if ( xmlMachineEntry.name() == "manufacturer" ) { -+ machineManufacturer = xmlMachineEntry.readElementText().replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'"); - manufacturerFound = true; -- } else if ( xmlLine.contains("= 0 ) { -- machinePlayers = xmlLine.mid(playersPos, xmlLine.indexOf("\"", playersPos) - playersPos); -+ xmlMachineEntry.skipCurrentElement(); -+ } else if ( xmlMachineEntry.name() == "input" ) { -+ if ( xmlMachineEntry.attributes().hasAttribute("players") ) { -+ machinePlayers = xmlMachineEntry.attributes().value("players").toString(); - playersFound = true; - } -- } else if ( xmlLine.contains("= 0 ) { -- machineDrvStat = xmlLine.mid(statusPos, xmlLine.indexOf("\"", statusPos) - statusPos); -+ xmlMachineEntry.skipCurrentElement(); -+ } else if ( xmlMachineEntry.name() == "driver" ) { -+ if ( xmlMachineEntry.attributes().hasAttribute("status") ) { -+ machineDrvStat = xmlMachineEntry.attributes().value("status").toString(); - statusFound = true; - } -- } -- endMachine = xmlLine.contains(endMark) || (yearFound && manufacturerFound && hasROMs && hasCHDs && playersFound && statusFound); -- i++; -+ xmlMachineEntry.skipCurrentElement(); -+ } else -+ xmlMachineEntry.skipCurrentElement(); -+ endMachine = yearFound && manufacturerFound && hasROMs && hasCHDs && playersFound && statusFound; - } - if ( machineCloneOf.isEmpty() ) { - if ( !hierarchyHash.contains(machineName) ) -@@ -2544,28 +2539,29 @@ void MachineList::verifyFinished(int exitCode, QProcess::ExitStatus exitStatus) - QTreeWidgetItem *versionItem = qmc2VersionItemHash.value(machineName); - // there are quite a number of sets in MAME that don't require any ROMs... many/most device-sets in particular - bool romRequired = true; -- int xmlCounter = 0; -- QStringList xmlLines(xmlDb()->xml(machineName).split("\n", QString::SkipEmptyParts)); -- if ( xmlLines.count() > 0 ) { -- int romCounter = 0; -- int chdCounter = 0; -- bool endFound = false; -- QString endMark = ""; -- while ( !endFound && xmlCounter < xmlLines.count() ) { -- if ( xmlLines.at(xmlCounter).contains("xml(machineName)); -+ if ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "machine" ) { -+ int romCounter = 0; -+ int chdCounter = 0; -+ bool endFound = false; -+ while ( xmlMachineEntry.readNextStartElement() && !endFound ) { -+ if ( xmlMachineEntry.name() == "rom" ) { -+ romCounter++; -+ endFound = true; -+ xmlMachineEntry.skipCurrentElement(); -+ } else if ( xmlMachineEntry.name() == "disk" ) { -+ chdCounter++; -+ endFound = true; -+ xmlMachineEntry.skipCurrentElement(); -+ } else -+ xmlMachineEntry.skipCurrentElement(); -+ } -+ if ( romCounter == 0 && chdCounter > 0 ) -+ romRequired = true; -+ else -+ romRequired = (romCounter > 0); - } -- if ( romCounter == 0 && chdCounter > 0 ) -- romRequired = true; -- else -- romRequired = (romCounter > 0); - } - if ( romItem && hierarchyItem ) { - if ( romStateCache.isOpen() ) { -diff --git a/src/machinelist.h b/src/machinelist.h -index 8a4eee1e0..679b90546 100644 ---- a/src/machinelist.h -+++ b/src/machinelist.h -@@ -132,11 +132,11 @@ class MachineList : public QObject - void verifyReadyReadStandardOutput(); - - // internal methods -- QString value(QString, QString, bool translate = false); -+ QString value(QXmlStreamReader *, QString, bool translate = false); - void parse(); - void parseMachineDetail(QTreeWidgetItem *); -- void insertAttributeItems(QTreeWidgetItem *, QString, QStringList, QStringList, bool translate = false); -- void insertAttributeItems(QList *itemList, QString element, QStringList attributes, QStringList descriptions, bool translate = false); -+ void insertAttributeItems(QTreeWidgetItem *, QXmlStreamReader *, QStringList, QStringList, bool translate = false); -+ void insertAttributeItems(QList *itemList, QXmlStreamReader *element, QStringList attributes, QStringList descriptions, bool translate = false); - void enableWidgets(bool enable = true); - void disableWidgets() { enableWidgets(false); } - void filter(bool initial = false); - -From 82309af74c9e07556f1249d019c29675be5145d6 Mon Sep 17 00:00:00 2001 -From: Julian Sikorski -Date: Fri, 9 Feb 2024 17:03:02 +0100 -Subject: [PATCH 2/5] imp: convert softwarelist.cpp to QXmlStreamReader - ---- - src/softwarelist.cpp | 60 +++++++++++++++++++++----------------------- - 1 file changed, 29 insertions(+), 31 deletions(-) - -diff --git a/src/softwarelist.cpp b/src/softwarelist.cpp -index 99f806da4..13c1f0f55 100644 ---- a/src/softwarelist.cpp -+++ b/src/softwarelist.cpp -@@ -1012,6 +1012,7 @@ QString &SoftwareList::lookupMountDevice(QString device, QString deviceInterface - QStringList xmlLines(qmc2MachineList->xmlDb()->xml(systemName).split('\n', QString::SkipEmptyParts)); - QStringList *xmlData = &xmlLines; - QStringList dynamicXmlData; -+ QXmlStreamReader xmlMachineEntry(qmc2MachineList->xmlDb()->xml(systemName)); - if ( comboBoxDeviceConfiguration->currentIndex() > 0 ) { - qmc2Config->beginGroup(QMC2_EMULATOR_PREFIX + QString("Configuration/Devices/%1/%2").arg(systemName).arg(comboBoxDeviceConfiguration->currentText())); - QStringList instances(qmc2Config->value("Instances").toStringList()); -@@ -1047,37 +1048,34 @@ QString &SoftwareList::lookupMountDevice(QString device, QString deviceInterface - #endif - } - -- int i = 0; -- while ( i < xmlData->count() && !xmlData->at(i).contains("") ) { -- QString line(xmlData->at(i++).simplified()); -- if ( line.startsWith("= 0 ) { -- startIndex += 11; -- endIndex = line.indexOf("\"", startIndex); -- QStringList devInterfaces(line.mid(startIndex, endIndex - startIndex).split(',', QString::SkipEmptyParts)); -- line = xmlData->at(i++).simplified(); -- startIndex = line.indexOf("briefname=\""); -- if ( startIndex >= 0 ) { -- startIndex += 11; -- endIndex = line.indexOf("\"", startIndex); -- devName = line.mid(startIndex, endIndex - startIndex); -- } -- if ( !devName.isEmpty() ) -- foreach (QString devIf, devInterfaces) -- deviceInstanceHash[devIf] << devName; -- } else { -- line = xmlData->at(i++).simplified(); -- startIndex = line.indexOf("briefname=\""); -- if ( startIndex >= 0 ) { -- startIndex += 11; -- endIndex = line.indexOf("\"", startIndex); -- devName = line.mid(startIndex, endIndex - startIndex); -- } -- if ( !devName.isEmpty() ) -- deviceInstanceHash[devName] << devName; -+ if ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "machine" ) { -+ while ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "device" && xmlMachineEntry.attributes().hasAttribute("type") ) { -+ QString devName; -+ if ( xmlMachineEntry.attributes().hasAttribute("interface") ) { -+ QStringList devInterfaces(xmlMachineEntry.attributes().value("interface").toString().split(',', QString::SkipEmptyParts)); -+ while ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "instance" && xmlMachineEntry.attributes().hasAttribute("briefname") ) { -+ devName = xmlMachineEntry.attributes().value("briefname").toString(); -+ if ( !devName.isEmpty() ) -+ foreach (QString devIf, devInterfaces) -+ deviceInstanceHash[devIf] << devName; -+ } -+ xmlMachineEntry.skipCurrentElement(); -+ } -+ } else { -+ while ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "instance" && xmlMachineEntry.attributes().hasAttribute("briefname") ) { -+ devName = xmlMachineEntry.attributes().value("briefname").toString(); -+ if ( !devName.isEmpty() ) -+ deviceInstanceHash[devName] << devName; -+ } -+ xmlMachineEntry.skipCurrentElement(); -+ } -+ } -+ } else -+ xmlMachineEntry.skipCurrentElement(); - } - } - } - -From 3bd0ec2c4744f1b73bf01a05d485aed31346686e Mon Sep 17 00:00:00 2001 -From: Julian Sikorski -Date: Fri, 16 Feb 2024 23:19:18 +0100 -Subject: [PATCH 3/5] imp: convert deviceconfigurator.cpp to QXmlStreamReader - ---- - src/deviceconfigurator.cpp | 80 +++++++++++++++++++------------------- - 1 file changed, 39 insertions(+), 41 deletions(-) - -diff --git a/src/deviceconfigurator.cpp b/src/deviceconfigurator.cpp -index 6b06ebc4e..e0da99d21 100644 ---- a/src/deviceconfigurator.cpp -+++ b/src/deviceconfigurator.cpp -@@ -2006,55 +2006,53 @@ QString DeviceTreeXmlHandler::getXmlData(const QString &machine) - - QString DeviceTreeXmlHandler::lookupDescription(const QString &machine) - { -- QStringList xmlLines(qmc2MachineList->xmlDb()->xml(machine).split('\n')); -- if ( xmlLines.count() > 1 ) { -- int index = 0; -- while ( index < xmlLines.count() && !xmlLines.at(index).startsWith("") ) -- index++; -- QString description(xmlLines.at(index)); -- description.remove("").remove(""); -- QTextDocument doc; -- doc.setHtml(description); -- return doc.toPlainText(); -+ QXmlStreamReader xmlMachineEntry(qmc2MachineList->xmlDb()->xml(machine)); -+ if ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "machine" ) { -+ while ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "description" ) { -+ QString description(xmlMachineEntry.readElementText()); -+ QTextDocument doc; -+ doc.setHtml(description); -+ return doc.toPlainText(); -+ } else -+ xmlMachineEntry.skipCurrentElement(); -+ } -+ } - } else - return QString(); - } - - QString DeviceTreeXmlHandler::lookupBiosOptions(const QString &machine, QStringList *bioses, QStringList *biosDescriptions) - { -- QStringList xmlLines(qmc2MachineList->xmlDb()->xml(machine).split('\n')); -- if ( xmlLines.count() > 1 ) { -- int index = 0; -- QString defaultOption; -- while ( index < xmlLines.count() ) { -- if ( xmlLines.at(index).startsWith("= 0 ) { -- startIndex += 6; -- int endIndex = xmlLines.at(index).indexOf("\"", startIndex); -- name = xmlLines.at(index).mid(startIndex, endIndex - startIndex); -- } -- startIndex = xmlLines.at(index).indexOf("description=\""); -- if ( startIndex >= 0 ) { -- startIndex += 13; -- int endIndex = xmlLines.at(index).indexOf("\"", startIndex); -- description = xmlLines.at(index).mid(startIndex, endIndex - startIndex); -- QTextDocument doc; -- doc.setHtml(description); -- description = doc.toPlainText(); -- } -- if ( !name.isEmpty() && !description.isEmpty() ) { -- bioses->append(name); -- biosDescriptions->append(description); -- if ( xmlLines.at(index).indexOf("default=\"yes\"") >= 0 ) -- defaultOption = name; -- } -+ QXmlStreamReader xmlMachineEntry(qmc2MachineList->xmlDb()->xml(machine)); -+ if ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "machine" ) { -+ QString defaultOption; -+ while ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "biosset" ) { -+ QString name; -+ QString description; -+ if ( xmlMachineEntry.attributes().hasAttribute("name") ) -+ name = xmlMachineEntry.attributes().value("name").toString(); -+ if ( xmlMachineEntry.attributes().hasAttribute("description") ) { -+ description = xmlMachineEntry.attributes().value("description").toString(); -+ QTextDocument doc; -+ doc.setHtml(description); -+ description = doc.toPlainText(); -+ } -+ if ( !name.isEmpty() && !description.isEmpty() ) { -+ bioses->append(name); -+ biosDescriptions->append(description); -+ if ( xmlMachineEntry.attributes().hasAttribute("default") && xmlMachineEntry.attributes().value("default").toString() == "yes" ) -+ defaultOption = name; -+ } -+ xmlMachineEntry.skipCurrentElement(); -+ } else -+ xmlMachineEntry.skipCurrentElement(); - } -- index++; -+ return defaultOption; - } -- return defaultOption; - } else - return QString(); - } - -From ddd40524240c15c44475462ee89ed51598da214c Mon Sep 17 00:00:00 2001 -From: Julian Sikorski -Date: Sat, 17 Feb 2024 00:08:28 +0100 -Subject: [PATCH 4/5] imp: convert romalyzer.cpp to QXmlStreamReader - ---- - src/romalyzer.cpp | 99 ++++++++++++++++++++++------------------------- - 1 file changed, 47 insertions(+), 52 deletions(-) - -diff --git a/src/romalyzer.cpp b/src/romalyzer.cpp -index ddb5b0b38..76789cf9f 100644 ---- a/src/romalyzer.cpp -+++ b/src/romalyzer.cpp -@@ -2753,18 +2753,15 @@ void ROMAlyzer::on_pushButtonChecksumWizardSearch_clicked() - lineEditSets->setEnabled(false); - labelStatus->setText(tr("Check-sum search")); - -- QString hashStartString; -- int hashStartOffset; -+ QString hashAttribute; - switch ( comboBoxChecksumWizardHashType->currentIndex() ) { - case QMC2_ROMALYZER_CSF_HASHTYPE_CRC: -- hashStartString = "crc=\""; -- hashStartOffset = 5; -+ hashAttribute = "crc"; - break; - - default: - case QMC2_ROMALYZER_CSF_HASHTYPE_SHA1: -- hashStartString = "sha1=\""; -- hashStartOffset = 6; -+ hashAttribute = "sha1"; - break; - } - -@@ -2775,29 +2772,28 @@ void ROMAlyzer::on_pushButtonChecksumWizardSearch_clicked() - int progressCount = 0, updateCount = 0; - foreach (QString list, uniqueSoftwareLists) { - foreach (QString set, qmc2MainWindow->swlDb->uniqueSoftwareSets(list)) { -- QStringList xmlLines(qmc2MainWindow->swlDb->xml(list, set).split('\n', QString::SkipEmptyParts)); -- for (int i = 0; i < xmlLines.count(); i++) { -- QString xmlLine(xmlLines.at(i)); -- int hashIndex = xmlLine.indexOf(hashStartString); -- if ( hashIndex >= 0 ) { -- int hashPos = hashIndex + hashStartOffset; -- QString currentChecksum(xmlLine.mid(hashPos, xmlLine.indexOf('\"', hashPos) - hashPos).toLower()); -- if ( currentChecksum.compare(searchedChecksum) == 0 ) { -- int fileNamePos; -- QString fileType; -- if ( xmlLine.startsWith("setText(QMC2_ROMALYZER_CSF_COLUMN_ID, list + ":" + set); -- item->setText(QMC2_ROMALYZER_CSF_COLUMN_FILENAME, fileName.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'")); -- item->setText(QMC2_ROMALYZER_CSF_COLUMN_TYPE, fileType); -- item->setText(QMC2_ROMALYZER_CSF_COLUMN_STATUS, tr("unknown")); -+ QXmlStreamReader xmlMachineEntry(qmc2MainWindow->swlDb->xml(list, set)); -+ if ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "machine" ) { -+ while ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.attributes().hasAttribute(hashAttribute) ) { -+ QString currentChecksum(xmlMachineEntry.attributes().value(hashAttribute).toString().toLower()); -+ if ( currentChecksum.compare(searchedChecksum) == 0 ) { -+ QString fileType; -+ if ( xmlMachineEntry.name() == "disk" ) -+ fileType = tr("CHD"); -+ else -+ fileType = tr("ROM"); -+ QString fileName(xmlMachineEntry.attributes().value("name").toString()); -+ QTreeWidgetItem *item = new QTreeWidgetItem(treeWidgetChecksumWizardSearchResult); -+ item->setText(QMC2_ROMALYZER_CSF_COLUMN_ID, list + ":" + set); -+ item->setText(QMC2_ROMALYZER_CSF_COLUMN_FILENAME, fileName.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'")); -+ item->setText(QMC2_ROMALYZER_CSF_COLUMN_TYPE, fileType); -+ item->setText(QMC2_ROMALYZER_CSF_COLUMN_STATUS, tr("unknown")); -+ } -+ xmlMachineEntry.skipCurrentElement(); -+ } else -+ xmlMachineEntry.skipCurrentElement(); - } - } - } -@@ -2820,29 +2816,28 @@ void ROMAlyzer::on_pushButtonChecksumWizardSearch_clicked() - qApp->processEvents(); - } - QString currentMachine(qmc2MainWindow->treeWidgetMachineList->topLevelItem(i)->text(QMC2_MACHINELIST_COLUMN_NAME)); -- QStringList xmlLines(qmc2MachineList->xmlDb()->xml(currentMachine).split('\n', QString::SkipEmptyParts)); -- for (int j = 0; j < xmlLines.count(); j++) { -- QString xmlLine(xmlLines.at(j)); -- int hashIndex = xmlLine.indexOf(hashStartString); -- if ( hashIndex >= 0 ) { -- int hashPos = hashIndex + hashStartOffset; -- QString currentChecksum(xmlLine.mid(hashPos, xmlLine.indexOf('\"', hashPos) - hashPos).toLower()); -- if ( currentChecksum.compare(searchedChecksum) == 0 ) { -- int fileNamePos; -- QString fileType; -- if ( xmlLine.startsWith("setText(QMC2_ROMALYZER_CSF_COLUMN_ID, currentMachine); -- item->setText(QMC2_ROMALYZER_CSF_COLUMN_FILENAME, fileName.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'")); -- item->setText(QMC2_ROMALYZER_CSF_COLUMN_TYPE, fileType); -- item->setText(QMC2_ROMALYZER_CSF_COLUMN_STATUS, tr("unknown")); -+ QXmlStreamReader xmlMachineEntry(qmc2MachineList->xmlDb()->xml(currentMachine)); -+ if ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "machine" ) { -+ while ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.attributes().hasAttribute(hashAttribute) ) { -+ QString currentChecksum(xmlMachineEntry.attributes().value(hashAttribute).toString().toLower()); -+ if ( currentChecksum.compare(searchedChecksum) == 0 ) { -+ QString fileType; -+ if ( xmlMachineEntry.name() == "disk" ) -+ fileType = tr("CHD"); -+ else -+ fileType = tr("ROM"); -+ QString fileName(xmlMachineEntry.attributes().value("name").toString()); -+ QTreeWidgetItem *item = new QTreeWidgetItem(treeWidgetChecksumWizardSearchResult); -+ item->setText(QMC2_ROMALYZER_CSF_COLUMN_ID, currentMachine); -+ item->setText(QMC2_ROMALYZER_CSF_COLUMN_FILENAME, fileName.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'")); -+ item->setText(QMC2_ROMALYZER_CSF_COLUMN_TYPE, fileType); -+ item->setText(QMC2_ROMALYZER_CSF_COLUMN_STATUS, tr("unknown")); -+ } -+ xmlMachineEntry.skipCurrentElement(); -+ } else -+ xmlMachineEntry.skipCurrentElement(); - } - } - } - -From 06d96bba32bf784f91018c81a59e2a4d19acbd69 Mon Sep 17 00:00:00 2001 -From: Julian Sikorski -Date: Sat, 17 Feb 2024 01:02:28 +0100 -Subject: [PATCH 5/5] imp: convert qmc2main.cpp to QXmlStreamReader - ---- - src/qmc2main.cpp | 64 +++++++++++++++++++++--------------------------- - 1 file changed, 28 insertions(+), 36 deletions(-) - -diff --git a/src/qmc2main.cpp b/src/qmc2main.cpp -index ec16009b2..e24fe89d6 100644 ---- a/src/qmc2main.cpp -+++ b/src/qmc2main.cpp -@@ -4631,44 +4631,36 @@ QStringList &MainWindow::getXmlChoices(const QString &machineName, const QString - return xmlChoices; - if ( defaultChoice ) - defaultChoice->clear(); -- QStringList xmlLines(qmc2MachineList->xmlDb()->xml(machineName).split('\n', QString::SkipEmptyParts)); -- QString defaultYes("default=\"yes\""); -- QString defaultOne("default=\"1\""); -- int i = 0; -- while ( i < xmlLines.count() ) { -- QString xmlLine(xmlLines.at(i++).simplified()); -- int index = xmlLine.indexOf('<' + optionElement); -- if ( index >= 0 ) { -- if ( optionAttribute.isEmpty() ) { -- index = xmlLine.indexOf('>', index); -- if ( index >= 0 ) { -- xmlLine.remove(0, index + 1); -- bool isDefaultChoice = false; -- if ( defaultChoice && (xmlLine.indexOf(defaultYes) >= 0 || xmlLine.indexOf(defaultOne) >= 0 || defaultChoice->isEmpty()) ) -- isDefaultChoice = true; -- xmlLine.replace("', ""); -- QTextDocument doc; -- doc.setHtml(xmlLine); -- xmlLine = doc.toPlainText(); -- xmlChoices << xmlLine; -- if ( isDefaultChoice ) -- *defaultChoice = xmlLine; -- } -- } else { -- QString prefix(optionAttribute + "=\""); -- index = xmlLine.indexOf(prefix); -- if ( index >= 0 ) { -- xmlLine.remove(0, index + prefix.length()); -- index = xmlLine.indexOf('\"'); -- if ( index >= 0 ) { -+ QXmlStreamReader xmlMachineEntry(qmc2MachineList->xmlDb()->xml(machineName)); -+ QString defaultYes("yes"); -+ QString defaultOne("1"); -+ if ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == "machine" ) { -+ while ( xmlMachineEntry.readNextStartElement() ) { -+ if ( xmlMachineEntry.name() == optionElement ) { -+ if ( optionAttribute.isEmpty() ) { -+ bool isDefaultChoice = false; -+ if ( defaultChoice && (xmlMachineEntry.attributes().hasAttribute("default") && xmlMachineEntry.attributes().value("default").toString() == defaultYes || xmlMachineEntry.attributes().value("default").toString() == defaultOne || defaultChoice->isEmpty()) ) -+ isDefaultChoice = true; - QTextDocument doc; -- doc.setHtml(xmlLine.left(index)); -- QString choice = doc.toPlainText(); -- xmlChoices << choice; -- if ( defaultChoice && (xmlLine.indexOf(defaultYes) >= 0 || xmlLine.indexOf(defaultOne) >= 0 || defaultChoice->isEmpty()) ) -- *defaultChoice = choice; -+ doc.setHtml(xmlMachineEntry.readElementText()); -+ QString xmlLine = doc.toPlainText(); -+ xmlChoices << xmlLine; -+ if ( isDefaultChoice ) -+ *defaultChoice = xmlLine; -+ } else { -+ if ( xmlMachineEntry.attributes().hasAttribute(optionAttribute) ) { -+ QTextDocument doc; -+ doc.setHtml(xmlMachineEntry.attributes().value(optionAttribute).toString()); -+ QString choice = doc.toPlainText(); -+ xmlChoices << choice; -+ if ( defaultChoice && (xmlMachineEntry.attributes().hasAttribute("default") && xmlMachineEntry.attributes().value("default").toString() == defaultYes || xmlMachineEntry.attributes().value("default").toString() == defaultOne || defaultChoice->isEmpty()) ) -+ *defaultChoice = choice; -+ xmlMachineEntry.skipCurrentElement(); -+ } - } -- } -+ } else -+ xmlMachineEntry.skipCurrentElement(); - } - } - } diff --git a/qmc2.spec b/qmc2.spec index 5fa8c4b..6f031e8 100644 --- a/qmc2.spec +++ b/qmc2.spec @@ -20,9 +20,12 @@ Patch1: %{name}-ini.patch #Fixes and improvements from upstream git Patch10: 0001-fix-MachineListDatabase-wasn-t-saved-to-qmc2.ini.patch Patch11: 0001-new-added-a-Brasilian-Portuguese-translation-thanks-.patch -Patch12: 0001-imp-Added-history.xml-support-and-use-XML-parser-to-.patch -Patch13: 41.patch -Patch14: 42.patch +Patch12: 0001-imp-added-Ubuntu-22.04-build-configuration.patch +Patch13: 0001-imp-removed-ancient-build-configs.patch +Patch14: 0001-imp-Added-history.xml-support-and-use-XML-parser-to-.patch +Patch15: 0002-imp-Updated-Fedora-and-Ubuntu-build-configurations.-.patch +Patch16: 0007-imp-Updated-bundled-libraries-to-their-current-upstr.patch +Patch17: 0008-imp-Replaced-custom-XML-parsing-with-QXmlStreamReade.patch BuildRequires: desktop-file-utils BuildRequires: git