diff -Nru 7zip-22.01+dfsg/C/7zAlloc.c 7zip-23.01+dfsg/C/7zAlloc.c --- 7zip-22.01+dfsg/C/7zAlloc.c 2017-04-03 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/7zAlloc.c 2023-03-04 09:00:00.000000000 +0000 @@ -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 -Nru 7zip-22.01+dfsg/C/7zAlloc.h 7zip-23.01+dfsg/C/7zAlloc.h --- 7zip-22.01+dfsg/C/7zAlloc.h 2017-04-03 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/7zAlloc.h 2023-03-04 09:00:00.000000000 +0000 @@ -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 -Nru 7zip-22.01+dfsg/C/7zArcIn.c 7zip-23.01+dfsg/C/7zArcIn.c --- 7zip-22.01+dfsg/C/7zArcIn.c 2021-02-09 15:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/7zArcIn.c 2023-05-11 15:00:00.000000000 +0000 @@ -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 @@ 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 @@ } 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 @@ 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 @@ p->NumFolders = 0; p->PackPositions = NULL; - SzBitUi32s_Init(&p->FolderCRCs); + SzBitUi32s_INIT(&p->FolderCRCs) p->FoCodersOffsets = NULL; p->FoStartPackStreamIndex = NULL; @@ -142,11 +143,11 @@ 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 @@ 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 @@ #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 @@ 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 SzReadNumber32(CSzData *sd, UInt32 *value) +static Z7_NO_INLINE SRes SzReadNumber32(CSzData *sd, UInt32 *value) { Byte firstByte; UInt64 value64; @@ -244,7 +254,7 @@ 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 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 @@ 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 @@ 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 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 @@ { 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 @@ 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 @@ 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 @@ 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 @@ { 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 @@ 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 @@ { 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] = True; - RINOK(SzReadNumber32(sd, &bp->OutIndex)); + RINOK(SzReadNumber32(sd, &bp->OutIndex)) if (bp->OutIndex >= numCoders || coderUsed[bp->OutIndex]) return SZ_ERROR_ARCHIVE; coderUsed[bp->OutIndex] = True; @@ -584,7 +594,7 @@ 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] = True; @@ -598,7 +608,7 @@ } -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 @@ { 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ { UInt32 index; - RINOK(SzReadNumber32(&sd, &index)); + RINOK(SzReadNumber32(&sd, &index)) if (index >= numInStreams || streamUsed[index]) return SZ_ERROR_ARCHIVE; streamUsed[index] = True; - RINOK(SzReadNumber32(&sd, &index)); + RINOK(SzReadNumber32(&sd, &index)) if (index >= numCoders || coderUsed[index]) return SZ_ERROR_ARCHIVE; coderUsed[index] = True; @@ -767,7 +777,7 @@ 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] = True; @@ -802,7 +812,7 @@ 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 @@ 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 @@ } 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 @@ { 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 @@ 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 @@ } if (type == k7zIdCRC || type == k7zIdSize || type == k7zIdEnd) break; - RINOK(SkipData(sd)); + RINOK(SkipData(sd)) } if (!ssi->sdNumSubStreams.Data) @@ -908,9 +918,9 @@ 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 @@ 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 @@ { 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 SzReadAndDecodePackedStreams( - ILookInStream *inStream, + ILookInStreamPtr inStream, CSzData *sd, CBuf *tempBufs, UInt32 numFoldersMax, @@ -988,7 +998,7 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 SRes SzReadHeader2( CSzArEx *p, /* allocMain */ CSzData *sd, - ILookInStream *inStream, + ILookInStreamPtr inStream, CBuf *tempBufs, UInt32 *numTempBufs, ISzAllocPtr allocMain, ISzAllocPtr allocTemp @@ -1111,26 +1121,26 @@ { 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 SzReadHeader( CSzArEx *p, CSzData *sd, - ILookInStream *inStream, + ILookInStreamPtr inStream, ISzAllocPtr allocMain, ISzAllocPtr allocTemp) { @@ -1498,7 +1501,7 @@ 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 SzArEx_Open2( CSzArEx *p, - ILookInStream *inStream, + ILookInStreamPtr inStream, ISzAllocPtr allocMain, ISzAllocPtr allocTemp) { @@ -1521,9 +1524,9 @@ 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 @@ { 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 @@ } -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_Extract( const CSzArEx *p, - ILookInStream *inStream, + ILookInStreamPtr inStream, UInt32 fileIndex, UInt32 *blockIndex, Byte **tempBuf, @@ -1656,7 +1659,7 @@ 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 @@ 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 @@ 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 @@ 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 -Nru 7zip-22.01+dfsg/C/7zBuf.h 7zip-23.01+dfsg/C/7zBuf.h --- 7zip-22.01+dfsg/C/7zBuf.h 2017-04-03 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/7zBuf.h 2023-03-04 11:00:00.000000000 +0000 @@ -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 -Nru 7zip-22.01+dfsg/C/7zCrc.c 7zip-23.01+dfsg/C/7zCrc.c --- 7zip-22.01+dfsg/C/7zCrc.c 2021-04-01 18:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/7zCrc.c 2023-04-02 11:00:00.000000000 +0000 @@ -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 @@ 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 @@ v = CRC_UPDATE_BYTE_2(v, *p); return v; } - +#endif /* ---------- hardware CRC ---------- */ @@ -78,16 +78,29 @@ #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 @@ #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 @@ return v; } -MY_FORCE_INLINE +Z7_FORCE_INLINE UInt32 __crc32w(UInt32 v, UInt32 data) { const UInt32 *table = g_CrcTable; @@ -124,7 +137,7 @@ return v; } -MY_FORCE_INLINE +Z7_FORCE_INLINE UInt32 __crc32d(UInt32 v, UInt64 data) { const UInt32 *table = g_CrcTable; @@ -156,9 +169,9 @@ // #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 @@ } 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 @@ 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 @@ -void MY_FAST_CALL CrcGenerateTable() +void Z7_FASTCALL CrcGenerateTable(void) { UInt32 i; for (i = 0; i < 256; i++) @@ -239,64 +255,62 @@ } 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 @@ #endif #endif } + +#undef kCrcPoly +#undef CRC64_NUM_TABLES +#undef CRC_UPDATE_BYTE_2 diff -Nru 7zip-22.01+dfsg/C/7zCrc.h 7zip-23.01+dfsg/C/7zCrc.h --- 7zip-22.01+dfsg/C/7zCrc.h 2013-01-18 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/7zCrc.h 2023-04-02 11:00:00.000000000 +0000 @@ -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 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 -Nru 7zip-22.01+dfsg/C/7zCrcOpt.c 7zip-23.01+dfsg/C/7zCrcOpt.c --- 7zip-22.01+dfsg/C/7zCrcOpt.c 2021-02-09 15:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/7zCrcOpt.c 2023-04-02 11:00:00.000000000 +0000 @@ -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 @@ 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 @@ #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 @@ 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 -Nru 7zip-22.01+dfsg/C/7zDec.c 7zip-23.01+dfsg/C/7zDec.c --- 7zip-22.01+dfsg/C/7zDec.c 2021-02-09 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/7zDec.c 2023-04-02 11:00:00.000000000 +0000 @@ -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 @@ 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 @@ p->cur = p->begin; p->end = p->begin + size; if (size != 0) - return *p->cur++;; + return *p->cur++; } p->extra = True; 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 @@ #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 @@ } -#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 @@ #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 @@ 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 @@ { 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 True; } return False; @@ -317,7 +339,7 @@ } - #ifndef _7Z_NO_METHODS_FILTERS + #if defined(Z7_USE_BRANCH_FILTER) if (f->NumCoders == 2) { @@ -333,13 +355,20 @@ 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 @@ 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 @@ SizeT tempSize3 = 0; Byte *tempBuf3 = 0; - RINOK(CheckSupportedFolder(folder)); + RINOK(CheckSupportedFolder(folder)) for (ci = 0; ci < folder->NumCoders; ci++) { @@ -404,8 +434,8 @@ 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 @@ } 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 @@ 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 @@ 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 @@ 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 @@ SRes SzAr_DecodeFolder(const CSzAr *p, UInt32 folderIndex, - ILookInStream *inStream, UInt64 startPos, + ILookInStreamPtr inStream, UInt64 startPos, Byte *outBuffer, size_t outSize, ISzAllocPtr allocMain) { diff -Nru 7zip-22.01+dfsg/C/7zFile.c 7zip-23.01+dfsg/C/7zFile.c --- 7zip-22.01+dfsg/C/7zFile.c 2021-04-29 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/7zFile.c 2023-04-02 11:00:00.000000000 +0000 @@ -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 @@ 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 @@ 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 @@ 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 @@ /* ---------- 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 @@ /* ---------- 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 @@ /* ---------- 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 -Nru 7zip-22.01+dfsg/C/7zFile.h 7zip-23.01+dfsg/C/7zFile.h --- 7zip-22.01+dfsg/C/7zFile.h 2021-02-15 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/7zFile.h 2023-03-05 09:00:00.000000000 +0000 @@ -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 -Nru 7zip-22.01+dfsg/C/7z.h 7zip-23.01+dfsg/C/7z.h --- 7zip-22.01+dfsg/C/7z.h 2019-07-02 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/7z.h 2023-04-02 11:00:00.000000000 +0000 @@ -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 @@ 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 @@ 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_FAIL */ -SRes SzArEx_Open(CSzArEx *p, ILookInStream *inStream, +SRes SzArEx_Open(CSzArEx *p, ILookInStreamPtr inStream, ISzAllocPtr allocMain, ISzAllocPtr allocTemp); EXTERN_C_END diff -Nru 7zip-22.01+dfsg/C/7zip_gcc_c.mak 7zip-23.01+dfsg/C/7zip_gcc_c.mak --- 7zip-22.01+dfsg/C/7zip_gcc_c.mak 2022-07-15 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/7zip_gcc_c.mak 2023-05-03 13:00:00.000000000 +0000 @@ -4,15 +4,28 @@ MY_ASM = jwasm MY_ASM = asmc +ifndef RC +#RC=windres.exe --target=pe-x86-64 +#RC=windres.exe -F pe-i386 +RC=windres.exe +endif + PROGPATH = $(O)/$(PROG) PROGPATH_STATIC = $(O)/$(PROG)s +ifneq ($(CC), xlc) +CFLAGS_WARN_WALL = -Wall -Werror -Wextra +endif # for object file CFLAGS_BASE_LIST = -c # for ASM file # CFLAGS_BASE_LIST = -S -CFLAGS_BASE = $(MY_ARCH_2) -O2 $(CFLAGS_BASE_LIST) -Wall -Werror -Wextra $(CFLAGS_WARN) \ + +FLAGS_FLTO = +FLAGS_FLTO = -flto + +CFLAGS_BASE = $(MY_ARCH_2) -O2 $(CFLAGS_BASE_LIST) $(CFLAGS_WARN_WALL) $(CFLAGS_WARN) \ -DNDEBUG -D_REENTRANT -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE @@ -93,9 +106,9 @@ endif -LIB2 = -lOle32 -loleaut32 -luuid -ladvapi32 -lUser32 +LIB2 = -lOle32 -loleaut32 -luuid -ladvapi32 -lUser32 -lShell32 -CXXFLAGS_EXTRA = -DUNICODE -D_UNICODE +CFLAGS_EXTRA = -DUNICODE -D_UNICODE # -Wno-delete-non-virtual-dtor @@ -103,8 +116,8 @@ RM = rm -f MY_MKDIR=mkdir -p -# CFLAGS_BASE := $(CFLAGS_BASE) -D_7ZIP_ST -# CXXFLAGS_EXTRA = -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE +# CFLAGS_BASE := $(CFLAGS_BASE) -DZ7_ST +# CFLAGS_EXTRA = -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE # LOCAL_LIBS=-lpthread # LOCAL_LIBS_DLL=$(LOCAL_LIBS) -ldl @@ -115,10 +128,6 @@ endif - -CFLAGS = $(LOCAL_FLAGS) $(CFLAGS_BASE2) $(CFLAGS_BASE) $(CC_SHARED) -o $@ - - ifdef IS_X64 AFLAGS_ABI = -elf64 -DABI_LINUX else @@ -129,12 +138,9 @@ endif AFLAGS = $(AFLAGS_ABI) -Fo$(O)/ +C_WARN_FLAGS = -CXX_WARN_FLAGS = -#-Wno-invalid-offsetof -#-Wno-reorder - -CXXFLAGS = $(LOCAL_FLAGS) $(CXXFLAGS_BASE2) $(CFLAGS_BASE) $(CXXFLAGS_EXTRA) $(CC_SHARED) -o $@ $(CXX_WARN_FLAGS) +CFLAGS = $(LOCAL_FLAGS) $(CFLAGS_BASE2) $(CFLAGS_BASE) $(CFLAGS_EXTRA) $(C_WARN_FLAGS) $(FLAGS_FLTO) $(CC_SHARED) -o $@ STATIC_TARGET= ifdef COMPL_STATIC @@ -147,18 +153,27 @@ $(O): $(MY_MKDIR) $(O) -LFLAGS_ALL = -s $(MY_ARCH_2) $(LDFLAGS) $(LD_arch) $(OBJS) $(MY_LIBS) $(LIB2) +ifneq ($(CC), $(CROSS_COMPILE)clang) +LFLAGS_STRIP = -s +endif + +LFLAGS_ALL = $(LFLAGS_STRIP) $(MY_ARCH_2) $(LDFLAGS) $(FLAGS_FLTO) $(LD_arch) $(OBJS) $(MY_LIBS) $(LIB2) $(PROGPATH): $(OBJS) - $(CXX) -o $(PROGPATH) $(LFLAGS_ALL) + $(CC) -o $(PROGPATH) $(LFLAGS_ALL) $(PROGPATH_STATIC): $(OBJS) - $(CXX) -static -o $(PROGPATH_STATIC) $(LFLAGS_ALL) + $(CC) -static -o $(PROGPATH_STATIC) $(LFLAGS_ALL) ifndef NO_DEFAULT_RES +# old mingw without -FO +# windres.exe $(RFLAGS) resource.rc $O/resource.o $O/resource.o: resource.rc - windres.exe $(RFLAGS) resource.rc $O/resource.o + $(RC) $(RFLAGS) resource.rc $(O)/resource.o endif +# windres.exe $(RFLAGS) resource.rc $(O)\resource.o +# windres.exe $(RFLAGS) resource.rc -FO $(O)/resource.o +# $(RC) $(RFLAGS) resource.rc -FO $(O)/resource.o @@ -256,10 +271,18 @@ $(CC) $(CFLAGS) $< $O/Sort.o: ../../../C/Sort.c $(CC) $(CFLAGS) $< +$O/SwapBytes.o: ../../../C/SwapBytes.c + $(CC) $(CFLAGS) $< $O/Xz.o: ../../../C/Xz.c $(CC) $(CFLAGS) $< $O/XzCrc64.o: ../../../C/XzCrc64.c $(CC) $(CFLAGS) $< +$O/XzDec.o: ../../../C/XzDec.c + $(CC) $(CFLAGS) $< +$O/XzEnc.o: ../../../C/XzEnc.c + $(CC) $(CFLAGS) $< +$O/XzIn.o: ../../../C/XzIn.c + $(CC) $(CFLAGS) $< ifdef USE_ASM @@ -310,7 +333,7 @@ endif $O/LzmaDec.o: ../../LzmaDec.c - $(CC) $(CFLAGS) -D_LZMA_DEC_OPT $< + $(CC) $(CFLAGS) -DZ7_LZMA_DEC_OPT $< else @@ -321,22 +344,16 @@ -$O/XzDec.o: ../../../C/XzDec.c - $(CC) $(CFLAGS) $< -$O/XzEnc.o: ../../../C/XzEnc.c - $(CC) $(CFLAGS) $< -$O/XzIn.o: ../../../C/XzIn.c - $(CC) $(CFLAGS) $< - - $O/7zMain.o: ../../../C/Util/7z/7zMain.c $(CC) $(CFLAGS) $< -$O/LzmaUtil.o: ../../../C/Util/Lzma/LzmaUtil.c - $(CC) $(CFLAGS) $< $O/7zipInstall.o: ../../../C/Util/7zipInstall/7zipInstall.c $(CC) $(CFLAGS) $< $O/7zipUninstall.o: ../../../C/Util/7zipUninstall/7zipUninstall.c $(CC) $(CFLAGS) $< +$O/LzmaUtil.o: ../../../C/Util/Lzma/LzmaUtil.c + $(CC) $(CFLAGS) $< +$O/XzUtil.o: ../../../C/Util/Xz/XzUtil.c + $(CC) $(CFLAGS) $< clean: diff -Nru 7zip-22.01+dfsg/C/7zStream.c 7zip-23.01+dfsg/C/7zStream.c --- 7zip-22.01+dfsg/C/7zStream.c 2021-02-09 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/7zStream.c 2023-04-02 11:00:00.000000000 +0000 @@ -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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ -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 @@ 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 -Nru 7zip-22.01+dfsg/C/7zTypes.h 7zip-23.01+dfsg/C/7zTypes.h --- 7zip-22.01+dfsg/C/7zTypes.h 2022-04-01 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/7zTypes.h 2023-04-02 11:00:00.000000000 +0000 @@ -1,8 +1,8 @@ /* 7zTypes.h -- Basic types -2022-04-01 : 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 @@ #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 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 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,17 +125,17 @@ #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) */ #define TEXT(quote) quote @@ -156,18 +161,18 @@ #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 @@ -206,37 +211,51 @@ #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 True 1 @@ -244,23 +263,23 @@ #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 @@ -268,27 +287,25 @@ || (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 @@ -296,41 +313,49 @@ /* 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 */ }; @@ -344,29 +369,26 @@ } 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) @@ -375,19 +397,18 @@ #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 */ @@ -399,13 +420,13 @@ 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); @@ -415,20 +436,19 @@ 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) @@ -466,13 +486,13 @@ -#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)))) */ /* @@ -481,24 +501,64 @@ 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))) + +#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 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))) +*/ #endif -#define CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) ((type *)(void *)(ptr)) +#define Z7_CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) ((type *)(void *)(ptr)) -/* -#define CONTAINER_FROM_VTBL(ptr, type, m) CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) -*/ -#define CONTAINER_FROM_VTBL(ptr, type, m) MY_container_of(ptr, type, m) +// #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 CONTAINER_FROM_VTBL_CLS(ptr, type, m) CONTAINER_FROM_VTBL_SIMPLE(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 @@ -527,3 +587,11 @@ EXTERN_C_END #endif + +/* +#ifndef Z7_ST +#ifdef _7ZIP_ST +#define Z7_ST +#endif +#endif +*/ diff -Nru 7zip-22.01+dfsg/C/7zVersion.h 7zip-23.01+dfsg/C/7zVersion.h --- 7zip-22.01+dfsg/C/7zVersion.h 2022-07-15 13:00:29.000000000 +0000 +++ 7zip-23.01+dfsg/C/7zVersion.h 2023-06-20 06:00:00.000000000 +0000 @@ -1,7 +1,7 @@ -#define MY_VER_MAJOR 22 +#define MY_VER_MAJOR 23 #define MY_VER_MINOR 01 #define MY_VER_BUILD 0 -#define MY_VERSION_NUMBERS "22.01" +#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 "2022-07-15" +#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-2022 Igor Pavlov" +#define MY_COPYRIGHT_CR "Copyright (c) 1999-2023 Igor Pavlov" #ifdef USE_COPYRIGHT_CR #define MY_COPYRIGHT MY_COPYRIGHT_CR diff -Nru 7zip-22.01+dfsg/C/7zWindows.h 7zip-23.01+dfsg/C/7zWindows.h --- 7zip-22.01+dfsg/C/7zWindows.h 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/7zWindows.h 2023-04-02 11:00:00.000000000 +0000 @@ -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 -Nru 7zip-22.01+dfsg/C/Aes.c 7zip-23.01+dfsg/C/Aes.c --- 7zip-22.01+dfsg/C/Aes.c 2021-05-13 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Aes.c 2023-04-02 11:00:00.000000000 +0000 @@ -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 @@ #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 @@ #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 @@ 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 @@ { 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 @@ 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 @@ #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 @@ #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 @@ #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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 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 @@ 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 @@ } } } + +#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 -Nru 7zip-22.01+dfsg/C/Aes.h 7zip-23.01+dfsg/C/Aes.h --- 7zip-22.01+dfsg/C/Aes.h 2019-08-28 18:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Aes.h 2023-04-02 11:00:00.000000000 +0000 @@ -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 @@ /* 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 @@ #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) - -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) +Z7_DECLARE_AES_CODE_FUNC (AesCbc_Decode) +Z7_DECLARE_AES_CODE_FUNC (AesCtr_Code) + +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 -Nru 7zip-22.01+dfsg/C/AesOpt.c 7zip-23.01+dfsg/C/AesOpt.c --- 7zip-22.01+dfsg/C/AesOpt.c 2021-04-01 18:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/AesOpt.c 2023-04-02 11:00:00.000000000 +0000 @@ -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 @@ 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 @@ 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 @@ #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 @@ #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 @@ #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_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 @@ const __m128i *w = wStart; WOP (DECLARE_VAR) - WOP (LOAD_data); + WOP (LOAD_data) WOP_KEY (AES_XOR, 1) do @@ -239,10 +240,10 @@ 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 @@ __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 (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 @@ 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 @@ while (--r); WOP_KEY (AES_ENC_LAST, 0) - WOP (CTR_END); + WOP (CTR_END) } WIDE_LOOP_END @@ -303,19 +306,19 @@ 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 @@ #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 @@ 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 @@ { 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 @@ __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 @@ _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 @@ __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 @@ #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 @@ #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 @@ 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 @@ 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_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 @@ #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_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 @@ { const v128 *w = wStart; WOP (DECLARE_VAR) - WOP (LOAD_data); + WOP (LOAD_data) WOP_KEY (AES_D_IMC, 2) do { @@ -695,7 +748,7 @@ 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 (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 @@ { const v128 *w = p; WOP (DECLARE_VAR) - WOP (CTR_START); + WOP (CTR_START) do { WOP_KEY (AES_E_MC, 0) @@ -746,7 +801,7 @@ 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 @@ 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 @@ #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 -Nru 7zip-22.01+dfsg/C/Alloc.c 7zip-23.01+dfsg/C/Alloc.c --- 7zip-22.01+dfsg/C/Alloc.c 2021-07-13 09:20:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Alloc.c 2023-04-02 11:00:00.000000000 +0000 @@ -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 @@ Print(s); } -static void PrintLn() +static void PrintLn(void) { Print("\n"); } @@ -89,10 +105,10 @@ 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 @@ } -#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 @@ #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 @@ #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 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 @@ 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 @@ 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 @@ 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 @@ #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 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 @@ 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 @@ { 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 -Nru 7zip-22.01+dfsg/C/Alloc.h 7zip-23.01+dfsg/C/Alloc.h --- 7zip-22.01+dfsg/C/Alloc.h 2021-07-13 09:19:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Alloc.h 2023-03-04 08:00:00.000000000 +0000 @@ -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 -Nru 7zip-22.01+dfsg/C/Bcj2.c 7zip-23.01+dfsg/C/Bcj2.c --- 7zip-22.01+dfsg/C/Bcj2.c 2021-02-09 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Bcj2.c 2023-03-01 12:00:00.000000000 +0000 @@ -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 @@ 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 @@ 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 -Nru 7zip-22.01+dfsg/C/Bcj2Enc.c 7zip-23.01+dfsg/C/Bcj2Enc.c --- 7zip-22.01+dfsg/C/Bcj2Enc.c 2021-02-09 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Bcj2Enc.c 2023-04-02 11:00:00.000000000 +0000 @@ -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 @@ p->bufs[BCJ2_STREAM_RC] = buf; return True; } - *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 False; } -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; + /* 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; } } - dest = p->bufs[BCJ2_STREAM_MAIN]; - if (num > (SizeT)(p->lims[BCJ2_STREAM_MAIN] - dest)) + 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 = False; - + #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 = True; + /* + if (relat != 0 || (Byte)v != 0xe8) + BoolInt isBigOffset = True; + */ + 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 = False; // 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 -Nru 7zip-22.01+dfsg/C/Bcj2.h 7zip-23.01+dfsg/C/Bcj2.h --- 7zip-22.01+dfsg/C/Bcj2.h 2014-11-10 18:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Bcj2.h 2023-03-02 17:00:00.000000000 +0000 @@ -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 @@ 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 @@ 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 @@ 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 @@ 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); + +/* 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) -#define BCJ2_RELAT_LIMIT_NUM_BITS 26 -#define BCJ2_RELAT_LIMIT ((UInt32)1 << BCJ2_RELAT_LIMIT_NUM_BITS) +#define Bcj2Enc_IsFinished(p) ((p)->flushRem == 0) -/* limit for CBcj2Enc::fileSize variable */ -#define BCJ2_FileSize_MAX ((UInt32)1 << 31) +/* 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 -Nru 7zip-22.01+dfsg/C/Blake2.h 7zip-23.01+dfsg/C/Blake2.h --- 7zip-22.01+dfsg/C/Blake2.h 2015-06-30 16:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Blake2.h 2023-03-04 11:00:00.000000000 +0000 @@ -1,9 +1,9 @@ /* Blake2.h -- BLAKE2 Hash -2015-06-30 : Igor Pavlov : Public domain +2023-03-04 : Igor Pavlov : Public domain 2015 : Samuel Neves : Public domain */ -#ifndef __BLAKE2_H -#define __BLAKE2_H +#ifndef ZIP7_INC_BLAKE2_H +#define ZIP7_INC_BLAKE2_H #include "7zTypes.h" diff -Nru 7zip-22.01+dfsg/C/Blake2s.c 7zip-23.01+dfsg/C/Blake2s.c --- 7zip-22.01+dfsg/C/Blake2s.c 2021-02-09 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Blake2s.c 2023-03-04 11:00:00.000000000 +0000 @@ -1,7 +1,9 @@ /* Blake2s.c -- BLAKE2s and BLAKE2sp Hash -2021-02-09 : Igor Pavlov : Public domain +2023-03-04 : Igor Pavlov : Public domain 2015 : Samuel Neves : Public domain */ +#include "Precomp.h" + #include #include "Blake2.h" @@ -78,21 +80,21 @@ a += b + m[sigma[2*i+1]]; d ^= a; d = rotr32(d, 8); c += d; b ^= c; b = rotr32(b, 7); \ #define R(r) \ - G(r,0,v[ 0],v[ 4],v[ 8],v[12]); \ - G(r,1,v[ 1],v[ 5],v[ 9],v[13]); \ - G(r,2,v[ 2],v[ 6],v[10],v[14]); \ - G(r,3,v[ 3],v[ 7],v[11],v[15]); \ - G(r,4,v[ 0],v[ 5],v[10],v[15]); \ - G(r,5,v[ 1],v[ 6],v[11],v[12]); \ - G(r,6,v[ 2],v[ 7],v[ 8],v[13]); \ - G(r,7,v[ 3],v[ 4],v[ 9],v[14]); \ + G(r,0,v[ 0],v[ 4],v[ 8],v[12]) \ + G(r,1,v[ 1],v[ 5],v[ 9],v[13]) \ + G(r,2,v[ 2],v[ 6],v[10],v[14]) \ + G(r,3,v[ 3],v[ 7],v[11],v[15]) \ + G(r,4,v[ 0],v[ 5],v[10],v[15]) \ + G(r,5,v[ 1],v[ 6],v[11],v[12]) \ + G(r,6,v[ 2],v[ 7],v[ 8],v[13]) \ + G(r,7,v[ 3],v[ 4],v[ 9],v[14]) \ { unsigned r; for (r = 0; r < BLAKE2S_NUM_ROUNDS; r++) { const Byte *sigma = k_Blake2s_Sigma[r]; - R(r); + R(r) } /* R(0); R(1); R(2); R(3); R(4); R(5); R(6); R(7); R(8); R(9); */ } @@ -130,7 +132,7 @@ } memcpy(p->buf + pos, data, rem); - Blake2s_Increment_Counter(S, BLAKE2S_BLOCK_SIZE); + Blake2s_Increment_Counter(S, BLAKE2S_BLOCK_SIZE) Blake2s_Compress(p); p->bufPos = 0; data += rem; @@ -143,13 +145,15 @@ { unsigned i; - Blake2s_Increment_Counter(S, (UInt32)p->bufPos); - Blake2s_Set_LastBlock(p); + Blake2s_Increment_Counter(S, (UInt32)p->bufPos) + Blake2s_Set_LastBlock(p) memset(p->buf + p->bufPos, 0, BLAKE2S_BLOCK_SIZE - p->bufPos); Blake2s_Compress(p); for (i = 0; i < 8; i++) - SetUi32(digest + sizeof(p->h[i]) * i, p->h[i]); + { + SetUi32(digest + sizeof(p->h[i]) * i, p->h[i]) + } } @@ -242,3 +246,5 @@ Blake2s_Final(&R, digest); } + +#undef rotr32 diff -Nru 7zip-22.01+dfsg/C/Bra86.c 7zip-23.01+dfsg/C/Bra86.c --- 7zip-22.01+dfsg/C/Bra86.c 2021-02-09 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Bra86.c 2023-04-02 11:00:00.000000000 +0000 @@ -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) { - 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) + 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 = 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; + } + + main_loop: + if (p >= lim) + goto fin; + for (;;) + { + 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; } - else + + 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; { - mask = (mask >> 1) | 4; - pos++; + 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 -Nru 7zip-22.01+dfsg/C/Bra.c 7zip-23.01+dfsg/C/Bra.c --- 7zip-22.01+dfsg/C/Bra.c 2021-02-09 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Bra.c 2023-04-02 11:00:00.000000000 +0000 @@ -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) + +#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 -SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) + +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) + +#ifdef Z7_CPU_FAST_ROTATE_SUPPORTED +#define BR_SPARC_USE_ROTATE +#endif -SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) +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 -Nru 7zip-22.01+dfsg/C/Bra.h 7zip-23.01+dfsg/C/Bra.h --- 7zip-22.01+dfsg/C/Bra.h 2013-01-18 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Bra.h 2023-04-02 11:00:00.000000000 +0000 @@ -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 -/* -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 +#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) - 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. +/* +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). + +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: - - 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; - } + (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. + +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 -Nru 7zip-22.01+dfsg/C/BraIA64.c 7zip-23.01+dfsg/C/BraIA64.c --- 7zip-22.01+dfsg/C/BraIA64.c 2017-01-28 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/BraIA64.c 2023-02-20 10:00:00.000000000 +0000 @@ -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 -Nru 7zip-22.01+dfsg/C/BwtSort.c 7zip-23.01+dfsg/C/BwtSort.c --- 7zip-22.01+dfsg/C/BwtSort.c 2021-04-01 18:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/BwtSort.c 2023-04-02 11:00:00.000000000 +0000 @@ -1,5 +1,5 @@ /* BwtSort.c -- BWT block sorting -2021-04-01 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -8,8 +8,6 @@ /* #define BLOCK_SORT_USE_HEAP_SORT */ -#define NO_INLINE MY_FAST_CALL - /* Don't change it !!! */ #define kNumHashBytes 2 #define kNumHashValues (1 << (kNumHashBytes * 8)) @@ -60,7 +58,10 @@ returns: 1 - if there are groups, 0 - no more groups */ -static UInt32 NO_INLINE SortGroup(UInt32 BlockSize, UInt32 NumSortedBytes, UInt32 groupOffset, UInt32 groupSize, int NumRefBits, UInt32 *Indices +static +UInt32 +Z7_FASTCALL +SortGroup(UInt32 BlockSize, UInt32 NumSortedBytes, UInt32 groupOffset, UInt32 groupSize, int NumRefBits, UInt32 *Indices #ifndef BLOCK_SORT_USE_HEAP_SORT , UInt32 left, UInt32 range #endif @@ -72,7 +73,7 @@ { /* #ifndef BLOCK_SORT_EXTERNAL_FLAGS - SetFinishedGroupSize(ind2, 1); + SetFinishedGroupSize(ind2, 1) #endif */ return 0; @@ -463,7 +464,7 @@ Indices[(size_t)(i - finishedGroupSize) + 1] &= kIndexMask; { UInt32 newGroupSize = groupSize + finishedGroupSize; - SetFinishedGroupSize(Indices + i - finishedGroupSize, newGroupSize); + SetFinishedGroupSize(Indices + i - finishedGroupSize, newGroupSize) finishedGroupSize = newGroupSize; } i += groupSize; diff -Nru 7zip-22.01+dfsg/C/BwtSort.h 7zip-23.01+dfsg/C/BwtSort.h --- 7zip-22.01+dfsg/C/BwtSort.h 2013-01-18 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/BwtSort.h 2023-03-03 10:00:00.000000000 +0000 @@ -1,8 +1,8 @@ /* BwtSort.h -- BWT block sorting -2013-01-18 : Igor Pavlov : Public domain */ +2023-03-03 : Igor Pavlov : Public domain */ -#ifndef __BWT_SORT_H -#define __BWT_SORT_H +#ifndef ZIP7_INC_BWT_SORT_H +#define ZIP7_INC_BWT_SORT_H #include "7zTypes.h" diff -Nru 7zip-22.01+dfsg/C/Compiler.h 7zip-23.01+dfsg/C/Compiler.h --- 7zip-22.01+dfsg/C/Compiler.h 2021-01-21 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Compiler.h 2023-04-02 11:00:00.000000000 +0000 @@ -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 -Nru 7zip-22.01+dfsg/C/CpuArch.c 7zip-23.01+dfsg/C/CpuArch.c --- 7zip-22.01+dfsg/C/CpuArch.c 2021-07-13 09:10:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/CpuArch.c 2023-05-18 08:00:00.000000000 +0000 @@ -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 False; -#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 True; } -static const UInt32 kVendors[][3] = +/* +static const UInt32 kVendors[][1] = +{ + { 0x756E6547 }, // , 0x49656E69, 0x6C65746E }, + { 0x68747541 }, // , 0x69746E65, 0x444D4163 }, + { 0x746E6543 } // , 0x48727561, 0x736C7561 } +}; +*/ + +/* +typedef struct { - { 0x756E6547, 0x49656E69, 0x6C65746E}, - { 0x68747541, 0x69746E65, 0x444D4163}, - { 0x746E6543, 0x48727561, 0x736C7561} + 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 @@ BoolInt CPU_Is_InOrder() { Cx86cpuid p; - int firm; UInt32 family, model; if (!x86cpuid_CheckAndRead(&p)) return True; - 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 True; + return False; // 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 False; - 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 False; #else @@ -232,94 +377,300 @@ #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 False; - if (p.maxFunc < 7) + if (z7_x86_cpuid_GetMaxFunc() < 7) return False; { - 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 -BoolInt CPU_IsSupported_AVX2() +#if defined(ATTRIB_XGETBV) +#include +#endif + + +// 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 False; + /* 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 False; + */ #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 False; + } + + /* 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 False; - if (p.maxFunc < 7) + if (z7_x86_cpuid_GetMaxFunc() < 7) return False; { - 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 False; - #endif - - if (!x86cpuid_CheckAndRead(&p)) - return False; - if (p.maxFunc < 7) + if (z7_x86_cpuid_GetMaxFunc() < 7) return False; { - 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_PageGB() +BoolInt CPU_IsSupported_PageGB(void) { - Cx86cpuid cpuid; - if (!x86cpuid_CheckAndRead(&cpuid)) - return False; + 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 False; - } - { - 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 @@ #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 @@ } } */ +/* + 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 @@ #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 -Nru 7zip-22.01+dfsg/C/CpuArch.h 7zip-23.01+dfsg/C/CpuArch.h --- 7zip-22.01+dfsg/C/CpuArch.h 2022-07-15 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/CpuArch.h 2023-04-02 12:00:00.000000000 +0000 @@ -1,8 +1,8 @@ /* CpuArch.h -- CPU specific code -2022-07-15 : 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 @@ || 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 @@ #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 @@ || defined(__PPC__) \ || defined(_POWER) +#define MY_CPU_PPC_OR_PPC64 + #if defined(__ppc64__) \ || defined(__powerpc64__) \ || defined(_LP64) \ @@ -197,6 +207,9 @@ #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 @@ -253,6 +266,67 @@ +#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) @@ -272,13 +346,11 @@ #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 @@ -305,51 +377,26 @@ #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) ( \ @@ -358,8 +405,6 @@ ((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); \ @@ -368,50 +413,83 @@ #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); } + +#define GetUi32a(p) GetUi32(p) +#define GetUi16a(p) GetUi16(p) +#define SetUi32a(p, v) SetUi32(p, v) +#define SetUi16a(p, v) SetUi16(p, v) -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 -}; - -void MyCPUID(UInt32 function, UInt32 *a, UInt32 *b, UInt32 *c, UInt32 *d); - -BoolInt x86cpuid_CheckAndRead(Cx86cpuid *p); -int x86cpuid_GetFirm(const Cx86cpuid *p); - -#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) +#elif defined(MY_CPU_LE) + +#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); } + +#define GetBe32a(p) GetBe32(p) +#define GetBe16a(p) GetBe16(p) +#define SetBe32a(p, v) SetBe32(p, v) +#define SetBe16a(p, v) SetBe16(p, v) + +#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); @@ -436,8 +514,8 @@ #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 -Nru 7zip-22.01+dfsg/C/Delta.h 7zip-23.01+dfsg/C/Delta.h --- 7zip-22.01+dfsg/C/Delta.h 2013-01-18 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Delta.h 2023-03-03 10:00:00.000000000 +0000 @@ -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 -Nru 7zip-22.01+dfsg/C/DllSecur.c 7zip-23.01+dfsg/C/DllSecur.c --- 7zip-22.01+dfsg/C/DllSecur.c 2022-07-15 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/DllSecur.c 2023-04-02 12:00:00.000000000 +0000 @@ -1,18 +1,28 @@ /* DllSecur.c -- DLL loading security -2022-07-15 : 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) - #pragma GCC diagnostic ignored "-Wcast-function-type" +#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); @@ -20,95 +30,82 @@ #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 -// #define MY_CAST_FUNC (void(*)()) -#define MY_CAST_FUNC +#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 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 -Nru 7zip-22.01+dfsg/C/DllSecur.h 7zip-23.01+dfsg/C/DllSecur.h --- 7zip-22.01+dfsg/C/DllSecur.h 2021-01-22 19:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/DllSecur.h 2023-03-03 10:00:00.000000000 +0000 @@ -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 -Nru 7zip-22.01+dfsg/C/HuffEnc.c 7zip-23.01+dfsg/C/HuffEnc.c --- 7zip-22.01+dfsg/C/HuffEnc.c 2021-02-09 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/HuffEnc.c 2023-03-04 15:00:00.000000000 +0000 @@ -1,5 +1,5 @@ /* HuffEnc.c -- functions for Huffman encoding -2021-02-09 : Igor Pavlov : Public domain */ +2023-03-04 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -106,7 +106,7 @@ p[--e] &= MASK; lenCounters[1] = 2; - while (e > 0) + while (e != 0) { UInt32 len = (p[p[--e] >> NUM_BITS] >> NUM_BITS) + 1; p[e] = (p[e] & MASK) | (len << NUM_BITS); @@ -146,3 +146,9 @@ } } } + +#undef kMaxLen +#undef NUM_BITS +#undef MASK +#undef NUM_COUNTERS +#undef HUFFMAN_SPEED_OPT diff -Nru 7zip-22.01+dfsg/C/HuffEnc.h 7zip-23.01+dfsg/C/HuffEnc.h --- 7zip-22.01+dfsg/C/HuffEnc.h 2013-01-18 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/HuffEnc.h 2023-03-05 17:00:00.000000000 +0000 @@ -1,8 +1,8 @@ /* HuffEnc.h -- Huffman encoding -2013-01-18 : Igor Pavlov : Public domain */ +2023-03-05 : Igor Pavlov : Public domain */ -#ifndef __HUFF_ENC_H -#define __HUFF_ENC_H +#ifndef ZIP7_INC_HUFF_ENC_H +#define ZIP7_INC_HUFF_ENC_H #include "7zTypes.h" diff -Nru 7zip-22.01+dfsg/C/LzFind.c 7zip-23.01+dfsg/C/LzFind.c --- 7zip-22.01+dfsg/C/LzFind.c 2021-11-29 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/LzFind.c 2023-03-14 18:00:00.000000000 +0000 @@ -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 @@ { 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 @@ #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 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 @@ 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 @@ 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 @@ // #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 @@ -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 @@ 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 @@ p->cutValue = 32; p->btMode = 1; p->numHashBytes = 4; + p->numHashBytes_Min = 2; + p->numHashOutBits = 0; p->bigHash = 0; } @@ -222,8 +231,10 @@ 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 @@ } } +#undef kCrcPoly + static void MatchFinder_FreeThisClassMemory(CMatchFinder *p, ISzAllocPtr alloc) { ISzAlloc_Free(alloc, p->hash); @@ -252,7 +265,7 @@ 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 @@ } +// 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 @@ 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; + } + } + 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 = hs; - hs++; - /* - hs4 = (1 << 20); - if (hs4 > hs) - hs4 = hs; - // hs4 = (1 << 16); // for test - p->hash4Mask = hs4 - 1; - */ + 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 @@ if (p->hash) { - p->son = p->hash + p->hashSizeSum; + p->son = p->hash + hashSizeSum; return 1; } } @@ -470,7 +552,8 @@ 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 @@ #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 @@ #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 @@ #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 */ + +#if defined(__clang__) +#include +#include +#endif -#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 +// 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); -MY_NO_INLINE +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 @@ #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 @@ #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 @@ } 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 @@ // 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 @@ 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 @@ /* (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 @@ } -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 @@ #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 @@ 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 @@ #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 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 @@ 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 @@ UInt32 *hash; GET_MATCHES_HEADER(3) - HASH3_CALC; + HASH3_CALC hash = p->hash; pos = p->pos; @@ -1107,7 +1191,7 @@ if (maxLen == lenLimit) { SkipMatchesSpec(MF_PARAMS(p)); - MOVE_POS_RET; + MOVE_POS_RET } } @@ -1123,7 +1207,7 @@ UInt32 *hash; GET_MATCHES_HEADER(4) - HASH4_CALC; + HASH4_CALC hash = p->hash; pos = p->pos; @@ -1190,7 +1274,7 @@ UInt32 *hash; GET_MATCHES_HEADER(5) - HASH5_CALC; + HASH5_CALC hash = p->hash; pos = p->pos; @@ -1246,7 +1330,7 @@ if (maxLen == lenLimit) { SkipMatchesSpec(MF_PARAMS(p)); - MOVE_POS_RET; + MOVE_POS_RET } break; } @@ -1263,7 +1347,7 @@ UInt32 *hash; GET_MATCHES_HEADER(4) - HASH4_CALC; + HASH4_CALC hash = p->hash; pos = p->pos; @@ -1314,12 +1398,12 @@ 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 @@ UInt32 *hash; GET_MATCHES_HEADER(5) - HASH5_CALC; + HASH5_CALC hash = p->hash; pos = p->pos; @@ -1386,19 +1470,19 @@ 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 @@ { SKIP_HEADER(2) { - HASH2_CALC; + HASH2_CALC curMatch = p->hash[hv]; p->hash[hv] = p->pos; } @@ -1420,7 +1504,7 @@ { SKIP_HEADER(3) { - HASH_ZIP_CALC; + HASH_ZIP_CALC curMatch = p->hash[hv]; p->hash[hv] = p->pos; } @@ -1433,7 +1517,7 @@ { UInt32 h2; UInt32 *hash; - HASH3_CALC; + HASH3_CALC hash = p->hash; curMatch = (hash + kFix3HashSize)[hv]; hash[h2] = @@ -1448,7 +1532,7 @@ { UInt32 h2, h3; UInt32 *hash; - HASH4_CALC; + HASH4_CALC hash = p->hash; curMatch = (hash + kFix4HashSize)[hv]; hash [h2] = @@ -1464,7 +1548,7 @@ { UInt32 h2, h3; UInt32 *hash; - HASH5_CALC; + HASH5_CALC hash = p->hash; curMatch = (hash + kFix5HashSize)[hv]; hash [h2] = @@ -1478,7 +1562,7 @@ #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 @@ HC_SKIP_HEADER(4) UInt32 h2, h3; - HASH4_CALC; + HASH4_CALC curMatch = (hash + kFix4HashSize)[hv]; hash [h2] = (hash + kFix3HashSize)[h3] = @@ -1540,7 +1624,7 @@ { HC_SKIP_HEADER(3) - HASH_ZIP_CALC; + HASH_ZIP_CALC curMatch = hash[hv]; hash[hv] = pos; @@ -1590,17 +1674,17 @@ -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 @@ 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 -Nru 7zip-22.01+dfsg/C/LzFind.h 7zip-23.01+dfsg/C/LzFind.h --- 7zip-22.01+dfsg/C/LzFind.h 2021-07-13 08:52:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/LzFind.h 2023-03-04 17:00:00.000000000 +0000 @@ -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 @@ 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 @@ UInt32 hashMask; UInt32 cutValue; - Byte *bufferBase; - ISeqInStream *stream; + Byte *bufBase; + ISeqInStreamPtr stream; UInt32 blockSize; UInt32 keepSizeBefore; @@ -43,7 +43,9 @@ 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_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 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 -Nru 7zip-22.01+dfsg/C/LzFindMt.c 7zip-23.01+dfsg/C/LzFindMt.c --- 7zip-22.01+dfsg/C/LzFindMt.c 2021-12-21 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/LzFindMt.c 2023-04-02 12:00:00.000000000 +0000 @@ -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 @@ 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 @@ */ -MY_NO_INLINE +Z7_NO_INLINE static void MtSync_Construct(CMtSync *p) { p->affinity = 0; p->wasCreated = False; p->csWasInitialized = False; p->csWasEntered = False; - Thread_Construct(&p->thread); + Thread_CONSTRUCT(&p->thread) Event_Construct(&p->canStart); Event_Construct(&p->wasStopped); Semaphore_Construct(&p->freeSemaphore); @@ -116,7 +116,7 @@ (p)->csWasEntered = False; } -MY_NO_INLINE +Z7_NO_INLINE static UInt32 MtSync_GetNextBlock(CMtSync *p) { UInt32 numBlocks = 0; @@ -140,14 +140,14 @@ // 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 @@ } -MY_NO_INLINE +Z7_NO_INLINE static void MtSync_Destruct(CMtSync *p) { PRF(printf("\nMtSync_Destruct %p\n", p)); @@ -220,11 +220,11 @@ // #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 @@ if (p->wasCreated) return SZ_OK; - RINOK_THREAD(CriticalSection_Init(&p->cs)); + RINOK_THREAD(CriticalSection_Init(&p->cs)) p->csWasInitialized = True; p->csWasEntered = False; - 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 = True; p->exit = True; /* p->exit is unused before (canStart) Event. @@ -264,13 +264,13 @@ else wres = Thread_Create(&p->thread, startAddress, obj); - RINOK_THREAD(wres); + RINOK_THREAD(wres) p->wasCreated = True; 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 @@ 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 @@ */ -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 @@ } -MY_NO_INLINE +Z7_NO_INLINE static void BtThreadFunc(CMatchFinderMt *mt) { CMtSync *p = &mt->btSync; @@ -864,15 +864,15 @@ 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 @@ } -MY_NO_INLINE +Z7_NO_INLINE static UInt32 MatchFinderMt_GetNextBlock_Bt(CMatchFinderMt *p) { if (p->failure_LZ_BT) @@ -1163,7 +1163,7 @@ */ -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 @@ (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 @@ } 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 @@ d[0] = 2; d += 2; } - #endif + // #endif if (c3 >= matchMinPos && cur[(ptrdiff_t)c3 - (ptrdiff_t)m] == cur[0]) { @@ -1228,7 +1227,7 @@ 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* 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* 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 @@ break; } } + +#undef RINOK_THREAD +#undef PRF +#undef MF +#undef GetUi24hi_from32 +#undef LOCK_BUFFER +#undef UNLOCK_BUFFER diff -Nru 7zip-22.01+dfsg/C/LzFindMt.h 7zip-23.01+dfsg/C/LzFindMt.h --- 7zip-22.01+dfsg/C/LzFindMt.h 2021-07-12 11:30:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/LzFindMt.h 2023-03-05 17:00:00.000000000 +0000 @@ -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 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 -Nru 7zip-22.01+dfsg/C/LzFindOpt.c 7zip-23.01+dfsg/C/LzFindOpt.c --- 7zip-22.01+dfsg/C/LzFindOpt.c 2021-07-14 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/LzFindOpt.c 2023-04-02 12:00:00.000000000 +0000 @@ -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 @@ // #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 @@ 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 @@ /* 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 -Nru 7zip-22.01+dfsg/C/LzHash.h 7zip-23.01+dfsg/C/LzHash.h --- 7zip-22.01+dfsg/C/LzHash.h 2019-10-30 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/LzHash.h 2023-03-05 17:00:00.000000000 +0000 @@ -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 -Nru 7zip-22.01+dfsg/C/Lzma2Dec.c 7zip-23.01+dfsg/C/Lzma2Dec.c --- 7zip-22.01+dfsg/C/Lzma2Dec.c 2021-02-09 15:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Lzma2Dec.c 2023-03-03 12:00:00.000000000 +0000 @@ -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 @@ 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 @@ 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 @@ Lzma2Dec_FreeProbs(&p, alloc); return res; } + +#undef PRF diff -Nru 7zip-22.01+dfsg/C/Lzma2Dec.h 7zip-23.01+dfsg/C/Lzma2Dec.h --- 7zip-22.01+dfsg/C/Lzma2Dec.h 2018-02-19 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Lzma2Dec.h 2023-03-03 12:00:00.000000000 +0000 @@ -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 @@ 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 @@ 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 -Nru 7zip-22.01+dfsg/C/Lzma2DecMt.c 7zip-23.01+dfsg/C/Lzma2DecMt.c --- 7zip-22.01+dfsg/C/Lzma2DecMt.c 2021-04-01 18:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Lzma2DecMt.c 2023-04-13 08:00:00.000000000 +0000 @@ -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 @@ -#ifndef _7ZIP_ST +#ifndef Z7_ST /* ---------- CLzma2DecMtThread ---------- */ @@ -81,7 +81,7 @@ /* ---------- CLzma2DecMt ---------- */ -typedef struct +struct CLzma2DecMt { // ISzAllocPtr alloc; ISzAllocPtr allocMid; @@ -90,9 +90,9 @@ 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 @@ 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 @@ // Lzma2DecMtProps_Init(&p->props); - #ifndef _7ZIP_ST + #ifndef Z7_ST p->mtc_WasConstructed = False; { 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 = False; @@ -156,16 +155,16 @@ } #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 @@ } -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 @@ } { 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 @@ #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 @@ { if (!t->dec_created) { - Lzma2Dec_Construct(&t->dec); + Lzma2Dec_CONSTRUCT(&t->dec) t->dec_created = True; AlignOffsetAlloc_CreateVTable(&t->alloc); { @@ -297,7 +298,7 @@ // 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 @@ 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 @@ 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 @@ 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 @@ } t->dec.decoder.dic = dest; - t->dec.decoder.dicBufSize = t->outPreSize; + t->dec.decoder.dicBufSize = (SizeT)t->outPreSize; t->needInit = True; @@ -462,7 +463,7 @@ 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 @@ { 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 @@ UNUSED_VAR(srcSize) UNUSED_VAR(isCross) - PRF_STR_INT_2("Write", coderIndex, srcSize); + PRF_STR_INT_2("Write", coderIndex, srcSize) *needContinue = False; *canRecode = True; @@ -588,7 +589,7 @@ *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 @@ { if (!p->dec_created) { - Lzma2Dec_Construct(&p->dec); + Lzma2Dec_CONSTRUCT(&p->dec) p->dec_created = True; } - 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_Decode_ST(CLzma2DecMt *p - #ifndef _7ZIP_ST + #ifndef Z7_ST , BoolInt tMode #endif ) @@ -646,7 +647,7 @@ CLzma2Dec *dec; - #ifndef _7ZIP_ST + #ifndef Z7_ST if (tMode) { Lzma2DecMt_FreeOutBufs(p); @@ -654,7 +655,7 @@ } #endif - RINOK(Lzma2Dec_Prepare_ST(p)); + RINOK(Lzma2Dec_Prepare_ST(p)) dec = &p->dec; @@ -681,7 +682,7 @@ if (inPos == inLim) { - #ifndef _7ZIP_ST + #ifndef Z7_ST if (tMode) { inData = MtDec_Read(&p->mtc, &inLim); @@ -710,7 +711,7 @@ { 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 @@ } } - inProcessed = inLim - inPos; + inProcessed = (SizeT)(inLim - inPos); res = Lzma2Dec_DecodeToDic(dec, dicPos + size, inData + inPos, &inProcessed, finishMode, &status); @@ -755,7 +756,7 @@ dec->decoder.dicPos = 0; wrPos = dec->decoder.dicPos; - RINOK(res2); + RINOK(res2) if (needStop) { @@ -788,7 +789,7 @@ 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 @@ -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 @@ *isMT = False; - #ifndef _7ZIP_ST + #ifndef Z7_ST tMode = False; @@ -939,7 +940,7 @@ p->readWasFinished = p->mtc.readWasFinished; p->inProcessed = p->mtc.inProcessed; - PRF_STR("----- decoding ST -----"); + PRF_STR("----- decoding ST -----") } } @@ -950,7 +951,7 @@ { SRes res = Lzma2Dec_Decode_ST(p - #ifndef _7ZIP_ST + #ifndef Z7_ST , tMode #endif ); @@ -967,7 +968,7 @@ 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 @@ /* ---------- 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_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 @@ 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 @@ return readRes; } } + +#undef PRF +#undef PRF_STR +#undef PRF_STR_INT_2 diff -Nru 7zip-22.01+dfsg/C/Lzma2DecMt.h 7zip-23.01+dfsg/C/Lzma2DecMt.h --- 7zip-22.01+dfsg/C/Lzma2DecMt.h 2018-02-17 14:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Lzma2DecMt.h 2023-04-13 08:00:00.000000000 +0000 @@ -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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 -Nru 7zip-22.01+dfsg/C/Lzma2Enc.c 7zip-23.01+dfsg/C/Lzma2Enc.c --- 7zip-22.01+dfsg/C/Lzma2Enc.c 2021-02-09 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Lzma2Enc.c 2023-04-13 08:00:00.000000000 +0000 @@ -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 @@ 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 @@ { 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 = True; } @@ -111,23 +111,23 @@ } -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 @@ 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 @@ { 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ } -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 @@ /* ---------- Lzma2 ---------- */ -typedef struct +struct CLzma2Enc { Byte propEncoded; CLzma2EncProps props; @@ -363,23 +363,22 @@ 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 @@ 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 = False; { 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 @@ #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 @@ } - #ifndef _7ZIP_ST + #ifndef Z7_ST if (p->mtCoder_WasConstructed) { MtCoder_Destruct(&p->mtCoder); @@ -458,13 +458,13 @@ 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 @@ } -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 @@ 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 @@ } } - 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 @@ 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 @@ &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 @@ inData + (size_t)unpackTotal, inSizeCur, LZMA2_KEEP_WINDOW_SIZE, me->alloc, - me->allocBig)); + me->allocBig)) } for (;;) @@ -621,7 +621,7 @@ unpackTotal += p->srcPos; - RINOK(res); + RINOK(res) if (p->srcPos != (inStream ? limitedInStream.processed : inSizeCur)) return SZ_ERROR_FAIL; @@ -652,12 +652,12 @@ -#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_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 @@ -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 @@ { unsigned i; - for (i = 0; i < MTCODER__THREADS_MAX; i++) + for (i = 0; i < MTCODER_THREADS_MAX; i++) p->coders[i].propsAreSet = False; } - #ifndef _7ZIP_ST + #ifndef Z7_ST if (p->props.numBlockThreads_Reduced > 1) { @@ -772,7 +772,7 @@ 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 @@ 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 @@ True, /* finished */ progress); } + +#undef PRF diff -Nru 7zip-22.01+dfsg/C/Lzma2Enc.h 7zip-23.01+dfsg/C/Lzma2Enc.h --- 7zip-22.01+dfsg/C/Lzma2Enc.h 2017-07-27 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Lzma2Enc.h 2023-04-13 08:00:00.000000000 +0000 @@ -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 @@ 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 @@ 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 -Nru 7zip-22.01+dfsg/C/Lzma86Dec.c 7zip-23.01+dfsg/C/Lzma86Dec.c --- 7zip-22.01+dfsg/C/Lzma86Dec.c 2016-05-16 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Lzma86Dec.c 2023-03-03 13:00:00.000000000 +0000 @@ -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 @@ 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 -Nru 7zip-22.01+dfsg/C/Lzma86Enc.c 7zip-23.01+dfsg/C/Lzma86Enc.c --- 7zip-22.01+dfsg/C/Lzma86Enc.c 2021-01-26 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Lzma86Enc.c 2023-03-03 13:00:00.000000000 +0000 @@ -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 @@ 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 -Nru 7zip-22.01+dfsg/C/Lzma86.h 7zip-23.01+dfsg/C/Lzma86.h --- 7zip-22.01+dfsg/C/Lzma86.h 2013-01-18 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Lzma86.h 2023-03-03 13:00:00.000000000 +0000 @@ -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 -Nru 7zip-22.01+dfsg/C/LzmaDec.c 7zip-23.01+dfsg/C/LzmaDec.c --- 7zip-22.01+dfsg/C/LzmaDec.c 2021-04-01 18:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/LzmaDec.c 2023-04-07 18:00:00.000000000 +0000 @@ -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 @@ */ -#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 @@ 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 @@ { 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 @@ 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 @@ } { - 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ distance++; do { - REV_BIT_VAR(prob, distance, m); + REV_BIT_VAR(prob, distance, m) } while (--numDirectBits); distance -= m; @@ -514,10 +514,10 @@ 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 @@ } while (dicPos < limit && buf < bufLimit); - NORMALIZE; + NORMALIZE p->buf = buf; p->range = range; @@ -613,7 +613,7 @@ -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 @@ (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 @@ 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 @@ 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 @@ 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 @@ unsigned m = 1; do { - REV_BIT_CHECK(prob, i, m); + REV_BIT_CHECK(prob, i, m) } while (--numDirectBits); } @@ -897,7 +897,7 @@ } break; } - NORMALIZE_CHECK; + NORMALIZE_CHECK *bufOut = buf; return res; @@ -943,7 +943,7 @@ */ -#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 @@ } if (p->remainLen != 0) { - RETURN__NOT_FINISHED__FOR_FINISH; + RETURN_NOT_FINISHED_FOR_FINISH } checkEndMarkNow = 1; } @@ -1072,7 +1072,7 @@ 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 @@ (*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 @@ 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 @@ { 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 @@ *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 -Nru 7zip-22.01+dfsg/C/LzmaDec.h 7zip-23.01+dfsg/C/LzmaDec.h --- 7zip-22.01+dfsg/C/LzmaDec.h 2020-03-19 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/LzmaDec.h 2023-04-02 12:00:00.000000000 +0000 @@ -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 @@ #define LZMA_PROPS_SIZE 5 -typedef struct _CLzmaProps +typedef struct { Byte lc; Byte lp; @@ -73,7 +73,8 @@ 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 -Nru 7zip-22.01+dfsg/C/LzmaEnc.c 7zip-23.01+dfsg/C/LzmaEnc.c --- 7zip-22.01+dfsg/C/LzmaEnc.c 2022-07-15 06:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/LzmaEnc.c 2023-04-13 08:00:00.000000000 +0000 @@ -1,5 +1,5 @@ /* LzmaEnc.c -- LZMA Encoder -2022-07-15: 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 @@ /* 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 @@ 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 @@ if (p->numThreads < 0) p->numThreads = - #ifndef _7ZIP_ST + #ifndef Z7_ST ((p->btMode && p->algo) ? 2 : 1); #else 1; @@ -293,7 +294,7 @@ #define kNumFullDistances (1 << (kEndPosModelIndex >> 1)) typedef -#ifdef _LZMA_PROB32 +#ifdef Z7_LZMA_PROB32 UInt32 #else UInt16 @@ -350,7 +351,7 @@ Byte *buf; Byte *bufLim; Byte *bufBase; - ISeqOutStream *outStream; + ISeqOutStreamPtr outStream; UInt64 processed; SRes res; } CRangeEnc; @@ -383,7 +384,7 @@ typedef UInt32 CProbPrice; -typedef struct +struct CLzmaEnc { void *matchFinderObj; IMatchFinder2 matchFinder; @@ -426,7 +427,7 @@ 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 @@ // we suppose that we have 8-bytes alignment after CMatchFinder - #ifndef _7ZIP_ST + #ifndef Z7_ST Byte pad[128]; #endif @@ -479,77 +480,59 @@ 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)); +// #define GET_CLzmaEnc_p CLzmaEnc *p = (CLzmaEnc*)(void *)p; +// #define GET_const_CLzmaEnc_p const CLzmaEnc *p = (const CLzmaEnc*)(const void *)p; -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; +#define COPY_ARR(dest, src, arr) memcpy((dest)->arr, (src)->arr, sizeof((src)->arr)); - COPY_ARR(dest, p, reps); +#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)); - 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)); +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 @@ p->fastMode = (props.algo == 0); // p->_maxMode = True; MFB.btMode = (Byte)(props.btMode ? 1 : 0); + // MFB.btMode = (Byte)(props.btMode); { unsigned numHashBytes = 4; if (props.btMode) @@ -595,13 +579,15 @@ 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 @@ } -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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ #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 @@ 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 @@ 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 @@ { 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 @@ } -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 @@ + 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 @@ 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 @@ 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 @@ else { unsigned slot; - GetPosSlot2(dist, slot); + GetPosSlot2(dist, slot) price += p->alignPrices[dist & kAlignMask]; price += p->posSlotPrices[lenToPosState][slot]; } @@ -1486,7 +1472,7 @@ unsigned delta = best - cur; if (delta != 0) { - MOVE_POS(p, delta); + MOVE_POS(p, delta) } } cur = best; @@ -1633,7 +1619,7 @@ { nextOpt->price = litPrice; nextOpt->len = 1; - MakeAs_Lit(nextOpt); + MakeAs_Lit(nextOpt) nextIsLit = True; } } @@ -1667,7 +1653,7 @@ { nextOpt->price = shortRepPrice; nextOpt->len = 1; - MakeAs_ShortRep(nextOpt); + MakeAs_ShortRep(nextOpt) nextIsLit = False; } } @@ -1871,7 +1857,7 @@ dist = MATCHES[(size_t)offs + 1]; // if (dist >= kNumFullDistances) - GetPosSlot2(dist, posSlot); + GetPosSlot2(dist, posSlot) for (len = /*2*/ startLen; ; len++) { @@ -1962,7 +1948,7 @@ break; dist = MATCHES[(size_t)offs + 1]; // if (dist >= kNumFullDistances) - GetPosSlot2(dist, posSlot); + GetPosSlot2(dist, posSlot) } } } @@ -2138,7 +2124,7 @@ { 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 @@ { 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 @@ 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 @@ 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 @@ } -MY_NO_INLINE static SRes Flush(CLzmaEnc *p, UInt32 nowPos) +Z7_NO_INLINE static SRes Flush(CLzmaEnc *p, UInt32 nowPos) { /* ReleaseMFStream(); */ p->finished = True; @@ -2213,7 +2199,7 @@ } -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 FillDistancesPrices(CLzmaEnc *p) +Z7_NO_INLINE static void FillDistancesPrices(CLzmaEnc *p) { // int y; for (y = 0; y < 100; y++) { @@ -2337,7 +2323,7 @@ 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 @@ { 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_Destruct(CLzmaEnc *p, ISzAllocPtr alloc, ISzAllocPtr allocBig) { - #ifndef _7ZIP_ST + #ifndef Z7_ST MatchFinderMt_Destruct(&p->matchFinderMt, allocBig); #endif @@ -2387,21 +2373,22 @@ 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 @@ if (p->finished) return p->result; - RINOK(CheckErrors(p)); + RINOK(CheckErrors(p)) nowPos32 = (UInt32)p->nowPos64; startPos32 = nowPos32; @@ -2473,7 +2460,7 @@ 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 @@ } 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 @@ 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 @@ 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 @@ 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 @@ { 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 @@ 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 @@ (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 @@ p->finished = False; 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 @@ { 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,25 +2936,25 @@ /* -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; } // (desiredPackSize == 0) is not allowed -SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit, +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; @@ -3006,12 +2986,12 @@ } -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]; @@ -3033,7 +3013,7 @@ } } - LzmaEnc_Finish(p); + LzmaEnc_Finish((CLzmaEncHandle)(void *)p); /* if (res == SZ_OK && !Inline_MatchFinder_IsFinishedOK(&MFB)) @@ -3045,21 +3025,22 @@ } -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); @@ -3083,23 +3064,24 @@ 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; @@ -3111,7 +3093,7 @@ 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) { @@ -3120,7 +3102,7 @@ res = SZ_ERROR_FAIL; } - *destLen -= outStream.rem; + *destLen -= (SizeT)outStream.rem; if (outStream.overflow) return SZ_ERROR_OUTPUT_EOF; return res; @@ -3129,9 +3111,9 @@ 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; @@ -3151,10 +3133,10 @@ /* -#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 -Nru 7zip-22.01+dfsg/C/LzmaEnc.h 7zip-23.01+dfsg/C/LzmaEnc.h --- 7zip-22.01+dfsg/C/LzmaEnc.h 2019-10-30 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/LzmaEnc.h 2023-04-13 08:00:00.000000000 +0000 @@ -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 @@ #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 @@ 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 @@ 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 @@ 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 -Nru 7zip-22.01+dfsg/C/LzmaLib.c 7zip-23.01+dfsg/C/LzmaLib.c --- 7zip-22.01+dfsg/C/LzmaLib.c 2015-06-13 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/LzmaLib.c 2023-04-02 12:00:00.000000000 +0000 @@ -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 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 -Nru 7zip-22.01+dfsg/C/LzmaLib.h 7zip-23.01+dfsg/C/LzmaLib.h --- 7zip-22.01+dfsg/C/LzmaLib.h 2021-04-03 07:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/LzmaLib.h 2023-04-02 12:00:00.000000000 +0000 @@ -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 @@ 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 @@ 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 -Nru 7zip-22.01+dfsg/C/MtCoder.c 7zip-23.01+dfsg/C/MtCoder.c --- 7zip-22.01+dfsg/C/MtCoder.c 2021-12-21 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/MtCoder.c 2023-04-13 08:00:00.000000000 +0000 @@ -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 @@ #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 = False; @@ -84,24 +76,6 @@ -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 @@ } 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 @@ 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 @@ 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 @@ 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 @@ t->inBuf = NULL; t->stop = False; 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 @@ 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 @@ 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 @@ 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 @@ p->numBlocksMax = numBlocksMax; p->stopReading = False; - #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] = False; p->numFinishedThreads = 0; #endif @@ -522,12 +496,12 @@ // 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 @@ 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 @@ } #endif + +#undef RINOK_THREAD diff -Nru 7zip-22.01+dfsg/C/MtCoder.h 7zip-23.01+dfsg/C/MtCoder.h --- 7zip-22.01+dfsg/C/MtCoder.h 2018-07-04 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/MtCoder.h 2023-04-13 08:00:00.000000000 +0000 @@ -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 @@ 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 @@ } CMtCoderBlock; -typedef struct _CMtCoder +typedef struct CMtCoder_ { /* input variables */ @@ -79,11 +79,11 @@ 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 @@ 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 @@ 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 -Nru 7zip-22.01+dfsg/C/MtDec.c 7zip-23.01+dfsg/C/MtDec.c --- 7zip-22.01+dfsg/C/MtDec.c 2021-12-21 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/MtDec.c 2023-04-02 12:00:00.000000000 +0000 @@ -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 @@ #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 @@ { 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 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 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 @@ /* - 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 @@ // #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 @@ // 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 @@ { size = p->inBufSize; - res = FullRead(p->inStream, data, &size); + res = SeqInStream_ReadMax(p->inStream, data, &size); // size = 10; // test @@ -615,7 +588,7 @@ // 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 @@ // ---------- WRITE ---------- - RINOK_THREAD(Event_Wait(&t->canWrite)); + RINOK_THREAD(Event_Wait(&t->canWrite)) { BoolInt isErrorMode = False; @@ -801,14 +774,14 @@ 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 @@ return SZ_OK; p->exitThread = True; } - RINOK_THREAD(Event_Set(&p->threads[0].canRead)); + RINOK_THREAD(Event_Set(&p->threads[0].canRead)) } } } @@ -836,7 +809,7 @@ #endif -static THREAD_FUNC_DECL ThreadFunc1(void *pp) +static THREAD_FUNC_DECL MtDec_ThreadFunc1(void *pp) { WRes res; @@ -845,7 +818,7 @@ // 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 @@ 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 @@ { 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 @@ 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 @@ 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 @@ p->exitThread = True; - 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 @@ { 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 @@ MtProgress_Init(&p->mtProgress, p->progress); - // RINOK_THREAD(ArEvent_OptCreate_And_Reset(&p->finishedEvent)); + // RINOK_THREAD(AutoResetEvent_OptCreate_And_Reset(&p->finishedEvent)) p->exitThread = False; p->exitThreadWRes = 0; @@ -1098,7 +1071,7 @@ 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 @@ } #endif + +#undef PRF diff -Nru 7zip-22.01+dfsg/C/MtDec.h 7zip-23.01+dfsg/C/MtDec.h --- 7zip-22.01+dfsg/C/MtDec.h 2020-03-05 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/MtDec.h 2023-04-02 12:00:00.000000000 +0000 @@ -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 _CMtDec +typedef struct CMtDec_ { /* input variables */ @@ -126,11 +126,11 @@ // 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 @@ 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 -Nru 7zip-22.01+dfsg/C/Ppmd7aDec.c 7zip-23.01+dfsg/C/Ppmd7aDec.c --- 7zip-22.01+dfsg/C/Ppmd7aDec.c 2021-04-13 19:22:40.000000000 +0000 +++ 7zip-23.01+dfsg/C/Ppmd7aDec.c 2023-04-02 12:00:00.000000000 +0000 @@ -1,5 +1,5 @@ /* Ppmd7aDec.c -- PPMd7a (PPMdH) 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 Carryless rangecoder (1999): Dmitry Subbotin : Public domain */ @@ -8,8 +8,8 @@ #include "Ppmd7.h" -#define kTop (1 << 24) -#define kBot (1 << 15) +#define kTop ((UInt32)1 << 24) +#define kBot ((UInt32)1 << 15) #define READ_BYTE(p) IByteIn_Read((p)->Stream) @@ -37,9 +37,9 @@ #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 Ppmd7a_RD_Decode(CPpmd7 *p, UInt32 start, UInt32 size) { start *= R->Range; R->Low += start; @@ -48,9 +48,9 @@ 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) Ppmd7a_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)) @@ -70,7 +70,7 @@ 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; if (summFreq > R->Range) return PPMD7_SYM_ERROR; @@ -81,7 +81,7 @@ 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 @@ 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 @@ 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); { @@ -176,7 +176,7 @@ R->Range = (R->Range & ~((UInt32)PPMD_BIN_SCALE - 1)) - 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 @@ { 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 @@ 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 @@ -277,3 +277,19 @@ while (s != s2); } } + +#undef kTop +#undef kBot +#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 -Nru 7zip-22.01+dfsg/C/Ppmd7.c 7zip-23.01+dfsg/C/Ppmd7.c --- 7zip-22.01+dfsg/C/Ppmd7.c 2021-04-13 19:20:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Ppmd7.c 2023-04-02 12:00:00.000000000 +0000 @@ -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 @@ 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 @@ #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 @@ // ---------- 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 *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 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ #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 @@ 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 @@ { 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 @@ { 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 @@ 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 @@ 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 @@ -#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 @@ if (s[0].Freq >= s[-1].Freq) { - SwapStates(s); + SWAP_STATES(s) s--; } } @@ -610,10 +610,10 @@ { /* 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 @@ p->Text = text; if (text >= p->UnitsStart) { - RestartModel(p); + Ppmd7_RestartModel(p); return; } maxSuccessor = REF(text); @@ -645,10 +645,10 @@ 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 @@ 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 @@ 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 @@ -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 @@ *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 @@ { 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 @@ } -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 @@ 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 @@ freq += 4; s->Freq = (Byte)freq; if (freq > MAX_FREQ) - Rescale(p); - NextContext(p); + Ppmd7_Rescale(p); + Ppmd7_NextContext(p); } @@ -1000,7 +1000,7 @@ p->FoundState->Freq = (Byte)(freq + (freq < 128)); p->PrevSuccess = 1; p->RunLength++; - NextContext(p); + Ppmd7_NextContext(p); } */ @@ -1013,7 +1013,7 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 -Nru 7zip-22.01+dfsg/C/Ppmd7Dec.c 7zip-23.01+dfsg/C/Ppmd7Dec.c --- 7zip-22.01+dfsg/C/Ppmd7Dec.c 2021-04-13 19:22:38.000000000 +0000 +++ 7zip-23.01+dfsg/C/Ppmd7Dec.c 2023-04-02 12:00:00.000000000 +0000 @@ -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 @@ #include "Ppmd7.h" -#define kTopValue (1 << 24) +#define kTopValue ((UInt32)1 << 24) #define READ_BYTE(p) IByteIn_Read((p)->Stream) @@ -37,9 +37,9 @@ #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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ // 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 @@ 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 @@ { 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 @@ 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 @@ 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 -Nru 7zip-22.01+dfsg/C/Ppmd7Enc.c 7zip-23.01+dfsg/C/Ppmd7Enc.c --- 7zip-22.01+dfsg/C/Ppmd7Enc.c 2021-04-13 19:22:38.000000000 +0000 +++ 7zip-23.01+dfsg/C/Ppmd7Enc.c 2023-04-02 12:00:00.000000000 +0000 @@ -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 @@ #include "Ppmd7.h" -#define kTopValue (1 << 24) +#define kTopValue ((UInt32)1 << 24) #define R (&p->rc.enc) @@ -20,8 +20,8 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ R->Range -= bound; RC_NORM_LOCAL(p) - PPMD_SetAllBitsIn256Bytes(charMask); + PPMD_SetAllBitsIn256Bytes(charMask) MASK(s->Symbol) = 0; p->PrevSuccess = 0; } @@ -248,14 +248,14 @@ 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 @@ R->Range /= sum; - RC_EncodeFinal(low, freq); + RC_EncodeFinal(low, freq) Ppmd7_Update2(p); return; } @@ -289,21 +289,21 @@ 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 @@ 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 -Nru 7zip-22.01+dfsg/C/Ppmd7.h 7zip-23.01+dfsg/C/Ppmd7.h --- 7zip-22.01+dfsg/C/Ppmd7.h 2021-04-13 18:42:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Ppmd7.h 2023-04-02 12:00:00.000000000 +0000 @@ -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 @@ UInt32 Range; UInt32 Code; UInt32 Low; - IByteIn *Stream; + IByteInPtr Stream; } CPpmd7_RangeDec; @@ -66,7 +66,7 @@ // Byte _dummy_[3]; UInt64 Low; UInt64 CacheSize; - IByteOut *Stream; + IByteOutPtr Stream; } CPpmd7z_RangeEnc; diff -Nru 7zip-22.01+dfsg/C/Ppmd8.c 7zip-23.01+dfsg/C/Ppmd8.c --- 7zip-22.01+dfsg/C/Ppmd8.c 2021-04-13 19:20:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Ppmd8.c 2023-04-02 12:00:00.000000000 +0000 @@ -1,5 +1,5 @@ /* Ppmd8.c -- PPMdI codec -2021-04-13 : Igor Pavlov : Public domain +2023-04-02 : Igor Pavlov : Public domain This code is based on PPMd var.I (2002): Dmitry Shkarin : Public domain */ #include "Precomp.h" @@ -14,7 +14,7 @@ MY_ALIGN(16) static const Byte PPMD8_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 PPMD8_kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051}; #define MAX_FREQ 124 #define UNIT_SIZE 12 @@ -33,7 +33,7 @@ #define ONE_STATE(ctx) Ppmd8Context_OneState(ctx) #define SUFFIX(ctx) CTX((ctx)->Suffix) -typedef CPpmd8_Context * CTX_PTR; +typedef CPpmd8_Context * PPMD8_CTX_PTR; struct CPpmd8_Node_; @@ -114,7 +114,7 @@ #define EMPTY_NODE 0xFFFFFFFF -static void InsertNode(CPpmd8 *p, void *node, unsigned indx) +static void Ppmd8_InsertNode(CPpmd8 *p, void *node, unsigned indx) { ((CPpmd8_Node *)node)->Stamp = EMPTY_NODE; ((CPpmd8_Node *)node)->Next = (CPpmd8_Node_Ref)p->FreeList[indx]; @@ -124,7 +124,7 @@ } -static void *RemoveNode(CPpmd8 *p, unsigned indx) +static void *Ppmd8_RemoveNode(CPpmd8 *p, unsigned indx) { CPpmd8_Node *node = NODE((CPpmd8_Node_Ref)p->FreeList[indx]); p->FreeList[indx] = node->Next; @@ -134,16 +134,16 @@ } -static void SplitBlock(CPpmd8 *p, void *ptr, unsigned oldIndx, unsigned newIndx) +static void Ppmd8_SplitBlock(CPpmd8 *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); + Ppmd8_InsertNode(p, ((Byte *)ptr) + U2B(k), nu - k - 1); } - InsertNode(p, ptr, i); + Ppmd8_InsertNode(p, ptr, i); } @@ -159,7 +159,7 @@ -static void GlueFreeBlocks(CPpmd8 *p) +static void Ppmd8_GlueFreeBlocks(CPpmd8 *p) { /* we use first UInt32 field of 12-bytes UNITs as record type stamp @@ -239,27 +239,27 @@ if (nu == 0) continue; for (; nu > 128; nu -= 128, node += 128) - InsertNode(p, node, PPMD_NUM_INDEXES - 1); + Ppmd8_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); + Ppmd8_InsertNode(p, node + k, (unsigned)nu - k - 1); } - InsertNode(p, node, i); + Ppmd8_InsertNode(p, node, i); } } -MY_NO_INLINE -static void *AllocUnitsRare(CPpmd8 *p, unsigned indx) +Z7_NO_INLINE +static void *Ppmd8_AllocUnitsRare(CPpmd8 *p, unsigned indx) { unsigned i; if (p->GlueCount == 0) { - GlueFreeBlocks(p); + Ppmd8_GlueFreeBlocks(p); if (p->FreeList[indx] != 0) - return RemoveNode(p, indx); + return Ppmd8_RemoveNode(p, indx); } i = indx; @@ -277,17 +277,17 @@ while (p->FreeList[i] == 0); { - void *block = RemoveNode(p, i); - SplitBlock(p, block, i, indx); + void *block = Ppmd8_RemoveNode(p, i); + Ppmd8_SplitBlock(p, block, i, indx); return block; } } -static void *AllocUnits(CPpmd8 *p, unsigned indx) +static void *Ppmd8_AllocUnits(CPpmd8 *p, unsigned indx) { if (p->FreeList[indx] != 0) - return RemoveNode(p, indx); + return Ppmd8_RemoveNode(p, indx); { UInt32 numBytes = U2B(I2U(indx)); Byte *lo = p->LoUnit; @@ -297,11 +297,11 @@ return lo; } } - return AllocUnitsRare(p, indx); + return Ppmd8_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,26 +315,26 @@ return oldPtr; if (p->FreeList[i1] != 0) { - void *ptr = RemoveNode(p, i1); - MyMem12Cpy(ptr, oldPtr, newNU); - InsertNode(p, oldPtr, i0); + void *ptr = Ppmd8_RemoveNode(p, i1); + MEM_12_CPY(ptr, oldPtr, newNU) + Ppmd8_InsertNode(p, oldPtr, i0); return ptr; } - SplitBlock(p, oldPtr, i0, i1); + Ppmd8_SplitBlock(p, oldPtr, i0, i1); return oldPtr; } static void FreeUnits(CPpmd8 *p, void *ptr, unsigned nu) { - InsertNode(p, ptr, U2I(nu)); + Ppmd8_InsertNode(p, ptr, U2I(nu)); } static void SpecialFreeUnit(CPpmd8 *p, void *ptr) { if ((Byte *)ptr != p->UnitsStart) - InsertNode(p, ptr, 0); + Ppmd8_InsertNode(p, ptr, 0); else { #ifdef PPMD8_FREEZE_SUPPORT @@ -352,10 +352,10 @@ void *ptr; if ((Byte *)oldPtr > p->UnitsStart + (1 << 14) || REF(oldPtr) > p->FreeList[indx]) return oldPtr; - ptr = RemoveNode(p, indx); - MyMem12Cpy(ptr, oldPtr, nu); + ptr = Ppmd8_RemoveNode(p, indx); + MEM_12_CPY(ptr, oldPtr, nu) if ((Byte *)oldPtr != p->UnitsStart) - InsertNode(p, oldPtr, indx); + Ppmd8_InsertNode(p, oldPtr, indx); else p->UnitsStart += U2B(I2U(indx)); return ptr; @@ -411,22 +411,22 @@ #define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) -static void SetSuccessor(CPpmd_State *p, CPpmd_Void_Ref v) +static void Ppmd8State_SetSuccessor(CPpmd_State *p, CPpmd_Void_Ref v) { - Ppmd_SET_SUCCESSOR(p, v); + Ppmd_SET_SUCCESSOR(p, v) } #define RESET_TEXT(offs) { p->Text = p->Base + p->AlignOffset + (offs); } -MY_NO_INLINE +Z7_NO_INLINE static -void RestartModel(CPpmd8 *p) +void Ppmd8_RestartModel(CPpmd8 *p) { unsigned i, k, m; memset(p->FreeList, 0, sizeof(p->FreeList)); memset(p->Stamps, 0, sizeof(p->Stamps)); - RESET_TEXT(0); + RESET_TEXT(0) p->HiUnit = p->Text + p->Size; p->LoUnit = p->UnitsStart = p->HiUnit - p->Size / 8 / UNIT_SIZE * 7 * UNIT_SIZE; p->GlueCount = 0; @@ -436,8 +436,8 @@ p->PrevSuccess = 0; { - CPpmd8_Context *mc = (CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */ - CPpmd_State *s = (CPpmd_State *)p->LoUnit; /* AllocUnits(p, PPMD_NUM_INDEXES - 1); */ + CPpmd8_Context *mc = (PPMD8_CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */ + CPpmd_State *s = (CPpmd_State *)p->LoUnit; /* Ppmd8_AllocUnits(p, PPMD_NUM_INDEXES - 1); */ p->LoUnit += U2B(256 / 2); p->MaxContext = p->MinContext = mc; @@ -452,7 +452,7 @@ { s->Symbol = (Byte)i; s->Freq = 1; - SetSuccessor(s, 0); + Ppmd8State_SetSuccessor(s, 0); } } @@ -475,7 +475,7 @@ { unsigned r; UInt16 *dest = p->BinSumm[m] + k; - UInt16 val = (UInt16)(PPMD_BIN_SCALE - kInitBinEsc[k] / (i + 1)); + const UInt16 val = (UInt16)(PPMD_BIN_SCALE - PPMD8_kInitBinEsc[k] / (i + 1)); for (r = 0; r < 64; r += 8) dest[r] = val; } @@ -507,7 +507,7 @@ { p->MaxOrder = maxOrder; p->RestoreMethod = restoreMethod; - RestartModel(p); + Ppmd8_RestartModel(p); } @@ -531,7 +531,7 @@ It increases Escape_Freq for sum of all removed symbols. */ -static void Refresh(CPpmd8 *p, CTX_PTR ctx, unsigned oldNU, unsigned scale) +static void Refresh(CPpmd8 *p, PPMD8_CTX_PTR ctx, unsigned oldNU, unsigned scale) { unsigned i = ctx->NumStats, escFreq, sumFreq, flags; CPpmd_State *s = (CPpmd_State *)ShrinkUnits(p, STATS(ctx), oldNU, (i + 2) >> 1); @@ -581,7 +581,7 @@ } -static void SwapStates(CPpmd_State *t1, CPpmd_State *t2) +static void SWAP_STATES(CPpmd_State *t1, CPpmd_State *t2) { CPpmd_State tmp = *t1; *t1 = *t2; @@ -597,7 +597,7 @@ if the (Union4.Stats) is close to (UnitsStart), it moves it up. */ -static CPpmd_Void_Ref CutOff(CPpmd8 *p, CTX_PTR ctx, unsigned order) +static CPpmd_Void_Ref CutOff(CPpmd8 *p, PPMD8_CTX_PTR ctx, unsigned order) { int ns = ctx->NumStats; unsigned nu; @@ -613,7 +613,7 @@ successor = CutOff(p, CTX(successor), order + 1); else successor = 0; - SetSuccessor(s, successor); + Ppmd8State_SetSuccessor(s, successor); if (successor || order <= 9) /* O_BOUND */ return REF(ctx); } @@ -630,11 +630,11 @@ if ((UInt32)((Byte *)stats - p->UnitsStart) <= (1 << 14) && (CPpmd_Void_Ref)ctx->Union4.Stats <= p->FreeList[indx]) { - void *ptr = RemoveNode(p, indx); + void *ptr = Ppmd8_RemoveNode(p, indx); ctx->Union4.Stats = STATS_REF(ptr); - MyMem12Cpy(ptr, (const void *)stats, nu); + MEM_12_CPY(ptr, (const void *)stats, nu) if ((Byte *)stats != p->UnitsStart) - InsertNode(p, stats, indx); + Ppmd8_InsertNode(p, stats, indx); else p->UnitsStart += U2B(I2U(indx)); stats = ptr; @@ -656,16 +656,16 @@ } else { - SwapStates(s, s2); - SetSuccessor(s2, 0); + SWAP_STATES(s, s2); + Ppmd8State_SetSuccessor(s2, 0); } } else { if (order < p->MaxOrder) - SetSuccessor(s, CutOff(p, CTX(successor), order + 1)); + Ppmd8State_SetSuccessor(s, CutOff(p, CTX(successor), order + 1)); else - SetSuccessor(s, 0); + Ppmd8State_SetSuccessor(s, 0); } } while (--s >= stats); @@ -711,7 +711,7 @@ removes Bin Context without Successor, if suffix of that context is also binary. */ -static CPpmd_Void_Ref RemoveBinContexts(CPpmd8 *p, CTX_PTR ctx, unsigned order) +static CPpmd_Void_Ref RemoveBinContexts(CPpmd8 *p, PPMD8_CTX_PTR ctx, unsigned order) { if (!ctx->NumStats) { @@ -721,7 +721,7 @@ successor = RemoveBinContexts(p, CTX(successor), order + 1); else successor = 0; - SetSuccessor(s, successor); + Ppmd8State_SetSuccessor(s, successor); /* Suffix context can be removed already, since different (high-order) Successors may refer to same context. So we check Flags == 0xFF (Stamp == EMPTY_NODE) */ if (!successor && (!SUFFIX(ctx)->NumStats || SUFFIX(ctx)->Flags == 0xFF)) @@ -737,9 +737,9 @@ { CPpmd_Void_Ref successor = SUCCESSOR(s); if ((Byte *)Ppmd8_GetPtr(p, successor) >= p->UnitsStart && order < p->MaxOrder) - SetSuccessor(s, RemoveBinContexts(p, CTX(successor), order + 1)); + Ppmd8State_SetSuccessor(s, RemoveBinContexts(p, CTX(successor), order + 1)); else - SetSuccessor(s, 0); + Ppmd8State_SetSuccessor(s, 0); } while (--s >= STATS(ctx)); } @@ -767,15 +767,15 @@ #endif -static void RestoreModel(CPpmd8 *p, CTX_PTR ctxError +static void RestoreModel(CPpmd8 *p, PPMD8_CTX_PTR ctxError #ifdef PPMD8_FREEZE_SUPPORT - , CTX_PTR fSuccessor + , PPMD8_CTX_PTR fSuccessor #endif ) { - CTX_PTR c; + PPMD8_CTX_PTR c; CPpmd_State *s; - RESET_TEXT(0); + RESET_TEXT(0) // we go here in cases of error of allocation for context (c1) // Order(MinContext) < Order(ctxError) <= Order(MaxContext) @@ -831,7 +831,7 @@ else #endif if (p->RestoreMethod == PPMD8_RESTORE_METHOD_RESTART || GetUsedMemory(p) < (p->Size >> 1)) - RestartModel(p); + Ppmd8_RestartModel(p); else { while (p->MaxContext->Suffix) @@ -850,8 +850,8 @@ -MY_NO_INLINE -static CTX_PTR CreateSuccessors(CPpmd8 *p, BoolInt skip, CPpmd_State *s1, CTX_PTR c) +Z7_NO_INLINE +static PPMD8_CTX_PTR Ppmd8_CreateSuccessors(CPpmd8 *p, BoolInt skip, CPpmd_State *s1, PPMD8_CTX_PTR c) { CPpmd_Byte_Ref upBranch = (CPpmd_Byte_Ref)SUCCESSOR(p->FoundState); @@ -927,15 +927,15 @@ do { - CTX_PTR c1; + PPMD8_CTX_PTR c1; /* = AllocContext(p); */ if (p->HiUnit != p->LoUnit) - c1 = (CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); + c1 = (PPMD8_CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); else if (p->FreeList[0] != 0) - c1 = (CTX_PTR)RemoveNode(p, 0); + c1 = (PPMD8_CTX_PTR)Ppmd8_RemoveNode(p, 0); else { - c1 = (CTX_PTR)AllocUnitsRare(p, 0); + c1 = (PPMD8_CTX_PTR)Ppmd8_AllocUnitsRare(p, 0); if (!c1) return NULL; } @@ -943,9 +943,9 @@ c1->NumStats = 0; c1->Union2.State2.Symbol = newSym; c1->Union2.State2.Freq = newFreq; - SetSuccessor(ONE_STATE(c1), upBranch); + Ppmd8State_SetSuccessor(ONE_STATE(c1), upBranch); c1->Suffix = REF(c); - SetSuccessor(ps[--numPs], REF(c1)); + Ppmd8State_SetSuccessor(ps[--numPs], REF(c1)); c = c1; } while (numPs != 0); @@ -954,10 +954,10 @@ } -static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c) +static PPMD8_CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, PPMD8_CTX_PTR c) { CPpmd_State *s = NULL; - CTX_PTR c1 = c; + PPMD8_CTX_PTR c1 = c; CPpmd_Void_Ref upBranch = REF(p->Text); #ifdef PPMD8_FREEZE_SUPPORT @@ -967,7 +967,7 @@ ps[numPs++] = p->FoundState; #endif - SetSuccessor(p->FoundState, upBranch); + Ppmd8State_SetSuccessor(p->FoundState, upBranch); p->OrderFall++; for (;;) @@ -985,8 +985,8 @@ #ifdef PPMD8_FREEZE_SUPPORT if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE) { - do { SetSuccessor(ps[--numPs], REF(c)); } while (numPs); - RESET_TEXT(1); + do { Ppmd8State_SetSuccessor(ps[--numPs], REF(c)); } while (numPs); + RESET_TEXT(1) p->OrderFall = 1; } #endif @@ -1014,7 +1014,7 @@ #ifdef PPMD8_FREEZE_SUPPORT ps[numPs++] = s; #endif - SetSuccessor(s, upBranch); + Ppmd8State_SetSuccessor(s, upBranch); p->OrderFall++; } @@ -1022,8 +1022,8 @@ if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE) { c = CTX(SUCCESSOR(s)); - do { SetSuccessor(ps[--numPs], REF(c)); } while (numPs); - RESET_TEXT(1); + do { Ppmd8State_SetSuccessor(ps[--numPs], REF(c)); } while (numPs); + RESET_TEXT(1) p->OrderFall = 1; return c; } @@ -1031,15 +1031,15 @@ #endif if (SUCCESSOR(s) <= upBranch) { - CTX_PTR successor; + PPMD8_CTX_PTR successor; CPpmd_State *s2 = p->FoundState; p->FoundState = s; - successor = CreateSuccessors(p, False, NULL, c); + successor = Ppmd8_CreateSuccessors(p, False, NULL, c); if (!successor) - SetSuccessor(s, 0); + Ppmd8State_SetSuccessor(s, 0); else - SetSuccessor(s, REF(successor)); + Ppmd8State_SetSuccessor(s, REF(successor)); p->FoundState = s2; } @@ -1047,7 +1047,7 @@ CPpmd_Void_Ref successor = SUCCESSOR(s); if (p->OrderFall == 1 && c1 == p->MaxContext) { - SetSuccessor(p->FoundState, successor); + Ppmd8State_SetSuccessor(p->FoundState, successor); p->Text--; } if (successor == 0) @@ -1059,11 +1059,11 @@ void Ppmd8_UpdateModel(CPpmd8 *p); -MY_NO_INLINE +Z7_NO_INLINE void Ppmd8_UpdateModel(CPpmd8 *p) { CPpmd_Void_Ref maxSuccessor, minSuccessor = SUCCESSOR(p->FoundState); - CTX_PTR c; + PPMD8_CTX_PTR c; unsigned s0, ns, fFreq = p->FoundState->Freq; Byte flag, fSymbol = p->FoundState->Symbol; { @@ -1096,7 +1096,7 @@ if (s[0].Freq >= s[-1].Freq) { - SwapStates(&s[0], &s[-1]); + SWAP_STATES(&s[0], &s[-1]); s--; } } @@ -1112,14 +1112,14 @@ c = p->MaxContext; if (p->OrderFall == 0 && minSuccessor) { - CTX_PTR cs = CreateSuccessors(p, True, s, p->MinContext); + PPMD8_CTX_PTR cs = Ppmd8_CreateSuccessors(p, True, s, p->MinContext); if (!cs) { - SetSuccessor(p->FoundState, 0); + Ppmd8State_SetSuccessor(p->FoundState, 0); RESTORE_MODEL(c, CTX(minSuccessor)); return; } - SetSuccessor(p->FoundState, REF(cs)); + Ppmd8State_SetSuccessor(p->FoundState, REF(cs)); p->MinContext = p->MaxContext = cs; return; } @@ -1141,7 +1141,7 @@ if (!minSuccessor) { - CTX_PTR cs = ReduceOrder(p, s, p->MinContext); + PPMD8_CTX_PTR cs = ReduceOrder(p, s, p->MinContext); if (!cs) { RESTORE_MODEL(c, NULL); @@ -1151,7 +1151,7 @@ } else if ((Byte *)Ppmd8_GetPtr(p, minSuccessor) < p->UnitsStart) { - CTX_PTR cs = CreateSuccessors(p, False, s, p->MinContext); + PPMD8_CTX_PTR cs = Ppmd8_CreateSuccessors(p, False, s, p->MinContext); if (!cs) { RESTORE_MODEL(c, NULL); @@ -1169,7 +1169,7 @@ else if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE) { maxSuccessor = minSuccessor; - RESET_TEXT(0); + RESET_TEXT(0) p->OrderFall = 0; } #endif @@ -1219,7 +1219,7 @@ unsigned i = U2I(oldNU); if (i != U2I((size_t)oldNU + 1)) { - void *ptr = AllocUnits(p, i + 1); + void *ptr = Ppmd8_AllocUnits(p, i + 1); void *oldPtr; if (!ptr) { @@ -1227,8 +1227,8 @@ return; } oldPtr = STATS(c); - MyMem12Cpy(ptr, oldPtr, oldNU); - InsertNode(p, oldPtr, i); + MEM_12_CPY(ptr, oldPtr, oldNU) + Ppmd8_InsertNode(p, oldPtr, i); c->Union4.Stats = STATS_REF(ptr); } } @@ -1243,7 +1243,7 @@ else { - CPpmd_State *s = (CPpmd_State*)AllocUnits(p, 0); + CPpmd_State *s = (CPpmd_State*)Ppmd8_AllocUnits(p, 0); if (!s) { RESTORE_MODEL(c, CTX(minSuccessor)); @@ -1255,7 +1255,7 @@ s->Symbol = c->Union2.State2.Symbol; s->Successor_0 = c->Union4.State4.Successor_0; s->Successor_1 = c->Union4.State4.Successor_1; - // SetSuccessor(s, c->Union4.Stats); // call it only for debug purposes to check the order of + // Ppmd8State_SetSuccessor(s, c->Union4.Stats); // call it only for debug purposes to check the order of // (Successor_0 and Successor_1) in LE/BE. c->Union4.Stats = REF(s); if (freq < MAX_FREQ / 4 - 1) @@ -1275,7 +1275,7 @@ UInt32 sf = (UInt32)s0 + sum; s->Symbol = fSymbol; c->NumStats = (Byte)(ns1 + 1); - SetSuccessor(s, maxSuccessor); + Ppmd8State_SetSuccessor(s, maxSuccessor); c->Flags |= flag; if (cf < 6 * sf) { @@ -1299,8 +1299,8 @@ -MY_NO_INLINE -static void Rescale(CPpmd8 *p) +Z7_NO_INLINE +static void Ppmd8_Rescale(CPpmd8 *p) { unsigned i, adder, sumFreq, escFreq; CPpmd_State *stats = STATS(p->MinContext); @@ -1389,7 +1389,7 @@ *s = *stats; s->Freq = (Byte)freq; p->FoundState = s; - InsertNode(p, stats, U2I(n0)); + Ppmd8_InsertNode(p, stats, U2I(n0)); return; } @@ -1452,9 +1452,9 @@ } -static void NextContext(CPpmd8 *p) +static void Ppmd8_NextContext(CPpmd8 *p) { - CTX_PTR c = CTX(SUCCESSOR(p->FoundState)); + PPMD8_CTX_PTR c = CTX(SUCCESSOR(p->FoundState)); if (p->OrderFall == 0 && (const Byte *)c >= p->UnitsStart) p->MaxContext = p->MinContext = c; else @@ -1471,12 +1471,12 @@ s->Freq = (Byte)freq; if (freq > s[-1].Freq) { - SwapStates(s, &s[-1]); + SWAP_STATES(s, &s[-1]); p->FoundState = --s; if (freq > MAX_FREQ) - Rescale(p); + Ppmd8_Rescale(p); } - NextContext(p); + Ppmd8_NextContext(p); } @@ -1492,8 +1492,8 @@ freq += 4; s->Freq = (Byte)freq; if (freq > MAX_FREQ) - Rescale(p); - NextContext(p); + Ppmd8_Rescale(p); + Ppmd8_NextContext(p); } @@ -1504,7 +1504,7 @@ p->FoundState->Freq = (Byte)(freq + (freq < 196)); // Ppmd8 (196) p->PrevSuccess = 1; p->RunLength++; - NextContext(p); + Ppmd8_NextContext(p); } */ @@ -1517,7 +1517,7 @@ p->MinContext->Union2.SummFreq = (UInt16)(p->MinContext->Union2.SummFreq + 4); s->Freq = (Byte)freq; if (freq > MAX_FREQ) - Rescale(p); + Ppmd8_Rescale(p); Ppmd8_UpdateModel(p); } @@ -1526,7 +1526,7 @@ GlueCount, and Glue method BinSum See / EscFreq - CreateSuccessors updates more suffix contexts + Ppmd8_CreateSuccessors updates more suffix contexts Ppmd8_UpdateModel consts. PrevSuccess Update @@ -1535,3 +1535,31 @@ (1 << 3) - there is symbol in Stats with (sym >= 0x40) in (1 << 4) - main symbol of context is (sym >= 0x40) */ + +#undef RESET_TEXT +#undef FLAG_RESCALED +#undef FLAG_PREV_HIGH +#undef HiBits_Prepare +#undef HiBits_Convert_3 +#undef HiBits_Convert_4 +#undef PPMD8_HiBitsFlag_3 +#undef PPMD8_HiBitsFlag_4 +#undef RESTORE_MODEL + +#undef MAX_FREQ +#undef UNIT_SIZE +#undef U2B +#undef U2I +#undef I2U + +#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 -Nru 7zip-22.01+dfsg/C/Ppmd8Dec.c 7zip-23.01+dfsg/C/Ppmd8Dec.c --- 7zip-22.01+dfsg/C/Ppmd8Dec.c 2021-04-13 19:22:38.000000000 +0000 +++ 7zip-23.01+dfsg/C/Ppmd8Dec.c 2023-04-02 12:00:00.000000000 +0000 @@ -1,5 +1,5 @@ /* Ppmd8Dec.c -- Ppmd8 (PPMdI) Decoder -2021-04-13 : Igor Pavlov : Public domain +2023-04-02 : Igor Pavlov : Public domain This code is based on: PPMd var.I (2002): Dmitry Shkarin : Public domain Carryless rangecoder (1999): Dmitry Subbotin : Public domain */ @@ -8,8 +8,8 @@ #include "Ppmd8.h" -#define kTop (1 << 24) -#define kBot (1 << 15) +#define kTop ((UInt32)1 << 24) +#define kBot ((UInt32)1 << 15) #define READ_BYTE(p) IByteIn_Read((p)->Stream.In) @@ -37,9 +37,9 @@ #define R p -MY_FORCE_INLINE -// MY_NO_INLINE -static void RangeDec_Decode(CPpmd8 *p, UInt32 start, UInt32 size) +Z7_FORCE_INLINE +// Z7_NO_INLINE +static void Ppmd8_RD_Decode(CPpmd8 *p, UInt32 start, UInt32 size) { start *= R->Range; R->Low += start; @@ -48,13 +48,13 @@ 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) Ppmd8_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) ((CPpmd8_Context *)Ppmd8_GetContext(p, ref)) -typedef CPpmd8_Context * CTX_PTR; +// typedef CPpmd8_Context * CTX_PTR; #define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) void Ppmd8_UpdateModel(CPpmd8 *p); @@ -81,7 +81,7 @@ if ((Int32)(count -= s->Freq) < 0) { Byte sym; - RC_DecodeFinal(0, s->Freq); + RC_DecodeFinal(0, s->Freq) p->FoundState = s; sym = s->Symbol; Ppmd8_Update1_0(p); @@ -96,7 +96,7 @@ 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; Ppmd8_Update1(p); @@ -109,10 +109,10 @@ return PPMD8_SYM_ERROR; hiCnt -= count; - RC_Decode(hiCnt, summFreq - hiCnt); + RC_Decode(hiCnt, summFreq - hiCnt) - PPMD_SetAllBitsIn256Bytes(charMask); + PPMD_SetAllBitsIn256Bytes(charMask) // i = p->MinContext->NumStats - 1; // do { MASK((--s)->Symbol) = 0; } while (--i); { @@ -152,7 +152,7 @@ // Ppmd8_UpdateBin(p); { unsigned freq = s->Freq; - CTX_PTR c = CTX(SUCCESSOR(s)); + CPpmd8_Context *c = CTX(SUCCESSOR(s)); sym = s->Symbol; p->FoundState = s; p->PrevSuccess = 1; @@ -176,7 +176,7 @@ R->Range = (R->Range & ~((UInt32)PPMD_BIN_SCALE - 1)) - size0; RC_NORM_LOCAL(R) - PPMD_SetAllBitsIn256Bytes(charMask); + PPMD_SetAllBitsIn256Bytes(charMask) MASK(Ppmd8Context_OneState(p->MinContext)->Symbol) = 0; p->PrevSuccess = 0; } @@ -227,7 +227,7 @@ see = Ppmd8_MakeEscFreq(p, numMasked, &freqSum); freqSum += hiCnt; freqSum2 = freqSum; - PPMD8_CORRECT_SUM_RANGE(R, freqSum2); + PPMD8_CORRECT_SUM_RANGE(R, freqSum2) count = RC_GetThreshold(freqSum2); @@ -235,7 +235,7 @@ if (count < hiCnt) { Byte sym; - // Ppmd_See_Update(see); // new (see->Summ) value can overflow over 16-bits in some rare cases + // Ppmd_See_UPDATE(see) // new (see->Summ) value can overflow over 16-bits in some rare cases s = Ppmd8_GetStats(p, p->MinContext); hiCnt = count; @@ -248,10 +248,10 @@ } } 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; Ppmd8_Update2(p); @@ -261,7 +261,7 @@ if (count >= freqSum2) return PPMD8_SYM_ERROR; - RC_Decode(hiCnt, freqSum2 - hiCnt); + RC_Decode(hiCnt, freqSum2 - 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 @@ -277,3 +277,19 @@ while (s != s2); } } + +#undef kTop +#undef kBot +#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 -Nru 7zip-22.01+dfsg/C/Ppmd8Enc.c 7zip-23.01+dfsg/C/Ppmd8Enc.c --- 7zip-22.01+dfsg/C/Ppmd8Enc.c 2021-04-13 19:22:39.000000000 +0000 +++ 7zip-23.01+dfsg/C/Ppmd8Enc.c 2023-04-02 12:00:00.000000000 +0000 @@ -1,5 +1,5 @@ /* Ppmd8Enc.c -- Ppmd8 (PPMdI) Encoder -2021-04-13 : Igor Pavlov : Public domain +2023-04-02 : Igor Pavlov : Public domain This code is based on: PPMd var.I (2002): Dmitry Shkarin : Public domain Carryless rangecoder (1999): Dmitry Subbotin : Public domain */ @@ -8,8 +8,8 @@ #include "Ppmd8.h" -#define kTop (1 << 24) -#define kBot (1 << 15) +#define kTop ((UInt32)1 << 24) +#define kBot ((UInt32)1 << 15) #define WRITE_BYTE(p) IByteOut_Write(p->Stream.Out, (Byte)(p->Low >> 24)) @@ -54,13 +54,13 @@ -MY_FORCE_INLINE -// MY_NO_INLINE -static void RangeEnc_Encode(CPpmd8 *p, UInt32 start, UInt32 size, UInt32 total) +Z7_FORCE_INLINE +// Z7_NO_INLINE +static void Ppmd8_RangeEnc_Encode(CPpmd8 *p, UInt32 start, UInt32 size, UInt32 total) { R->Low += start * (R->Range /= total); R->Range *= size; - RC_NORM_LOCAL(R); + RC_NORM_LOCAL(R) } @@ -72,19 +72,19 @@ -#define RC_Encode(start, size, total) RangeEnc_Encode(p, start, size, total); -#define RC_EncodeFinal(start, size, total) RC_Encode(start, size, total); RC_NORM_REMOTE(p); +#define RC_Encode(start, size, total) Ppmd8_RangeEnc_Encode(p, start, size, total); +#define RC_EncodeFinal(start, size, total) RC_Encode(start, size, total) RC_NORM_REMOTE(p) #define CTX(ref) ((CPpmd8_Context *)Ppmd8_GetContext(p, ref)) -typedef CPpmd8_Context * CTX_PTR; +// typedef CPpmd8_Context * CTX_PTR; #define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) void Ppmd8_UpdateModel(CPpmd8 *p); #define MASK(sym) ((unsigned char *)charMask)[sym] -// MY_FORCE_INLINE +// Z7_FORCE_INLINE // static void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol) { @@ -104,7 +104,7 @@ if (s->Symbol == symbol) { - RC_EncodeFinal(0, s->Freq, summFreq); + RC_EncodeFinal(0, s->Freq, summFreq) p->FoundState = s; Ppmd8_Update1_0(p); return; @@ -117,7 +117,7 @@ if ((++s)->Symbol == symbol) { - RC_EncodeFinal(sum, s->Freq, summFreq); + RC_EncodeFinal(sum, s->Freq, summFreq) p->FoundState = s; Ppmd8_Update1(p); return; @@ -127,10 +127,10 @@ while (--i); - RC_Encode(sum, summFreq - sum, summFreq); + RC_Encode(sum, summFreq - sum, summFreq) - PPMD_SetAllBitsIn256Bytes(charMask); + PPMD_SetAllBitsIn256Bytes(charMask) // MASK(s->Symbol) = 0; // i = p->MinContext->NumStats; // do { MASK((--s)->Symbol) = 0; } while (--i); @@ -153,20 +153,20 @@ UInt16 *prob = Ppmd8_GetBinSumm(p); CPpmd_State *s = Ppmd8Context_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(R); + RC_NORM(R) // p->FoundState = s; // Ppmd8_UpdateBin(p); { - unsigned freq = s->Freq; - CTX_PTR c = CTX(SUCCESSOR(s)); + const unsigned freq = s->Freq; + CPpmd8_Context *c = CTX(SUCCESSOR(s)); p->FoundState = s; p->PrevSuccess = 1; p->RunLength++; @@ -187,7 +187,7 @@ R->Range = (R->Range & ~((UInt32)PPMD_BIN_SCALE - 1)) - bound; RC_NORM_LOCAL(R) - PPMD_SetAllBitsIn256Bytes(charMask); + PPMD_SetAllBitsIn256Bytes(charMask) MASK(s->Symbol) = 0; p->PrevSuccess = 0; } @@ -248,14 +248,14 @@ 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; @@ -277,9 +277,9 @@ } } - PPMD8_CORRECT_SUM_RANGE(p, sum); + PPMD8_CORRECT_SUM_RANGE(p, sum) - RC_EncodeFinal(low, freq, sum); + RC_EncodeFinal(low, freq, sum) Ppmd8_Update2(p); return; } @@ -291,19 +291,19 @@ { UInt32 total = sum + escFreq; see->Summ = (UInt16)(see->Summ + total); - PPMD8_CORRECT_SUM_RANGE(p, total); + PPMD8_CORRECT_SUM_RANGE(p, total) - RC_Encode(sum, total - sum, total); + RC_Encode(sum, total - sum, total) } { - CPpmd_State *s2 = Ppmd8_GetStats(p, p->MinContext); + const CPpmd_State *s2 = Ppmd8_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; @@ -312,3 +312,27 @@ } } } + + + + + + + + + +#undef kTop +#undef kBot +#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 CTX +#undef SUCCESSOR +#undef MASK diff -Nru 7zip-22.01+dfsg/C/Ppmd8.h 7zip-23.01+dfsg/C/Ppmd8.h --- 7zip-22.01+dfsg/C/Ppmd8.h 2021-04-13 18:42:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Ppmd8.h 2023-04-02 12:00:00.000000000 +0000 @@ -1,11 +1,11 @@ /* Ppmd8.h -- Ppmd8 (PPMdI) compression codec -2021-04-13 : Igor Pavlov : Public domain +2023-04-02 : Igor Pavlov : Public domain This code is based on: PPMd var.I (2002): Dmitry Shkarin : Public domain Carryless rangecoder (1999): Dmitry Subbotin : Public domain */ -#ifndef __PPMD8_H -#define __PPMD8_H +#ifndef ZIP7_INC_PPMD8_H +#define ZIP7_INC_PPMD8_H #include "Ppmd.h" @@ -87,8 +87,8 @@ UInt32 Low; union { - IByteIn *In; - IByteOut *Out; + IByteInPtr In; + IByteOutPtr Out; } Stream; Byte Indx2Units[PPMD_NUM_INDEXES + 2]; // +2 for alignment diff -Nru 7zip-22.01+dfsg/C/Ppmd.h 7zip-23.01+dfsg/C/Ppmd.h --- 7zip-22.01+dfsg/C/Ppmd.h 2021-04-13 20:06:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Ppmd.h 2023-03-05 15:00:00.000000000 +0000 @@ -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 @@ 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 -Nru 7zip-22.01+dfsg/C/Precomp.h 7zip-23.01+dfsg/C/Precomp.h --- 7zip-22.01+dfsg/C/Precomp.h 2013-11-12 07:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Precomp.h 2023-04-02 12:00:00.000000000 +0000 @@ -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 -Nru 7zip-22.01+dfsg/C/RotateDefs.h 7zip-23.01+dfsg/C/RotateDefs.h --- 7zip-22.01+dfsg/C/RotateDefs.h 2015-03-25 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/RotateDefs.h 2023-06-18 11:00:00.000000000 +0000 @@ -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 -Nru 7zip-22.01+dfsg/C/Sha1.c 7zip-23.01+dfsg/C/Sha1.c --- 7zip-22.01+dfsg/C/Sha1.c 2021-07-13 09:52:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Sha1.c 2023-04-02 12:00:00.000000000 +0000 @@ -1,5 +1,5 @@ /* Sha1.c -- SHA-1 Hash -2021-07-13 : Igor Pavlov : Public domain +2023-04-02 : Igor Pavlov : Public domain This code is based on public domain code of Steve Reid from Wei Dai's Crypto++ library. */ #include "Precomp.h" @@ -17,48 +17,48 @@ #ifdef MY_CPU_X86_OR_AMD64 #ifdef _MSC_VER #if _MSC_VER >= 1200 - #define _SHA_SUPPORTED + #define Z7_COMPILER_SHA1_SUPPORTED #endif #elif defined(__clang__) #if (__clang_major__ >= 8) // fix that check - #define _SHA_SUPPORTED + #define Z7_COMPILER_SHA1_SUPPORTED #endif #elif defined(__GNUC__) #if (__GNUC__ >= 8) // fix that check - #define _SHA_SUPPORTED + #define Z7_COMPILER_SHA1_SUPPORTED #endif #elif defined(__INTEL_COMPILER) #if (__INTEL_COMPILER >= 1800) // fix that check - #define _SHA_SUPPORTED + #define Z7_COMPILER_SHA1_SUPPORTED #endif #endif #elif defined(MY_CPU_ARM_OR_ARM64) #ifdef _MSC_VER #if _MSC_VER >= 1910 && _MSC_VER >= 1929 && _MSC_FULL_VER >= 192930037 - #define _SHA_SUPPORTED + #define Z7_COMPILER_SHA1_SUPPORTED #endif #elif defined(__clang__) #if (__clang_major__ >= 8) // fix that check - #define _SHA_SUPPORTED + #define Z7_COMPILER_SHA1_SUPPORTED #endif #elif defined(__GNUC__) #if (__GNUC__ >= 6) // fix that check - #define _SHA_SUPPORTED + #define Z7_COMPILER_SHA1_SUPPORTED #endif #endif #endif -void MY_FAST_CALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks); +void Z7_FASTCALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks); -#ifdef _SHA_SUPPORTED - void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks); +#ifdef Z7_COMPILER_SHA1_SUPPORTED + void Z7_FASTCALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks); - static SHA1_FUNC_UPDATE_BLOCKS g_FUNC_UPDATE_BLOCKS = Sha1_UpdateBlocks; - static SHA1_FUNC_UPDATE_BLOCKS g_FUNC_UPDATE_BLOCKS_HW; + static SHA1_FUNC_UPDATE_BLOCKS g_SHA1_FUNC_UPDATE_BLOCKS = Sha1_UpdateBlocks; + static SHA1_FUNC_UPDATE_BLOCKS g_SHA1_FUNC_UPDATE_BLOCKS_HW; - #define UPDATE_BLOCKS(p) p->func_UpdateBlocks + #define SHA1_UPDATE_BLOCKS(p) p->func_UpdateBlocks #else - #define UPDATE_BLOCKS(p) Sha1_UpdateBlocks + #define SHA1_UPDATE_BLOCKS(p) Sha1_UpdateBlocks #endif @@ -66,16 +66,16 @@ { SHA1_FUNC_UPDATE_BLOCKS func = Sha1_UpdateBlocks; - #ifdef _SHA_SUPPORTED + #ifdef Z7_COMPILER_SHA1_SUPPORTED if (algo != SHA1_ALGO_SW) { if (algo == SHA1_ALGO_DEFAULT) - func = g_FUNC_UPDATE_BLOCKS; + func = g_SHA1_FUNC_UPDATE_BLOCKS; else { if (algo != SHA1_ALGO_HW) return False; - func = g_FUNC_UPDATE_BLOCKS_HW; + func = g_SHA1_FUNC_UPDATE_BLOCKS_HW; if (!func) return False; } @@ -91,21 +91,22 @@ /* define it for speed optimization */ -// #define _SHA1_UNROLL +// #define Z7_SHA1_UNROLL // allowed unroll steps: (1, 2, 4, 5, 20) -#ifdef _SHA1_UNROLL +#undef Z7_SHA1_BIG_W +#ifdef Z7_SHA1_UNROLL #define STEP_PRE 20 #define STEP_MAIN 20 #else - #define _SHA1_BIG_W + #define Z7_SHA1_BIG_W #define STEP_PRE 5 #define STEP_MAIN 5 #endif -#ifdef _SHA1_BIG_W +#ifdef Z7_SHA1_BIG_W #define kNumW 80 #define w(i) W[i] #else @@ -150,11 +151,11 @@ */ #define M5(i, fx, wx0, wx1) \ - T5 ( a,b,c,d,e, fx, wx0((i) ) ); \ - T5 ( e,a,b,c,d, fx, wx1((i)+1) ); \ - T5 ( d,e,a,b,c, fx, wx1((i)+2) ); \ - T5 ( c,d,e,a,b, fx, wx1((i)+3) ); \ - T5 ( b,c,d,e,a, fx, wx1((i)+4) ); \ + T5 ( a,b,c,d,e, fx, wx0((i) ) ) \ + T5 ( e,a,b,c,d, fx, wx1((i)+1) ) \ + T5 ( d,e,a,b,c, fx, wx1((i)+2) ) \ + T5 ( c,d,e,a,b, fx, wx1((i)+3) ) \ + T5 ( b,c,d,e,a, fx, wx1((i)+4) ) \ #define R5(i, fx, wx) \ M5 ( i, fx, wx, wx) \ @@ -163,17 +164,17 @@ #if STEP_PRE > 5 #define R20_START \ - R5 ( 0, f0, w0); \ - R5 ( 5, f0, w0); \ - R5 ( 10, f0, w0); \ - M5 ( 15, f0, w0, w1); \ + R5 ( 0, f0, w0) \ + R5 ( 5, f0, w0) \ + R5 ( 10, f0, w0) \ + M5 ( 15, f0, w0, w1) \ #elif STEP_PRE == 5 #define R20_START \ { size_t i; for (i = 0; i < 15; i += STEP_PRE) \ - { R5(i, f0, w0); } } \ - M5 ( 15, f0, w0, w1); \ + { R5(i, f0, w0) } } \ + M5 ( 15, f0, w0, w1) \ #else @@ -187,8 +188,8 @@ #define R20_START \ { size_t i; for (i = 0; i < 16; i += STEP_PRE) \ - { R_PRE(i, f0, w0); } } \ - R4 ( 16, f0, w1); \ + { R_PRE(i, f0, w0) } } \ + R4 ( 16, f0, w1) \ #endif @@ -197,10 +198,10 @@ #if STEP_MAIN > 5 #define R20(ii, fx) \ - R5 ( (ii) , fx, w1); \ - R5 ( (ii) + 5 , fx, w1); \ - R5 ( (ii) + 10, fx, w1); \ - R5 ( (ii) + 15, fx, w1); \ + R5 ( (ii) , fx, w1) \ + R5 ( (ii) + 5 , fx, w1) \ + R5 ( (ii) + 10, fx, w1) \ + R5 ( (ii) + 15, fx, w1) \ #else @@ -216,7 +217,7 @@ #define R20(ii, fx) \ { size_t i; for (i = (ii); i < (ii) + 20; i += STEP_MAIN) \ - { R_MAIN(i, fx, w1); } } \ + { R_MAIN(i, fx, w1) } } \ #endif @@ -235,8 +236,8 @@ void Sha1_Init(CSha1 *p) { p->func_UpdateBlocks = - #ifdef _SHA_SUPPORTED - g_FUNC_UPDATE_BLOCKS; + #ifdef Z7_COMPILER_SHA1_SUPPORTED + g_SHA1_FUNC_UPDATE_BLOCKS; #else NULL; #endif @@ -244,8 +245,8 @@ } -MY_NO_INLINE -void MY_FAST_CALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks) +Z7_NO_INLINE +void Z7_FASTCALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks) { UInt32 a, b, c, d, e; UInt32 W[kNumW]; @@ -266,9 +267,9 @@ #endif R20_START - R20(20, f1); - R20(40, f2); - R20(60, f3); + R20(20, f1) + R20(40, f2) + R20(60, f3) a += state[0]; b += state[1]; @@ -288,7 +289,7 @@ } -#define Sha1_UpdateBlock(p) UPDATE_BLOCKS(p)(p->state, p->buffer, 1) +#define Sha1_UpdateBlock(p) SHA1_UPDATE_BLOCKS(p)(p->state, p->buffer, 1) void Sha1_Update(CSha1 *p, const Byte *data, size_t size) { @@ -318,7 +319,7 @@ } { size_t numBlocks = size >> 6; - UPDATE_BLOCKS(p)(p->state, data, numBlocks); + SHA1_UPDATE_BLOCKS(p)(p->state, data, numBlocks); size &= 0x3F; if (size == 0) return; @@ -361,18 +362,18 @@ memset(&p->buffer[pos], 0, (64 - 8) - pos); { - UInt64 numBits = (p->count << 3); - SetBe32(p->buffer + 64 - 8, (UInt32)(numBits >> 32)); - SetBe32(p->buffer + 64 - 4, (UInt32)(numBits)); + const UInt64 numBits = (p->count << 3); + SetBe32(p->buffer + 64 - 8, (UInt32)(numBits >> 32)) + SetBe32(p->buffer + 64 - 4, (UInt32)(numBits)) } Sha1_UpdateBlock(p); - SetBe32(digest, p->state[0]); - SetBe32(digest + 4, p->state[1]); - SetBe32(digest + 8, p->state[2]); - SetBe32(digest + 12, p->state[3]); - SetBe32(digest + 16, p->state[4]); + SetBe32(digest, p->state[0]) + SetBe32(digest + 4, p->state[1]) + SetBe32(digest + 8, p->state[2]) + SetBe32(digest + 12, p->state[3]) + SetBe32(digest + 16, p->state[4]) @@ -384,10 +385,10 @@ void Sha1_PrepareBlock(const CSha1 *p, Byte *block, unsigned size) { const UInt64 numBits = (p->count + size) << 3; - SetBe32(&((UInt32 *)(void *)block)[SHA1_NUM_BLOCK_WORDS - 2], (UInt32)(numBits >> 32)); - SetBe32(&((UInt32 *)(void *)block)[SHA1_NUM_BLOCK_WORDS - 1], (UInt32)(numBits)); + SetBe32(&((UInt32 *)(void *)block)[SHA1_NUM_BLOCK_WORDS - 2], (UInt32)(numBits >> 32)) + SetBe32(&((UInt32 *)(void *)block)[SHA1_NUM_BLOCK_WORDS - 1], (UInt32)(numBits)) // SetBe32((UInt32 *)(block + size), 0x80000000); - SetUi32((UInt32 *)(void *)(block + size), 0x80); + SetUi32((UInt32 *)(void *)(block + size), 0x80) size += 4; while (size != (SHA1_NUM_BLOCK_WORDS - 2) * 4) { @@ -407,19 +408,19 @@ st[3] = p->state[3]; st[4] = p->state[4]; - UPDATE_BLOCKS(p)(st, data, 1); + SHA1_UPDATE_BLOCKS(p)(st, data, 1); - SetBe32(destDigest + 0 , st[0]); - SetBe32(destDigest + 1 * 4, st[1]); - SetBe32(destDigest + 2 * 4, st[2]); - SetBe32(destDigest + 3 * 4, st[3]); - SetBe32(destDigest + 4 * 4, st[4]); + SetBe32(destDigest + 0 , st[0]) + SetBe32(destDigest + 1 * 4, st[1]) + SetBe32(destDigest + 2 * 4, st[2]) + SetBe32(destDigest + 3 * 4, st[3]) + SetBe32(destDigest + 4 * 4, st[4]) } -void Sha1Prepare() +void Sha1Prepare(void) { - #ifdef _SHA_SUPPORTED + #ifdef Z7_COMPILER_SHA1_SUPPORTED SHA1_FUNC_UPDATE_BLOCKS f, f_hw; f = Sha1_UpdateBlocks; f_hw = NULL; @@ -467,7 +468,31 @@ f = f_hw = Sha1_UpdateBlocks_HW; } } - g_FUNC_UPDATE_BLOCKS = f; - g_FUNC_UPDATE_BLOCKS_HW = f_hw; + g_SHA1_FUNC_UPDATE_BLOCKS = f; + g_SHA1_FUNC_UPDATE_BLOCKS_HW = f_hw; #endif } + +#undef kNumW +#undef w +#undef w0 +#undef w1 +#undef f0 +#undef f1 +#undef f2 +#undef f3 +#undef T1 +#undef T5 +#undef M5 +#undef R1 +#undef R2 +#undef R4 +#undef R5 +#undef R20_START +#undef R_PRE +#undef R_MAIN +#undef STEP_PRE +#undef STEP_MAIN +#undef Z7_SHA1_BIG_W +#undef Z7_SHA1_UNROLL +#undef Z7_COMPILER_SHA1_SUPPORTED diff -Nru 7zip-22.01+dfsg/C/Sha1.h 7zip-23.01+dfsg/C/Sha1.h --- 7zip-22.01+dfsg/C/Sha1.h 2021-02-09 15:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Sha1.h 2023-04-02 12:00:00.000000000 +0000 @@ -1,8 +1,8 @@ /* Sha1.h -- SHA-1 Hash -2021-02-08 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ -#ifndef __7Z_SHA1_H -#define __7Z_SHA1_H +#ifndef ZIP7_INC_SHA1_H +#define ZIP7_INC_SHA1_H #include "7zTypes.h" @@ -14,7 +14,7 @@ #define SHA1_BLOCK_SIZE (SHA1_NUM_BLOCK_WORDS * 4) #define SHA1_DIGEST_SIZE (SHA1_NUM_DIGEST_WORDS * 4) -typedef void (MY_FAST_CALL *SHA1_FUNC_UPDATE_BLOCKS)(UInt32 state[5], const Byte *data, size_t numBlocks); +typedef void (Z7_FASTCALL *SHA1_FUNC_UPDATE_BLOCKS)(UInt32 state[5], const Byte *data, size_t numBlocks); /* if (the system supports different SHA1 code implementations) @@ -34,9 +34,9 @@ { SHA1_FUNC_UPDATE_BLOCKS func_UpdateBlocks; UInt64 count; - UInt64 __pad_2[2]; + UInt64 _pad_2[2]; UInt32 state[SHA1_NUM_DIGEST_WORDS]; - UInt32 __pad_3[3]; + UInt32 _pad_3[3]; Byte buffer[SHA1_BLOCK_SIZE]; } CSha1; @@ -62,7 +62,7 @@ void Sha1_PrepareBlock(const CSha1 *p, Byte *block, unsigned size); void Sha1_GetBlockDigest(const CSha1 *p, const Byte *data, Byte *destDigest); -// void MY_FAST_CALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks); +// void Z7_FASTCALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks); /* call Sha1Prepare() once at program start. diff -Nru 7zip-22.01+dfsg/C/Sha1Opt.c 7zip-23.01+dfsg/C/Sha1Opt.c --- 7zip-22.01+dfsg/C/Sha1Opt.c 2021-04-01 18:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Sha1Opt.c 2023-04-02 12:00:00.000000000 +0000 @@ -1,7 +1,9 @@ /* Sha1Opt.c -- SHA-1 optimized code for SHA-1 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 - #pragma clang diagnostic ignored "-Wvector-conversion" - #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("Sha1 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" @@ -87,37 +77,37 @@ _mm_sha1* */ -#define ADD_EPI32(dest, src) dest = _mm_add_epi32(dest, src); + #define XOR_SI128(dest, src) dest = _mm_xor_si128(dest, src); #define SHUFFLE_EPI8(dest, mask) dest = _mm_shuffle_epi8(dest, mask); #define SHUFFLE_EPI32(dest, mask) dest = _mm_shuffle_epi32(dest, mask); - -#define SHA1_RND4(abcd, e0, f) abcd = _mm_sha1rnds4_epu32(abcd, e0, f); -#define SHA1_NEXTE(e, m) e = _mm_sha1nexte_epu32(e, m); - - - - - -#define SHA1_MSG1(dest, src) dest = _mm_sha1msg1_epu32(dest, src); -#define SHA1_MSG2(dest, src) dest = _mm_sha1msg2_epu32(dest, src); +#ifdef __clang__ +#define SHA1_RNDS4_RET_TYPE_CAST (__m128i) +#else +#define SHA1_RNDS4_RET_TYPE_CAST +#endif +#define SHA1_RND4(abcd, e0, f) abcd = SHA1_RNDS4_RET_TYPE_CAST _mm_sha1rnds4_epu32(abcd, e0, f); +#define SHA1_NEXTE(e, m) e = _mm_sha1nexte_epu32(e, m); +#define ADD_EPI32(dest, src) dest = _mm_add_epi32(dest, src); +#define SHA1_MSG1(dest, src) dest = _mm_sha1msg1_epu32(dest, src); +#define SHA1_MSG2(dest, src) dest = _mm_sha1msg2_epu32(dest, src); #define LOAD_SHUFFLE(m, k) \ m = _mm_loadu_si128((const __m128i *)(const void *)(data + (k) * 16)); \ - SHUFFLE_EPI8(m, mask); \ + SHUFFLE_EPI8(m, mask) \ #define SM1(m0, m1, m2, m3) \ - SHA1_MSG1(m0, m1); \ + SHA1_MSG1(m0, m1) \ #define SM2(m0, m1, m2, m3) \ - XOR_SI128(m3, m1); \ - SHA1_MSG2(m3, m2); \ + XOR_SI128(m3, m1) \ + SHA1_MSG2(m3, m2) \ #define SM3(m0, m1, m2, m3) \ - XOR_SI128(m3, m1); \ + XOR_SI128(m3, m1) \ SM1(m0, m1, m2, m3) \ - SHA1_MSG2(m3, m2); \ + SHA1_MSG2(m3, m2) \ #define NNN(m0, m1, m2, m3) @@ -139,9 +129,9 @@ #define R4(k, e0, e1, m0, m1, m2, m3, OP) \ e1 = abcd; \ - SHA1_RND4(abcd, e0, (k) / 5); \ - SHA1_NEXTE(e1, m1); \ - OP(m0, m1, m2, m3); \ + SHA1_RND4(abcd, e0, (k) / 5) \ + SHA1_NEXTE(e1, m1) \ + OP(m0, m1, m2, m3) \ #define R16(k, mx, OP0, OP1, OP2, OP3) \ R4 ( (k)*4+0, e0,e1, m0,m1,m2,m3, OP0 ) \ @@ -150,18 +140,18 @@ R4 ( (k)*4+3, e1,e0, m3,mx,m1,m2, OP3 ) \ #define PREPARE_STATE \ - SHUFFLE_EPI32 (abcd, 0x1B); \ - SHUFFLE_EPI32 (e0, 0x1B); \ + SHUFFLE_EPI32 (abcd, 0x1B) \ + SHUFFLE_EPI32 (e0, 0x1B) \ -void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks); +void Z7_FASTCALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks); #ifdef ATTRIB_SHA ATTRIB_SHA #endif -void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks) +void Z7_FASTCALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks) { const __m128i mask = _mm_set_epi32(0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f); @@ -190,15 +180,15 @@ LOAD_SHUFFLE (m2, 2) LOAD_SHUFFLE (m3, 3) - ADD_EPI32(e0, m0); + ADD_EPI32(e0, m0) - R16 ( 0, m0, SM1, SM3, SM3, SM3 ); - R16 ( 1, m0, SM3, SM3, SM3, SM3 ); - R16 ( 2, m0, SM3, SM3, SM3, SM3 ); - R16 ( 3, m0, SM3, SM3, SM3, SM3 ); - R16 ( 4, e2, SM2, NNN, NNN, NNN ); + R16 ( 0, m0, SM1, SM3, SM3, SM3 ) + R16 ( 1, m0, SM3, SM3, SM3, SM3 ) + R16 ( 2, m0, SM3, SM3, SM3, SM3 ) + R16 ( 3, m0, SM3, SM3, SM3, SM3 ) + R16 ( 4, e2, SM2, NNN, NNN, NNN ) - ADD_EPI32(abcd, abcd_save); + ADD_EPI32(abcd, abcd_save) data += 64; } @@ -274,11 +264,11 @@ #define H(e) e = vsha1h_u32(vgetq_lane_u32(abcd, 0)) #define T(m, c) t = vaddq_u32(m, c) -void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); +void Z7_FASTCALL Sha1_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); #ifdef ATTRIB_SHA ATTRIB_SHA #endif -void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) +void Z7_FASTCALL Sha1_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) { v128 abcd; v128 c0, c1, c2, c3; @@ -353,12 +343,12 @@ // #include // #include "Sha1.h" -void MY_FAST_CALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks); +void Z7_FASTCALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks); #pragma message("Sha1 HW-SW stub was used") -void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks); -void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks) +void Z7_FASTCALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks); +void Z7_FASTCALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks) { Sha1_UpdateBlocks(state, data, numBlocks); /* @@ -371,3 +361,26 @@ } #endif + +#undef SU0 +#undef SU1 +#undef C +#undef P +#undef M +#undef H +#undef T +#undef MY_rev32_for_LE +#undef NNN +#undef LOAD_128 +#undef STORE_128 +#undef LOAD_SHUFFLE +#undef SM1 +#undef SM2 +#undef SM3 +#undef NNN +#undef R4 +#undef R16 +#undef PREPARE_STATE +#undef USE_HW_SHA +#undef ATTRIB_SHA +#undef USE_VER_MIN diff -Nru 7zip-22.01+dfsg/C/Sha256.c 7zip-23.01+dfsg/C/Sha256.c --- 7zip-22.01+dfsg/C/Sha256.c 2021-04-01 18:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Sha256.c 2023-04-02 12:00:00.000000000 +0000 @@ -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 @@ #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 @@ { 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 False; - func = g_FUNC_UPDATE_BLOCKS_HW; + func = g_SHA256_FUNC_UPDATE_BLOCKS_HW; if (!func) return False; } @@ -92,17 +92,18 @@ /* 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_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 @@ #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 @@ #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 @@ -#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 @@ #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 @@ #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 @@ 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 @@ #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 @@ 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 @@ #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 @@ } { 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 @@ { 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,8 +452,8 @@ { 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; } @@ -460,9 +461,9 @@ } -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; @@ -480,7 +481,36 @@ // 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 -Nru 7zip-22.01+dfsg/C/Sha256.h 7zip-23.01+dfsg/C/Sha256.h --- 7zip-22.01+dfsg/C/Sha256.h 2021-01-01 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Sha256.h 2023-04-02 12:00:00.000000000 +0000 @@ -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 @@ #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 @@ { 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 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 -Nru 7zip-22.01+dfsg/C/Sha256Opt.c 7zip-23.01+dfsg/C/Sha256Opt.c --- 7zip-22.01+dfsg/C/Sha256Opt.c 2021-04-01 18:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Sha256Opt.c 2023-04-02 12:00:00.000000000 +0000 @@ -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 @@ #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 @@ #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 @@ // 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 @@ 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 @@ - 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 @@ 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 @@ // #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 @@ } #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 -Nru 7zip-22.01+dfsg/C/Sort.h 7zip-23.01+dfsg/C/Sort.h --- 7zip-22.01+dfsg/C/Sort.h 2014-04-05 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Sort.h 2023-03-05 18:00:00.000000000 +0000 @@ -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 -Nru 7zip-22.01+dfsg/C/SwapBytes.c 7zip-23.01+dfsg/C/SwapBytes.c --- 7zip-22.01+dfsg/C/SwapBytes.c 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/SwapBytes.c 2023-04-07 07:00:00.000000000 +0000 @@ -0,0 +1,800 @@ +/* SwapBytes.c -- Byte Swap conversion filter +2023-04-07 : Igor Pavlov : Public domain */ + +#include "Precomp.h" + +#include "Compiler.h" +#include "CpuArch.h" +#include "RotateDefs.h" +#include "SwapBytes.h" + +typedef UInt16 CSwapUInt16; +typedef UInt32 CSwapUInt32; + +// #define k_SwapBytes_Mode_BASE 0 + +#ifdef MY_CPU_X86_OR_AMD64 + +#define k_SwapBytes_Mode_SSE2 1 +#define k_SwapBytes_Mode_SSSE3 2 +#define k_SwapBytes_Mode_AVX2 3 + + // #if defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1900) + #if defined(__clang__) && (__clang_major__ >= 4) \ + || defined(Z7_GCC_VERSION) && (Z7_GCC_VERSION >= 40701) + #define k_SwapBytes_Mode_MAX k_SwapBytes_Mode_AVX2 + #define SWAP_ATTRIB_SSE2 __attribute__((__target__("sse2"))) + #define SWAP_ATTRIB_SSSE3 __attribute__((__target__("ssse3"))) + #define SWAP_ATTRIB_AVX2 __attribute__((__target__("avx2"))) + #elif defined(_MSC_VER) + #if (_MSC_VER == 1900) + #pragma warning(disable : 4752) // found Intel(R) Advanced Vector Extensions; consider using /arch:AVX + #endif + #if (_MSC_VER >= 1900) + #define k_SwapBytes_Mode_MAX k_SwapBytes_Mode_AVX2 + #elif (_MSC_VER >= 1500) // (VS2008) + #define k_SwapBytes_Mode_MAX k_SwapBytes_Mode_SSSE3 + #elif (_MSC_VER >= 1310) // (VS2003) + #define k_SwapBytes_Mode_MAX k_SwapBytes_Mode_SSE2 + #endif + #endif // _MSC_VER + +/* +// for debug +#ifdef k_SwapBytes_Mode_MAX +#undef k_SwapBytes_Mode_MAX +#endif +*/ + +#ifndef k_SwapBytes_Mode_MAX +#define k_SwapBytes_Mode_MAX 0 +#endif + +#if (k_SwapBytes_Mode_MAX != 0) && defined(MY_CPU_AMD64) + #define k_SwapBytes_Mode_MIN k_SwapBytes_Mode_SSE2 +#else + #define k_SwapBytes_Mode_MIN 0 +#endif + +#if (k_SwapBytes_Mode_MAX >= k_SwapBytes_Mode_AVX2) + #define USE_SWAP_AVX2 +#endif +#if (k_SwapBytes_Mode_MAX >= k_SwapBytes_Mode_SSSE3) + #define USE_SWAP_SSSE3 +#endif +#if (k_SwapBytes_Mode_MAX >= k_SwapBytes_Mode_SSE2) + #define USE_SWAP_128 +#endif + +#if k_SwapBytes_Mode_MAX <= k_SwapBytes_Mode_MIN || !defined(USE_SWAP_128) +#define FORCE_SWAP_MODE +#endif + + +#ifdef USE_SWAP_128 +/* + MMX + SSE + SSE2 + SSE3 + SSSE3 + SSE4.1 + SSE4.2 + SSE4A + AES + AVX, AVX2, FMA +*/ + +#include // sse2 +// typedef __m128i v128; + +#define SWAP2_128(i) { \ + const __m128i v = *(const __m128i *)(const void *)(items + (i) * 8); \ + *( __m128i *)( void *)(items + (i) * 8) = \ + _mm_or_si128( \ + _mm_slli_epi16(v, 8), \ + _mm_srli_epi16(v, 8)); } +// _mm_or_si128() has more ports to execute than _mm_add_epi16(). + +static +#ifdef SWAP_ATTRIB_SSE2 +SWAP_ATTRIB_SSE2 +#endif +void +Z7_FASTCALL +SwapBytes2_128(CSwapUInt16 *items, const CSwapUInt16 *lim) +{ + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + do + { + SWAP2_128(0) SWAP2_128(1) items += 2 * 8; + SWAP2_128(0) SWAP2_128(1) items += 2 * 8; + } + while (items != lim); +} + +/* +// sse2 +#define SWAP4_128_pack(i) { \ + __m128i v = *(const __m128i *)(const void *)(items + (i) * 4); \ + __m128i v0 = _mm_unpacklo_epi8(v, mask); \ + __m128i v1 = _mm_unpackhi_epi8(v, mask); \ + v0 = _mm_shufflelo_epi16(v0, 0x1b); \ + v1 = _mm_shufflelo_epi16(v1, 0x1b); \ + v0 = _mm_shufflehi_epi16(v0, 0x1b); \ + v1 = _mm_shufflehi_epi16(v1, 0x1b); \ + *(__m128i *)(void *)(items + (i) * 4) = _mm_packus_epi16(v0, v1); } + +static +#ifdef SWAP_ATTRIB_SSE2 +SWAP_ATTRIB_SSE2 +#endif +void +Z7_FASTCALL +SwapBytes4_128_pack(CSwapUInt32 *items, const CSwapUInt32 *lim) +{ + const __m128i mask = _mm_setzero_si128(); + // const __m128i mask = _mm_set_epi16(0, 0, 0, 0, 0, 0, 0, 0); + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + do + { + SWAP4_128_pack(0); items += 1 * 4; + // SWAP4_128_pack(0); SWAP4_128_pack(1); items += 2 * 4; + } + while (items != lim); +} + +// sse2 +#define SWAP4_128_shift(i) { \ + __m128i v = *(const __m128i *)(const void *)(items + (i) * 4); \ + __m128i v2; \ + v2 = _mm_or_si128( \ + _mm_slli_si128(_mm_and_si128(v, mask), 1), \ + _mm_and_si128(_mm_srli_si128(v, 1), mask)); \ + v = _mm_or_si128( \ + _mm_slli_epi32(v, 24), \ + _mm_srli_epi32(v, 24)); \ + *(__m128i *)(void *)(items + (i) * 4) = _mm_or_si128(v2, v); } + +static +#ifdef SWAP_ATTRIB_SSE2 +SWAP_ATTRIB_SSE2 +#endif +void +Z7_FASTCALL +SwapBytes4_128_shift(CSwapUInt32 *items, const CSwapUInt32 *lim) +{ + #define M1 0xff00 + const __m128i mask = _mm_set_epi32(M1, M1, M1, M1); + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + do + { + // SWAP4_128_shift(0) SWAP4_128_shift(1) items += 2 * 4; + // SWAP4_128_shift(0) SWAP4_128_shift(1) items += 2 * 4; + SWAP4_128_shift(0); items += 1 * 4; + } + while (items != lim); +} +*/ + + +#if defined(USE_SWAP_SSSE3) || defined(USE_SWAP_AVX2) + +#define SWAP_SHUF_REV_SEQ_2_VALS(v) (v)+1, (v) +#define SWAP_SHUF_REV_SEQ_4_VALS(v) (v)+3, (v)+2, (v)+1, (v) + +#define SWAP2_SHUF_MASK_16_BYTES \ + SWAP_SHUF_REV_SEQ_2_VALS (0 * 2), \ + SWAP_SHUF_REV_SEQ_2_VALS (1 * 2), \ + SWAP_SHUF_REV_SEQ_2_VALS (2 * 2), \ + SWAP_SHUF_REV_SEQ_2_VALS (3 * 2), \ + SWAP_SHUF_REV_SEQ_2_VALS (4 * 2), \ + SWAP_SHUF_REV_SEQ_2_VALS (5 * 2), \ + SWAP_SHUF_REV_SEQ_2_VALS (6 * 2), \ + SWAP_SHUF_REV_SEQ_2_VALS (7 * 2) + +#define SWAP4_SHUF_MASK_16_BYTES \ + SWAP_SHUF_REV_SEQ_4_VALS (0 * 4), \ + SWAP_SHUF_REV_SEQ_4_VALS (1 * 4), \ + SWAP_SHUF_REV_SEQ_4_VALS (2 * 4), \ + SWAP_SHUF_REV_SEQ_4_VALS (3 * 4) + +#if defined(USE_SWAP_AVX2) +/* if we use 256_BIT_INIT_MASK, each static array mask will be larger for 16 bytes */ +// #define SWAP_USE_256_BIT_INIT_MASK +#endif + +#if defined(SWAP_USE_256_BIT_INIT_MASK) && defined(USE_SWAP_AVX2) +#define SWAP_MASK_INIT_SIZE 32 +#else +#define SWAP_MASK_INIT_SIZE 16 +#endif + +MY_ALIGN(SWAP_MASK_INIT_SIZE) +static const Byte k_ShufMask_Swap2[] = +{ + SWAP2_SHUF_MASK_16_BYTES + #if SWAP_MASK_INIT_SIZE > 16 + , SWAP2_SHUF_MASK_16_BYTES + #endif +}; + +MY_ALIGN(SWAP_MASK_INIT_SIZE) +static const Byte k_ShufMask_Swap4[] = +{ + SWAP4_SHUF_MASK_16_BYTES + #if SWAP_MASK_INIT_SIZE > 16 + , SWAP4_SHUF_MASK_16_BYTES + #endif +}; + + +#ifdef USE_SWAP_SSSE3 + +#include // ssse3 + +#define SHUF_128(i) *(items + (i)) = \ + _mm_shuffle_epi8(*(items + (i)), mask); // SSSE3 + +// Z7_NO_INLINE +static +#ifdef SWAP_ATTRIB_SSSE3 +SWAP_ATTRIB_SSSE3 +#endif +Z7_ATTRIB_NO_VECTORIZE +void +Z7_FASTCALL +ShufBytes_128(void *items8, const void *lim8, const void *mask128_ptr) +{ + __m128i *items = (__m128i *)items8; + const __m128i *lim = (const __m128i *)lim8; + // const __m128i mask = _mm_set_epi8(SHUF_SWAP2_MASK_16_VALS); + // const __m128i mask = _mm_set_epi8(SHUF_SWAP4_MASK_16_VALS); + // const __m128i mask = _mm_load_si128((const __m128i *)(const void *)&(k_ShufMask_Swap4[0])); + // const __m128i mask = _mm_load_si128((const __m128i *)(const void *)&(k_ShufMask_Swap4[0])); + // const __m128i mask = *(const __m128i *)(const void *)&(k_ShufMask_Swap4[0]); + const __m128i mask = *(const __m128i *)mask128_ptr; + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + do + { + SHUF_128(0) SHUF_128(1) items += 2; + SHUF_128(0) SHUF_128(1) items += 2; + } + while (items != lim); +} + +#endif // USE_SWAP_SSSE3 + + + +#ifdef USE_SWAP_AVX2 + +#include // avx, avx2 +#if defined(__clang__) +#include +#include +#endif + +#define SHUF_256(i) *(items + (i)) = \ + _mm256_shuffle_epi8(*(items + (i)), mask); // AVX2 + +// Z7_NO_INLINE +static +#ifdef SWAP_ATTRIB_AVX2 +SWAP_ATTRIB_AVX2 +#endif +Z7_ATTRIB_NO_VECTORIZE +void +Z7_FASTCALL +ShufBytes_256(void *items8, const void *lim8, const void *mask128_ptr) +{ + __m256i *items = (__m256i *)items8; + const __m256i *lim = (const __m256i *)lim8; + /* + UNUSED_VAR(mask128_ptr) + __m256i mask = + for Swap4: _mm256_setr_epi8(SWAP4_SHUF_MASK_16_BYTES, SWAP4_SHUF_MASK_16_BYTES); + for Swap2: _mm256_setr_epi8(SWAP2_SHUF_MASK_16_BYTES, SWAP2_SHUF_MASK_16_BYTES); + */ + const __m256i mask = + #if SWAP_MASK_INIT_SIZE > 16 + *(const __m256i *)(const void *)mask128_ptr; + #else + /* msvc: broadcastsi128() version reserves the stack for no reason + msvc 19.29-: _mm256_insertf128_si256() / _mm256_set_m128i)) versions use non-avx movdqu xmm0,XMMWORD PTR [r8] + msvc 19.30+ (VS2022): replaces _mm256_set_m128i(m,m) to vbroadcastf128(m) as we want + */ + // _mm256_broadcastsi128_si256(*mask128_ptr); + /* + #define MY_mm256_set_m128i(hi, lo) _mm256_insertf128_si256(_mm256_castsi128_si256(lo), (hi), 1) + MY_mm256_set_m128i + */ + _mm256_set_m128i( + *(const __m128i *)mask128_ptr, + *(const __m128i *)mask128_ptr); + #endif + + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + do + { + SHUF_256(0) SHUF_256(1) items += 2; + SHUF_256(0) SHUF_256(1) items += 2; + } + while (items != lim); +} + +#endif // USE_SWAP_AVX2 +#endif // USE_SWAP_SSSE3 || USE_SWAP_AVX2 +#endif // USE_SWAP_128 + + + +// compile message "NEON intrinsics not available with the soft-float ABI" +#elif defined(MY_CPU_ARM_OR_ARM64) || \ + (defined(__ARM_ARCH) && (__ARM_ARCH >= 7)) +// #elif defined(MY_CPU_ARM64) + + #if defined(__clang__) && (__clang_major__ >= 8) \ + || defined(__GNUC__) && (__GNUC__ >= 8) + #if (defined(__ARM_ARCH) && (__ARM_ARCH >= 7)) \ + || defined(MY_CPU_ARM64) + #define USE_SWAP_128 + #endif + #ifdef MY_CPU_ARM64 + // #define SWAP_ATTRIB_NEON __attribute__((__target__(""))) + #else + // #define SWAP_ATTRIB_NEON __attribute__((__target__("fpu=crypto-neon-fp-armv8"))) + #endif + #elif defined(_MSC_VER) + #if (_MSC_VER >= 1910) + #define USE_SWAP_128 + #endif + #endif + + #if defined(_MSC_VER) && defined(MY_CPU_ARM64) + #include + #else + #include + #endif + +#ifndef USE_SWAP_128 + #define FORCE_SWAP_MODE +#else + +#ifdef MY_CPU_ARM64 + // for debug : comment it + #define FORCE_SWAP_MODE +#else + #define k_SwapBytes_Mode_NEON 1 +#endif +// typedef uint8x16_t v128; +#define SWAP2_128(i) *(uint8x16_t *) (void *)(items + (i) * 8) = \ + vrev16q_u8(*(const uint8x16_t *)(const void *)(items + (i) * 8)); +#define SWAP4_128(i) *(uint8x16_t *) (void *)(items + (i) * 4) = \ + vrev32q_u8(*(const uint8x16_t *)(const void *)(items + (i) * 4)); + +// Z7_NO_INLINE +static +#ifdef SWAP_ATTRIB_NEON +SWAP_ATTRIB_NEON +#endif +Z7_ATTRIB_NO_VECTORIZE +void +Z7_FASTCALL +SwapBytes2_128(CSwapUInt16 *items, const CSwapUInt16 *lim) +{ + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + do + { + SWAP2_128(0) SWAP2_128(1) items += 2 * 8; + SWAP2_128(0) SWAP2_128(1) items += 2 * 8; + } + while (items != lim); +} + +// Z7_NO_INLINE +static +#ifdef SWAP_ATTRIB_NEON +SWAP_ATTRIB_NEON +#endif +Z7_ATTRIB_NO_VECTORIZE +void +Z7_FASTCALL +SwapBytes4_128(CSwapUInt32 *items, const CSwapUInt32 *lim) +{ + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + do + { + SWAP4_128(0) SWAP4_128(1) items += 2 * 4; + SWAP4_128(0) SWAP4_128(1) items += 2 * 4; + } + while (items != lim); +} + +#endif // USE_SWAP_128 + +#else // MY_CPU_ARM_OR_ARM64 +#define FORCE_SWAP_MODE +#endif // MY_CPU_ARM_OR_ARM64 + + + + + + +#if defined(Z7_MSC_VER_ORIGINAL) && defined(MY_CPU_X86) + /* _byteswap_ushort() in MSVC x86 32-bit works via slow { mov dh, al; mov dl, ah } + So we use own versions of byteswap function */ + #if (_MSC_VER < 1400 ) // old MSVC-X86 without _rotr16() support + #define SWAP2_16(i) { UInt32 v = items[i]; v += (v << 16); v >>= 8; items[i] = (CSwapUInt16)v; } + #else // is new MSVC-X86 with fast _rotr16() + #include + #define SWAP2_16(i) { items[i] = _rotr16(items[i], 8); } + #endif +#else // is not MSVC-X86 + #define SWAP2_16(i) { CSwapUInt16 v = items[i]; items[i] = Z7_BSWAP16(v); } +#endif // MSVC-X86 + +#if defined(Z7_CPU_FAST_BSWAP_SUPPORTED) + #define SWAP4_32(i) { CSwapUInt32 v = items[i]; items[i] = Z7_BSWAP32(v); } +#else + #define SWAP4_32(i) \ + { UInt32 v = items[i]; \ + v = ((v & 0xff00ff) << 8) + ((v >> 8) & 0xff00ff); \ + v = rotlFixed(v, 16); \ + items[i] = v; } +#endif + + + + +#if defined(FORCE_SWAP_MODE) && defined(USE_SWAP_128) + #define DEFAULT_Swap2 SwapBytes2_128 + #if !defined(MY_CPU_X86_OR_AMD64) + #define DEFAULT_Swap4 SwapBytes4_128 + #endif +#endif + +#if !defined(DEFAULT_Swap2) || !defined(DEFAULT_Swap4) + +#define SWAP_BASE_FUNCS_PREFIXES \ +Z7_FORCE_INLINE \ +static \ +Z7_ATTRIB_NO_VECTOR \ +void Z7_FASTCALL + + +#ifdef MY_CPU_64BIT + +#if defined(MY_CPU_ARM64) \ + && defined(__ARM_ARCH) && (__ARM_ARCH >= 8) \ + && ( (defined(__GNUC__) && (__GNUC__ >= 4)) \ + || (defined(__clang__) && (__clang_major__ >= 4))) + + #define SWAP2_64_VAR(v) asm ("rev16 %x0,%x0" : "+r" (v)); + #define SWAP4_64_VAR(v) asm ("rev32 %x0,%x0" : "+r" (v)); + +#else // is not ARM64-GNU + +#if !defined(MY_CPU_X86_OR_AMD64) || (k_SwapBytes_Mode_MIN == 0) || !defined(USE_SWAP_128) + #define SWAP2_64_VAR(v) \ + v = ( 0x00ff00ff00ff00ff & (v >> 8)) \ + + ((0x00ff00ff00ff00ff & v) << 8); + /* plus gives faster code in MSVC */ +#endif + +#ifdef Z7_CPU_FAST_BSWAP_SUPPORTED + #define SWAP4_64_VAR(v) \ + v = Z7_BSWAP64(v); \ + v = Z7_ROTL64(v, 32); +#else + #define SWAP4_64_VAR(v) \ + v = ( 0x000000ff000000ff & (v >> 24)) \ + + ((0x000000ff000000ff & v) << 24 ) \ + + ( 0x0000ff000000ff00 & (v >> 8)) \ + + ((0x0000ff000000ff00 & v) << 8 ) \ + ; +#endif + +#endif // ARM64-GNU + + +#ifdef SWAP2_64_VAR + +#define SWAP2_64(i) { \ + UInt64 v = *(const UInt64 *)(const void *)(items + (i) * 4); \ + SWAP2_64_VAR(v) \ + *(UInt64 *)(void *)(items + (i) * 4) = v; } + +SWAP_BASE_FUNCS_PREFIXES +SwapBytes2_64(CSwapUInt16 *items, const CSwapUInt16 *lim) +{ + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + do + { + SWAP2_64(0) SWAP2_64(1) items += 2 * 4; + SWAP2_64(0) SWAP2_64(1) items += 2 * 4; + } + while (items != lim); +} + + #define DEFAULT_Swap2 SwapBytes2_64 + #if !defined(FORCE_SWAP_MODE) + #define SWAP2_DEFAULT_MODE 0 + #endif +#else // !defined(SWAP2_64_VAR) + #define DEFAULT_Swap2 SwapBytes2_128 + #if !defined(FORCE_SWAP_MODE) + #define SWAP2_DEFAULT_MODE 1 + #endif +#endif // SWAP2_64_VAR + + +#define SWAP4_64(i) { \ + UInt64 v = *(const UInt64 *)(const void *)(items + (i) * 2); \ + SWAP4_64_VAR(v) \ + *(UInt64 *)(void *)(items + (i) * 2) = v; } + +SWAP_BASE_FUNCS_PREFIXES +SwapBytes4_64(CSwapUInt32 *items, const CSwapUInt32 *lim) +{ + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + do + { + SWAP4_64(0) SWAP4_64(1) items += 2 * 2; + SWAP4_64(0) SWAP4_64(1) items += 2 * 2; + } + while (items != lim); +} + +#define DEFAULT_Swap4 SwapBytes4_64 + +#else // is not 64BIT + + +#if defined(MY_CPU_ARM_OR_ARM64) \ + && defined(__ARM_ARCH) && (__ARM_ARCH >= 6) \ + && ( (defined(__GNUC__) && (__GNUC__ >= 4)) \ + || (defined(__clang__) && (__clang_major__ >= 4))) + +#ifdef MY_CPU_64BIT + #define SWAP2_32_VAR(v) asm ("rev16 %w0,%w0" : "+r" (v)); +#else + #define SWAP2_32_VAR(v) asm ("rev16 %0,%0" : "+r" (v)); // for clang/gcc + // asm ("rev16 %r0,%r0" : "+r" (a)); // for gcc +#endif + +#elif defined(_MSC_VER) && (_MSC_VER < 1300) && defined(MY_CPU_X86) \ + || !defined(Z7_CPU_FAST_BSWAP_SUPPORTED) \ + || !defined(Z7_CPU_FAST_ROTATE_SUPPORTED) + // old msvc doesn't support _byteswap_ulong() + #define SWAP2_32_VAR(v) \ + v = ((v & 0xff00ff) << 8) + ((v >> 8) & 0xff00ff); + +#else // is not ARM and is not old-MSVC-X86 and fast BSWAP/ROTATE are supported + #define SWAP2_32_VAR(v) \ + v = Z7_BSWAP32(v); \ + v = rotlFixed(v, 16); + +#endif // GNU-ARM* + +#define SWAP2_32(i) { \ + UInt32 v = *(const UInt32 *)(const void *)(items + (i) * 2); \ + SWAP2_32_VAR(v); \ + *(UInt32 *)(void *)(items + (i) * 2) = v; } + + +SWAP_BASE_FUNCS_PREFIXES +SwapBytes2_32(CSwapUInt16 *items, const CSwapUInt16 *lim) +{ + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + do + { + SWAP2_32(0) SWAP2_32(1) items += 2 * 2; + SWAP2_32(0) SWAP2_32(1) items += 2 * 2; + } + while (items != lim); +} + + +SWAP_BASE_FUNCS_PREFIXES +SwapBytes4_32(CSwapUInt32 *items, const CSwapUInt32 *lim) +{ + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + do + { + SWAP4_32(0) SWAP4_32(1) items += 2; + SWAP4_32(0) SWAP4_32(1) items += 2; + } + while (items != lim); +} + +#define DEFAULT_Swap2 SwapBytes2_32 +#define DEFAULT_Swap4 SwapBytes4_32 +#if !defined(FORCE_SWAP_MODE) + #define SWAP2_DEFAULT_MODE 0 +#endif + +#endif // MY_CPU_64BIT +#endif // if !defined(DEFAULT_Swap2) || !defined(DEFAULT_Swap4) + + + +#if !defined(FORCE_SWAP_MODE) +static unsigned g_SwapBytes_Mode; +#endif + +/* size of largest unrolled loop iteration: 128 bytes = 4 * 32 bytes (AVX). */ +#define SWAP_ITERATION_BLOCK_SIZE_MAX (1 << 7) + +// 32 bytes for (AVX) or 2 * 16-bytes for NEON. +#define SWAP_VECTOR_ALIGN_SIZE (1 << 5) + +Z7_NO_INLINE +void z7_SwapBytes2(CSwapUInt16 *items, size_t numItems) +{ + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + for (; numItems != 0 && ((unsigned)(ptrdiff_t)items & (SWAP_VECTOR_ALIGN_SIZE - 1)) != 0; numItems--) + { + SWAP2_16(0) + items++; + } + { + const size_t k_Align_Mask = SWAP_ITERATION_BLOCK_SIZE_MAX / sizeof(CSwapUInt16) - 1; + size_t numItems2 = numItems; + CSwapUInt16 *lim; + numItems &= k_Align_Mask; + numItems2 &= ~(size_t)k_Align_Mask; + lim = items + numItems2; + if (numItems2 != 0) + { + #if !defined(FORCE_SWAP_MODE) + #ifdef MY_CPU_X86_OR_AMD64 + #ifdef USE_SWAP_AVX2 + if (g_SwapBytes_Mode > k_SwapBytes_Mode_SSSE3) + ShufBytes_256((__m256i *)(void *)items, + (const __m256i *)(const void *)lim, + (const __m128i *)(const void *)&(k_ShufMask_Swap2[0])); + else + #endif + #ifdef USE_SWAP_SSSE3 + if (g_SwapBytes_Mode >= k_SwapBytes_Mode_SSSE3) + ShufBytes_128((__m128i *)(void *)items, + (const __m128i *)(const void *)lim, + (const __m128i *)(const void *)&(k_ShufMask_Swap2[0])); + else + #endif + #endif // MY_CPU_X86_OR_AMD64 + #if SWAP2_DEFAULT_MODE == 0 + if (g_SwapBytes_Mode != 0) + SwapBytes2_128(items, lim); + else + #endif + #endif // FORCE_SWAP_MODE + DEFAULT_Swap2(items, lim); + } + items = lim; + } + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + for (; numItems != 0; numItems--) + { + SWAP2_16(0) + items++; + } +} + + +Z7_NO_INLINE +void z7_SwapBytes4(CSwapUInt32 *items, size_t numItems) +{ + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + for (; numItems != 0 && ((unsigned)(ptrdiff_t)items & (SWAP_VECTOR_ALIGN_SIZE - 1)) != 0; numItems--) + { + SWAP4_32(0) + items++; + } + { + const size_t k_Align_Mask = SWAP_ITERATION_BLOCK_SIZE_MAX / sizeof(CSwapUInt32) - 1; + size_t numItems2 = numItems; + CSwapUInt32 *lim; + numItems &= k_Align_Mask; + numItems2 &= ~(size_t)k_Align_Mask; + lim = items + numItems2; + if (numItems2 != 0) + { + #if !defined(FORCE_SWAP_MODE) + #ifdef MY_CPU_X86_OR_AMD64 + #ifdef USE_SWAP_AVX2 + if (g_SwapBytes_Mode > k_SwapBytes_Mode_SSSE3) + ShufBytes_256((__m256i *)(void *)items, + (const __m256i *)(const void *)lim, + (const __m128i *)(const void *)&(k_ShufMask_Swap4[0])); + else + #endif + #ifdef USE_SWAP_SSSE3 + if (g_SwapBytes_Mode >= k_SwapBytes_Mode_SSSE3) + ShufBytes_128((__m128i *)(void *)items, + (const __m128i *)(const void *)lim, + (const __m128i *)(const void *)&(k_ShufMask_Swap4[0])); + else + #endif + #else // MY_CPU_X86_OR_AMD64 + + if (g_SwapBytes_Mode != 0) + SwapBytes4_128(items, lim); + else + #endif // MY_CPU_X86_OR_AMD64 + #endif // FORCE_SWAP_MODE + DEFAULT_Swap4(items, lim); + } + items = lim; + } + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + for (; numItems != 0; numItems--) + { + SWAP4_32(0) + items++; + } +} + + +// #define SHOW_HW_STATUS + +#ifdef SHOW_HW_STATUS +#include +#define PRF(x) x +#else +#define PRF(x) +#endif + +void z7_SwapBytesPrepare(void) +{ +#ifndef FORCE_SWAP_MODE + unsigned mode = 0; // k_SwapBytes_Mode_BASE; + +#ifdef MY_CPU_ARM_OR_ARM64 + { + if (CPU_IsSupported_NEON()) + { + // #pragma message ("=== SwapBytes NEON") + PRF(printf("\n=== SwapBytes NEON\n");) + mode = k_SwapBytes_Mode_NEON; + } + } +#else // MY_CPU_ARM_OR_ARM64 + { + #ifdef USE_SWAP_AVX2 + if (CPU_IsSupported_AVX2()) + { + // #pragma message ("=== SwapBytes AVX2") + PRF(printf("\n=== SwapBytes AVX2\n");) + mode = k_SwapBytes_Mode_AVX2; + } + else + #endif + #ifdef USE_SWAP_SSSE3 + if (CPU_IsSupported_SSSE3()) + { + // #pragma message ("=== SwapBytes SSSE3") + PRF(printf("\n=== SwapBytes SSSE3\n");) + mode = k_SwapBytes_Mode_SSSE3; + } + else + #endif + #if !defined(MY_CPU_AMD64) + if (CPU_IsSupported_SSE2()) + #endif + { + // #pragma message ("=== SwapBytes SSE2") + PRF(printf("\n=== SwapBytes SSE2\n");) + mode = k_SwapBytes_Mode_SSE2; + } + } +#endif // MY_CPU_ARM_OR_ARM64 + g_SwapBytes_Mode = mode; + // g_SwapBytes_Mode = 0; // for debug +#endif // FORCE_SWAP_MODE + PRF(printf("\n=== SwapBytesPrepare\n");) +} + +#undef PRF diff -Nru 7zip-22.01+dfsg/C/SwapBytes.h 7zip-23.01+dfsg/C/SwapBytes.h --- 7zip-22.01+dfsg/C/SwapBytes.h 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/SwapBytes.h 2023-04-02 12:00:00.000000000 +0000 @@ -0,0 +1,17 @@ +/* SwapBytes.h -- Byte Swap conversion filter +2023-04-02 : Igor Pavlov : Public domain */ + +#ifndef ZIP7_INC_SWAP_BYTES_H +#define ZIP7_INC_SWAP_BYTES_H + +#include "7zTypes.h" + +EXTERN_C_BEGIN + +void z7_SwapBytes2(UInt16 *data, size_t numItems); +void z7_SwapBytes4(UInt32 *data, size_t numItems); +void z7_SwapBytesPrepare(void); + +EXTERN_C_END + +#endif diff -Nru 7zip-22.01+dfsg/C/Threads.c 7zip-23.01+dfsg/C/Threads.c --- 7zip-22.01+dfsg/C/Threads.c 2021-12-21 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Threads.c 2023-03-04 18:00:00.000000000 +0000 @@ -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 @@ 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 @@ // ---------- 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 @@ // #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 @@ 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 @@ { if (cpuSet) { - #ifdef _7ZIP_AFFINITY_SUPPORTED + #ifdef Z7_AFFINITY_SUPPORTED /* printf("\n affinity :"); @@ -292,7 +300,7 @@ 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_Close(CThread *p) { - // Print("Thread_Close"); + // Print("Thread_Close") int ret; if (!p->_created) return 0; @@ -326,7 +334,7 @@ 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 @@ 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 ? True : False); p->_created = 1; @@ -363,7 +371,7 @@ WRes Event_Set(CEvent *p) { - RINOK(pthread_mutex_lock(&p->_mutex)); + RINOK(pthread_mutex_lock(&p->_mutex)) p->_state = True; int res1 = pthread_cond_broadcast(&p->_cond); int res2 = pthread_mutex_unlock(&p->_mutex); @@ -372,14 +380,14 @@ WRes Event_Reset(CEvent *p) { - RINOK(pthread_mutex_lock(&p->_mutex)); + RINOK(pthread_mutex_lock(&p->_mutex)) p->_state = False; 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 == False) { // ETIMEDOUT @@ -411,8 +419,8 @@ { 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 @@ 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 @@ 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 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 @@ void CriticalSection_Enter(CCriticalSection *p) { - // Print("CriticalSection_Enter"); + // Print("CriticalSection_Enter") if (p) { // int ret = @@ -507,7 +515,7 @@ void CriticalSection_Leave(CCriticalSection *p) { - // Print("CriticalSection_Leave"); + // Print("CriticalSection_Leave") if (p) { // int ret = @@ -517,7 +525,7 @@ void CriticalSection_Delete(CCriticalSection *p) { - // Print("CriticalSection_Delete"); + // Print("CriticalSection_Delete") if (p) { // int ret = @@ -527,14 +535,28 @@ 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 -Nru 7zip-22.01+dfsg/C/Threads.h 7zip-23.01+dfsg/C/Threads.h --- 7zip-22.01+dfsg/C/Threads.h 2021-12-21 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Threads.h 2023-04-02 11:00:00.000000000 +0000 @@ -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 @@ 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 @@ #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 @@ #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_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 @@ #endif // _WIN32 +WRes AutoResetEvent_OptCreate_And_Reset(CAutoResetEvent *p); + EXTERN_C_END #endif diff -Nru 7zip-22.01+dfsg/C/Util/7z/7z.dsp 7zip-23.01+dfsg/C/Util/7z/7z.dsp --- 7zip-22.01+dfsg/C/Util/7z/7z.dsp 2015-06-10 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/7z/7z.dsp 2023-03-06 12:00:00.000000000 +0000 @@ -42,7 +42,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /MD /W4 /WX /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /FAcs /Yu"Precomp.h" /FD /c +# ADD CPP /nologo /MD /W4 /WX /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /D "Z7_PPMD_SUPPORT" /FAcs /Yu"Precomp.h" /FD /c # ADD BASE RSC /l 0x419 /d "NDEBUG" # ADD RSC /l 0x419 /d "NDEBUG" BSC32=bscmake.exe @@ -67,7 +67,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_SZ_ALLOC_DEBUG2" /D "_SZ_NO_INT_64_A" /D "WIN32" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /Yu"Precomp.h" /FD /GZ /c +# ADD CPP /nologo /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_SZ_ALLOC_DEBUG2" /D "_SZ_NO_INT_64_A" /D "WIN32" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /D "Z7_PPMD_SUPPORT" /Yu"Precomp.h" /FD /GZ /c # ADD BASE RSC /l 0x419 /d "_DEBUG" # ADD RSC /l 0x419 /d "_DEBUG" BSC32=bscmake.exe @@ -145,6 +145,10 @@ # End Source File # Begin Source File +SOURCE=..\..\7zWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\Bcj2.c # End Source File # Begin Source File diff -Nru 7zip-22.01+dfsg/C/Util/7z/7zMain.c 7zip-23.01+dfsg/C/Util/7z/7zMain.c --- 7zip-22.01+dfsg/C/Util/7z/7zMain.c 2021-04-29 11:46:20.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/7z/7zMain.c 2023-04-04 17:00:00.000000000 +0000 @@ -1,5 +1,5 @@ /* 7zMain.c - Test application for 7z Decoder -2021-04-29 : Igor Pavlov : Public domain */ +2023-04-04 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -32,10 +32,10 @@ #endif #endif - #define kInputBufSize ((size_t)1 << 18) static const ISzAlloc g_Alloc = { SzAlloc, SzFree }; +// static const ISzAlloc g_Alloc_temp = { SzAllocTemp, SzFreeTemp }; static void Print(const char *s) @@ -53,19 +53,19 @@ } #ifndef _WIN32 -#define _USE_UTF8 +#define MY_USE_UTF8 #endif -/* #define _USE_UTF8 */ +/* #define MY_USE_UTF8 */ -#ifdef _USE_UTF8 +#ifdef MY_USE_UTF8 -#define _UTF8_START(n) (0x100 - (1 << (7 - (n)))) +#define MY_UTF8_START(n) (0x100 - (1 << (7 - (n)))) -#define _UTF8_RANGE(n) (((UInt32)1) << ((n) * 5 + 6)) +#define MY_UTF8_RANGE(n) (((UInt32)1) << ((n) * 5 + 6)) -#define _UTF8_HEAD(n, val) ((Byte)(_UTF8_START(n) + (val >> (6 * (n))))) -#define _UTF8_CHAR(n, val) ((Byte)(0x80 + (((val) >> (6 * (n))) & 0x3F))) +#define MY_UTF8_HEAD(n, val) ((Byte)(MY_UTF8_START(n) + (val >> (6 * (n))))) +#define MY_UTF8_CHAR(n, val) ((Byte)(0x80 + (((val) >> (6 * (n))) & 0x3F))) static size_t Utf16_To_Utf8_Calc(const UInt16 *src, const UInt16 *srcLim) { @@ -82,7 +82,7 @@ if (val < 0x80) continue; - if (val < _UTF8_RANGE(1)) + if (val < MY_UTF8_RANGE(1)) { size++; continue; @@ -90,7 +90,7 @@ if (val >= 0xD800 && val < 0xDC00 && src != srcLim) { - UInt32 c2 = *src; + const UInt32 c2 = *src; if (c2 >= 0xDC00 && c2 < 0xE000) { src++; @@ -119,33 +119,33 @@ continue; } - if (val < _UTF8_RANGE(1)) + if (val < MY_UTF8_RANGE(1)) { - dest[0] = _UTF8_HEAD(1, val); - dest[1] = _UTF8_CHAR(0, val); + dest[0] = MY_UTF8_HEAD(1, val); + dest[1] = MY_UTF8_CHAR(0, val); dest += 2; continue; } if (val >= 0xD800 && val < 0xDC00 && src != srcLim) { - UInt32 c2 = *src; + const UInt32 c2 = *src; if (c2 >= 0xDC00 && c2 < 0xE000) { src++; val = (((val - 0xD800) << 10) | (c2 - 0xDC00)) + 0x10000; - dest[0] = _UTF8_HEAD(3, val); - dest[1] = _UTF8_CHAR(2, val); - dest[2] = _UTF8_CHAR(1, val); - dest[3] = _UTF8_CHAR(0, val); + dest[0] = MY_UTF8_HEAD(3, val); + dest[1] = MY_UTF8_CHAR(2, val); + dest[2] = MY_UTF8_CHAR(1, val); + dest[3] = MY_UTF8_CHAR(0, val); dest += 4; continue; } } - dest[0] = _UTF8_HEAD(2, val); - dest[1] = _UTF8_CHAR(1, val); - dest[2] = _UTF8_CHAR(0, val); + dest[0] = MY_UTF8_HEAD(2, val); + dest[1] = MY_UTF8_CHAR(1, val); + dest[2] = MY_UTF8_CHAR(0, val); dest += 3; } } @@ -163,7 +163,7 @@ #endif static SRes Utf16_To_Char(CBuf *buf, const UInt16 *s - #ifndef _USE_UTF8 + #ifndef MY_USE_UTF8 , UINT codePage #endif ) @@ -171,7 +171,7 @@ unsigned len = 0; for (len = 0; s[len] != 0; len++) {} - #ifndef _USE_UTF8 + #ifndef MY_USE_UTF8 { const unsigned size = len * 3 + 100; if (!Buf_EnsureSize(buf, size)) @@ -216,7 +216,7 @@ CBuf buf; WRes res; Buf_Init(&buf); - RINOK(Utf16_To_Char(&buf, name MY_FILE_CODE_PAGE_PARAM)); + RINOK(Utf16_To_Char(&buf, name MY_FILE_CODE_PAGE_PARAM)) res = #ifdef _WIN32 @@ -239,7 +239,7 @@ CBuf buf; WRes res; Buf_Init(&buf); - RINOK(Utf16_To_Char(&buf, name MY_FILE_CODE_PAGE_PARAM)); + RINOK(Utf16_To_Char(&buf, name MY_FILE_CODE_PAGE_PARAM)) res = OutFile_Open(p, (const char *)buf.data); Buf_Free(&buf, &g_Alloc); return res; @@ -253,7 +253,7 @@ SRes res; Buf_Init(&buf); res = Utf16_To_Char(&buf, s - #ifndef _USE_UTF8 + #ifndef MY_USE_UTF8 , CP_OEMCP #endif ); @@ -328,12 +328,12 @@ static LONG TIME_GetBias() { - time_t utc = time(NULL); + const time_t utc = time(NULL); struct tm *ptm = localtime(&utc); - int localdaylight = ptm->tm_isdst; /* daylight for local timezone */ + const int localdaylight = ptm->tm_isdst; /* daylight for local timezone */ ptm = gmtime(&utc); ptm->tm_isdst = localdaylight; /* use local daylight, not that of Greenwich */ - LONG bias = (int)(mktime(ptm)-utc); + const LONG bias = (int)(mktime(ptm) - utc); return bias; } @@ -352,7 +352,7 @@ { UInt64 v = GET_TIME_64(fileTime); v = (UInt64)((Int64)v - (Int64)TIME_GetBias() * TICKS_PER_SEC); - SET_FILETIME(localFileTime, v); + SET_FILETIME(localFileTime, v) return TRUE; } @@ -364,7 +364,7 @@ static Int64 Time_FileTimeToUnixTime64(const FILETIME *ft) { - UInt64 winTime = GET_TIME_64(ft); + const UInt64 winTime = GET_TIME_64(ft); return (Int64)(winTime / kNumTimeQuantumsInSecond) - (Int64)kUnixTimeOffset; } @@ -384,8 +384,8 @@ if (sec2 == sec) { ts->tv_sec = sec2; - UInt64 winTime = GET_TIME_64(ft); - ts->tv_nsec = (long)((winTime % 10000000) * 100);; + const UInt64 winTime = GET_TIME_64(ft); + ts->tv_nsec = (long)((winTime % 10000000) * 100); return; } } @@ -407,7 +407,7 @@ CBuf buf; int res; Buf_Init(&buf); - RINOK(Utf16_To_Char(&buf, name MY_FILE_CODE_PAGE_PARAM)); + RINOK(Utf16_To_Char(&buf, name MY_FILE_CODE_PAGE_PARAM)) FILETIME_To_timespec(NULL, ×[0]); FILETIME_To_timespec(mTime, ×[1]); res = utimensat(AT_FDCWD, (const char *)buf.data, times, flags); @@ -461,7 +461,7 @@ ms[1] = 29; for (mon = 0;; mon++) { - unsigned d = ms[mon]; + const unsigned d = ms[mon]; if (v < d) break; v -= d; @@ -474,7 +474,7 @@ UIntToStr_2(s, sec); s[2] = 0; } -static void PrintLF() +static void PrintLF(void) { Print("\n"); } @@ -541,7 +541,7 @@ // #define NUM_PARENTS_MAX 128 -int MY_CDECL main(int numargs, char *args[]) +int Z7_CDECL main(int numargs, char *args[]) { ISzAlloc allocImp; ISzAlloc allocTempImp; @@ -581,6 +581,7 @@ allocImp = g_Alloc; allocTempImp = g_Alloc; + // allocTempImp = g_Alloc_temp; { WRes wres = @@ -611,7 +612,7 @@ { lookStream.bufSize = kInputBufSize; lookStream.realStream = &archiveStream.vt; - LookToRead2_Init(&lookStream); + LookToRead2_INIT(&lookStream) } } @@ -767,7 +768,7 @@ } else { - WRes wres = OutFile_OpenUtf16(&outFile, destPath); + const WRes wres = OutFile_OpenUtf16(&outFile, destPath); if (wres != 0) { PrintError_WRes("cannot open output file", wres); @@ -779,7 +780,7 @@ processedSize = outSizeProcessed; { - WRes wres = File_Write(&outFile, outBuffer + offset, &processedSize); + const WRes wres = File_Write(&outFile, outBuffer + offset, &processedSize); if (wres != 0 || processedSize != outSizeProcessed) { PrintError_WRes("cannot write output file", wres); @@ -819,7 +820,7 @@ #endif { - WRes wres = File_Close(&outFile); + const WRes wres = File_Close(&outFile); if (wres != 0) { PrintError_WRes("cannot close output file", wres); diff -Nru 7zip-22.01+dfsg/C/Util/7z/makefile 7zip-23.01+dfsg/C/Util/7z/makefile --- 7zip-22.01+dfsg/C/Util/7z/makefile 2015-06-10 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/7z/makefile 2023-02-20 11:00:00.000000000 +0000 @@ -1,4 +1,4 @@ -CFLAGS = $(CFLAGS) -D_7ZIP_PPMD_SUPPPORT +CFLAGS = $(CFLAGS) -DZ7_PPMD_SUPPORT -DZ7_EXTRACT_ONLY PROG = 7zDec.exe diff -Nru 7zip-22.01+dfsg/C/Util/7z/makefile.gcc 7zip-23.01+dfsg/C/Util/7z/makefile.gcc --- 7zip-22.01+dfsg/C/Util/7z/makefile.gcc 2021-04-29 12:13:06.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/7z/makefile.gcc 2023-03-02 16:00:00.000000000 +0000 @@ -1,6 +1,6 @@ PROG = 7zdec -LOCAL_FLAGS = -D_7ZIP_PPMD_SUPPPORT +LOCAL_FLAGS = -DZ7_PPMD_SUPPORT -DZ7_EXTRACT_ONLY include ../../../CPP/7zip/LzmaDec_gcc.mak @@ -19,8 +19,6 @@ $O/Ppmd7Dec.o \ $O/7zCrc.o \ $O/7zCrcOpt.o \ - $O/Sha256.o \ - $O/Sha256Opt.o \ $O/7zAlloc.o \ $O/7zArcIn.o \ $O/7zBuf.o \ diff -Nru 7zip-22.01+dfsg/C/Util/7z/Precomp.h 7zip-23.01+dfsg/C/Util/7z/Precomp.h --- 7zip-22.01+dfsg/C/Util/7z/Precomp.h 2014-06-16 06:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/7z/Precomp.h 2023-03-04 09:00:00.000000000 +0000 @@ -1,8 +1,12 @@ /* Precomp.h -- StdAfx -2013-06-16 : Igor Pavlov : Public domain */ +2023-03-04 : Igor Pavlov : Public domain */ -#ifndef __7Z_PRECOMP_H -#define __7Z_PRECOMP_H +#ifndef ZIP7_INC_PRECOMP_H +#define ZIP7_INC_PRECOMP_H + +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../Compiler.h" #include "../../7zTypes.h" diff -Nru 7zip-22.01+dfsg/C/Util/7zipInstall/7zipInstall.c 7zip-23.01+dfsg/C/Util/7zipInstall/7zipInstall.c --- 7zip-22.01+dfsg/C/Util/7zipInstall/7zipInstall.c 2022-07-15 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/7zipInstall/7zipInstall.c 2023-04-04 17:00:00.000000000 +0000 @@ -1,16 +1,31 @@ /* 7zipInstall.c - 7-Zip Installer -2022-07-15 : Igor Pavlov : Public domain */ +2023-04-04 : Igor Pavlov : Public domain */ #include "Precomp.h" #define SZ_ERROR_ABORT 100 -#ifdef _MSC_VER +#include "../../7zWindows.h" + +#if defined(_MSC_VER) && _MSC_VER < 1600 #pragma warning(disable : 4201) // nonstandard extension used : nameless struct/union #endif -#include +#ifdef Z7_OLD_WIN_SDK +struct IShellView; +#define SHFOLDERAPI EXTERN_C DECLSPEC_IMPORT HRESULT STDAPICALLTYPE +SHFOLDERAPI SHGetFolderPathW(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath); +#define BIF_NEWDIALOGSTYLE 0x0040 // Use the new dialog layout with the ability to resize +typedef enum { + SHGFP_TYPE_CURRENT = 0, // current value for user, verify it exists + SHGFP_TYPE_DEFAULT = 1, // default value, may not exist +} SHGFP_TYPE; +#endif +#if defined(__MINGW32__) || defined(__MINGW64__) +#include +#else #include +#endif #include "../../7z.h" #include "../../7zAlloc.h" @@ -22,40 +37,46 @@ #include "resource.h" -#if defined(__GNUC__) && (__GNUC__ >= 8) - #pragma GCC diagnostic ignored "-Wcast-function-type" +#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 #define LLL_(quote) L##quote #define LLL(quote) LLL_(quote) -#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) - #define wcscat lstrcatW -#define wcslen lstrlenW +#define wcslen (size_t)lstrlenW #define wcscpy lstrcpyW // wcsncpy() and lstrcpynW() work differently. We don't use them. - #define kInputBufSize ((size_t)1 << 18) - -#define _7ZIP_CUR_VER ((MY_VER_MAJOR << 16) | MY_VER_MINOR) -#define _7ZIP_DLL_VER_COMPAT ((16 << 16) | 3) +#define Z7_7ZIP_CUR_VER ((MY_VER_MAJOR << 16) | MY_VER_MINOR) +#define Z7_7ZIP_DLL_VER_COMPAT ((16 << 16) | 3) static LPCSTR const k_7zip = "7-Zip"; static LPCWSTR const k_Reg_Software_7zip = L"Software\\7-Zip"; -// #define _64BIT_INSTALLER 1 +// #define Z7_64BIT_INSTALLER 1 #ifdef _WIN64 - #define _64BIT_INSTALLER 1 + #define Z7_64BIT_INSTALLER 1 #endif #define k_7zip_with_Ver_base L"7-Zip " LLL(MY_VERSION) -#ifdef _64BIT_INSTALLER +#ifdef Z7_64BIT_INSTALLER // #define USE_7ZIP_32_DLL @@ -84,14 +105,14 @@ static LPCWSTR const k_Reg_Path = L"Path"; static LPCWSTR const k_Reg_Path32 = L"Path" - #ifdef _64BIT_INSTALLER + #ifdef Z7_64BIT_INSTALLER L"64" #else L"32" #endif ; -#if defined(_64BIT_INSTALLER) && !defined(_WIN64) +#if defined(Z7_64BIT_INSTALLER) && !defined(_WIN64) #define k_Reg_WOW_Flag KEY_WOW64_64KEY #else #define k_Reg_WOW_Flag 0 @@ -126,8 +147,6 @@ static WCHAR path[MAX_PATH * 2 + 40]; -// #define MAKE_CHAR_UPPER(c) ((((c) >= 'a' && (c) <= 'z') ? (c) -= 0x20 : (c))) - static void CpyAscii(wchar_t *dest, const char *s) { @@ -200,9 +219,12 @@ return 0; } - my_GetFileVersionInfoSizeW = (Func_GetFileVersionInfoSizeW)GetProcAddress(g_version_dll_hModule, "GetFileVersionInfoSizeW"); - my_GetFileVersionInfoW = (Func_GetFileVersionInfoW)GetProcAddress(g_version_dll_hModule, "GetFileVersionInfoW"); - my_VerQueryValueW = (Func_VerQueryValueW)GetProcAddress(g_version_dll_hModule, "VerQueryValueW"); + my_GetFileVersionInfoSizeW = (Func_GetFileVersionInfoSizeW) MY_CAST_FUNC GetProcAddress(g_version_dll_hModule, + "GetFileVersionInfoSizeW"); + my_GetFileVersionInfoW = (Func_GetFileVersionInfoW) MY_CAST_FUNC GetProcAddress(g_version_dll_hModule, + "GetFileVersionInfoW"); + my_VerQueryValueW = (Func_VerQueryValueW) MY_CAST_FUNC GetProcAddress(g_version_dll_hModule, + "VerQueryValueW"); if (!my_GetFileVersionInfoSizeW || !my_GetFileVersionInfoW @@ -253,7 +275,7 @@ } } -static WRes CreateComplexDir() +static WRes CreateComplexDir(void) { WCHAR s[MAX_PATH + 10]; @@ -287,7 +309,7 @@ { size_t len = wcslen(s); { - int pos = ReverseFind_PathSepar(s); + const int pos = ReverseFind_PathSepar(s); if (pos < 0) return wres; if ((unsigned)pos < prefixSize) @@ -297,7 +319,7 @@ if (len == 1) return 0; s[pos] = 0; - len = pos; + len = (unsigned)pos; } } @@ -309,7 +331,7 @@ break; if (wres == ERROR_ALREADY_EXISTS) { - DWORD attrib = GetFileAttributesW(s); + const DWORD attrib = GetFileAttributesW(s); if (attrib != INVALID_FILE_ATTRIBUTES) if ((attrib & FILE_ATTRIBUTE_DIRECTORY) == 0) return ERROR_ALREADY_EXISTS; @@ -323,7 +345,7 @@ for (;;) { - size_t pos = wcslen(s); + const size_t pos = wcslen(s); if (pos >= len) return 0; s[pos] = CHAR_PATH_SEPARATOR; @@ -339,7 +361,7 @@ { DWORD cnt = MAX_PATH * sizeof(name[0]); DWORD type = 0; - LONG res = RegQueryValueExW(hKey, name, NULL, &type, (LPBYTE)dest, (DWORD *)&cnt); + const LONG res = RegQueryValueExW(hKey, name, NULL, &type, (LPBYTE)dest, &cnt); if (type != REG_SZ) return False; return res == ERROR_SUCCESS; @@ -348,11 +370,11 @@ static int MyRegistry_QueryString2(HKEY hKey, LPCWSTR keyName, LPCWSTR valName, LPWSTR dest) { HKEY key = 0; - LONG res = RegOpenKeyExW(hKey, keyName, 0, KEY_READ | k_Reg_WOW_Flag, &key); + const LONG res = RegOpenKeyExW(hKey, keyName, 0, KEY_READ | k_Reg_WOW_Flag, &key); if (res != ERROR_SUCCESS) return False; { - BoolInt res2 = MyRegistry_QueryString(key, valName, dest); + const BoolInt res2 = MyRegistry_QueryString(key, valName, dest); RegCloseKey(key); return res2; } @@ -550,7 +572,7 @@ for (;; i++) { - wchar_t c = s[i]; + const wchar_t c = s[i]; if (c == 0) break; if (c == '/') @@ -587,7 +609,7 @@ return NULL; for (i = 0;; i++) { - Byte b = s2[i]; + const char b = s2[i]; if (b == 0) return s1; if (MyWCharLower_Ascii(s1[i]) != (Byte)MyCharLower_Ascii(b)) @@ -610,7 +632,7 @@ static int Install(void); -static void OnClose() +static void OnClose(void) { if (g_Install_was_Pressed && !g_Finished) { @@ -624,7 +646,13 @@ g_HWND = NULL; } -static INT_PTR CALLBACK MyDlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) +static +#ifdef Z7_OLD_WIN_SDK + BOOL +#else + INT_PTR +#endif +CALLBACK MyDlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { // UNUSED_VAR(hwnd) UNUSED_VAR(lParam) @@ -730,7 +758,7 @@ return res; } -static void SetRegKey_Path() +static void SetRegKey_Path(void) { SetRegKey_Path2(HKEY_CURRENT_USER); SetRegKey_Path2(HKEY_LOCAL_MACHINE); @@ -828,7 +856,7 @@ static LPCWSTR const k_Shell_Approved = L"Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved"; static LPCWSTR const k_7zip_ShellExtension = L"7-Zip Shell Extension"; -static void WriteCLSID() +static void WriteCLSID(void) { HKEY destKey; LONG res; @@ -879,12 +907,12 @@ , "Drive\\shellex\\DragDropHandlers" }; -static void WriteShellEx() +static void WriteShellEx(void) { unsigned i; WCHAR destPath[MAX_PATH + 40]; - for (i = 0; i < ARRAY_SIZE(k_ShellEx_Items); i++) + for (i = 0; i < Z7_ARRAY_SIZE(k_ShellEx_Items); i++) { CpyAscii(destPath, k_ShellEx_Items[i]); CatAscii(destPath, "\\7-Zip"); @@ -968,7 +996,7 @@ quoteMode = !quoteMode; continue; } - if (pos >= ARRAY_SIZE(cmd) - 1) + if (pos >= Z7_ARRAY_SIZE(cmd) - 1) exit(1); cmd[pos++] = c; } @@ -1026,7 +1054,7 @@ for (;;) { { - wchar_t c = *s; + const wchar_t c = *s; if (c == 0) break; if (c == ' ') @@ -1070,11 +1098,12 @@ } } - #if defined(_64BIT_INSTALLER) && !defined(_WIN64) + #if defined(Z7_64BIT_INSTALLER) && !defined(_WIN64) { BOOL isWow64 = FALSE; - Func_IsWow64Process func_IsWow64Process = (Func_IsWow64Process) - GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "IsWow64Process"); + const Func_IsWow64Process func_IsWow64Process = (Func_IsWow64Process) + MY_CAST_FUNC GetProcAddress(GetModuleHandleW(L"kernel32.dll"), + "IsWow64Process"); if (func_IsWow64Process) func_IsWow64Process(GetCurrentProcess(), &isWow64); @@ -1093,7 +1122,7 @@ { HKEY key = 0; BoolInt ok = False; - LONG res = RegOpenKeyExW(HKEY_CURRENT_USER, k_Reg_Software_7zip, 0, KEY_READ | k_Reg_WOW_Flag, &key); + const LONG res = RegOpenKeyExW(HKEY_CURRENT_USER, k_Reg_Software_7zip, 0, KEY_READ | k_Reg_WOW_Flag, &key); if (res == ERROR_SUCCESS) { ok = MyRegistry_QueryString(key, k_Reg_Path32, path); @@ -1109,7 +1138,7 @@ CpyAscii(path, "\\Program Files\\"); #else - #ifdef _64BIT_INSTALLER + #ifdef Z7_64BIT_INSTALLER { DWORD ttt = GetEnvironmentVariableW(L"ProgramW6432", path, MAX_PATH); if (ttt == 0 || ttt > MAX_PATH) @@ -1150,7 +1179,7 @@ return 1; { - HICON hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON)); + const HICON hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON)); // SendMessage(g_HWND, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon); SendMessage(g_HWND, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon); } @@ -1244,7 +1273,7 @@ allocTempImp.Free = SzFreeTemp; { - DWORD len = GetModuleFileNameW(NULL, sfxPath, MAX_PATH); + const DWORD len = GetModuleFileNameW(NULL, sfxPath, MAX_PATH); if (len == 0 || len > MAX_PATH) return 1; } @@ -1286,7 +1315,7 @@ for (;;) { - wchar_t c = path[i++]; + const wchar_t c = path[i++]; if (c == 0) break; if (c != ' ') @@ -1318,7 +1347,7 @@ { lookStream.bufSize = kInputBufSize; lookStream.realStream = &archiveStream.vt; - LookToRead2_Init(&lookStream); + LookToRead2_INIT(&lookStream) } } @@ -1372,7 +1401,7 @@ } { - size_t len = SzArEx_GetFileNameUtf16(&db, i, NULL); + const size_t len = SzArEx_GetFileNameUtf16(&db, i, NULL); if (len >= MAX_PATH) { res = SZ_ERROR_FAIL; @@ -1468,8 +1497,8 @@ #endif ) { - DWORD ver = GetFileVersion(path); - fileLevel = ((ver < _7ZIP_DLL_VER_COMPAT || ver > _7ZIP_CUR_VER) ? 2 : 1); + const DWORD ver = GetFileVersion(path); + fileLevel = ((ver < Z7_7ZIP_DLL_VER_COMPAT || ver > Z7_7ZIP_CUR_VER) ? 2 : 1); tempIndex++; continue; } @@ -1537,7 +1566,7 @@ #endif { - SRes winRes2 = File_Close(&outFile); + const WRes winRes2 = File_Close(&outFile); if (res != SZ_OK) break; if (winRes2 != 0) diff -Nru 7zip-22.01+dfsg/C/Util/7zipInstall/7zipInstall.dsp 7zip-23.01+dfsg/C/Util/7zipInstall/7zipInstall.dsp --- 7zip-22.01+dfsg/C/Util/7zipInstall/7zipInstall.dsp 2017-04-04 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/7zipInstall/7zipInstall.dsp 2023-04-04 10:00:00.000000000 +0000 @@ -152,6 +152,10 @@ # End Source File # Begin Source File +SOURCE=..\..\7zWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\Bcj2.c # End Source File # Begin Source File @@ -220,6 +224,10 @@ # PROP Default_Filter "" # Begin Source File +SOURCE=..\..\Compiler.h +# End Source File +# Begin Source File + SOURCE=.\Precomp.c # ADD CPP /Yc"Precomp.h" # End Source File diff -Nru 7zip-22.01+dfsg/C/Util/7zipInstall/makefile 7zip-23.01+dfsg/C/Util/7zipInstall/makefile --- 7zip-22.01+dfsg/C/Util/7zipInstall/makefile 2019-02-19 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/7zipInstall/makefile 2023-04-04 13:00:00.000000000 +0000 @@ -1,15 +1,16 @@ PROG = 7zipInstall.exe MY_FIXED = 1 -!IFDEF _64BIT_INSTALLER -CFLAGS = $(CFLAGS) -D_64BIT_INSTALLER +!IFDEF Z7_64BIT_INSTALLER +CFLAGS = $(CFLAGS) -DZ7_64BIT_INSTALLER !ENDIF -CFLAGS = $(CFLAGS) -D_LZMA_SIZE_OPT - CFLAGS = $(CFLAGS) \ - -D_7Z_NO_METHOD_LZMA2 \ - -D_7Z_NO_METHODS_FILTERS + -DZ7_LZMA_SIZE_OPT \ + -DZ7_NO_METHOD_LZMA2 \ + -DZ7_NO_METHODS_FILTERS \ + -DZ7_USE_NATIVE_BRANCH_FILTER \ + -DZ7_EXTRACT_ONLY \ MAIN_OBJS = \ $O\7zipInstall.obj \ @@ -25,6 +26,7 @@ $O\7zDec.obj \ $O\7zStream.obj \ $O\Bcj2.obj \ + $O\Bra.obj \ $O\CpuArch.obj \ $O\DllSecur.obj \ $O\LzmaDec.obj \ diff -Nru 7zip-22.01+dfsg/C/Util/7zipInstall/Precomp.h 7zip-23.01+dfsg/C/Util/7zipInstall/Precomp.h --- 7zip-22.01+dfsg/C/Util/7zipInstall/Precomp.h 2015-05-24 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/7zipInstall/Precomp.h 2023-03-04 09:00:00.000000000 +0000 @@ -1,11 +1,14 @@ /* Precomp.h -- StdAfx -2015-05-24 : Igor Pavlov : Public domain */ +2023-03-04 : 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" +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif +#include "../../Compiler.h" #include "../../7zTypes.h" #endif diff -Nru 7zip-22.01+dfsg/C/Util/7zipUninstall/7zipUninstall.c 7zip-23.01+dfsg/C/Util/7zipUninstall/7zipUninstall.c --- 7zip-22.01+dfsg/C/Util/7zipUninstall/7zipUninstall.c 2022-07-15 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/7zipUninstall/7zipUninstall.c 2023-04-04 13:00:00.000000000 +0000 @@ -3,40 +3,64 @@ #include "Precomp.h" -#ifdef _MSC_VER +// #define SZ_ERROR_ABORT 100 + +#include "../../7zWindows.h" + +#if defined(_MSC_VER) && _MSC_VER < 1600 #pragma warning(disable : 4201) // nonstandard extension used : nameless struct/union -#pragma warning(disable : 4011) // vs2010: identifier truncated to _CRT_SECURE_CPP_OVERLOAD_SECURE #endif -// #define SZ_ERROR_ABORT 100 - -#include +#ifdef Z7_OLD_WIN_SDK +struct IShellView; +#define SHFOLDERAPI EXTERN_C DECLSPEC_IMPORT HRESULT STDAPICALLTYPE +SHFOLDERAPI SHGetFolderPathW(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath); +#define BIF_NEWDIALOGSTYLE 0x0040 // Use the new dialog layout with the ability to resize +typedef enum { + SHGFP_TYPE_CURRENT = 0, // current value for user, verify it exists + SHGFP_TYPE_DEFAULT = 1, // default value, may not exist +} SHGFP_TYPE; +#endif +#if defined(__MINGW32__) || defined(__MINGW64__) +#include +#else #include +#endif #include "../../7zVersion.h" #include "resource.h" -#if defined(__GNUC__) && (__GNUC__ >= 8) - #pragma GCC diagnostic ignored "-Wcast-function-type" +#if (defined(__GNUC__) && (__GNUC__ >= 8)) || defined(__clang__) + // #pragma GCC diagnostic ignored "-Wcast-function-type" #endif +#if 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 + + #define LLL_(quote) L##quote #define LLL(quote) LLL_(quote) -#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define wcscat lstrcatW +#define wcslen (size_t)lstrlenW +#define wcscpy lstrcpyW // static LPCWSTR const k_7zip = L"7-Zip"; -// #define _64BIT_INSTALLER 1 +// #define Z7_64BIT_INSTALLER 1 #ifdef _WIN64 - #define _64BIT_INSTALLER 1 + #define Z7_64BIT_INSTALLER 1 #endif #define k_7zip_with_Ver_base L"7-Zip " LLL(MY_VERSION) -#ifdef _64BIT_INSTALLER +#ifdef Z7_64BIT_INSTALLER // #define USE_7ZIP_32_DLL @@ -64,14 +88,14 @@ static LPCWSTR const k_Reg_Path = L"Path"; static LPCWSTR const k_Reg_Path32 = L"Path" - #ifdef _64BIT_INSTALLER + #ifdef Z7_64BIT_INSTALLER L"64" #else L"32" #endif ; -#if defined(_64BIT_INSTALLER) && !defined(_WIN64) +#if defined(Z7_64BIT_INSTALLER) && !defined(_WIN64) #define k_Reg_WOW_Flag KEY_WOW64_64KEY #else #define k_Reg_WOW_Flag 0 @@ -116,14 +140,14 @@ static LPCWSTR const kUninstallExe = L"Uninstall.exe"; -#define MAKE_CHAR_UPPER(c) ((((c) >= 'a' && (c) <= 'z') ? (c) -= 0x20 : (c))) +#define MAKE_CHAR_UPPER(c) ((((c) >= 'a' && (c) <= 'z') ? (c) - 0x20 : (c))) static void CpyAscii(wchar_t *dest, const char *s) { for (;;) { - Byte b = (Byte)*s++; + const Byte b = (Byte)*s++; *dest++ = b; if (b == 0) return; @@ -173,7 +197,7 @@ for (;;) { wchar_t c1; - wchar_t c2 = *s2++; + const wchar_t c2 = *s2++; if (c2 == 0) return True; c1 = *s1++; @@ -184,7 +208,7 @@ static void NormalizePrefix(WCHAR *s) { - size_t len = wcslen(s); + const size_t len = wcslen(s); if (len != 0) if (s[len - 1] != WCHAR_PATH_SEPARATOR) { @@ -197,7 +221,7 @@ { DWORD cnt = MAX_PATH * sizeof(name[0]); DWORD type = 0; - LONG res = RegQueryValueExW(hKey, name, NULL, &type, (LPBYTE)dest, (DWORD *)&cnt); + const LONG res = RegQueryValueExW(hKey, name, NULL, &type, (LPBYTE)dest, &cnt); if (type != REG_SZ) return False; return res == ERROR_SUCCESS; @@ -206,11 +230,11 @@ static int MyRegistry_QueryString2(HKEY hKey, LPCWSTR keyName, LPCWSTR valName, LPWSTR dest) { HKEY key = 0; - LONG res = RegOpenKeyExW(hKey, keyName, 0, KEY_READ | k_Reg_WOW_Flag, &key); + const LONG res = RegOpenKeyExW(hKey, keyName, 0, KEY_READ | k_Reg_WOW_Flag, &key); if (res != ERROR_SUCCESS) return False; { - BoolInt res2 = MyRegistry_QueryString(key, valName, dest); + const BoolInt res2 = MyRegistry_QueryString(key, valName, dest); RegCloseKey(key); return res2; } @@ -237,11 +261,11 @@ static int MyRegistry_QueryString2_32(HKEY hKey, LPCWSTR keyName, LPCWSTR valName, LPWSTR dest) { HKEY key = 0; - LONG res = RegOpenKeyExW(hKey, keyName, 0, KEY_READ | k_Reg_WOW_Flag_32, &key); + const LONG res = RegOpenKeyExW(hKey, keyName, 0, KEY_READ | k_Reg_WOW_Flag_32, &key); if (res != ERROR_SUCCESS) return False; { - BoolInt res2 = MyRegistry_QueryString(key, valName, dest); + const BoolInt res2 = MyRegistry_QueryString(key, valName, dest); RegCloseKey(key); return res2; } @@ -282,7 +306,7 @@ static void SetRegKey_Path2(HKEY parentKey) { HKEY key = 0; - LONG res = MyRegistry_OpenKey_ReadWrite(parentKey, k_Reg_Software_7zip, &key); + const LONG res = MyRegistry_OpenKey_ReadWrite(parentKey, k_Reg_Software_7zip, &key); if (res == ERROR_SUCCESS) { MyReg_DeleteVal_Path_if_Equal(key, k_Reg_Path32); @@ -293,7 +317,7 @@ } } -static void SetRegKey_Path() +static void SetRegKey_Path(void) { SetRegKey_Path2(HKEY_CURRENT_USER); SetRegKey_Path2(HKEY_LOCAL_MACHINE); @@ -426,7 +450,7 @@ return AreStringsEqual_NoCase(s + wcslen(prefix), name); } -static void WriteCLSID() +static void WriteCLSID(void) { WCHAR s[MAX_PATH + 30]; @@ -435,14 +459,14 @@ if (AreEqual_Path_PrefixName(s, path, L"7-zip.dll")) { { - LONG res = MyRegistry_DeleteKey(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip_Inproc); + const LONG res = MyRegistry_DeleteKey(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip_Inproc); if (res == ERROR_SUCCESS) MyRegistry_DeleteKey(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip); } { unsigned i; - for (i = 0; i < ARRAY_SIZE(k_ShellEx_Items); i++) + for (i = 0; i < Z7_ARRAY_SIZE(k_ShellEx_Items); i++) { WCHAR destPath[MAX_PATH]; CpyAscii(destPath, k_ShellEx_Items[i]); @@ -454,7 +478,7 @@ { HKEY destKey = 0; - LONG res = MyRegistry_OpenKey_ReadWrite(HKEY_LOCAL_MACHINE, k_Shell_Approved, &destKey); + const LONG res = MyRegistry_OpenKey_ReadWrite(HKEY_LOCAL_MACHINE, k_Shell_Approved, &destKey); if (res == ERROR_SUCCESS) { RegDeleteValueW(destKey, k_7zip_CLSID); @@ -472,14 +496,14 @@ if (AreEqual_Path_PrefixName(s, path, L"7-zip32.dll")) { { - LONG res = MyRegistry_DeleteKey_32(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip_Inproc); + const LONG res = MyRegistry_DeleteKey_32(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip_Inproc); if (res == ERROR_SUCCESS) MyRegistry_DeleteKey_32(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip); } { unsigned i; - for (i = 0; i < ARRAY_SIZE(k_ShellEx_Items); i++) + for (i = 0; i < Z7_ARRAY_SIZE(k_ShellEx_Items); i++) { WCHAR destPath[MAX_PATH]; CpyAscii(destPath, k_ShellEx_Items[i]); @@ -491,7 +515,7 @@ { HKEY destKey = 0; - LONG res = MyRegistry_OpenKey_ReadWrite_32(HKEY_LOCAL_MACHINE, k_Shell_Approved, &destKey); + const LONG res = MyRegistry_OpenKey_ReadWrite_32(HKEY_LOCAL_MACHINE, k_Shell_Approved, &destKey); if (res == ERROR_SUCCESS) { RegDeleteValueW(destKey, k_7zip_CLSID); @@ -526,7 +550,7 @@ BoolInt quoteMode = False; for (;; s++) { - wchar_t c = *s; + const wchar_t c = *s; if (c == 0 || (c == L' ' && !quoteMode)) break; if (c == L'\"') @@ -534,7 +558,7 @@ quoteMode = !quoteMode; continue; } - if (pos >= ARRAY_SIZE(cmd) - 1) + if (pos >= Z7_ARRAY_SIZE(cmd) - 1) exit(1); cmd[pos++] = c; } @@ -558,7 +582,7 @@ } */ -static BoolInt DoesFileOrDirExist() +static BoolInt DoesFileOrDirExist(void) { return (GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES); } @@ -573,7 +597,7 @@ #endif } -static BOOL RemoveFileAfterReboot() +static BOOL RemoveFileAfterReboot(void) { return RemoveFileAfterReboot2(path); } @@ -584,7 +608,7 @@ { for (;;) { - wchar_t c = *s++; + const wchar_t c = *s++; if (c == 0) return False; if (c == ' ') @@ -594,7 +618,7 @@ static void AddPathParam(wchar_t *dest, const wchar_t *src) { - BoolInt needQuote = IsThereSpace(src); + const BoolInt needQuote = IsThereSpace(src); if (needQuote) CatAscii(dest, "\""); wcscat(dest, src); @@ -618,9 +642,9 @@ return True; } -static BOOL RemoveDir() +static BOOL RemoveDir(void) { - DWORD attrib = GetFileAttributesW(path); + const DWORD attrib = GetFileAttributesW(path); if (attrib == INVALID_FILE_ATTRIBUTES) return TRUE; if (RemoveDirectoryW(path)) @@ -670,7 +694,7 @@ -static int Install() +static int Install(void) { SRes res = SZ_OK; WRes winRes = 0; @@ -724,7 +748,7 @@ for (;;) { - char c = *curName; + const char c = *curName; if (c == 0) break; curName++; @@ -743,7 +767,7 @@ SetWindowTextW(g_InfoLine_HWND, temp); { - DWORD attrib = GetFileAttributesW(path); + const DWORD attrib = GetFileAttributesW(path); if (attrib == INVALID_FILE_ATTRIBUTES) continue; if (attrib & FILE_ATTRIBUTE_READONLY) @@ -803,7 +827,7 @@ } -static void OnClose() +static void OnClose(void) { if (g_Install_was_Pressed && !g_Finished) { @@ -817,7 +841,13 @@ g_HWND = NULL; } -static INT_PTR CALLBACK MyDlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) +static +#ifdef Z7_OLD_WIN_SDK + BOOL +#else + INT_PTR +#endif +CALLBACK MyDlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { UNUSED_VAR(lParam) @@ -905,7 +935,7 @@ #endif #ifndef UNDER_CE - func_RegDeleteKeyExW = (Func_RegDeleteKeyExW) + func_RegDeleteKeyExW = (Func_RegDeleteKeyExW) MY_CAST_FUNC GetProcAddress(GetModuleHandleW(L"advapi32.dll"), "RegDeleteKeyExW"); #endif @@ -976,7 +1006,7 @@ { wchar_t *name; - DWORD len = GetModuleFileNameW(NULL, modulePath, MAX_PATH); + const DWORD len = GetModuleFileNameW(NULL, modulePath, MAX_PATH); if (len == 0 || len > MAX_PATH) return 1; @@ -987,7 +1017,7 @@ wchar_t *s = modulePrefix; for (;;) { - wchar_t c = *s++; + const wchar_t c = *s++; if (c == 0) break; if (c == WCHAR_PATH_SEPARATOR) @@ -1037,7 +1067,7 @@ unsigned k; for (k = 0; k < 8; k++) { - unsigned t = value & 0xF; + const unsigned t = value & 0xF; value >>= 4; s[7 - k] = (wchar_t)((t < 10) ? ('0' + t) : ('A' + (t - 10))); } @@ -1134,7 +1164,7 @@ return 1; { - HICON hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON)); + const HICON hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON)); // SendMessage(g_HWND, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon); SendMessage(g_HWND, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon); } diff -Nru 7zip-22.01+dfsg/C/Util/7zipUninstall/7zipUninstall.dsp 7zip-23.01+dfsg/C/Util/7zipUninstall/7zipUninstall.dsp --- 7zip-22.01+dfsg/C/Util/7zipUninstall/7zipUninstall.dsp 2017-02-03 19:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/7zipUninstall/7zipUninstall.dsp 2023-04-04 11:00:00.000000000 +0000 @@ -104,6 +104,14 @@ # PROP Default_Filter "" # Begin Source File +SOURCE=..\..\7zWindows.h +# End Source File +# Begin Source File + +SOURCE=..\..\Compiler.h +# End Source File +# Begin Source File + SOURCE=.\Precomp.c # ADD CPP /Yc"Precomp.h" # End Source File diff -Nru 7zip-22.01+dfsg/C/Util/7zipUninstall/makefile 7zip-23.01+dfsg/C/Util/7zipUninstall/makefile --- 7zip-22.01+dfsg/C/Util/7zipUninstall/makefile 2018-04-20 15:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/7zipUninstall/makefile 2023-04-04 13:00:00.000000000 +0000 @@ -1,8 +1,8 @@ PROG = 7zipUninstall.exe MY_FIXED = 1 -!IFDEF _64BIT_INSTALLER -CFLAGS = $(CFLAGS) -D_64BIT_INSTALLER +!IFDEF Z7_64BIT_INSTALLER +CFLAGS = $(CFLAGS) -DZ7_64BIT_INSTALLER !ENDIF MAIN_OBJS = \ diff -Nru 7zip-22.01+dfsg/C/Util/7zipUninstall/Precomp.h 7zip-23.01+dfsg/C/Util/7zipUninstall/Precomp.h --- 7zip-22.01+dfsg/C/Util/7zipUninstall/Precomp.h 2015-05-24 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/7zipUninstall/Precomp.h 2023-03-04 09:00:00.000000000 +0000 @@ -1,11 +1,14 @@ /* Precomp.h -- StdAfx -2015-05-24 : Igor Pavlov : Public domain */ +2023-03-04 : 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" +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif +#include "../../Compiler.h" #include "../../7zTypes.h" #endif diff -Nru 7zip-22.01+dfsg/C/Util/Lzma/LzmaUtil.c 7zip-23.01+dfsg/C/Util/Lzma/LzmaUtil.c --- 7zip-22.01+dfsg/C/Util/Lzma/LzmaUtil.c 2021-11-01 11:09:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/Lzma/LzmaUtil.c 2023-04-04 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ /* LzmaUtil.c -- Test application for LZMA compression -2021-11-01 : Igor Pavlov : Public domain */ +2023-03-07 : Igor Pavlov : Public domain */ -#include "../../Precomp.h" +#include "Precomp.h" #include #include @@ -21,48 +21,80 @@ static const char * const kCantAllocateMessage = "Cannot allocate memory"; static const char * const kDataErrorMessage = "Data error"; -static void PrintHelp(char *buffer) +static void Print(const char *s) { - strcat(buffer, - "\nLZMA-C " MY_VERSION_CPU " : " MY_COPYRIGHT_DATE "\n\n" - "Usage: lzma inputFile outputFile\n" - " e: encode file\n" - " d: decode file\n"); + fputs(s, stdout); } -static int PrintError(char *buffer, const char *message) +static void PrintHelp(void) { - strcat(buffer, "\nError: "); - strcat(buffer, message); - strcat(buffer, "\n"); + Print( + "\n" "LZMA-C " MY_VERSION_CPU " : " MY_COPYRIGHT_DATE + "\n" + "\n" "Usage: lzma inputFile outputFile" + "\n" " e: encode file" + "\n" " d: decode file" + "\n"); +} + +static int PrintError(const char *message) +{ + Print("\nError: "); + Print(message); + Print("\n"); return 1; } -static int PrintError_WRes(char *buffer, const char *message, WRes wres) +#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; } \ + *s++ = (charType)('0' + (unsigned)val); \ + while (i != 0) { i--; *s++ = (charType)temp[i]; } \ + *s = 0; \ + return s; + +static char * Convert_unsigned_To_str(unsigned val, char *s) { - strcat(buffer, "\nError: "); - strcat(buffer, message); - sprintf(buffer + strlen(buffer), "\nSystem error code: %d", (unsigned)wres); + CONVERT_INT_TO_STR(char, 32) +} + +static void Print_unsigned(unsigned code) +{ + char str[32]; + Convert_unsigned_To_str(code, str); + Print(str); +} + +static int PrintError_WRes(const char *message, WRes wres) +{ + PrintError(message); + Print("\nSystem error code: "); + Print_unsigned((unsigned)wres); #ifndef _WIN32 { const char *s = strerror(wres); if (s) - sprintf(buffer + strlen(buffer), " : %s", s); + { + Print(" : "); + Print(s); + } } #endif - strcat(buffer, "\n"); + Print("\n"); return 1; } -static int PrintErrorNumber(char *buffer, SRes val) +static int PrintErrorNumber(SRes val) { - sprintf(buffer + strlen(buffer), "\n7-Zip error code: %d\n", (unsigned)val); + Print("\n7-Zip error code: "); + Print_unsigned((unsigned)val); + Print("\n"); return 1; } -static int PrintUserError(char *buffer) +static int PrintUserError(void) { - return PrintError(buffer, "Incorrect command"); + return PrintError("Incorrect command"); } @@ -70,10 +102,10 @@ #define OUT_BUF_SIZE (1 << 16) -static SRes Decode2(CLzmaDec *state, ISeqOutStream *outStream, ISeqInStream *inStream, +static SRes Decode2(CLzmaDec *state, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, UInt64 unpackSize) { - int thereIsSize = (unpackSize != (UInt64)(Int64)-1); + const int thereIsSize = (unpackSize != (UInt64)(Int64)-1); Byte inBuf[IN_BUF_SIZE]; Byte outBuf[OUT_BUF_SIZE]; size_t inPos = 0, inSize = 0, outPos = 0; @@ -83,7 +115,7 @@ if (inPos == inSize) { inSize = IN_BUF_SIZE; - RINOK(inStream->Read(inStream, inBuf, &inSize)); + RINOK(inStream->Read(inStream, inBuf, &inSize)) inPos = 0; } { @@ -124,7 +156,7 @@ } -static SRes Decode(ISeqOutStream *outStream, ISeqInStream *inStream) +static SRes Decode(ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream) { UInt64 unpackSize; int i; @@ -137,27 +169,29 @@ /* Read and parse header */ - RINOK(SeqInStream_Read(inStream, header, sizeof(header))); - + { + size_t size = sizeof(header); + RINOK(SeqInStream_ReadMax(inStream, header, &size)) + if (size != sizeof(header)) + return SZ_ERROR_INPUT_EOF; + } unpackSize = 0; for (i = 0; i < 8; i++) unpackSize += (UInt64)header[LZMA_PROPS_SIZE + i] << (i * 8); - LzmaDec_Construct(&state); - RINOK(LzmaDec_Allocate(&state, header, LZMA_PROPS_SIZE, &g_Alloc)); + LzmaDec_CONSTRUCT(&state) + RINOK(LzmaDec_Allocate(&state, header, LZMA_PROPS_SIZE, &g_Alloc)) res = Decode2(&state, outStream, inStream, unpackSize); LzmaDec_Free(&state, &g_Alloc); return res; } -static SRes Encode(ISeqOutStream *outStream, ISeqInStream *inStream, UInt64 fileSize, char *rs) +static SRes Encode(ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, UInt64 fileSize) { CLzmaEncHandle enc; SRes res; CLzmaEncProps props; - UNUSED_VAR(rs); - enc = LzmaEnc_Create(&g_Alloc); if (enc == 0) return SZ_ERROR_MEM; @@ -187,7 +221,7 @@ } -static int main2(int numArgs, const char *args[], char *rs) +int Z7_CDECL main(int numArgs, const char *args[]) { CFileSeqInStream inStream; CFileOutStream outStream; @@ -208,29 +242,31 @@ if (numArgs == 1) { - PrintHelp(rs); + PrintHelp(); return 0; } if (numArgs < 3 || numArgs > 4 || strlen(args[1]) != 1) - return PrintUserError(rs); + return PrintUserError(); c = args[1][0]; encodeMode = (c == 'e' || c == 'E'); if (!encodeMode && c != 'd' && c != 'D') - return PrintUserError(rs); + return PrintUserError(); + /* { size_t t4 = sizeof(UInt32); size_t t8 = sizeof(UInt64); if (t4 != 4 || t8 != 8) - return PrintError(rs, "Incorrect UInt32 or UInt64"); + return PrintError("Incorrect UInt32 or UInt64"); } + */ { - WRes wres = InFile_Open(&inStream.file, args[2]); + const WRes wres = InFile_Open(&inStream.file, args[2]); if (wres != 0) - return PrintError_WRes(rs, "Cannot open input file", wres); + return PrintError_WRes("Cannot open input file", wres); } if (numArgs > 3) @@ -239,18 +275,18 @@ useOutFile = True; wres = OutFile_Open(&outStream.file, args[3]); if (wres != 0) - return PrintError_WRes(rs, "Cannot open output file", wres); + return PrintError_WRes("Cannot open output file", wres); } else if (encodeMode) - PrintUserError(rs); + PrintUserError(); if (encodeMode) { UInt64 fileSize; - WRes wres = File_GetLength(&inStream.file, &fileSize); + const WRes wres = File_GetLength(&inStream.file, &fileSize); if (wres != 0) - return PrintError_WRes(rs, "Cannot get file length", wres); - res = Encode(&outStream.vt, &inStream.vt, fileSize, rs); + return PrintError_WRes("Cannot get file length", wres); + res = Encode(&outStream.vt, &inStream.vt, fileSize); } else { @@ -264,23 +300,14 @@ if (res != SZ_OK) { if (res == SZ_ERROR_MEM) - return PrintError(rs, kCantAllocateMessage); + return PrintError(kCantAllocateMessage); else if (res == SZ_ERROR_DATA) - return PrintError(rs, kDataErrorMessage); + return PrintError(kDataErrorMessage); else if (res == SZ_ERROR_WRITE) - return PrintError_WRes(rs, kCantWriteMessage, outStream.wres); + return PrintError_WRes(kCantWriteMessage, outStream.wres); else if (res == SZ_ERROR_READ) - return PrintError_WRes(rs, kCantReadMessage, inStream.wres); - return PrintErrorNumber(rs, res); + return PrintError_WRes(kCantReadMessage, inStream.wres); + return PrintErrorNumber(res); } return 0; } - - -int MY_CDECL main(int numArgs, const char *args[]) -{ - char rs[1000] = { 0 }; - int res = main2(numArgs, args, rs); - fputs(rs, stdout); - return res; -} diff -Nru 7zip-22.01+dfsg/C/Util/Lzma/LzmaUtil.dsp 7zip-23.01+dfsg/C/Util/Lzma/LzmaUtil.dsp --- 7zip-22.01+dfsg/C/Util/Lzma/LzmaUtil.dsp 2021-11-01 11:10:01.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/Lzma/LzmaUtil.dsp 2023-04-04 20:00:00.000000000 +0000 @@ -106,6 +106,10 @@ # End Source File # Begin Source File +SOURCE=..\..\7zWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\Alloc.c # End Source File # Begin Source File @@ -114,6 +118,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Compiler.h +# End Source File +# Begin Source File + SOURCE=..\..\CpuArch.h # End Source File # Begin Source File @@ -162,6 +170,14 @@ # End Source File # Begin Source File +SOURCE=..\..\Precomp.h +# End Source File +# Begin Source File + +SOURCE=.\Precomp.h +# End Source File +# Begin Source File + SOURCE=..\..\Threads.c # End Source File # Begin Source File diff -Nru 7zip-22.01+dfsg/C/Util/Lzma/Precomp.h 7zip-23.01+dfsg/C/Util/Lzma/Precomp.h --- 7zip-22.01+dfsg/C/Util/Lzma/Precomp.h 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/Lzma/Precomp.h 2023-03-04 09:00:00.000000000 +0000 @@ -0,0 +1,14 @@ +/* Precomp.h -- StdAfx +2023-03-04 : Igor Pavlov : Public domain */ + +#ifndef ZIP7_INC_PRECOMP_H +#define ZIP7_INC_PRECOMP_H + +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif + +#include "../../Compiler.h" +#include "../../7zTypes.h" + +#endif diff -Nru 7zip-22.01+dfsg/C/Util/LzmaLib/LzmaLib.dsp 7zip-23.01+dfsg/C/Util/LzmaLib/LzmaLib.dsp --- 7zip-22.01+dfsg/C/Util/LzmaLib/LzmaLib.dsp 2021-07-20 07:04:41.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/LzmaLib/LzmaLib.dsp 2023-04-04 13:00:00.000000000 +0000 @@ -101,6 +101,10 @@ SOURCE=.\LzmaLibExports.c # End Source File +# Begin Source File + +SOURCE=.\Precomp.h +# End Source File # End Group # Begin Source File @@ -108,6 +112,10 @@ # End Source File # Begin Source File +SOURCE=..\..\7zWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\Alloc.c # End Source File # Begin Source File @@ -116,6 +124,14 @@ # End Source File # Begin Source File +SOURCE=..\..\Compiler.h +# End Source File +# Begin Source File + +SOURCE=..\..\CpuArch.h +# End Source File +# Begin Source File + SOURCE=..\..\IStream.h # End Source File # Begin Source File @@ -168,6 +184,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Precomp.h +# End Source File +# Begin Source File + SOURCE=.\resource.rc # End Source File # Begin Source File diff -Nru 7zip-22.01+dfsg/C/Util/LzmaLib/LzmaLibExports.c 7zip-23.01+dfsg/C/Util/LzmaLib/LzmaLibExports.c --- 7zip-22.01+dfsg/C/Util/LzmaLib/LzmaLibExports.c 2015-11-08 11:34:01.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/LzmaLib/LzmaLibExports.c 2023-03-05 17:00:00.000000000 +0000 @@ -1,14 +1,15 @@ /* LzmaLibExports.c -- LZMA library DLL Entry point -2015-11-08 : Igor Pavlov : Public domain */ +2023-03-05 : Igor Pavlov : Public domain */ -#include "../../Precomp.h" +#include "Precomp.h" -#include +#include "../../7zWindows.h" +BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved); BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { - UNUSED_VAR(hInstance); - UNUSED_VAR(dwReason); - UNUSED_VAR(lpReserved); + UNUSED_VAR(hInstance) + UNUSED_VAR(dwReason) + UNUSED_VAR(lpReserved) return TRUE; } diff -Nru 7zip-22.01+dfsg/C/Util/LzmaLib/makefile 7zip-23.01+dfsg/C/Util/LzmaLib/makefile --- 7zip-22.01+dfsg/C/Util/LzmaLib/makefile 2021-11-01 11:02:42.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/LzmaLib/makefile 2023-03-05 18:00:00.000000000 +0000 @@ -21,6 +21,7 @@ $O\Threads.obj \ OBJS = \ + $O\Precomp.obj \ $(LIB_OBJS) \ $(C_OBJS) \ $O\resource.res @@ -30,7 +31,24 @@ $(SLIBPATH): $O $(OBJS) lib -out:$(SLIBPATH) $(OBJS) $(LIBS) + +MAK_SINGLE_FILE = 1 + +$O\Precomp.obj: Precomp.c + $(CCOMPL_PCH) + +!IFDEF MAK_SINGLE_FILE + $(LIB_OBJS): $(*B).c - $(COMPL_O2) + $(CCOMPL_USE) $(C_OBJS): ../../$(*B).c - $(COMPL_O2) + $(CCOMPL_USE) + +!ELSE + +{.}.c{$O}.obj:: + $(CCOMPLB_USE) +{../../../C}.c{$O}.obj:: + $(CCOMPLB_USE) + +!ENDIF diff -Nru 7zip-22.01+dfsg/C/Util/LzmaLib/Precomp.c 7zip-23.01+dfsg/C/Util/LzmaLib/Precomp.c --- 7zip-22.01+dfsg/C/Util/LzmaLib/Precomp.c 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/LzmaLib/Precomp.c 2013-01-23 18:00:00.000000000 +0000 @@ -0,0 +1,4 @@ +/* Precomp.c -- StdAfx +2013-01-21 : Igor Pavlov : Public domain */ + +#include "Precomp.h" diff -Nru 7zip-22.01+dfsg/C/Util/LzmaLib/Precomp.h 7zip-23.01+dfsg/C/Util/LzmaLib/Precomp.h --- 7zip-22.01+dfsg/C/Util/LzmaLib/Precomp.h 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/LzmaLib/Precomp.h 2023-03-04 09:00:00.000000000 +0000 @@ -0,0 +1,14 @@ +/* Precomp.h -- StdAfx +2023-03-04 : Igor Pavlov : Public domain */ + +#ifndef ZIP7_INC_PRECOMP_H +#define ZIP7_INC_PRECOMP_H + +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif + +#include "../../Compiler.h" +#include "../../7zTypes.h" + +#endif diff -Nru 7zip-22.01+dfsg/C/Util/SfxSetup/makefile 7zip-23.01+dfsg/C/Util/SfxSetup/makefile --- 7zip-22.01+dfsg/C/Util/SfxSetup/makefile 2018-04-20 14:23:35.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/SfxSetup/makefile 2023-04-04 13:00:00.000000000 +0000 @@ -1,6 +1,9 @@ PROG = 7zS2.sfx MY_FIXED = 1 +CFLAGS = $(CFLAGS) \ + -DZ7_EXTRACT_ONLY \ + C_OBJS = \ $O\7zAlloc.obj \ $O\7zArcIn.obj \ diff -Nru 7zip-22.01+dfsg/C/Util/SfxSetup/makefile_con 7zip-23.01+dfsg/C/Util/SfxSetup/makefile_con --- 7zip-22.01+dfsg/C/Util/SfxSetup/makefile_con 2018-04-20 14:23:46.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/SfxSetup/makefile_con 2023-04-04 13:00:00.000000000 +0000 @@ -1,6 +1,8 @@ PROG = 7zS2con.sfx MY_FIXED = 1 -CFLAGS = $(CFLAGS) -D_CONSOLE + +CFLAGS = $(CFLAGS) -D_CONSOLE \ + -DZ7_EXTRACT_ONLY \ C_OBJS = \ $O\7zAlloc.obj \ diff -Nru 7zip-22.01+dfsg/C/Util/SfxSetup/Precomp.h 7zip-23.01+dfsg/C/Util/SfxSetup/Precomp.h --- 7zip-22.01+dfsg/C/Util/SfxSetup/Precomp.h 2014-06-16 05:58:24.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/SfxSetup/Precomp.h 2023-03-04 09:00:00.000000000 +0000 @@ -1,8 +1,12 @@ /* Precomp.h -- StdAfx -2013-06-16 : Igor Pavlov : Public domain */ +2023-03-04 : Igor Pavlov : Public domain */ -#ifndef __7Z_PRECOMP_H -#define __7Z_PRECOMP_H +#ifndef ZIP7_INC_PRECOMP_H +#define ZIP7_INC_PRECOMP_H + +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../Compiler.h" #include "../../7zTypes.h" diff -Nru 7zip-22.01+dfsg/C/Util/SfxSetup/SfxSetup.c 7zip-23.01+dfsg/C/Util/SfxSetup/SfxSetup.c --- 7zip-22.01+dfsg/C/Util/SfxSetup/SfxSetup.c 2019-02-02 18:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Util/SfxSetup/SfxSetup.c 2023-04-04 13:00:00.000000000 +0000 @@ -26,6 +26,12 @@ #define kInputBufSize ((size_t)1 << 18) + +#define wcscat lstrcatW +#define wcslen (size_t)lstrlenW +#define wcscpy lstrcpyW +// wcsncpy() and lstrcpynW() work differently. We don't use them. + static const char * const kExts[] = { "bat" @@ -64,7 +70,7 @@ return len; } -#define MAKE_CHAR_UPPER(c) ((((c) >= 'a' && (c) <= 'z') ? (c) -= 0x20 : (c))) +#define MAKE_CHAR_UPPER(c) ((((c) >= 'a' && (c) <= 'z') ? (c) - 0x20 : (c))) static unsigned FindItem(const char * const *items, unsigned num, const wchar_t *s, unsigned len) { @@ -72,13 +78,13 @@ for (i = 0; i < num; i++) { const char *item = items[i]; - unsigned itemLen = (unsigned)strlen(item); + const unsigned itemLen = (unsigned)strlen(item); unsigned j; if (len != itemLen) continue; for (j = 0; j < len; j++) { - unsigned c = (Byte)item[j]; + const unsigned c = (Byte)item[j]; if (c != s[j] && MAKE_CHAR_UPPER(c) != s[j]) break; } @@ -96,10 +102,20 @@ } #endif + +#ifdef _CONSOLE +static void PrintStr(const char *s) +{ + fputs(s, stdout); +} +#endif + static void PrintErrorMessage(const char *message) { #ifdef _CONSOLE - printf("\n7-Zip Error: %s\n", message); + PrintStr("\n7-Zip Error: "); + PrintStr(message); + PrintStr("\n"); #else #ifdef UNDER_CE WCHAR messageW[256 + 4]; @@ -179,7 +195,7 @@ WIN32_FIND_DATAW fd; HANDLE handle; WRes res = 0; - size_t len = wcslen(path); + const size_t len = wcslen(path); wcscpy(path + len, L"*"); handle = FindFirstFileW(path, &fd); path[len] = L'\0'; @@ -228,7 +244,7 @@ } #ifdef _CONSOLE -int MY_CDECL main() +int Z7_CDECL main(void) #else int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, #ifdef UNDER_CE @@ -290,7 +306,7 @@ BoolInt quoteMode = False; for (;; cmdLineParams++) { - wchar_t c = *cmdLineParams; + const wchar_t c = *cmdLineParams; if (c == L'\"') quoteMode = !quoteMode; else if (c == 0 || (c == L' ' && !quoteMode)) @@ -324,7 +340,7 @@ unsigned k; for (k = 0; k < 8; k++) { - unsigned t = value & 0xF; + const unsigned t = value & 0xF; value >>= 4; s[7 - k] = (wchar_t)((t < 10) ? ('0' + t) : ('A' + (t - 10))); } @@ -386,7 +402,7 @@ { lookStream.bufSize = kInputBufSize; lookStream.realStream = &archiveStream.vt; - LookToRead2_Init(&lookStream); + LookToRead2_INIT(&lookStream) } } @@ -455,11 +471,11 @@ unsigned extLen; const WCHAR *name = temp + nameStartPos; unsigned len = (unsigned)wcslen(name); - unsigned nameLen = FindExt(temp + nameStartPos, &extLen); - unsigned extPrice = FindItem(kExts, sizeof(kExts) / sizeof(kExts[0]), name + len - extLen, extLen); - unsigned namePrice = FindItem(kNames, sizeof(kNames) / sizeof(kNames[0]), name, nameLen); + const unsigned nameLen = FindExt(temp + nameStartPos, &extLen); + const unsigned extPrice = FindItem(kExts, sizeof(kExts) / sizeof(kExts[0]), name + len - extLen, extLen); + const unsigned namePrice = FindItem(kNames, sizeof(kNames) / sizeof(kNames[0]), name, nameLen); - unsigned price = namePrice + extPrice * 64 + (nameStartPos == 0 ? 0 : (1 << 12)); + const unsigned price = namePrice + extPrice * 64 + (nameStartPos == 0 ? 0 : (1 << 12)); if (minPrice > price) { minPrice = price; @@ -500,7 +516,7 @@ #endif { - SRes res2 = File_Close(&outFile); + const SRes res2 = File_Close(&outFile); if (res != SZ_OK) break; if (res2 != SZ_OK) @@ -550,7 +566,7 @@ WCHAR oldCurDir[MAX_PATH + 2]; oldCurDir[0] = 0; { - DWORD needLen = GetCurrentDirectory(MAX_PATH + 1, oldCurDir); + const DWORD needLen = GetCurrentDirectory(MAX_PATH + 1, oldCurDir); if (needLen == 0 || needLen > MAX_PATH) oldCurDir[0] = 0; SetCurrentDirectory(workCurDir); diff -Nru 7zip-22.01+dfsg/C/warn_clang_mac.mak 7zip-23.01+dfsg/C/warn_clang_mac.mak --- 7zip-22.01+dfsg/C/warn_clang_mac.mak 2021-04-28 11:21:39.000000000 +0000 +++ 7zip-23.01+dfsg/C/warn_clang_mac.mak 2023-05-03 13:00:00.000000000 +0000 @@ -1,37 +1 @@ -CFLAGS_WARN_CLANG_3_8_UNIQ = \ - -Wno-reserved-id-macro \ - -Wno-old-style-cast \ - -Wno-c++11-long-long \ - -Wno-unused-macros \ - -CFLAGS_WARN_CLANG_3_8 = \ - $(CFLAGS_WARN_CLANG_3_8_UNIQ) \ - -Weverything \ - -Wno-extra-semi \ - -Wno-sign-conversion \ - -Wno-language-extension-token \ - -Wno-global-constructors \ - -Wno-non-virtual-dtor \ - -Wno-switch-enum \ - -Wno-covered-switch-default \ - -Wno-cast-qual \ - -Wno-padded \ - -Wno-exit-time-destructors \ - -Wno-weak-vtables \ - -CFLAGS_WARN_CLANG_12= $(CFLAGS_WARN_CLANG_3_8) \ - -Wno-extra-semi-stmt \ - -Wno-zero-as-null-pointer-constant \ - -Wno-deprecated-dynamic-exception-spec \ - -Wno-c++98-compat-pedantic \ - -Wno-atomic-implicit-seq-cst \ - -Wconversion \ - -Wno-sign-conversion \ - -CFLAGS_WARN_MAC = \ - -Wno-poison-system-directories \ - -Wno-c++11-long-long \ - -Wno-atomic-implicit-seq-cst \ - - -CFLAGS_WARN = $(CFLAGS_WARN_CLANG_12) $(CFLAGS_WARN_MAC) +CFLAGS_WARN = -Weverything -Wfatal-errors -Wno-poison-system-directories diff -Nru 7zip-22.01+dfsg/C/warn_clang.mak 7zip-23.01+dfsg/C/warn_clang.mak --- 7zip-22.01+dfsg/C/warn_clang.mak 2021-04-28 11:21:35.000000000 +0000 +++ 7zip-23.01+dfsg/C/warn_clang.mak 2023-05-06 05:00:00.000000000 +0000 @@ -1,37 +1 @@ -CFLAGS_WARN_CLANG_3_8_UNIQ = \ - -Wno-reserved-id-macro \ - -Wno-old-style-cast \ - -Wno-c++11-long-long \ - -Wno-unused-macros \ - -CFLAGS_WARN_CLANG_3_8 = \ - $(CFLAGS_WARN_CLANG_3_8_UNIQ) \ - -Weverything \ - -Wno-extra-semi \ - -Wno-sign-conversion \ - -Wno-language-extension-token \ - -Wno-global-constructors \ - -Wno-non-virtual-dtor \ - -Wno-switch-enum \ - -Wno-covered-switch-default \ - -Wno-cast-qual \ - -Wno-padded \ - -Wno-exit-time-destructors \ - -Wno-weak-vtables \ - -CFLAGS_WARN_CLANG_12= $(CFLAGS_WARN_CLANG_3_8) \ - -Wno-extra-semi-stmt \ - -Wno-zero-as-null-pointer-constant \ - -Wno-deprecated-dynamic-exception-spec \ - -Wno-c++98-compat-pedantic \ - -Wno-atomic-implicit-seq-cst \ - -Wconversion \ - -Wno-sign-conversion \ - -CFLAGS_WARN_1 = \ - -Wno-deprecated-copy-dtor \ - - - - -CFLAGS_WARN = $(CFLAGS_WARN_CLANG_12) $(CFLAGS_WARN_1) +CFLAGS_WARN = -Weverything -Wfatal-errors diff -Nru 7zip-22.01+dfsg/C/Xz.c 7zip-23.01+dfsg/C/Xz.c --- 7zip-22.01+dfsg/C/Xz.c 2021-02-09 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/Xz.c 2023-04-02 12:00:00.000000000 +0000 @@ -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 @@ 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 -Nru 7zip-22.01+dfsg/C/XzCrc64.c 7zip-23.01+dfsg/C/XzCrc64.c --- 7zip-22.01+dfsg/C/XzCrc64.c 2017-05-23 14:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/XzCrc64.c 2023-04-02 11:00:00.000000000 +0000 @@ -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 @@ } 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 @@ { 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 -Nru 7zip-22.01+dfsg/C/XzCrc64.h 7zip-23.01+dfsg/C/XzCrc64.h --- 7zip-22.01+dfsg/C/XzCrc64.h 2013-01-18 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/XzCrc64.h 2023-04-02 11:00:00.000000000 +0000 @@ -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 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 -Nru 7zip-22.01+dfsg/C/XzCrc64Opt.c 7zip-23.01+dfsg/C/XzCrc64Opt.c --- 7zip-22.01+dfsg/C/XzCrc64Opt.c 2021-02-09 15:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/XzCrc64Opt.c 2023-04-02 11:00:00.000000000 +0000 @@ -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 @@ #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 @@ } for (; size > 0; size--, p++) v = CRC64_UPDATE_BYTE_2_BE(v, *p); - return CRC_UINT64_SWAP(v); + return Z7_BSWAP64(v); } #endif diff -Nru 7zip-22.01+dfsg/C/XzDec.c 7zip-23.01+dfsg/C/XzDec.c --- 7zip-22.01+dfsg/C/XzDec.c 2021-09-04 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/XzDec.c 2023-04-13 08:00:00.000000000 +0000 @@ -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 @@ return 0; } -/* ---------- BraState ---------- */ + +/* ---------- XzBcFilterState ---------- */ #define BRA_BUF_SIZE (1 << 14) @@ -76,27 +77,29 @@ 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 @@ 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 @@ 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 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 BraState_Filter(void *pp, Byte *data, SizeT size) +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 = False; *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 @@ 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 @@ } -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 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 @@ { 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 @@ 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 @@ p->Init = Lzma2State_Init; p->Code2 = Lzma2State_Code2; p->Filter = NULL; - Lzma2Dec_Construct(&spec->decoder); + Lzma2Dec_CONSTRUCT(&spec->decoder) } spec->outBufMode = False; if (outBuf) @@ -519,7 +550,8 @@ } 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 @@ SizeT destLen2, srcLen2; int wasFinished; - PRF_STR("------- MixCoder Single ----------"); + PRF_STR("------- MixCoder Single ----------") srcLen2 = srcLenOrig; destLen2 = destLenOrig; @@ -615,14 +647,14 @@ 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 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 @@ if (f->propsSize != 1) return False; } - 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 False; } @@ -821,22 +852,24 @@ 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 @@ 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 @@ (*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 @@ 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 @@ } 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 @@ } 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 @@ p->headerParsedOk = True; 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 @@ -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "MtDec.h" #endif @@ -1400,7 +1433,7 @@ p->outStep_ST = 1 << 20; p->ignoreErrors = False; - #ifndef _7ZIP_ST + #ifndef Z7_ST p->numThreads = 1; p->inBufSize_MT = 1 << 18; p->memUseMax = sizeof(size_t) << 28; @@ -1409,7 +1442,7 @@ -#ifndef _7ZIP_ST +#ifndef Z7_ST /* ---------- CXzDecMtThread ---------- */ @@ -1448,7 +1481,7 @@ /* ---------- CXzDecMt ---------- */ -typedef struct +struct CXzDecMt { CAlignOffsetAlloc alignOffsetAlloc; ISzAllocPtr allocMid; @@ -1456,9 +1489,9 @@ 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 @@ ECoderStatus status; SRes codeRes; - #ifndef _7ZIP_ST + #ifndef Z7_ST BoolInt mainDecoderWasCalled; // int statErrorDefined; int finishedDecoderIndex; @@ -1504,10 +1537,9 @@ BoolInt mtc_WasConstructed; CMtDec mtc; - CXzDecMtThread coders[MTDEC__THREADS_MAX]; + CXzDecMtThread coders[MTDEC_THREADS_MAX]; #endif - -} CXzDecMt; +}; @@ -1535,11 +1567,11 @@ XzDecMtProps_Init(&p->props); - #ifndef _7ZIP_ST + #ifndef Z7_ST p->mtc_WasConstructed = False; { 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 = False; @@ -1549,16 +1581,16 @@ } #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 @@ } -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 @@ } { 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 @@ #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 @@ coder->dec.parseMode = True; coder->dec.headerParsedOk = False; - PRF_STR_INT("Parse", srcSize2); + PRF_STR_INT("Parse", srcSize2) res = XzUnpacker_Code(&coder->dec, NULL, &destSize, @@ -2071,7 +2105,7 @@ } 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 @@ return res; } - RINOK(res); + RINOK(res) if (coder->inPreSize != coder->inCodeSize || coder->blockPackTotal != coder->inCodeSize) @@ -2106,13 +2140,13 @@ // (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 @@ 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 @@ 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 @@ */ static SRes XzDecMt_Decode_ST(CXzDecMt *p - #ifndef _7ZIP_ST + #ifndef Z7_ST , BoolInt tMode #endif , CXzStatInfo *stat) @@ -2343,7 +2377,7 @@ CXzUnpacker *dec; - #ifndef _7ZIP_ST + #ifndef Z7_ST if (tMode) { XzDecMt_FreeOutBufs(p); @@ -2400,7 +2434,7 @@ if (inPos == inLim) { - #ifndef _7ZIP_ST + #ifndef Z7_ST if (tMode) { inData = MtDec_Read(&p->mtc, &inLim); @@ -2577,19 +2611,19 @@ -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 @@ */ - #ifndef _7ZIP_ST + #ifndef Z7_ST p->isBlockHeaderState_Parse = False; p->isBlockHeaderState_Write = False; @@ -2782,7 +2816,7 @@ return res; } - PRF_STR("----- decoding ST -----"); + PRF_STR("----- decoding ST -----") } #endif @@ -2792,13 +2826,13 @@ { 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 @@ return res; } } + +#undef PRF +#undef PRF_STR +#undef PRF_STR_INT_2 diff -Nru 7zip-22.01+dfsg/C/XzEnc.c 7zip-23.01+dfsg/C/XzEnc.c --- 7zip-22.01+dfsg/C/XzEnc.c 2021-04-01 17:13:46.000000000 +0000 +++ 7zip-23.01+dfsg/C/XzEnc.c 2023-04-13 08:00:00.000000000 +0000 @@ -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 @@ 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 @@ 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 @@ 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_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 @@ 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 @@ 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 @@ typedef struct { ISeqInStream vt; - ISeqInStream *realStream; + ISeqInStreamPtr realStream; const Byte *data; UInt64 limit; UInt64 processed; @@ -251,9 +251,9 @@ 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 @@ 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 @@ typedef struct { - ISeqInStream p; - ISeqInStream *realStream; + ISeqInStream vt; + ISeqInStreamPtr realStream; IStateCoder StateCoder; Byte *buf; size_t curPos; @@ -323,7 +323,39 @@ } 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 @@ } 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 @@ { 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 @@ { 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 @@ 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 @@ 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 @@ } *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 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 @@ 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 @@ 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 @@ /* 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ *inStreamFinished = False; - 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 @@ else if (fp->ipDefined) { Byte *ptr = filter->props; - SetUi32(ptr, fp->ip); + SetUi32(ptr, fp->ip) filter->propsSize = 4; } } @@ -777,13 +809,13 @@ 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 @@ 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 @@ #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 @@ if (outBuf) seqSizeOutStream.processed += outSize; - RINOK(res); + RINOK(res) blockSizes->unpackSize = checkInStream.processed; } { @@ -866,7 +898,7 @@ 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 @@ 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 @@ 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 @@ -typedef struct +struct CXzEnc { ISzAllocPtr alloc; ISzAllocPtr allocBig; @@ -933,20 +965,19 @@ 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 @@ 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 = False; { - 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_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 @@ 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 @@ 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 @@ MtProgressThunk_CreateVTable(&progressThunk); progressThunk.mtProgress = &me->mtCoder.mtProgress; - MtProgressThunk_Init(&progressThunk); + MtProgressThunk_INIT(&progressThunk) { CXzEncBlockInfo blockSizes; @@ -1112,11 +1144,11 @@ 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 @@ -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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ &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 @@ #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_EncodeEmpty(ISeqOutStream *outStream) +SRes Xz_EncodeEmpty(ISeqOutStreamPtr outStream) { SRes res; CXzEncIndex xzIndex; diff -Nru 7zip-22.01+dfsg/C/XzEnc.h 7zip-23.01+dfsg/C/XzEnc.h --- 7zip-22.01+dfsg/C/XzEnc.h 2017-06-27 14:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/XzEnc.h 2023-04-13 08:00:00.000000000 +0000 @@ -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 @@ 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 -Nru 7zip-22.01+dfsg/C/Xz.h 7zip-23.01+dfsg/C/Xz.h --- 7zip-22.01+dfsg/C/Xz.h 2021-04-01 17:13:50.000000000 +0000 +++ 7zip-23.01+dfsg/C/Xz.h 2023-04-13 08:00:00.000000000 +0000 @@ -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 @@ #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 @@ 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 { CXzStreamFlags flags; + // Byte _pad[6]; size_t numBlocks; CXzBlockSizes *blocks; UInt64 startOffset; @@ -134,7 +137,7 @@ 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 @@ } 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 @@ } 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 @@ 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 @@ 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 @@ 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 -Nru 7zip-22.01+dfsg/C/XzIn.c 7zip-23.01+dfsg/C/XzIn.c --- 7zip-22.01+dfsg/C/XzIn.c 2021-09-04 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/C/XzIn.c 2023-04-02 12:00:00.000000000 +0000 @@ -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 @@ 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 @@ *isIndex = False; 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 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 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 @@ { 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ 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 @@ || 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 @@ 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 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 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 @@ 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 @@ 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 -Nru 7zip-22.01+dfsg/CPP/7zip/7zip_gcc.mak 7zip-23.01+dfsg/CPP/7zip/7zip_gcc.mak --- 7zip-22.01+dfsg/CPP/7zip/7zip_gcc.mak 2022-07-15 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/7zip_gcc.mak 2023-05-03 13:00:00.000000000 +0000 @@ -12,23 +12,35 @@ MY_ASM = jwasm endif +ifndef RC +RC=windres.exe --target=pe-x86-64 +RC=windres.exe -F pe-i386 +RC=windres.exe +endif + PROGPATH = $(O)/$(PROG) PROGPATH_STATIC = $(O)/$(PROG)s ifneq ($(CC), xlc) -CFLAGS_WARN_WALL = -Wall -Werror -Wextra +CFLAGS_WARN_WALL = -Werror -Wall -Wextra endif # for object file +# -Wa,-aln=test.s +# -save-temps CFLAGS_BASE_LIST = -c # CFLAGS_BASE_LIST = -S CFLAGS_BASE = -O2 $(CFLAGS_BASE_LIST) $(CFLAGS_WARN_WALL) $(CFLAGS_WARN) \ -DNDEBUG -D_REENTRANT -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE \ -fPIC -# -D_7ZIP_AFFINITY_DISABLE +FLAGS_FLTO = -ffunction-sections +FLAGS_FLTO = -flto +FLAGS_FLTO = +# +# -DZ7_AFFINITY_DISABLE ifdef SystemDrive @@ -83,8 +95,7 @@ else LDFLAGS = $(LDFLAGS_STATIC) -# -s is not required for clang, do we need it for GGC ??? -# -s +# -s is not required for clang, do we need it for GCC ??? #-static -static-libgcc -static-libstdc++ @@ -113,7 +124,7 @@ DEL_OBJ_EXE = -$(RM) $(O)\*.o $(O)\$(PROG).exe $(O)\$(PROG).dll endif -LIB2_GUI = -lOle32 -lGdi32 -lComctl32 -lComdlg32 $(LIB_HTMLHELP) +LIB2_GUI = -lOle32 -lGdi32 -lComctl32 -lComdlg32 -lShell32 $(LIB_HTMLHELP) LIB2 = -loleaut32 -luuid -ladvapi32 -lUser32 $(LIB2_GUI) CXXFLAGS_EXTRA = -DUNICODE -D_UNICODE @@ -126,7 +137,7 @@ MY_MKDIR=mkdir -p DEL_OBJ_EXE = -$(RM) $(PROGPATH) $(PROGPATH_STATIC) $(OBJS) -# CFLAGS_BASE := $(CFLAGS_BASE) -D_7ZIP_ST +# CFLAGS_BASE := $(CFLAGS_BASE) -DZ7_ST # CXXFLAGS_EXTRA = -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE # LOCAL_LIBS=-lpthread @@ -138,7 +149,7 @@ -CFLAGS = $(MY_ARCH_2) $(LOCAL_FLAGS) $(CFLAGS_BASE2) $(CFLAGS_BASE) $(CC_SHARED) -o $@ +CFLAGS = $(MY_ARCH_2) $(LOCAL_FLAGS) $(CFLAGS_BASE2) $(CFLAGS_BASE) $(FLAGS_FLTO) $(CC_SHARED) -o $@ ifdef IS_MINGW @@ -170,7 +181,7 @@ ifdef USE_ASM -CONSOLE_ASM_FLAGS=-D_7ZIP_ASM +CONSOLE_ASM_FLAGS=-DZ7_7ZIP_ASM else CONSOLE_ASM_FLAGS= endif @@ -179,7 +190,7 @@ #-Wno-invalid-offsetof #-Wno-reorder -CXXFLAGS = $(MY_ARCH_2) $(LOCAL_FLAGS) $(CXXFLAGS_BASE2) $(CFLAGS_BASE) $(CXXFLAGS_EXTRA) $(CC_SHARED) -o $@ $(CXX_WARN_FLAGS) +CXXFLAGS = $(MY_ARCH_2) $(LOCAL_FLAGS) $(CXXFLAGS_BASE2) $(CFLAGS_BASE) $(FLAGS_FLTO) $(CXXFLAGS_EXTRA) $(CC_SHARED) $(CXX_WARN_FLAGS) $(CXX_STD_FLAGS) -o $@ STATIC_TARGET= ifdef COMPL_STATIC @@ -192,7 +203,20 @@ $(O): $(MY_MKDIR) $(O) -LFLAGS_ALL = -s $(MY_ARCH_2) $(LDFLAGS) $(LD_arch) $(OBJS) $(MY_LIBS) $(LIB2) +# LDFLAGS3= -flto +# LDFLAGS3= -Wl,--gc-sections +# -Wl,--print-gc-sections + +ifneq ($(CC), $(CROSS_COMPILE)clang) +LFLAGS_STRIP = -s +endif + +LFLAGS_ALL = $(LFLAGS_STRIP) $(MY_ARCH_2) $(LDFLAGS) $(FLAGS_FLTO) $(LD_arch) $(OBJS) $(MY_LIBS) $(LIB2) + +# -s : GCC : Remove all symbol table and relocation information from the executable. +# -s : CLANG : unsupported +# -s + $(PROGPATH): $(OBJS) $(CXX) -o $(PROGPATH) $(LFLAGS_ALL) @@ -206,7 +230,14 @@ ifndef NO_DEFAULT_RES $O/resource.o: resource.rc - windres.exe $(RFLAGS) resource.rc $O/resource.o + $(RC) $(RFLAGS) resource.rc $@ + +# windres.exe : in old version mingw: +# $(RFLAGS) resource.rc $O/resource.o +# windres.exe : in new version mingw: +# $(RC) $(RFLAGS) resource.rc -FO $@ + + endif $O/LzmaAlone.o: LzmaAlone.cpp @@ -383,6 +414,8 @@ $(CXX) $(CXXFLAGS) $< $O/MethodProps.o: ../../Common/MethodProps.cpp $(CXX) $(CXXFLAGS) $< +$O/MultiOutStream.o: ../../Common/MultiOutStream.cpp + $(CXX) $(CXXFLAGS) $< $O/OffsetStream.o: ../../Common/OffsetStream.cpp $(CXX) $(CXXFLAGS) $< $O/OutBuffer.o: ../../Common/OutBuffer.cpp @@ -1144,10 +1177,19 @@ $(CC) $(CFLAGS) $< $O/Sort.o: ../../../../C/Sort.c $(CC) $(CFLAGS) $< +$O/SwapBytes.o: ../../../../C/SwapBytes.c + $(CC) $(CFLAGS) $< $O/Xz.o: ../../../../C/Xz.c $(CC) $(CFLAGS) $< $O/XzCrc64.o: ../../../../C/XzCrc64.c $(CC) $(CFLAGS) $< +$O/XzDec.o: ../../../../C/XzDec.c + $(CC) $(CFLAGS) $< +$O/XzEnc.o: ../../../../C/XzEnc.c + $(CC) $(CFLAGS) $< +$O/XzIn.o: ../../../../C/XzIn.c + $(CC) $(CFLAGS) $< + ifdef USE_ASM ifdef IS_X64 @@ -1216,7 +1258,7 @@ endif $O/LzmaDec.o: ../../../../C/LzmaDec.c - $(CC) $(CFLAGS) -D_LZMA_DEC_OPT $< + $(CC) $(CFLAGS) -DZ7_LZMA_DEC_OPT $< else @@ -1227,13 +1269,6 @@ -$O/XzDec.o: ../../../../C/XzDec.c - $(CC) $(CFLAGS) $< -$O/XzEnc.o: ../../../../C/XzEnc.c - $(CC) $(CFLAGS) $< -$O/XzIn.o: ../../../../C/XzIn.c - $(CC) $(CFLAGS) $< - $O/7zMain.o: ../../../../C/Util/7z/7zMain.c $(CC) $(CFLAGS) $< diff -Nru 7zip-22.01+dfsg/CPP/7zip/7zip.mak 7zip-23.01+dfsg/CPP/7zip/7zip.mak --- 7zip-22.01+dfsg/CPP/7zip/7zip.mak 2014-06-23 15:56:48.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/7zip.mak 2023-04-07 18:00:00.000000000 +0000 @@ -5,14 +5,14 @@ $(WIN_OBJS) \ $(WIN_CTRL_OBJS) \ $(7ZIP_COMMON_OBJS) \ - $(AR_OBJS) \ - $(AR_COMMON_OBJS) \ $(UI_COMMON_OBJS) \ $(AGENT_OBJS) \ $(CONSOLE_OBJS) \ $(EXPLORER_OBJS) \ $(FM_OBJS) \ $(GUI_OBJS) \ + $(AR_COMMON_OBJS) \ + $(AR_OBJS) \ $(7Z_OBJS) \ $(CAB_OBJS) \ $(CHM_OBJS) \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zCompressionMode.h 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zCompressionMode.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zCompressionMode.h 2021-08-27 09:21:46.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zCompressionMode.h 2023-05-04 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // 7zCompressionMode.h -#ifndef __7Z_COMPRESSION_MODE_H -#define __7Z_COMPRESSION_MODE_H +#ifndef ZIP7_INC_7Z_COMPRESSION_MODE_H +#define ZIP7_INC_7Z_COMPRESSION_MODE_H #include "../../Common/MethodId.h" #include "../../Common/MethodProps.h" @@ -53,7 +53,7 @@ bool DefaultMethod_was_Inserted; bool Filter_was_Inserted; - #ifndef _7ZIP_ST + #ifndef Z7_ST UInt32 NumThreads; bool NumThreads_WasForced; bool MultiThreadMixer; @@ -69,7 +69,7 @@ CCompressionMethodMode(): DefaultMethod_was_Inserted(false) , Filter_was_Inserted(false) - #ifndef _7ZIP_ST + #ifndef Z7_ST , NumThreads(1) , NumThreads_WasForced(false) , MultiThreadMixer(true) @@ -79,6 +79,10 @@ , PasswordIsDefined(false) {} +#ifdef Z7_CPP_IS_SUPPORTED_default + CCompressionMethodMode(const CCompressionMethodMode &) = default; + CCompressionMethodMode& operator =(const CCompressionMethodMode &) = default; +#endif ~CCompressionMethodMode() { Password.Wipe_and_Empty(); } }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zDecode.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zDecode.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zDecode.cpp 2021-03-07 16:25:28.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zDecode.cpp 2023-03-29 10:00:00.000000000 +0000 @@ -5,25 +5,23 @@ #include "../../Common/LimitedStreams.h" #include "../../Common/ProgressUtils.h" #include "../../Common/StreamObjects.h" +#include "../../Common/StreamUtils.h" #include "7zDecode.h" namespace NArchive { namespace N7z { -class CDecProgress: - public ICompressProgressInfo, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CDecProgress + , ICompressProgressInfo +) CMyComPtr _progress; public: CDecProgress(ICompressProgressInfo *progress): _progress(progress) {} - - MY_UNKNOWN_IMP1(ICompressProgressInfo) - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); }; -STDMETHODIMP CDecProgress::SetRatioInfo(const UInt64 * /* inSize */, const UInt64 *outSize) +Z7_COM7F_IMF(CDecProgress::SetRatioInfo(const UInt64 * /* inSize */, const UInt64 *outSize)) { return _progress->SetRatioInfo(NULL, outSize); } @@ -110,20 +108,23 @@ } CDecoder::CDecoder(bool useMixerMT): - _bindInfoPrev_Defined(false), - _useMixerMT(useMixerMT) -{} + _bindInfoPrev_Defined(false) +{ + #if defined(USE_MIXER_ST) && defined(USE_MIXER_MT) + _useMixerMT = useMixerMT; + #else + UNUSED_VAR(useMixerMT) + #endif +} -struct CLockedInStream: - public IUnknown, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_0( + CLockedInStream +) +public: CMyComPtr Stream; UInt64 Pos; - MY_UNKNOWN_IMP - #ifdef USE_MIXER_MT NWindows::NSynchronization::CCriticalSection CriticalSection; #endif @@ -132,10 +133,10 @@ #ifdef USE_MIXER_MT -class CLockedSequentialInStreamMT: - public ISequentialInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CLockedSequentialInStreamMT + , ISequentialInStream +) CLockedInStream *_glob; UInt64 _pos; CMyComPtr _globRef; @@ -146,24 +147,20 @@ _glob = lockedInStream; _pos = startPos; } - - MY_UNKNOWN_IMP1(ISequentialInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); }; -STDMETHODIMP CLockedSequentialInStreamMT::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CLockedSequentialInStreamMT::Read(void *data, UInt32 size, UInt32 *processedSize)) { NWindows::NSynchronization::CCriticalSectionLock lock(_glob->CriticalSection); if (_pos != _glob->Pos) { - RINOK(_glob->Stream->Seek((Int64)_pos, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_glob->Stream, _pos)) _glob->Pos = _pos; } UInt32 realProcessedSize = 0; - HRESULT res = _glob->Stream->Read(data, size, &realProcessedSize); + const HRESULT res = _glob->Stream->Read(data, size, &realProcessedSize); _pos += realProcessedSize; _glob->Pos = _pos; if (processedSize) @@ -176,10 +173,10 @@ #ifdef USE_MIXER_ST -class CLockedSequentialInStreamST: - public ISequentialInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CLockedSequentialInStreamST + , ISequentialInStream +) CLockedInStream *_glob; UInt64 _pos; CMyComPtr _globRef; @@ -190,22 +187,18 @@ _glob = lockedInStream; _pos = startPos; } - - MY_UNKNOWN_IMP1(ISequentialInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); }; -STDMETHODIMP CLockedSequentialInStreamST::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CLockedSequentialInStreamST::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (_pos != _glob->Pos) { - RINOK(_glob->Stream->Seek((Int64)_pos, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_glob->Stream, _pos)) _glob->Pos = _pos; } UInt32 realProcessedSize = 0; - HRESULT res = _glob->Stream->Read(data, size, &realProcessedSize); + const HRESULT res = _glob->Stream->Read(data, size, &realProcessedSize); _pos += realProcessedSize; _glob->Pos = _pos; if (processedSize) @@ -234,9 +227,9 @@ , bool &dataAfterEnd_Error - _7Z_DECODER_CRYPRO_VARS_DECL + Z7_7Z_DECODER_CRYPRO_VARS_DECL - #if !defined(_7ZIP_ST) + #if !defined(Z7_ST) , bool mtMode, UInt32 numThreads, UInt64 memUsage #endif ) @@ -268,7 +261,7 @@ We don't need to init isEncrypted and passwordIsDefined We must upgrade them only - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO isEncrypted = false; passwordIsDefined = false; #endif @@ -300,13 +293,13 @@ #endif } - RINOK(_mixer->SetBindInfo(bindInfo)); + RINOK(_mixer->SetBindInfo(bindInfo)) FOR_VECTOR(i, folderInfo.Coders) { const CCoderInfo &coderInfo = folderInfo.Coders[i]; - #ifndef _SFX + #ifndef Z7_SFX // we don't support RAR codecs here if ((coderInfo.MethodID >> 8) == 0x403) return E_NOTIMPL; @@ -315,7 +308,7 @@ CCreatedCoder cod; RINOK(CreateCoder_Id( EXTERNAL_CODECS_LOC_VARS - coderInfo.MethodID, false, cod)); + coderInfo.MethodID, false, cod)) if (coderInfo.IsSimpleCoder()) { @@ -333,13 +326,13 @@ // now there is no codec that uses another external codec /* - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS CMyComPtr setCompressCodecsInfo; decoderUnknown.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo); if (setCompressCodecsInfo) { // we must use g_ExternalCodecs also - RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(__externalCodecs->GetCodecs)); + RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(_externalCodecs->GetCodecs)); } #endif */ @@ -349,14 +342,14 @@ _bindInfoPrev_Defined = true; } - RINOK(_mixer->ReInit2()); + RINOK(_mixer->ReInit2()) UInt32 packStreamIndex = 0; UInt32 unpackStreamIndexStart = folders.FoToCoderUnpackSizes[folderIndex]; unsigned i; - #if !defined(_7ZIP_ST) + #if !defined(Z7_ST) bool mt_wasUsed = false; #endif @@ -365,59 +358,81 @@ const CCoderInfo &coderInfo = folderInfo.Coders[i]; IUnknown *decoder = _mixer->GetCoder(i).GetUnknown(); - #if !defined(_7ZIP_ST) + // now there is no codec that uses another external codec + /* + #ifdef Z7_EXTERNAL_CODECS + { + Z7_DECL_CMyComPtr_QI_FROM(ISetCompressCodecsInfo, + setCompressCodecsInfo, decoder) + if (setCompressCodecsInfo) + { + // we must use g_ExternalCodecs also + RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(_externalCodecs->GetCodecs)) + } + } + #endif + */ + + #if !defined(Z7_ST) if (!mt_wasUsed) { if (mtMode) { - CMyComPtr setCoderMt; - decoder->QueryInterface(IID_ICompressSetCoderMt, (void **)&setCoderMt); + Z7_DECL_CMyComPtr_QI_FROM(ICompressSetCoderMt, + setCoderMt, decoder) if (setCoderMt) { mt_wasUsed = true; - RINOK(setCoderMt->SetNumberOfThreads(numThreads)); + RINOK(setCoderMt->SetNumberOfThreads(numThreads)) } } // if (memUsage != 0) { - CMyComPtr setMemLimit; - decoder->QueryInterface(IID_ICompressSetMemLimit, (void **)&setMemLimit); + Z7_DECL_CMyComPtr_QI_FROM(ICompressSetMemLimit, + setMemLimit, decoder) if (setMemLimit) { mt_wasUsed = true; - RINOK(setMemLimit->SetMemLimit(memUsage)); + RINOK(setMemLimit->SetMemLimit(memUsage)) } } } #endif { - CMyComPtr setDecoderProperties; - decoder->QueryInterface(IID_ICompressSetDecoderProperties2, (void **)&setDecoderProperties); + Z7_DECL_CMyComPtr_QI_FROM( + ICompressSetDecoderProperties2, + setDecoderProperties, decoder) + const CByteBuffer &props = coderInfo.Props; + const UInt32 size32 = (UInt32)props.Size(); + if (props.Size() != size32) + return E_NOTIMPL; if (setDecoderProperties) { - const CByteBuffer &props = coderInfo.Props; - const UInt32 size32 = (UInt32)props.Size(); - if (props.Size() != size32) - return E_NOTIMPL; HRESULT res = setDecoderProperties->SetDecoderProperties2((const Byte *)props, size32); if (res == E_INVALIDARG) res = E_NOTIMPL; - RINOK(res); + RINOK(res) + } + else if (size32 != 0) + { + // v23: we fail, if decoder doesn't support properties + return E_NOTIMPL; } } - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO { - CMyComPtr cryptoSetPassword; - decoder->QueryInterface(IID_ICryptoSetPassword, (void **)&cryptoSetPassword); + Z7_DECL_CMyComPtr_QI_FROM( + ICryptoSetPassword, + cryptoSetPassword, decoder) if (cryptoSetPassword) { isEncrypted = true; if (!getTextPassword) return E_NOTIMPL; CMyComBSTR_Wipe passwordBSTR; - RINOK(getTextPassword->CryptoGetTextPassword(&passwordBSTR)); + RINOK(getTextPassword->CryptoGetTextPassword(&passwordBSTR)) passwordIsDefined = true; password.Wipe_and_Empty(); size_t len = 0; @@ -429,23 +444,24 @@ CByteBuffer_Wipe buffer(len * 2); for (size_t k = 0; k < len; k++) { - wchar_t c = passwordBSTR[k]; + const wchar_t c = passwordBSTR[k]; ((Byte *)buffer)[k * 2] = (Byte)c; ((Byte *)buffer)[k * 2 + 1] = (Byte)(c >> 8); } - RINOK(cryptoSetPassword->CryptoSetPassword((const Byte *)buffer, (UInt32)buffer.Size())); + RINOK(cryptoSetPassword->CryptoSetPassword((const Byte *)buffer, (UInt32)buffer.Size())) } } #endif bool finishMode = false; { - CMyComPtr setFinishMode; - decoder->QueryInterface(IID_ICompressSetFinishMode, (void **)&setFinishMode); + Z7_DECL_CMyComPtr_QI_FROM( + ICompressSetFinishMode, + setFinishMode, decoder) if (setFinishMode) { finishMode = fullUnpack; - RINOK(setFinishMode->SetFinishMode(BoolToUInt(finishMode))); + RINOK(setFinishMode->SetFinishMode(BoolToUInt(finishMode))) } } @@ -497,8 +513,8 @@ if (folderInfo.PackStreams.Size() > 1) { // lockedInStream.Pos = (UInt64)(Int64)-1; - // RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &lockedInStream.Pos)); - RINOK(inStream->Seek((Int64)(startPos + packPositions[0]), STREAM_SEEK_SET, &lockedInStreamSpec->Pos)); + // RINOK(InStream_GetPos(inStream, lockedInStream.Pos)) + RINOK(inStream->Seek((Int64)(startPos + packPositions[0]), STREAM_SEEK_SET, &lockedInStreamSpec->Pos)) lockedInStreamSpec->Stream = inStream; #ifdef USE_MIXER_MT @@ -523,7 +539,7 @@ if (folderInfo.PackStreams.Size() == 1) { - RINOK(inStream->Seek((Int64)packPos, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(inStream, packPos)) packStream = inStream; } else diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zDecode.h 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zDecode.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zDecode.h 2017-09-16 12:23:35.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zDecode.h 2023-03-04 09:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // 7zDecode.h -#ifndef __7Z_DECODE_H -#define __7Z_DECODE_H +#ifndef ZIP7_INC_7Z_DECODE_H +#define ZIP7_INC_7Z_DECODE_H #include "../Common/CoderMixer2.h" @@ -24,10 +24,13 @@ class CDecoder { bool _bindInfoPrev_Defined; + #ifdef USE_MIXER_ST + #ifdef USE_MIXER_MT + bool _useMixerMT; + #endif + #endif CBindInfoEx _bindInfoPrev; - bool _useMixerMT; - #ifdef USE_MIXER_ST NCoderMixer2::CMixerST *_mixerST; #endif @@ -57,9 +60,9 @@ , ISequentialInStream **inStreamMainRes , bool &dataAfterEnd_Error - _7Z_DECODER_CRYPRO_VARS_DECL + Z7_7Z_DECODER_CRYPRO_VARS_DECL - #if !defined(_7ZIP_ST) + #if !defined(Z7_ST) , bool mtMode, UInt32 numThreads, UInt64 memUsage #endif ); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7z.dsp 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7z.dsp --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7z.dsp 2015-10-18 10:00:05.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7z.dsp 2023-04-04 20:00:00.000000000 +0000 @@ -43,7 +43,7 @@ # PROP Ignore_Export_Lib 1 # PROP Target_Dir "" # ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MY7Z_EXPORTS" /YX /FD /c -# ADD CPP /nologo /Gz /MD /W3 /GX /O1 /I "..\..\..\\" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MY7Z_EXPORTS" /D "EXTERNAL_CODECS" /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gz /MD /W3 /GX /O1 /I "..\..\..\\" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MY7Z_EXPORTS" /D "Z7_EXTERNAL_CODECS" /Yu"StdAfx.h" /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "NDEBUG" @@ -53,7 +53,7 @@ # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 -# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /out:"C:\Program Files\7-zip\Formats\7z.dll" /opt:NOWIN98 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /out:"C:\Util\Formats\7z.dll" /opt:NOWIN98 # SUBTRACT LINK32 /pdb:none !ELSEIF "$(CFG)" == "7z - Win32 Debug" @@ -70,7 +70,7 @@ # PROP Ignore_Export_Lib 1 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MY7Z_EXPORTS" /YX /FD /GZ /c -# ADD CPP /nologo /Gz /MTd /W3 /Gm /GX /ZI /Od /I "..\..\..\\" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MY7Z_EXPORTS" /D "EXTERNAL_CODECS" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gz /MTd /W3 /Gm /GX /ZI /Od /I "..\..\..\\" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MY7Z_EXPORTS" /D "Z7_EXTERNAL_CODECS" /Yu"StdAfx.h" /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "_DEBUG" @@ -80,7 +80,7 @@ # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept -# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /out:"C:\Program Files\7-zip\Formats\7z.dll" /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /out:"C:\Util\Formats\7z.dll" /pdbtype:sept !ENDIF @@ -101,7 +101,11 @@ # End Source File # Begin Source File -SOURCE=..\DllExports.cpp +SOURCE=..\..\Compress\CodecExports.cpp +# End Source File +# Begin Source File + +SOURCE=..\DllExports2.cpp # End Source File # Begin Source File @@ -514,14 +518,6 @@ # PROP Default_Filter "" # Begin Source File -SOURCE=..\..\..\Windows\DLL.cpp -# End Source File -# Begin Source File - -SOURCE=..\..\..\Windows\DLL.h -# End Source File -# Begin Source File - SOURCE=..\..\..\Windows\FileDir.cpp # End Source File # Begin Source File diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zEncode.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zEncode.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zEncode.cpp 2021-08-02 10:33:10.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zEncode.cpp 2023-03-29 17:00:00.000000000 +0000 @@ -2,6 +2,8 @@ #include "StdAfx.h" +#include "../../../Common/ComTry.h" + #include "../../Common/CreateCoder.h" #include "../../Common/FilterCoder.h" #include "../../Common/LimitedStreams.h" @@ -19,11 +21,11 @@ { unsigned numIn = _bindInfo.Coders.Size(); - _SrcIn_to_DestOut.ClearAndSetSize(numIn); - _DestOut_to_SrcIn.ClearAndSetSize(numIn); + SrcIn_to_DestOut.ClearAndSetSize(numIn); + DestOut_to_SrcIn.ClearAndSetSize(numIn); unsigned numOut = _bindInfo.GetNum_Bonds_and_PackStreams(); - _SrcOut_to_DestIn.ClearAndSetSize(numOut); + SrcOut_to_DestIn.ClearAndSetSize(numOut); // _DestIn_to_SrcOut.ClearAndSetSize(numOut); UInt32 destIn = 0; @@ -38,15 +40,15 @@ numIn--; numOut -= coder.NumStreams; - _SrcIn_to_DestOut[numIn] = destOut; - _DestOut_to_SrcIn[destOut] = numIn; + SrcIn_to_DestOut[numIn] = destOut; + DestOut_to_SrcIn[destOut] = numIn; destOut++; for (UInt32 j = 0; j < coder.NumStreams; j++, destIn++) { UInt32 index = numOut + j; - _SrcOut_to_DestIn[index] = destIn; + SrcOut_to_DestIn[index] = destIn; // _DestIn_to_SrcOut[destIn] = index; } } @@ -62,8 +64,8 @@ { CBond &fb = folder.Bonds[i]; const NCoderMixer2::CBond &mixerBond = _bindInfo.Bonds[_bindInfo.Bonds.Size() - 1 - i]; - fb.PackIndex = _SrcOut_to_DestIn[mixerBond.PackIndex]; - fb.UnpackIndex = _SrcIn_to_DestOut[mixerBond.UnpackIndex]; + fb.PackIndex = SrcOut_to_DestIn[mixerBond.PackIndex]; + fb.UnpackIndex = SrcIn_to_DestOut[mixerBond.UnpackIndex]; } folder.Coders.SetSize(_bindInfo.Coders.Size()); @@ -81,15 +83,16 @@ folder.PackStreams.SetSize(_bindInfo.PackStreams.Size()); for (i = 0; i < _bindInfo.PackStreams.Size(); i++) - folder.PackStreams[i] = _SrcOut_to_DestIn[_bindInfo.PackStreams[i]]; + folder.PackStreams[i] = SrcOut_to_DestIn[_bindInfo.PackStreams[i]]; } static HRESULT SetCoderProps2(const CProps &props, const UInt64 *dataSizeReduce, IUnknown *coder) { - CMyComPtr setCoderProperties; - coder->QueryInterface(IID_ICompressSetCoderProperties, (void **)&setCoderProperties); + Z7_DECL_CMyComPtr_QI_FROM( + ICompressSetCoderProperties, + setCoderProperties, coder) if (setCoderProperties) return props.SetCoderProps(setCoderProperties, dataSizeReduce); return props.AreThereNonOptionalProps() ? E_INVALIDARG : S_OK; @@ -103,11 +106,11 @@ OutSize = 0; } -STDMETHODIMP CMtEncMultiProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */) +Z7_COM7F_IMF(CMtEncMultiProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */)) { UInt64 outSize2; { - #ifndef _7ZIP_ST + #ifndef Z7_ST NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection); #endif outSize2 = OutSize; @@ -146,7 +149,7 @@ #endif } - RINOK(_mixer->SetBindInfo(_bindInfo)); + RINOK(_mixer->SetBindInfo(_bindInfo)) FOR_VECTOR (m, _options.Methods) { @@ -158,23 +161,27 @@ { RINOK(CreateCoder_Index( EXTERNAL_CODECS_LOC_VARS - (unsigned)methodFull.CodecIndex, true, cod)); + (unsigned)methodFull.CodecIndex, true, cod)) } else { RINOK(CreateCoder_Id( EXTERNAL_CODECS_LOC_VARS - methodFull.Id, true, cod)); + methodFull.Id, true, cod)) } - if (cod.NumStreams != methodFull.NumStreams) - return E_FAIL; if (!cod.Coder && !cod.Coder2) + { + return E_NOTIMPL; // unsupported method, if encoder + // return E_FAIL; + } + + if (cod.NumStreams != methodFull.NumStreams) return E_FAIL; CMyComPtr encoderCommon = cod.Coder ? (IUnknown *)cod.Coder : (IUnknown *)cod.Coder2; - #ifndef _7ZIP_ST + #ifndef Z7_ST if (methodFull.Set_NumThreads) { CMyComPtr setCoderMt; @@ -184,12 +191,12 @@ RINOK(setCoderMt->SetNumberOfThreads( /* _options.NumThreads */ methodFull.NumThreads - )); + )) } } #endif - RINOK(SetCoderProps2(methodFull, inSizeForReduce, encoderCommon)); + RINOK(SetCoderProps2(methodFull, inSizeForReduce, encoderCommon)) /* CMyComPtr resetSalt; @@ -202,13 +209,13 @@ // now there is no codec that uses another external codec /* - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS CMyComPtr setCompressCodecsInfo; encoderCommon.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo); if (setCompressCodecsInfo) { // we must use g_ExternalCodecs also - RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(__externalCodecs->GetCodecs)); + RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(_externalCodecs->GetCodecs)); } #endif */ @@ -226,7 +233,7 @@ ((Byte *)buffer)[i * 2] = (Byte)c; ((Byte *)buffer)[i * 2 + 1] = (Byte)(c >> 8); } - RINOK(cryptoSetPassword->CryptoSetPassword((const Byte *)buffer, (UInt32)sizeInBytes)); + RINOK(cryptoSetPassword->CryptoSetPassword((const Byte *)buffer, (UInt32)sizeInBytes)) } _mixer->AddCoder(cod); @@ -236,85 +243,94 @@ -class CSequentialOutTempBufferImp2: - public ISequentialOutStream, - public CMyUnknownImp -{ - CInOutTempBuffer *_buf; +Z7_CLASS_IMP_COM_1( + CSequentialOutTempBufferImp2 + , ISequentialOutStream +) public: - CMtEncMultiProgress *_mtProgresSpec; + CInOutTempBuffer TempBuffer; + CMtEncMultiProgress *_mtProgressSpec; - CSequentialOutTempBufferImp2(): _buf(0), _mtProgresSpec(NULL) {} - void Init(CInOutTempBuffer *buffer) { _buf = buffer; } - MY_UNKNOWN_IMP1(ISequentialOutStream) - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); + CSequentialOutTempBufferImp2(): _mtProgressSpec(NULL) {} }; -STDMETHODIMP CSequentialOutTempBufferImp2::Write(const void *data, UInt32 size, UInt32 *processed) +Z7_COM7F_IMF(CSequentialOutTempBufferImp2::Write(const void *data, UInt32 size, UInt32 *processed)) { - HRESULT res = _buf->Write_HRESULT(data, size); - if (res != S_OK) - { - if (processed) - *processed = 0; - return res; - } + COM_TRY_BEGIN + if (processed) + *processed = 0; + RINOK(TempBuffer.Write_HRESULT(data, size)) if (processed) *processed = size; - if (_mtProgresSpec) - _mtProgresSpec->AddOutSize(size); + if (_mtProgressSpec) + _mtProgressSpec->AddOutSize(size); return S_OK; + COM_TRY_END } -class CSequentialOutMtNotify: - public ISequentialOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CSequentialOutMtNotify + , ISequentialOutStream +) public: CMyComPtr _stream; - CMtEncMultiProgress *_mtProgresSpec; + CMtEncMultiProgress *_mtProgressSpec; - CSequentialOutMtNotify(): _mtProgresSpec(NULL) {} - MY_UNKNOWN_IMP1(ISequentialOutStream) - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); + CSequentialOutMtNotify(): _mtProgressSpec(NULL) {} }; -STDMETHODIMP CSequentialOutMtNotify::Write(const void *data, UInt32 size, UInt32 *processed) +Z7_COM7F_IMF(CSequentialOutMtNotify::Write(const void *data, UInt32 size, UInt32 *processed)) { UInt32 realProcessed = 0; HRESULT res = _stream->Write(data, size, &realProcessed); if (processed) *processed = realProcessed; - if (_mtProgresSpec) - _mtProgresSpec->AddOutSize(size); + if (_mtProgressSpec) + _mtProgressSpec->AddOutSize(size); return res; } +static HRESULT FillProps_from_Coder(IUnknown *coder, CByteBuffer &props) +{ + Z7_DECL_CMyComPtr_QI_FROM( + ICompressWriteCoderProperties, + writeCoderProperties, coder) + if (writeCoderProperties) + { + CDynBufSeqOutStream *outStreamSpec = new CDynBufSeqOutStream; + CMyComPtr dynOutStream(outStreamSpec); + outStreamSpec->Init(); + RINOK(writeCoderProperties->WriteCoderProperties(dynOutStream)) + outStreamSpec->CopyToBuffer(props); + } + else + props.Free(); + return S_OK; +} -HRESULT CEncoder::Encode( +HRESULT CEncoder::Encode1( DECL_EXTERNAL_CODECS_LOC_VARS ISequentialInStream *inStream, // const UInt64 *inStreamSize, const UInt64 *inSizeForReduce, + UInt64 expectedDataSize, CFolder &folderItem, - CRecordVector &coderUnpackSizes, - UInt64 &unpackSize, + // CRecordVector &coderUnpackSizes, + // UInt64 &unpackSize, ISequentialOutStream *outStream, CRecordVector &packSizes, ICompressProgressInfo *compressProgress) { - RINOK(EncoderConstr()); + RINOK(EncoderConstr()) if (!_mixerRef) { - RINOK(CreateMixerCoder(EXTERNAL_CODECS_LOC_VARS inSizeForReduce)); + RINOK(CreateMixerCoder(EXTERNAL_CODECS_LOC_VARS inSizeForReduce)) } - RINOK(_mixer->ReInit2()); + RINOK(_mixer->ReInit2()) CMtEncMultiProgress *mtProgressSpec = NULL; CMyComPtr mtProgress; @@ -322,30 +338,21 @@ CSequentialOutMtNotify *mtOutStreamNotifySpec = NULL; CMyComPtr mtOutStreamNotify; - CObjectVector inOutTempBuffers; - CObjectVector tempBufferSpecs; + CRecordVector tempBufferSpecs; CObjectVector > tempBuffers; - unsigned numMethods = _bindInfo.Coders.Size(); - unsigned i; for (i = 1; i < _bindInfo.PackStreams.Size(); i++) { - CInOutTempBuffer &iotb = inOutTempBuffers.AddNew(); - iotb.Create(); - iotb.InitWriting(); - } - - for (i = 1; i < _bindInfo.PackStreams.Size(); i++) - { - CSequentialOutTempBufferImp2 *tempBufferSpec = new CSequentialOutTempBufferImp2; + CSequentialOutTempBufferImp2 *tempBufferSpec = new CSequentialOutTempBufferImp2(); CMyComPtr tempBuffer = tempBufferSpec; - tempBufferSpec->Init(&inOutTempBuffers[i - 1]); - tempBuffers.Add(tempBuffer); tempBufferSpecs.Add(tempBufferSpec); + tempBuffers.Add(tempBuffer); } + const unsigned numMethods = _bindInfo.Coders.Size(); + for (i = 0; i < numMethods; i++) _mixer->SetCoderInfo(i, NULL, NULL, false); @@ -360,15 +367,19 @@ */ + /* CSequentialInStreamSizeCount2 *inStreamSizeCountSpec = new CSequentialInStreamSizeCount2; CMyComPtr inStreamSizeCount = inStreamSizeCountSpec; + */ CSequentialOutStreamSizeCount *outStreamSizeCountSpec = NULL; CMyComPtr outStreamSizeCount; - inStreamSizeCountSpec->Init(inStream); + // inStreamSizeCountSpec->Init(inStream); + + // ISequentialInStream *inStreamPointer = inStreamSizeCount; + ISequentialInStream *inStreamPointer = inStream; - ISequentialInStream *inStreamPointer = inStreamSizeCount; CRecordVector outStreamPointers; SetFolder(folderItem); @@ -376,49 +387,66 @@ for (i = 0; i < numMethods; i++) { IUnknown *coder = _mixer->GetCoder(i).GetUnknown(); + /* + { + CEncoder *sfEncoder = NULL; + Z7_DECL_CMyComPtr_QI_FROM( + IGetSfEncoderInternal, + sf, coder) + if (sf) + { + RINOK(sf->GetSfEncoder(&sfEncoder)); + if (!sfEncoder) + return E_FAIL; - CMyComPtr resetInitVector; - coder->QueryInterface(IID_ICryptoResetInitVector, (void **)&resetInitVector); - if (resetInitVector) + } + } + */ + /* + #ifdef Z7_EXTERNAL_CODECS { - resetInitVector->ResetInitVector(); + Z7_DECL_CMyComPtr_QI_FROM( + ISetCompressCodecsInfo, + setCompressCodecsInfo, coder) + if (setCompressCodecsInfo) + { + // we must use g_ExternalCodecs also + RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(_externalCodecs->GetCodecs)) + } } - + #endif + */ { - CMyComPtr optProps; - coder->QueryInterface(IID_ICompressSetCoderPropertiesOpt, (void **)&optProps); - if (optProps) + Z7_DECL_CMyComPtr_QI_FROM( + ICryptoResetInitVector, + resetInitVector, coder) + if (resetInitVector) { - PROPID propID = NCoderPropID::kExpectedDataSize; - NWindows::NCOM::CPropVariant prop = (UInt64)unpackSize; - RINOK(optProps->SetCoderPropertiesOpt(&propID, &prop, 1)); + RINOK(resetInitVector->ResetInitVector()) } } - - CMyComPtr writeCoderProperties; - coder->QueryInterface(IID_ICompressWriteCoderProperties, (void **)&writeCoderProperties); - - CByteBuffer &props = folderItem.Coders[numMethods - 1 - i].Props; - - if (writeCoderProperties) { - CDynBufSeqOutStream *outStreamSpec = new CDynBufSeqOutStream; - CMyComPtr dynOutStream(outStreamSpec); - outStreamSpec->Init(); - RINOK(writeCoderProperties->WriteCoderProperties(dynOutStream)); - outStreamSpec->CopyToBuffer(props); + Z7_DECL_CMyComPtr_QI_FROM( + ICompressSetCoderPropertiesOpt, + optProps, coder) + if (optProps) + { + const PROPID propID = NCoderPropID::kExpectedDataSize; + NWindows::NCOM::CPropVariant prop = (UInt64)expectedDataSize; + RINOK(optProps->SetCoderPropertiesOpt(&propID, &prop, 1)) + } } - else - props.Free(); + // we must write properties from coder after ResetInitVector() + RINOK(FillProps_from_Coder(coder, folderItem.Coders[numMethods - 1 - i].Props)) } _mixer->SelectMainCoder(false); - UInt32 mainCoder = _mixer->MainCoderIndex; + const UInt32 mainCoder = _mixer->MainCoderIndex; bool useMtProgress = false; if (!_mixer->Is_PackSize_Correct_for_Coder(mainCoder)) { - #ifdef _7ZIP_ST + #ifdef Z7_ST if (!_mixer->IsThere_ExternalCoder_in_PackTree(mainCoder)) #endif useMtProgress = true; @@ -433,11 +461,11 @@ mtOutStreamNotifySpec = new CSequentialOutMtNotify; mtOutStreamNotify = mtOutStreamNotifySpec; mtOutStreamNotifySpec->_stream = outStream; - mtOutStreamNotifySpec->_mtProgresSpec = mtProgressSpec; + mtOutStreamNotifySpec->_mtProgressSpec = mtProgressSpec; - FOR_VECTOR(t, tempBufferSpecs) + FOR_VECTOR (t, tempBufferSpecs) { - tempBufferSpecs[t]->_mtProgresSpec = mtProgressSpec; + tempBufferSpecs[t]->_mtProgressSpec = mtProgressSpec; } } @@ -459,35 +487,49 @@ RINOK(_mixer->Code( &inStreamPointer, &outStreamPointers.Front(), - mtProgress ? (ICompressProgressInfo *)mtProgress : compressProgress, dataAfterEnd_Error)); + mtProgress ? (ICompressProgressInfo *)mtProgress : compressProgress, dataAfterEnd_Error)) if (_bindInfo.PackStreams.Size() != 0) packSizes.Add(outStreamSizeCountSpec->GetSize()); for (i = 1; i < _bindInfo.PackStreams.Size(); i++) { - CInOutTempBuffer &inOutTempBuffer = inOutTempBuffers[i - 1]; - RINOK(inOutTempBuffer.WriteToStream(outStream)); - packSizes.Add(inOutTempBuffer.GetDataSize()); + CInOutTempBuffer &iotb = tempBufferSpecs[i - 1]->TempBuffer; + RINOK(iotb.WriteToStream(outStream)) + packSizes.Add(iotb.GetDataSize()); } - unpackSize = 0; - - for (i = 0; i < _bindInfo.Coders.Size(); i++) + /* Code() in some future codec can change properties. + v23: so we fill properties again after Code() */ + for (i = 0; i < numMethods; i++) + { + IUnknown *coder = _mixer->GetCoder(i).GetUnknown(); + RINOK(FillProps_from_Coder(coder, folderItem.Coders[numMethods - 1 - i].Props)) + } + + return S_OK; +} + + +void CEncoder::Encode_Post( + UInt64 unpackSize, + CRecordVector &coderUnpackSizes) +{ + // unpackSize = 0; + for (unsigned i = 0; i < _bindInfo.Coders.Size(); i++) { - int bond = _bindInfo.FindBond_for_UnpackStream(_DestOut_to_SrcIn[i]); + const int bond = _bindInfo.FindBond_for_UnpackStream(DestOut_to_SrcIn[i]); UInt64 streamSize; if (bond < 0) { - streamSize = inStreamSizeCountSpec->GetSize(); - unpackSize = streamSize; + // streamSize = inStreamSizeCountSpec->GetSize(); + // unpackSize = streamSize; + streamSize = unpackSize; } else streamSize = _mixer->GetBondStreamSize((unsigned)bond); coderUnpackSizes.Add(streamSize); } - - return S_OK; } @@ -610,15 +652,15 @@ if (_bindInfo.Coders[ci].NumStreams == 0) break; - UInt32 outIndex = _bindInfo.Coder_to_Stream[ci]; - int bond = _bindInfo.FindBond_for_PackStream(outIndex); + const UInt32 outIndex = _bindInfo.Coder_to_Stream[ci]; + const int bond = _bindInfo.FindBond_for_PackStream(outIndex); if (bond >= 0) { ci = _bindInfo.Bonds[(unsigned)bond].UnpackIndex; continue; } - int si = _bindInfo.FindStream_in_PackStreams(outIndex); + const int si = _bindInfo.FindStream_in_PackStreams(outIndex); if (si >= 0) _bindInfo.PackStreams.MoveToFront((unsigned)si); break; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zEncode.h 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zEncode.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zEncode.h 2021-01-26 19:01:51.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zEncode.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // 7zEncode.h -#ifndef __7Z_ENCODE_H -#define __7Z_ENCODE_H +#ifndef ZIP7_INC_7Z_ENCODE_H +#define ZIP7_INC_7Z_ENCODE_H #include "7zCompressionMode.h" @@ -12,12 +12,12 @@ namespace NArchive { namespace N7z { -class CMtEncMultiProgress: - public ICompressProgressInfo, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CMtEncMultiProgress, + ICompressProgressInfo +) CMyComPtr _progress; - #ifndef _7ZIP_ST + #ifndef Z7_ST NWindows::NSynchronization::CCriticalSection CriticalSection; #endif @@ -30,18 +30,15 @@ void AddOutSize(UInt64 addOutSize) { - #ifndef _7ZIP_ST + #ifndef Z7_ST NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection); #endif OutSize += addOutSize; } - - MY_UNKNOWN_IMP1(ICompressProgressInfo) - - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); }; -class CEncoder MY_UNCOPYABLE + +class CEncoder Z7_final MY_UNCOPYABLE { #ifdef USE_MIXER_ST NCoderMixer2::CMixerST *_mixerST; @@ -57,10 +54,10 @@ NCoderMixer2::CBindInfo _bindInfo; CRecordVector _decompressionMethods; - CRecordVector _SrcIn_to_DestOut; - CRecordVector _SrcOut_to_DestIn; - // CRecordVector _DestIn_to_SrcOut; - CRecordVector _DestOut_to_SrcIn; + CRecordVector SrcIn_to_DestOut; + CRecordVector SrcOut_to_DestIn; + // CRecordVector DestIn_to_SrcOut; + CRecordVector DestOut_to_SrcIn; void InitBindConv(); void SetFolder(CFolder &folder); @@ -74,17 +71,23 @@ CEncoder(const CCompressionMethodMode &options); ~CEncoder(); HRESULT EncoderConstr(); - HRESULT Encode( + HRESULT Encode1( DECL_EXTERNAL_CODECS_LOC_VARS ISequentialInStream *inStream, // const UInt64 *inStreamSize, const UInt64 *inSizeForReduce, + UInt64 expectedDataSize, CFolder &folderItem, - CRecordVector &coderUnpackSizes, - UInt64 &unpackSize, + // CRecordVector &coderUnpackSizes, + // UInt64 &unpackSize, ISequentialOutStream *outStream, CRecordVector &packSizes, ICompressProgressInfo *compressProgress); + + void Encode_Post( + UInt64 unpackSize, + CRecordVector &coderUnpackSizes); + }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zExtract.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zExtract.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zExtract.cpp 2021-08-08 17:53:08.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zExtract.cpp 2023-03-29 17:00:00.000000000 +0000 @@ -16,10 +16,11 @@ namespace NArchive { namespace N7z { -class CFolderOutStream: - public ISequentialOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CFolderOutStream + , ISequentialOutStream + /* , ICompressGetSubStreamSize */ +) CMyComPtr _stream; public: bool TestMode; @@ -31,6 +32,7 @@ UInt64 _rem; const UInt32 *_indexes; + // unsigned _startIndex; unsigned _numFiles; unsigned _fileIndex; @@ -40,8 +42,6 @@ HRESULT ProcessEmptyFiles(); public: - MY_UNKNOWN_IMP1(ISequentialOutStream) - const CDbEx *_db; CMyComPtr ExtractCallback; @@ -52,8 +52,6 @@ CheckCrc(true) {} - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - HRESULT Init(unsigned startIndex, const UInt32 *indexes, unsigned numFiles); HRESULT FlushCorrupted(Int32 callbackOperationResult); @@ -63,6 +61,7 @@ HRESULT CFolderOutStream::Init(unsigned startIndex, const UInt32 *indexes, unsigned numFiles) { + // _startIndex = startIndex; _fileIndex = startIndex; _indexes = indexes; _numFiles = numFiles; @@ -76,11 +75,10 @@ HRESULT CFolderOutStream::OpenFile(bool isCorrupted) { const CFileItem &fi = _db->Files[_fileIndex]; - UInt32 nextFileIndex = (_indexes ? *_indexes : _fileIndex); - Int32 askMode = (_fileIndex == nextFileIndex) ? - (TestMode ? - NExtract::NAskMode::kTest : - NExtract::NAskMode::kExtract) : + const UInt32 nextFileIndex = (_indexes ? *_indexes : _fileIndex); + Int32 askMode = (_fileIndex == nextFileIndex) ? TestMode ? + NExtract::NAskMode::kTest : + NExtract::NAskMode::kExtract : NExtract::NAskMode::kSkip; if (isCorrupted @@ -90,7 +88,7 @@ askMode = NExtract::NAskMode::kTest; CMyComPtr realOutStream; - RINOK(ExtractCallback->GetStream(_fileIndex, &realOutStream, askMode)); + RINOK(ExtractCallback->GetStream(_fileIndex, &realOutStream, askMode)) _stream = realOutStream; _crc = CRC_INIT_VAL; @@ -136,13 +134,13 @@ { while (_numFiles != 0 && _db->Files[_fileIndex].Size == 0) { - RINOK(OpenFile()); - RINOK(CloseFile()); + RINOK(OpenFile()) + RINOK(CloseFile()) } return S_OK; } -STDMETHODIMP CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -170,16 +168,16 @@ _rem -= cur; if (_rem == 0) { - RINOK(CloseFile()); - RINOK(ProcessEmptyFiles()); + RINOK(CloseFile()) + RINOK(ProcessEmptyFiles()) } - RINOK(result); + RINOK(result) if (cur == 0) break; continue; } - RINOK(ProcessEmptyFiles()); + RINOK(ProcessEmptyFiles()) if (_numFiles == 0) { // we support partial extracting @@ -192,7 +190,7 @@ // return S_FALSE; return k_My_HRESULT_WritingWasCut; } - RINOK(OpenFile()); + RINOK(OpenFile()) } return S_OK; @@ -204,18 +202,32 @@ { if (_fileIsOpen) { - RINOK(CloseFile_and_SetResult(callbackOperationResult)); + RINOK(CloseFile_and_SetResult(callbackOperationResult)) } else { - RINOK(OpenFile(true)); + RINOK(OpenFile(true)) } } return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testModeSpec, IArchiveExtractCallback *extractCallbackSpec) +/* +Z7_COM7F_IMF(CFolderOutStream::GetSubStreamSize(UInt64 subStream, UInt64 *value)) +{ + *value = 0; + // const unsigned numFiles_Original = _numFiles + _fileIndex - _startIndex; + const unsigned numFiles_Original = _numFiles; + if (subStream >= numFiles_Original) + return S_FALSE; // E_FAIL; + *value = _db->Files[_startIndex + (unsigned)subStream].Size; + return S_OK; +} +*/ + + +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testModeSpec, IArchiveExtractCallback *extractCallbackSpec)) { // for GCC // CFolderOutStream *folderOutStream = new CFolderOutStream; @@ -229,7 +241,7 @@ // numItems = (UInt32)(Int32)-1; - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _db.Files.Size(); @@ -244,8 +256,8 @@ for (i = 0; i < numItems; i++) { - UInt32 fileIndex = allFilesMode ? i : indices[i]; - CNum folderIndex = _db.FileIndexToFolderIndexMap[fileIndex]; + const UInt32 fileIndex = allFilesMode ? i : indices[i]; + const CNum folderIndex = _db.FileIndexToFolderIndexMap[fileIndex]; if (folderIndex == kNumNoIndex) continue; if (folderIndex != prevFolder || fileIndex < nextFile) @@ -257,7 +269,7 @@ } } - RINOK(extractCallback->SetTotal(importantTotalUnpacked)); + RINOK(extractCallback->SetTotal(importantTotalUnpacked)) CLocalProgress *lps = new CLocalProgress; CMyComPtr progress = lps; @@ -268,8 +280,8 @@ false #elif !defined(USE_MIXER_ST) true - #elif !defined(__7Z_SET_PROPERTIES) - #ifdef _7ZIP_ST + #elif !defined(Z7_7Z_SET_PROPERTIES) + #ifdef Z7_ST false #else true @@ -281,8 +293,8 @@ UInt64 curPacked, curUnpacked; - CMyComPtr callbackMessage; - extractCallback.QueryInterface(IID_IArchiveExtractCallbackMessage, &callbackMessage); + CMyComPtr callbackMessage; + extractCallback.QueryInterface(IID_IArchiveExtractCallbackMessage2, &callbackMessage); CFolderOutStream *folderOutStream = new CFolderOutStream; CMyComPtr outStream(folderOutStream); @@ -294,7 +306,7 @@ for (UInt32 i = 0;; lps->OutSize += curUnpacked, lps->InSize += curPacked) { - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) if (i >= numItems) break; @@ -303,7 +315,7 @@ curPacked = 0; UInt32 fileIndex = allFilesMode ? i : indices[i]; - CNum folderIndex = _db.FileIndexToFolderIndexMap[fileIndex]; + const CNum folderIndex = _db.FileIndexToFolderIndexMap[fileIndex]; UInt32 numSolidFiles = 1; @@ -316,7 +328,7 @@ for (k = i + 1; k < numItems; k++) { - UInt32 fileIndex2 = allFilesMode ? k : indices[k]; + const UInt32 fileIndex2 = allFilesMode ? k : indices[k]; if (_db.FileIndexToFolderIndexMap[fileIndex2] != folderIndex || fileIndex2 < nextFile) break; @@ -330,20 +342,26 @@ } { - HRESULT result = folderOutStream->Init(fileIndex, + const HRESULT result = folderOutStream->Init(fileIndex, allFilesMode ? NULL : indices + i, numSolidFiles); i += numSolidFiles; - RINOK(result); + RINOK(result) } - // to test solid block with zero unpacked size we disable that code if (folderOutStream->WasWritingFinished()) + { + // for debug: to test zero size stream unpacking + // if (folderIndex == kNumNoIndex) // enable this check for debug continue; + } + + if (folderIndex == kNumNoIndex) + return E_FAIL; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO CMyComPtr getTextPassword; if (extractCallback) extractCallback.QueryInterface(IID_ICryptoGetTextPassword, &getTextPassword); @@ -351,16 +369,15 @@ try { - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO bool isEncrypted = false; bool passwordIsDefined = false; UString_Wipe password; #endif - bool dataAfterEnd_Error = false; - HRESULT result = decoder.Decode( + const HRESULT result = decoder.Decode( EXTERNAL_CODECS_VARS _inStream, _db.ArcInfo.DataStartPosition, @@ -372,15 +389,15 @@ NULL // *inStreamMainRes , dataAfterEnd_Error - _7Z_DECODER_CRYPRO_VARS - #if !defined(_7ZIP_ST) + Z7_7Z_DECODER_CRYPRO_VARS + #if !defined(Z7_ST) , true, _numThreads, _memUsage_Decompress #endif ); if (result == S_FALSE || result == E_NOTIMPL || dataAfterEnd_Error) { - bool wasFinished = folderOutStream->WasWritingFinished(); + const bool wasFinished = folderOutStream->WasWritingFinished(); int resOp = NExtract::NOperationResult::kDataError; @@ -392,14 +409,14 @@ resOp = NExtract::NOperationResult::kDataAfterEnd; } - RINOK(folderOutStream->FlushCorrupted(resOp)); + RINOK(folderOutStream->FlushCorrupted(resOp)) if (wasFinished) { // we don't show error, if it's after required files if (/* !folderOutStream->ExtraWriteWasCut && */ callbackMessage) { - RINOK(callbackMessage->ReportExtractResult(NEventIndexType::kBlockIndex, folderIndex, resOp)); + RINOK(callbackMessage->ReportExtractResult(NEventIndexType::kBlockIndex, folderIndex, resOp)) } } continue; @@ -408,12 +425,12 @@ if (result != S_OK) return result; - RINOK(folderOutStream->FlushCorrupted(NExtract::NOperationResult::kDataError)); + RINOK(folderOutStream->FlushCorrupted(NExtract::NOperationResult::kDataError)) continue; } catch(...) { - RINOK(folderOutStream->FlushCorrupted(NExtract::NOperationResult::kDataError)); + RINOK(folderOutStream->FlushCorrupted(NExtract::NOperationResult::kDataError)) // continue; // return E_FAIL; throw; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zFolderInStream.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zFolderInStream.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zFolderInStream.cpp 2022-05-04 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zFolderInStream.cpp 2023-05-11 16:00:00.000000000 +0000 @@ -15,32 +15,38 @@ _updateCallback = updateCallback; _indexes = indexes; _numFiles = numFiles; + + _totalSize_for_Coder = 0; + ClearFileInfo(); Processed.ClearAndReserve(numFiles); - CRCs.ClearAndReserve(numFiles); Sizes.ClearAndReserve(numFiles); - - if (Need_CTime) CTimes.ClearAndReserve(numFiles); - if (Need_ATime) ATimes.ClearAndReserve(numFiles); - if (Need_MTime) MTimes.ClearAndReserve(numFiles); - if (Need_Attrib) Attribs.ClearAndReserve(numFiles); + CRCs.ClearAndReserve(numFiles); TimesDefined.ClearAndReserve(numFiles); - + MTimes.ClearAndReserve(Need_MTime ? numFiles : (unsigned)0); + CTimes.ClearAndReserve(Need_CTime ? numFiles : (unsigned)0); + ATimes.ClearAndReserve(Need_ATime ? numFiles : (unsigned)0); + Attribs.ClearAndReserve(Need_Attrib ? numFiles : (unsigned)0); + + // FolderCrc = CRC_INIT_VAL; _stream.Release(); } -HRESULT CFolderInStream::OpenStream() +void CFolderInStream::ClearFileInfo() { _pos = 0; _crc = CRC_INIT_VAL; _size_Defined = false; _times_Defined = false; _size = 0; + FILETIME_Clear(_mTime); FILETIME_Clear(_cTime); FILETIME_Clear(_aTime); - FILETIME_Clear(_mTime); _attrib = 0; +} +HRESULT CFolderInStream::OpenStream() +{ while (Processed.Size() < _numFiles) { CMyComPtr stream; @@ -83,7 +89,7 @@ } } - RINOK(AddFileInfo(result == S_OK)); + RINOK(AddFileInfo(result == S_OK)) } return S_OK; } @@ -117,13 +123,13 @@ // const UInt32 index = _indexes[Processed.Size()]; Processed.AddInReserved(isProcessed); Sizes.AddInReserved(_pos); - const UInt32 crc = CRC_GET_DIGEST(_crc); - CRCs.AddInReserved(crc); + CRCs.AddInReserved(CRC_GET_DIGEST(_crc)); + if (Need_Attrib) Attribs.AddInReserved(_attrib); TimesDefined.AddInReserved(_times_Defined); + if (Need_MTime) AddFt(MTimes, _mTime); if (Need_CTime) AddFt(CTimes, _cTime); if (Need_ATime) AddFt(ATimes, _aTime); - if (Need_MTime) AddFt(MTimes, _mTime); - if (Need_Attrib) Attribs.AddInReserved(_attrib); + ClearFileInfo(); /* if (isProcessed && _reportArcProp) RINOK(ReportItemProps(_reportArcProp, index, _pos, &crc)) @@ -131,7 +137,7 @@ return _updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK); } -STDMETHODIMP CFolderInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CFolderInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -139,38 +145,65 @@ { if (_stream) { + /* + if (_pos == 0) + { + const UInt32 align = (UInt32)1 << AlignLog; + const UInt32 offset = (UInt32)_totalSize_for_Coder & (align - 1); + if (offset != 0) + { + UInt32 cur = align - offset; + if (cur > size) + cur = size; + memset(data, 0, cur); + data = (Byte *)data + cur; + size -= cur; + // _pos += cur; // for debug + _totalSize_for_Coder += cur; + if (processedSize) + *processedSize += cur; + continue; + } + } + */ UInt32 cur = size; const UInt32 kMax = (UInt32)1 << 20; if (cur > kMax) cur = kMax; - RINOK(_stream->Read(data, cur, &cur)); + RINOK(_stream->Read(data, cur, &cur)) if (cur != 0) { + // if (Need_Crc) _crc = CrcUpdate(_crc, data, cur); + /* + if (FolderCrc) + FolderCrc = CrcUpdate(FolderCrc, data, cur); + */ _pos += cur; + _totalSize_for_Coder += cur; if (processedSize) - *processedSize = cur; + *processedSize = cur; // use +=cur, if continue is possible in loop return S_OK; } _stream.Release(); - RINOK(AddFileInfo(true)); + RINOK(AddFileInfo(true)) } if (Processed.Size() >= _numFiles) break; - RINOK(OpenStream()); + RINOK(OpenStream()) } return S_OK; } -STDMETHODIMP CFolderInStream::GetSubStreamSize(UInt64 subStream, UInt64 *value) +Z7_COM7F_IMF(CFolderInStream::GetSubStreamSize(UInt64 subStream, UInt64 *value)) { *value = 0; if (subStream > Sizes.Size()) return S_FALSE; // E_FAIL; - unsigned index = (unsigned)subStream; + const unsigned index = (unsigned)subStream; if (index < Sizes.Size()) { *value = Sizes[index]; @@ -187,4 +220,45 @@ return S_OK; } + +/* +HRESULT CFolderInStream::CloseCrcStream() +{ + if (!_crcStream) + return S_OK; + if (!_crcStream_Spec->WasFinished()) + return E_FAIL; + _crc = _crcStream_Spec->GetCRC() ^ CRC_INIT_VAL; // change it + const UInt64 size = _crcStream_Spec->GetSize(); + _pos = size; + _totalSize_for_Coder += size; + _crcStream.Release(); + // _crcStream->ReleaseStream(); + _stream.Release(); + return AddFileInfo(true); +} + +Z7_COM7F_IMF(CFolderInStream::GetNextInSubStream(UInt64 *streamIndexRes, ISequentialInStream **stream) +{ + RINOK(CloseCrcStream()) + *stream = NULL; + *streamIndexRes = Processed.Size(); + if (Processed.Size() >= _numFiles) + return S_OK; + RINOK(OpenStream()); + if (!_stream) + return S_OK; + if (!_crcStream) + { + _crcStream_Spec = new CSequentialInStreamWithCRC; + _crcStream = _crcStream_Spec; + } + _crcStream_Spec->Init(); + _crcStream_Spec->SetStream(_stream); + *stream = _crcStream; + _crcStream->AddRef(); + return S_OK; +} +*/ + }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zFolderInStream.h 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zFolderInStream.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zFolderInStream.h 2022-05-04 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zFolderInStream.h 2023-05-11 16:00:00.000000000 +0000 @@ -1,12 +1,13 @@ // 7zFolderInStream.h -#ifndef __7Z_FOLDER_IN_STREAM_H -#define __7Z_FOLDER_IN_STREAM_H +#ifndef ZIP7_INC_7Z_FOLDER_IN_STREAM_H +#define ZIP7_INC_7Z_FOLDER_IN_STREAM_H #include "../../../../C/7zCrc.h" #include "../../../Common/MyCom.h" #include "../../../Common/MyVector.h" +// #include "../Common/InStreamWithCRC.h" #include "../../ICoder.h" #include "../IArchive.h" @@ -14,20 +15,26 @@ namespace NArchive { namespace N7z { -class CFolderInStream: - public ISequentialInStream, - public ICompressGetSubStreamSize, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_2( + CFolderInStream + , ISequentialInStream + , ICompressGetSubStreamSize +) + /* + Z7_COM7F_IMP(GetNextStream(UInt64 *streamIndex)) + Z7_IFACE_COM7_IMP(ICompressInSubStreams) + */ + CMyComPtr _stream; + UInt64 _totalSize_for_Coder; UInt64 _pos; UInt32 _crc; bool _size_Defined; bool _times_Defined; UInt64 _size; + FILETIME _mTime; FILETIME _cTime; FILETIME _aTime; - FILETIME _mTime; UInt32 _attrib; unsigned _numFiles; @@ -35,34 +42,40 @@ CMyComPtr _updateCallback; + void ClearFileInfo(); HRESULT OpenStream(); HRESULT AddFileInfo(bool isProcessed); - + // HRESULT CloseCrcStream(); public: + bool Need_MTime; + bool Need_CTime; + bool Need_ATime; + bool Need_Attrib; + // bool Need_Crc; + // bool Need_FolderCrc; + // unsigned AlignLog; + CRecordVector Processed; - CRecordVector CRCs; CRecordVector Sizes; - CRecordVector CTimes; - CRecordVector ATimes; - CRecordVector MTimes; + CRecordVector CRCs; CRecordVector Attribs; CRecordVector TimesDefined; + CRecordVector MTimes; + CRecordVector CTimes; + CRecordVector ATimes; + // UInt32 FolderCrc; - bool Need_CTime; - bool Need_ATime; - bool Need_MTime; - bool Need_Attrib; - + // UInt32 GetFolderCrc() const { return CRC_GET_DIGEST(FolderCrc); } + // CSequentialInStreamWithCRC *_crcStream_Spec; + // CMyComPtr _crcStream; // CMyComPtr _reportArcProp; - MY_UNKNOWN_IMP2(ISequentialInStream, ICompressGetSubStreamSize) - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(GetSubStreamSize)(UInt64 subStream, UInt64 *value); - void Init(IArchiveUpdateCallback *updateCallback, const UInt32 *indexes, unsigned numFiles); bool WasFinished() const { return Processed.Size() == _numFiles; } + UInt64 Get_TotalSize_for_Coder() const { return _totalSize_for_Coder; } + /* UInt64 GetFullSize() const { UInt64 size = 0; @@ -70,12 +83,16 @@ size += Sizes[i]; return size; } + */ CFolderInStream(): + Need_MTime(false), Need_CTime(false), Need_ATime(false), - Need_MTime(false), Need_Attrib(false) + // , Need_Crc(true) + // , Need_FolderCrc(false) + // , AlignLog(0) {} }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zHandler.cpp 2022-03-30 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zHandler.cpp 2023-03-29 17:00:00.000000000 +0000 @@ -7,7 +7,7 @@ #include "../../../Common/ComTry.h" #include "../../../Common/IntToString.h" -#ifndef __7Z_SET_PROPERTIES +#ifndef Z7_7Z_SET_PROPERTIES #include "../../../Windows/System.h" #endif @@ -16,8 +16,8 @@ #include "7zHandler.h" #include "7zProperties.h" -#ifdef __7Z_SET_PROPERTIES -#ifdef EXTRACT_ONLY +#ifdef Z7_7Z_SET_PROPERTIES +#ifdef Z7_EXTRACT_ONLY #include "../Common/ParseProperties.h" #endif #endif @@ -30,40 +30,40 @@ CHandler::CHandler() { - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO _isEncrypted = false; _passwordIsDefined = false; #endif - #ifdef EXTRACT_ONLY + #ifdef Z7_EXTRACT_ONLY _crcSize = 4; - #ifdef __7Z_SET_PROPERTIES + #ifdef Z7_7Z_SET_PROPERTIES _useMultiThreadMixer = true; #endif #endif } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _db.Files.Size(); return S_OK; } -#ifdef _SFX +#ifdef Z7_SFX IMP_IInArchive_ArcProps_NO_Table -STDMETHODIMP CHandler::GetNumberOfProperties(UInt32 *numProps) +Z7_COM7F_IMF(CHandler::GetNumberOfProperties(UInt32 *numProps)) { *numProps = 0; return S_OK; } -STDMETHODIMP CHandler::GetPropertyInfo(UInt32 /* index */, - BSTR * /* name */, PROPID * /* propID */, VARTYPE * /* varType */) +Z7_COM7F_IMF(CHandler::GetPropertyInfo(UInt32 /* index */, + BSTR * /* name */, PROPID * /* propID */, VARTYPE * /* varType */)) { return E_NOTIMPL; } @@ -110,8 +110,7 @@ static char *GetStringForSizeValue(char *s, UInt32 val) { - unsigned i; - for (i = 0; i <= 31; i++) + for (unsigned i = 0; i < 32; i++) if (((UInt32)1 << i) == val) { if (i >= 10) @@ -190,15 +189,15 @@ #endif -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { - #ifndef _SFX + #ifndef Z7_SFX COM_TRY_BEGIN #endif NCOM::CPropVariant prop; switch (propID) { - #ifndef _SFX + #ifndef Z7_SFX case kpidMethod: { AString s; @@ -220,6 +219,12 @@ GetStringForSizeValue(temp, pm.LzmaDic); s += temp; } + /* + else if (id == k_ZSTD) + { + s += "ZSTD"; + } + */ else AddMethodName(s, id); } @@ -269,7 +274,7 @@ } } return prop.Detach(value); - #ifndef _SFX + #ifndef Z7_SFX COM_TRY_END #endif } @@ -285,17 +290,17 @@ { if (folderIndex == kNumNoIndex) return false; - size_t startPos = _db.FoCodersDataOffset[folderIndex]; + const size_t startPos = _db.FoCodersDataOffset[folderIndex]; const Byte *p = _db.CodersData + startPos; - size_t size = _db.FoCodersDataOffset[folderIndex + 1] - startPos; + const size_t size = _db.FoCodersDataOffset[folderIndex + 1] - startPos; CInByte2 inByte; inByte.Init(p, size); CNum numCoders = inByte.ReadNum(); for (; numCoders != 0; numCoders--) { - Byte mainByte = inByte.ReadByte(); - unsigned idSize = (mainByte & 0xF); + const Byte mainByte = inByte.ReadByte(); + const unsigned idSize = (mainByte & 0xF); const Byte *longID = inByte.GetPtr(); UInt64 id64 = 0; for (unsigned j = 0; j < idSize; j++) @@ -309,20 +314,20 @@ return false; } -STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) +Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps)) { *numProps = 0; return S_OK; } -STDMETHODIMP CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID) +Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID)) { *name = NULL; *propID = kpidNtSecure; return S_OK; } -STDMETHODIMP CHandler::GetParent(UInt32 /* index */, UInt32 *parent, UInt32 *parentType) +Z7_COM7F_IMF(CHandler::GetParent(UInt32 /* index */, UInt32 *parent, UInt32 *parentType)) { /* const CFileItem &file = _db.Files[index]; @@ -334,7 +339,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) +Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType)) { *data = NULL; *dataSize = 0; @@ -376,7 +381,7 @@ return S_OK; } -#ifndef _SFX +#ifndef Z7_SFX HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const { @@ -389,9 +394,9 @@ unsigned pos = kTempSize; temp[--pos] = 0; - size_t startPos = _db.FoCodersDataOffset[folderIndex]; + const size_t startPos = _db.FoCodersDataOffset[folderIndex]; const Byte *p = _db.CodersData + startPos; - size_t size = _db.FoCodersDataOffset[folderIndex + 1] - startPos; + const size_t size = _db.FoCodersDataOffset[folderIndex + 1] - startPos; CInByte2 inByte; inByte.Init(p, size); @@ -403,10 +408,10 @@ { if (pos < 32) // max size of property break; - Byte mainByte = inByte.ReadByte(); - unsigned idSize = (mainByte & 0xF); - const Byte *longID = inByte.GetPtr(); + const Byte mainByte = inByte.ReadByte(); UInt64 id64 = 0; + const unsigned idSize = (mainByte & 0xF); + const Byte *longID = inByte.GetPtr(); for (unsigned j = 0; j < idSize; j++) id64 = ((id64 << 8) | longID[j]); inByte.SkipDataNoCheck(idSize); @@ -432,21 +437,21 @@ if (id64 <= (UInt32)0xFFFFFFFF) { - UInt32 id = (UInt32)id64; + const UInt32 id = (UInt32)id64; if (id == k_LZMA) { name = "LZMA"; if (propsSize == 5) { - UInt32 dicSize = GetUi32((const Byte *)props + 1); + const UInt32 dicSize = GetUi32((const Byte *)props + 1); char *dest = GetStringForSizeValue(s, dicSize); UInt32 d = props[0]; if (d != 0x5D) { - UInt32 lc = d % 9; + const UInt32 lc = d % 9; d /= 9; - UInt32 pb = d / 5; - UInt32 lp = d % 5; + const UInt32 pb = d / 5; + const UInt32 lp = d % 5; if (lc != 3) dest = AddProp32(dest, "lc", lc); if (lp != 0) dest = AddProp32(dest, "lp", lp); if (pb != 2) dest = AddProp32(dest, "pb", pb); @@ -477,6 +482,16 @@ if (propsSize == 1) ConvertUInt32ToString((UInt32)props[0] + 1, s); } + else if (id == k_ARM64) + { + name = "ARM64"; + if (propsSize == 4) + ConvertUInt32ToString(GetUi32(props), s); + /* + else if (propsSize != 0) + MyStringCopy(s, "unsupported"); + */ + } else if (id == k_BCJ2) name = "BCJ2"; else if (id == k_BCJ) name = "BCJ"; else if (id == k_AES) @@ -484,8 +499,8 @@ name = "7zAES"; if (propsSize >= 1) { - Byte firstByte = props[0]; - UInt32 numCyclesPower = firstByte & 0x3F; + const Byte firstByte = props[0]; + const UInt32 numCyclesPower = firstByte & 0x3F; ConvertUInt32ToString(numCyclesPower, s); } } @@ -493,8 +508,8 @@ if (name) { - unsigned nameLen = MyStringLen(name); - unsigned propsLen = MyStringLen(s); + const unsigned nameLen = MyStringLen(name); + const unsigned propsLen = MyStringLen(s); unsigned totalLen = nameLen + propsLen; if (propsLen != 0) totalLen++; @@ -523,7 +538,7 @@ pos -= ConvertMethodIdToString_Back(temp + pos, id64); else { - unsigned len = methodName.Len(); + const unsigned len = methodName.Len(); if (len + 5 > pos) break; pos -= len; @@ -547,9 +562,9 @@ #endif -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { - RINOK(PropVariant_Clear(value)); + RINOK(PropVariant_Clear(value)) // COM_TRY_BEGIN // NCOM::CPropVariant prop; @@ -576,7 +591,7 @@ { // prop = ref2.PackSize; { - CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; + const CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; if (folderIndex != kNumNoIndex) { if (_db.FolderStartFileIndex[folderIndex] == (CNum)index2) @@ -617,24 +632,24 @@ case kpidPath: return _db.GetPath_Prop(index, value); - #ifndef _SFX + #ifndef Z7_SFX case kpidMethod: return SetMethodToProp(_db.FileIndexToFolderIndexMap[index2], value); case kpidBlock: { - CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; + const CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; if (folderIndex != kNumNoIndex) PropVarEm_Set_UInt32(value, (UInt32)folderIndex); } break; - /* + #ifdef Z7_7Z_SHOW_PACK_STREAMS_SIZES case kpidPackedSize0: case kpidPackedSize1: case kpidPackedSize2: case kpidPackedSize3: case kpidPackedSize4: { - CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; + const CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; if (folderIndex != kNumNoIndex) { if (_db.FolderStartFileIndex[folderIndex] == (CNum)index2 && @@ -648,7 +663,7 @@ PropVarEm_Set_UInt64(value, 0); } break; - */ + #endif #endif } @@ -657,13 +672,13 @@ // COM_TRY_END } -STDMETHODIMP CHandler::Open(IInStream *stream, +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *maxCheckStartPosition, - IArchiveOpenCallback *openArchiveCallback) + IArchiveOpenCallback *openArchiveCallback)) { COM_TRY_BEGIN Close(); - #ifndef _SFX + #ifndef Z7_SFX _fileInfoPopIDs.Clear(); #endif @@ -671,31 +686,31 @@ { CMyComPtr openArchiveCallbackTemp = openArchiveCallback; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO CMyComPtr getTextPassword; if (openArchiveCallback) openArchiveCallbackTemp.QueryInterface(IID_ICryptoGetTextPassword, &getTextPassword); #endif CInArchive archive( - #ifdef __7Z_SET_PROPERTIES + #ifdef Z7_7Z_SET_PROPERTIES _useMultiThreadMixer #else true #endif ); _db.IsArc = false; - RINOK(archive.Open(stream, maxCheckStartPosition)); + RINOK(archive.Open(stream, maxCheckStartPosition)) _db.IsArc = true; HRESULT result = archive.ReadDatabase( EXTERNAL_CODECS_VARS _db - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO , getTextPassword, _isEncrypted, _passwordIsDefined, _password #endif ); - RINOK(result); + RINOK(result) _inStream = stream; } @@ -708,19 +723,19 @@ return E_OUTOFMEMORY; } // _inStream = stream; - #ifndef _SFX + #ifndef Z7_SFX FillPopIDs(); #endif return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { COM_TRY_BEGIN _inStream.Release(); _db.Clear(); - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO _isEncrypted = false; _passwordIsDefined = false; _password.Wipe_and_Empty(); @@ -729,10 +744,10 @@ COM_TRY_END } -#ifdef __7Z_SET_PROPERTIES -#ifdef EXTRACT_ONLY +#ifdef Z7_7Z_SET_PROPERTIES +#ifdef Z7_EXTRACT_ONLY -STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) +Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps)) { COM_TRY_BEGIN @@ -747,19 +762,19 @@ return E_INVALIDARG; const PROPVARIANT &value = values[i]; UInt32 number; - unsigned index = ParseStringToUInt32(name, number); + const unsigned index = ParseStringToUInt32(name, number); if (index == 0) { if (name.IsEqualTo("mtf")) { - RINOK(PROPVARIANT_to_bool(value, _useMultiThreadMixer)); + RINOK(PROPVARIANT_to_bool(value, _useMultiThreadMixer)) continue; } { HRESULT hres; if (SetCommonProperty(name, value, hres)) { - RINOK(hres); + RINOK(hres) continue; } } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zHandler.h 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zHandler.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zHandler.h 2022-05-10 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zHandler.h 2023-02-01 10:00:00.000000000 +0000 @@ -1,26 +1,26 @@ // 7z/Handler.h -#ifndef __7Z_HANDLER_H -#define __7Z_HANDLER_H +#ifndef ZIP7_7Z_HANDLER_H +#define ZIP7_7Z_HANDLER_H #include "../../ICoder.h" #include "../IArchive.h" #include "../../Common/CreateCoder.h" -#ifndef __7Z_SET_PROPERTIES +#ifndef Z7_7Z_SET_PROPERTIES -#ifdef EXTRACT_ONLY - #if !defined(_7ZIP_ST) && !defined(_SFX) - #define __7Z_SET_PROPERTIES +#ifdef Z7_EXTRACT_ONLY + #if !defined(Z7_ST) && !defined(Z7_SFX) + #define Z7_7Z_SET_PROPERTIES #endif #else - #define __7Z_SET_PROPERTIES + #define Z7_7Z_SET_PROPERTIES #endif #endif -// #ifdef __7Z_SET_PROPERTIES +// #ifdef Z7_7Z_SET_PROPERTIES #include "../Common/HandlerOut.h" // #endif @@ -31,7 +31,7 @@ namespace N7z { -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY class COutHandler: public CMultiMethodProps { @@ -79,73 +79,63 @@ #endif -class CHandler: +class CHandler Z7_final: public IInArchive, public IArchiveGetRawProps, - #ifdef __7Z_SET_PROPERTIES + #ifdef Z7_7Z_SET_PROPERTIES public ISetProperties, #endif - #ifndef EXTRACT_ONLY + #ifndef Z7_EXTRACT_ONLY public IOutArchive, #endif - PUBLIC_ISetCompressCodecsInfo + Z7_PUBLIC_ISetCompressCodecsInfo_IFEC public CMyUnknownImp, - #ifndef EXTRACT_ONLY + #ifndef Z7_EXTRACT_ONLY public COutHandler #else public CCommonMethodProps #endif { -public: - MY_QUERYINTERFACE_BEGIN2(IInArchive) - MY_QUERYINTERFACE_ENTRY(IArchiveGetRawProps) - #ifdef __7Z_SET_PROPERTIES - MY_QUERYINTERFACE_ENTRY(ISetProperties) - #endif - #ifndef EXTRACT_ONLY - MY_QUERYINTERFACE_ENTRY(IOutArchive) - #endif - QUERY_ENTRY_ISetCompressCodecsInfo - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IInArchive(;) - INTERFACE_IArchiveGetRawProps(;) - - #ifdef __7Z_SET_PROPERTIES - STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps); - #endif - - #ifndef EXTRACT_ONLY - INTERFACE_IOutArchive(;) - #endif - + Z7_COM_QI_BEGIN2(IInArchive) + Z7_COM_QI_ENTRY(IArchiveGetRawProps) + #ifdef Z7_7Z_SET_PROPERTIES + Z7_COM_QI_ENTRY(ISetProperties) + #endif + #ifndef Z7_EXTRACT_ONLY + Z7_COM_QI_ENTRY(IOutArchive) + #endif + Z7_COM_QI_ENTRY_ISetCompressCodecsInfo_IFEC + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(IInArchive) + Z7_IFACE_COM7_IMP(IArchiveGetRawProps) + #ifdef Z7_7Z_SET_PROPERTIES + Z7_IFACE_COM7_IMP(ISetProperties) + #endif + #ifndef Z7_EXTRACT_ONLY + Z7_IFACE_COM7_IMP(IOutArchive) + #endif DECL_ISetCompressCodecsInfo - CHandler(); - ~CHandler() - { - Close(); - } - private: CMyComPtr _inStream; NArchive::N7z::CDbEx _db; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO bool _isEncrypted; bool _passwordIsDefined; UString _password; // _Wipe - #endif + #endif - #ifdef EXTRACT_ONLY + #ifdef Z7_EXTRACT_ONLY - #ifdef __7Z_SET_PROPERTIES + #ifdef Z7_7Z_SET_PROPERTIES bool _useMultiThreadMixer; #endif @@ -162,7 +152,7 @@ #endif bool IsFolderEncrypted(CNum folderIndex) const; - #ifndef _SFX + #ifndef Z7_SFX CRecordVector _fileInfoPopIDs; void FillPopIDs(); @@ -172,6 +162,13 @@ #endif DECL_EXTERNAL_CODECS_VARS + +public: + CHandler(); + ~CHandler() + { + Close(); + } }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zHandlerOut.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zHandlerOut.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zHandlerOut.cpp 2022-05-09 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zHandlerOut.cpp 2023-05-11 16:00:00.000000000 +0000 @@ -13,7 +13,7 @@ #include "7zOut.h" #include "7zUpdate.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY using namespace NWindows; @@ -35,7 +35,7 @@ 1 << 20; #endif -STDMETHODIMP CHandler::GetFileTimeType(UInt32 *type) +Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *type)) { *type = NFileTimeType::kWindows; return S_OK; @@ -43,10 +43,11 @@ HRESULT CHandler::PropsMethod_To_FullMethod(CMethodFull &dest, const COneMethodInfo &m) { + bool isFilter; dest.CodecIndex = FindMethod_Index( EXTERNAL_CODECS_VARS m.MethodName, true, - dest.Id, dest.NumStreams); + dest.Id, dest.NumStreams, isFilter); if (dest.CodecIndex < 0) return E_INVALIDARG; (CProps &)dest = (CProps &)m; @@ -118,7 +119,7 @@ SetGlobalLevelTo(oneMethodInfo); - #ifndef _7ZIP_ST + #ifndef Z7_ST const bool numThreads_WasSpecifiedInMethod = (oneMethodInfo.Get_NumThreads() >= 0); if (!numThreads_WasSpecifiedInMethod) { @@ -128,9 +129,9 @@ #endif CMethodFull &methodFull = methodMode.Methods.AddNew(); - RINOK(PropsMethod_To_FullMethod(methodFull, oneMethodInfo)); + RINOK(PropsMethod_To_FullMethod(methodFull, oneMethodInfo)) - #ifndef _7ZIP_ST + #ifndef Z7_ST methodFull.Set_NumThreads = true; methodFull.NumThreads = methodMode.NumThreads; #endif @@ -147,15 +148,55 @@ case k_Deflate: dicSize = (UInt32)1 << 15; break; case k_Deflate64: dicSize = (UInt32)1 << 16; break; case k_BZip2: dicSize = oneMethodInfo.Get_BZip2_BlockSize(); break; + // case k_ZSTD: dicSize = 1 << 23; break; default: continue; } UInt64 numSolidBytes; - + + /* + if (methodFull.Id == k_ZSTD) + { + // continue; + NCompress::NZstd::CEncoderProps encoderProps; + RINOK(oneMethodInfo.Set_PropsTo_zstd(encoderProps)); + CZstdEncProps &zstdProps = encoderProps.EncProps; + ZstdEncProps_NormalizeFull(&zstdProps); + UInt64 cs = (UInt64)(zstdProps.jobSize); + UInt32 winSize = (UInt32)(1 << zstdProps.windowLog); + if (cs < winSize) + cs = winSize; + numSolidBytes = cs << 6; + const UInt64 kSolidBytes_Zstd_Max = ((UInt64)1 << 34); + if (numSolidBytes > kSolidBytes_Zstd_Max) + numSolidBytes = kSolidBytes_Zstd_Max; + + methodFull.Set_NumThreads = false; // we don't use ICompressSetCoderMt::SetNumberOfThreads() for LZMA2 encoder + + #ifndef Z7_ST + if (!numThreads_WasSpecifiedInMethod + && !methodMode.NumThreads_WasForced + && methodMode.MemoryUsageLimit_WasSet + ) + { + const UInt32 numThreads_Original = methodMode.NumThreads; + const UInt32 numThreads_New = ZstdEncProps_GetNumThreads_for_MemUsageLimit( + &zstdProps, + methodMode.MemoryUsageLimit, + numThreads_Original); + if (numThreads_Original != numThreads_New) + { + CMultiMethodProps::SetMethodThreadsTo_Replace(methodFull, numThreads_New); + } + } + #endif + } + else + */ if (methodFull.Id == k_LZMA2) { // he we calculate default chunk Size for LZMA2 as defined in LZMA2 encoder code - /* lzma2 code use dictionary upo to fake 4 GiB to calculate ChunkSize. + /* lzma2 code use dictionary up to fake 4 GiB to calculate ChunkSize. So we do same */ UInt64 cs = (UInt64)dicSize << 2; const UInt32 kMinSize = (UInt32)1 << 20; @@ -167,10 +208,10 @@ cs &= ~(UInt64)(kMinSize - 1); // we want to use at least 64 chunks (threads) per one solid block. - // here we don't use chunckSize property + // here we don't use chunkSize property numSolidBytes = cs << 6; - // here we get real chunckSize + // here we get real chunkSize cs = oneMethodInfo.Get_Xz_BlockSize(); if (dicSize > cs) dicSize = cs; @@ -181,7 +222,7 @@ methodFull.Set_NumThreads = false; // we don't use ICompressSetCoderMt::SetNumberOfThreads() for LZMA2 encoder - #ifndef _7ZIP_ST + #ifndef Z7_ST if (!numThreads_WasSpecifiedInMethod && !methodMode.NumThreads_WasForced && methodMode.MemoryUsageLimit_WasSet @@ -261,7 +302,7 @@ // ft = 0; // ftDefined = false; NCOM::CPropVariant prop; - RINOK(updateCallback->GetProperty(index, propID, &prop)); + RINOK(updateCallback->GetProperty(index, propID, &prop)) if (prop.vt == VT_FILETIME) { ft = prop.filetime.dwLowDateTime | ((UInt64)prop.filetime.dwHighDateTime << 32); @@ -344,13 +385,13 @@ } */ -STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, - IArchiveUpdateCallback *updateCallback) +Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, + IArchiveUpdateCallback *updateCallback)) { COM_TRY_BEGIN - const CDbEx *db = 0; - #ifdef _7Z_VOL + const CDbEx *db = NULL; + #ifdef Z7_7Z_VOL if (_volumes.Size() > 1) return E_FAIL; const CVolume *volume = 0; @@ -360,7 +401,7 @@ db = &volume->Database; } #else - if (_inStream != 0) + if (_inStream) db = &_db; #endif @@ -368,8 +409,9 @@ return E_NOTIMPL; /* - CMyComPtr getRawProps; - updateCallback->QueryInterface(IID_IArchiveGetRawProps, (void **)&getRawProps); + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveGetRawProps, + getRawProps, updateCallback) CUniqBlocks secureBlocks; secureBlocks.AddUniq(NULL, 0); @@ -406,7 +448,7 @@ UInt32 indexInArchive; if (!updateCallback) return E_FAIL; - RINOK(updateCallback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArchive)); + RINOK(updateCallback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArchive)) CUpdateItem ui; ui.NewProps = IntToBool(newProps); ui.NewData = IntToBool(newData); @@ -445,7 +487,7 @@ if (need_Attrib) { NCOM::CPropVariant prop; - RINOK(updateCallback->GetProperty(i, kpidAttrib, &prop)); + RINOK(updateCallback->GetProperty(i, kpidAttrib, &prop)) if (prop.vt == VT_EMPTY) ui.AttribDefined = false; else if (prop.vt != VT_UI4) @@ -458,9 +500,9 @@ } // we need MTime to sort files. - if (need_CTime) RINOK(GetTime(updateCallback, i, kpidCTime, ui.CTime, ui.CTimeDefined)); - if (need_ATime) RINOK(GetTime(updateCallback, i, kpidATime, ui.ATime, ui.ATimeDefined)); - if (need_MTime) RINOK(GetTime(updateCallback, i, kpidMTime, ui.MTime, ui.MTimeDefined)); + if (need_CTime) RINOK(GetTime(updateCallback, i, kpidCTime, ui.CTime, ui.CTimeDefined)) + if (need_ATime) RINOK(GetTime(updateCallback, i, kpidATime, ui.ATime, ui.ATimeDefined)) + if (need_MTime) RINOK(GetTime(updateCallback, i, kpidMTime, ui.MTime, ui.MTimeDefined)) /* if (getRawProps) @@ -478,7 +520,7 @@ { NCOM::CPropVariant prop; - RINOK(updateCallback->GetProperty(i, kpidPath, &prop)); + RINOK(updateCallback->GetProperty(i, kpidPath, &prop)) if (prop.vt == VT_EMPTY) { } @@ -492,7 +534,7 @@ } { NCOM::CPropVariant prop; - RINOK(updateCallback->GetProperty(i, kpidIsDir, &prop)); + RINOK(updateCallback->GetProperty(i, kpidIsDir, &prop)) if (prop.vt == VT_EMPTY) folderStatusIsDefined = false; else if (prop.vt != VT_BOOL) @@ -506,7 +548,7 @@ { NCOM::CPropVariant prop; - RINOK(updateCallback->GetProperty(i, kpidIsAnti, &prop)); + RINOK(updateCallback->GetProperty(i, kpidIsAnti, &prop)) if (prop.vt == VT_EMPTY) ui.IsAnti = false; else if (prop.vt != VT_BOOL) @@ -623,7 +665,7 @@ if (!ui.IsDir) { NCOM::CPropVariant prop; - RINOK(updateCallback->GetProperty(i, kpidSize, &prop)); + RINOK(updateCallback->GetProperty(i, kpidSize, &prop)) if (prop.vt != VT_UI8) return E_INVALIDARG; ui.Size = (UInt64)prop.uhVal.QuadPart; @@ -650,7 +692,7 @@ methodMode.MemoryUsageLimit = _memUsage_Compress; methodMode.MemoryUsageLimit_WasSet = _memUsage_WasSet; - #ifndef _7ZIP_ST + #ifndef Z7_ST { UInt32 numThreads = _numThreads; const UInt32 kNumThreads_Max = 1024; @@ -664,13 +706,14 @@ } #endif - HRESULT res = SetMainMethod(methodMode); - RINOK(res); + const HRESULT res = SetMainMethod(methodMode); + RINOK(res) - RINOK(SetHeaderMethod(headerMethod)); + RINOK(SetHeaderMethod(headerMethod)) - CMyComPtr getPassword2; - updateCallback->QueryInterface(IID_ICryptoGetTextPassword2, (void **)&getPassword2); + Z7_DECL_CMyComPtr_QI_FROM( + ICryptoGetTextPassword2, + getPassword2, updateCallback) methodMode.PasswordIsDefined = false; methodMode.Password.Wipe_and_Empty(); @@ -678,7 +721,7 @@ { CMyComBSTR_Wipe password; Int32 passwordIsDefined; - RINOK(getPassword2->CryptoGetTextPassword2(&passwordIsDefined, &password)); + RINOK(getPassword2->CryptoGetTextPassword2(&passwordIsDefined, &password)) methodMode.PasswordIsDefined = IntToBool(passwordIsDefined); if (methodMode.PasswordIsDefined && password) methodMode.Password = password; @@ -688,7 +731,7 @@ bool encryptHeaders = false; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO if (!methodMode.PasswordIsDefined && _passwordIsDefined) { // if header is compressed, we use that password for updated archive @@ -701,7 +744,7 @@ { if (_encryptHeadersSpecified) encryptHeaders = _encryptHeaders; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO else encryptHeaders = _passwordIsDefined; #endif @@ -716,13 +759,14 @@ if (numItems < 2) compressMainHeader = false; - int level = GetLevel(); + const int level = GetLevel(); CUpdateOptions options; options.Need_CTime = need_CTime; options.Need_ATime = need_ATime; options.Need_MTime = need_MTime; options.Need_Attrib = need_Attrib; + // options.Need_Crc = (_crcSize != 0); // for debug options.Method = &methodMode; options.HeaderMethod = (_compressHeaders || encryptHeaders) ? &headerMethod : NULL; @@ -748,12 +792,6 @@ options.MultiThreadMixer = _useMultiThreadMixer; - COutArchive archive; - CArchiveDatabaseOut newDatabase; - - CMyComPtr getPassword; - updateCallback->QueryInterface(IID_ICryptoGetTextPassword, (void **)&getPassword); - /* if (secureBlocks.Sorted.Size() > 1) { @@ -766,9 +804,9 @@ } */ - res = Update( + return Update( EXTERNAL_CODECS_VARS - #ifdef _7Z_VOL + #ifdef Z7_7Z_VOL volume ? volume->Stream: 0, volume ? db : 0, #else @@ -778,18 +816,7 @@ updateItems, // treeFolders, // secureBlocks, - archive, newDatabase, outStream, updateCallback, options - #ifndef _NO_CRYPTO - , getPassword - #endif - ); - - RINOK(res); - - updateItems.ClearAndFree(); - - return archive.WriteDatabase(EXTERNAL_CODECS_VARS - newDatabase, options.HeaderMethod, options.HeaderOptions); + outStream, updateCallback, options); COM_TRY_END } @@ -798,7 +825,7 @@ { stream = 0; { - unsigned index = ParseStringToUInt32(srcString, coder); + const unsigned index = ParseStringToUInt32(srcString, coder); if (index == 0) return E_INVALIDARG; srcString.DeleteFrontal(index); @@ -806,7 +833,7 @@ if (srcString[0] == 's') { srcString.Delete(0); - unsigned index = ParseStringToUInt32(srcString, stream); + const unsigned index = ParseStringToUInt32(srcString, stream); if (index == 0) return E_INVALIDARG; srcString.DeleteFrontal(index); @@ -860,7 +887,7 @@ i += (unsigned)(end - start); if (i == s2.Len()) return E_INVALIDARG; - wchar_t c = s2[i++]; + const wchar_t c = s2[i++]; if (c == 'f') { if (v < 1) @@ -912,7 +939,7 @@ static HRESULT PROPVARIANT_to_BoolPair(const PROPVARIANT &prop, CBoolPair &dest) { - RINOK(PROPVARIANT_to_bool(prop, dest.Val)); + RINOK(PROPVARIANT_to_bool(prop, dest.Val)) dest.Def = true; return S_OK; } @@ -935,7 +962,7 @@ } UInt32 number; - unsigned index = ParseStringToUInt32(name, number); + const unsigned index = ParseStringToUInt32(name, number); // UString realName = name.Ptr(index); if (index == 0) { @@ -946,20 +973,20 @@ if (name.IsEqualTo("hcf")) { bool compressHeadersFull = true; - RINOK(PROPVARIANT_to_bool(value, compressHeadersFull)); + RINOK(PROPVARIANT_to_bool(value, compressHeadersFull)) return compressHeadersFull ? S_OK: E_INVALIDARG; } if (name.IsEqualTo("he")) { - RINOK(PROPVARIANT_to_bool(value, _encryptHeaders)); + RINOK(PROPVARIANT_to_bool(value, _encryptHeaders)) _encryptHeadersSpecified = true; return S_OK; } { bool processed; - RINOK(TimeOptions.Parse(name, value, processed)); + RINOK(TimeOptions.Parse(name, value, processed)) if (processed) { if ( TimeOptions.Prec != (UInt32)(Int32)-1 @@ -982,7 +1009,7 @@ return CMultiMethodProps::SetProperty(name, value); } -STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) +Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps)) { COM_TRY_BEGIN _bonds.Clear(); @@ -997,6 +1024,7 @@ const PROPVARIANT &value = values[i]; + if (name.Find(L':') >= 0) // 'b' was used as NCoderPropID::kBlockSize2 before v23 if (name[0] == 'b') { if (value.vt != VT_EMPTY) @@ -1004,12 +1032,12 @@ name.Delete(0); CBond2 bond; - RINOK(ParseBond(name, bond.OutCoder, bond.OutStream)); + RINOK(ParseBond(name, bond.OutCoder, bond.OutStream)) if (name[0] != ':') return E_INVALIDARG; name.Delete(0); UInt32 inStream = 0; - RINOK(ParseBond(name, bond.InCoder, inStream)); + RINOK(ParseBond(name, bond.InCoder, inStream)) if (inStream != 0) return E_INVALIDARG; if (!name.IsEmpty()) @@ -1018,7 +1046,7 @@ continue; } - RINOK(SetProperty(name, value)); + RINOK(SetProperty(name, value)) } unsigned numEmptyMethods = GetNumEmptyMethods(); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zHeader.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zHeader.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zHeader.cpp 2013-11-24 13:19:36.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zHeader.cpp 2023-03-04 09:00:00.000000000 +0000 @@ -8,7 +8,7 @@ namespace N7z { Byte kSignature[kSignatureSize] = {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C}; -#ifdef _7Z_VOL +#ifdef Z7_7Z_VOL Byte kFinishSignature[kSignatureSize] = {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C + 1}; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zHeader.h 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zHeader.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zHeader.h 2020-07-04 10:05:04.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zHeader.h 2023-03-29 09:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // 7z/7zHeader.h -#ifndef __7Z_HEADER_H -#define __7Z_HEADER_H +#ifndef ZIP7_INC_7Z_HEADER_H +#define ZIP7_INC_7Z_HEADER_H #include "../../../Common/MyTypes.h" @@ -11,13 +11,13 @@ const unsigned kSignatureSize = 6; extern Byte kSignature[kSignatureSize]; -// #define _7Z_VOL +// #define Z7_7Z_VOL // 7z-MultiVolume is not finished yet. // It can work already, but I still do not like some // things of that new multivolume format. // So please keep it commented. -#ifdef _7Z_VOL +#ifdef Z7_7Z_VOL extern Byte kFinishSignature[kSignatureSize]; #endif @@ -38,7 +38,7 @@ const UInt32 kStartHeaderSize = 20; -#ifdef _7Z_VOL +#ifdef Z7_7Z_VOL struct CFinishHeader: public CStartHeader { UInt64 ArchiveStartOffset; // data offset from end if that struct @@ -99,6 +99,7 @@ const UInt32 k_Copy = 0; const UInt32 k_Delta = 3; +const UInt32 k_ARM64 = 0xa; const UInt32 k_LZMA2 = 0x21; @@ -122,14 +123,17 @@ const UInt32 k_AES = 0x6F10701; +// const UInt32 k_ZSTD = 0x4015D; // winzip zstd +// 0x4F71101, 7z-zstd static inline bool IsFilterMethod(UInt64 m) { - if (m > (UInt64)0xFFFFFFFF) + if (m > (UInt32)0xFFFFFFFF) return false; switch ((UInt32)m) { case k_Delta: + case k_ARM64: case k_BCJ: case k_BCJ2: case k_PPC: diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zIn.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zIn.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zIn.cpp 2021-04-14 10:28:29.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zIn.cpp 2023-04-08 08:00:00.000000000 +0000 @@ -11,6 +11,7 @@ #include "../../../../C/7zCrc.h" #include "../../../../C/CpuArch.h" +#include "../../../Common/MyBuffer2.h" // #include "../../../Common/UTFConvert.h" #include "../../Common/StreamObjects.h" @@ -24,7 +25,7 @@ #define Get64(p) GetUi64(p) // define FORMAT_7Z_RECOVERY if you want to recover multivolume archives with empty StartHeader -#ifndef _SFX +#ifndef Z7_SFX #define FORMAT_7Z_RECOVERY #endif @@ -34,6 +35,9 @@ namespace NArchive { namespace N7z { +#define k_Scan_NumCoders_MAX 64 +#define k_Scan_NumCodersStreams_in_Folder_MAX 64 + unsigned BoolVector_CountSum(const CBoolVector &v); unsigned BoolVector_CountSum(const CBoolVector &v) { @@ -62,13 +66,13 @@ class CInArchiveException {}; class CUnsupportedFeatureException: public CInArchiveException {}; -MY_ATTR_NORETURN +Z7_ATTR_NORETURN static void ThrowException() { throw CInArchiveException(); } -MY_ATTR_NORETURN +Z7_ATTR_NORETURN static inline void ThrowEndOfData() { ThrowException(); } -MY_ATTR_NORETURN +Z7_ATTR_NORETURN static inline void ThrowUnsupported() { throw CUnsupportedFeatureException(); } -MY_ATTR_NORETURN +Z7_ATTR_NORETURN static inline void ThrowIncorrect() { ThrowException(); } class CStreamSwitch @@ -113,12 +117,12 @@ void CStreamSwitch::Set(CInArchive *archive, const CObjectVector *dataVector) { Remove(); - Byte external = archive->ReadByte(); + const Byte external = archive->ReadByte(); if (external != 0) { if (!dataVector) ThrowIncorrect(); - CNum dataIndex = archive->ReadNum(); + const CNum dataIndex = archive->ReadNum(); if (dataIndex >= dataVector->Size()) ThrowIncorrect(); Set(archive, (*dataVector)[dataIndex]); @@ -171,7 +175,7 @@ return 0; } - unsigned b = *p++; + const unsigned b = *p++; size--; if ((b & 0x80) == 0) @@ -192,10 +196,10 @@ for (unsigned i = 1; i < 8; i++) { - unsigned mask = (unsigned)0x80 >> i; + const unsigned mask = (unsigned)0x80 >> i; if ((b & mask) == 0) { - UInt64 high = b & (mask - 1); + const UInt64 high = b & (mask - 1); value |= (high << (i * 8)); processed = i + 1; return value; @@ -219,7 +223,7 @@ UInt64 CInByte2::ReadNumber() { size_t processed; - UInt64 res = ReadNumberSpec(_buffer + _pos, _size - _pos, processed); + const UInt64 res = ReadNumberSpec(_buffer + _pos, _size - _pos, processed); if (processed == 0) ThrowEndOfData(); _pos += processed; @@ -239,7 +243,7 @@ } } */ - UInt64 value = ReadNumber(); + const UInt64 value = ReadNumber(); if (value > kNumMax) ThrowUnsupported(); return (CNum)value; @@ -249,7 +253,7 @@ { if (_pos + 4 > _size) ThrowEndOfData(); - UInt32 res = Get32(_buffer + _pos); + const UInt32 res = Get32(_buffer + _pos); _pos += 4; return res; } @@ -258,54 +262,101 @@ { if (_pos + 8 > _size) ThrowEndOfData(); - UInt64 res = Get64(_buffer + _pos); + const UInt64 res = Get64(_buffer + _pos); _pos += 8; return res; } -#define CHECK_SIGNATURE if (p[0] != '7' || p[1] != 'z' || p[2] != 0xBC || p[3] != 0xAF || p[4] != 0x27 || p[5] != 0x1C) return false; +#define Y0 '7' +#define Y1 'z' +#define Y2 0xBC +#define Y3 0xAF +#define Y4 0x27 +#define Y5 0x1C + +#define IS_SIGNATURE(p)( \ + (p)[2] == Y2 && \ + (p)[3] == Y3 && \ + (p)[5] == Y5 && \ + (p)[4] == Y4 && \ + (p)[1] == Y1 && \ + (p)[0] == Y0) + +/* FindSignature_10() is allowed to access data up to and including &limit[9]. + limit[10] access is not allowed. + return: + (return_ptr < limit) : signature was found at (return_ptr) + (return_ptr >= limit) : limit was reached or crossed. So no signature found before limit +*/ +Z7_NO_INLINE +static const Byte *FindSignature_10(const Byte *p, const Byte *limit) +{ + for (;;) + { + for (;;) + { + if (p >= limit) + return limit; + const Byte b = p[5]; + p += 6; + if (b == Y0) { break; } + if (b == Y1) { p -= 1; break; } + if (b == Y2) { p -= 2; break; } + if (b == Y3) { p -= 3; break; } + if (b == Y4) { p -= 4; break; } + if (b == Y5) { p -= 5; break; } + } + if (IS_SIGNATURE(p - 1)) + return p - 1; + } +} -static inline bool TestSignature(const Byte *p) + +static inline bool TestStartCrc(const Byte *p) { - CHECK_SIGNATURE return CrcCalc(p + 12, 20) == Get32(p + 8); } -#ifdef FORMAT_7Z_RECOVERY static inline bool TestSignature2(const Byte *p) { - CHECK_SIGNATURE; - if (CrcCalc(p + 12, 20) == Get32(p + 8)) + if (!IS_SIGNATURE(p)) + return false; + #ifdef FORMAT_7Z_RECOVERY + if (TestStartCrc(p)) return true; for (unsigned i = 8; i < kHeaderSize; i++) if (p[i] != 0) return false; return (p[6] != 0 || p[7] != 0); + #else + return TestStartCrc(p); + #endif } -#else -#define TestSignature2(p) TestSignature(p) -#endif + HRESULT CInArchive::FindAndReadSignature(IInStream *stream, const UInt64 *searchHeaderSizeLimit) { - RINOK(ReadStream_FALSE(stream, _header, kHeaderSize)); + RINOK(ReadStream_FALSE(stream, _header, kHeaderSize)) if (TestSignature2(_header)) return S_OK; if (searchHeaderSizeLimit && *searchHeaderSizeLimit == 0) return S_FALSE; - const UInt32 kBufSize = 1 << 15; - CByteArr buf(kBufSize); + const UInt32 kBufSize = (1 << 15) + kHeaderSize; // must be > (kHeaderSize * 2) + CAlignedBuffer1 buf(kBufSize); memcpy(buf, _header, kHeaderSize); UInt64 offset = 0; for (;;) { - UInt32 readSize = kBufSize - kHeaderSize; + UInt32 readSize = + (offset == 0) ? + kBufSize - kHeaderSize - kHeaderSize : + kBufSize - kHeaderSize; if (searchHeaderSizeLimit) { - UInt64 rem = *searchHeaderSizeLimit - offset; + const UInt64 rem = *searchHeaderSizeLimit - offset; if (readSize > rem) readSize = (UInt32)rem; if (readSize == 0) @@ -313,29 +364,28 @@ } UInt32 processed = 0; - RINOK(stream->Read(buf + kHeaderSize, readSize, &processed)); + RINOK(stream->Read(buf + kHeaderSize, readSize, &processed)) if (processed == 0) return S_FALSE; + + /* &buf[0] was already tested for signature before. + So first search here will be for &buf[1] */ for (UInt32 pos = 0;;) { const Byte *p = buf + pos + 1; - const Byte *lim = buf + processed; - for (; p <= lim; p += 4) - { - if (p[0] == '7') break; - if (p[1] == '7') { p += 1; break; } - if (p[2] == '7') { p += 2; break; } - if (p[3] == '7') { p += 3; break; } - }; - if (p > lim) + const Byte *lim = buf + processed + 1; + /* we have (kHeaderSize - 1 = 31) filled bytes starting from (lim), + and it's safe to access just 10 bytes in that reserved area */ + p = FindSignature_10(p, lim); + if (p >= lim) break; pos = (UInt32)(p - buf); - if (TestSignature(p)) + if (TestStartCrc(p)) { memcpy(_header, p, kHeaderSize); _arhiveBeginStreamPosition += offset + pos; - return stream->Seek((Int64)(_arhiveBeginStreamPosition + kHeaderSize), STREAM_SEEK_SET, NULL); + return InStream_SeekSet(stream, _arhiveBeginStreamPosition + kHeaderSize); } } @@ -349,10 +399,8 @@ { HeadersSize = 0; Close(); - RINOK(stream->Seek(0, STREAM_SEEK_CUR, &_arhiveBeginStreamPosition)) - RINOK(stream->Seek(0, STREAM_SEEK_END, &_fileEndPosition)) - RINOK(stream->Seek((Int64)_arhiveBeginStreamPosition, STREAM_SEEK_SET, NULL)) - RINOK(FindAndReadSignature(stream, searchHeaderSizeLimit)); + RINOK(InStream_GetPos_GetSize(stream, _arhiveBeginStreamPosition, _fileEndPosition)) + RINOK(FindAndReadSignature(stream, searchHeaderSizeLimit)) _stream = stream; return S_OK; } @@ -378,9 +426,9 @@ void CInByte2::ParseFolder(CFolder &folder) { - UInt32 numCoders = ReadNum(); + const UInt32 numCoders = ReadNum(); - if (numCoders == 0) + if (numCoders == 0 || numCoders > k_Scan_NumCoders_MAX) ThrowUnsupported(); folder.Coders.SetSize(numCoders); @@ -391,10 +439,10 @@ { CCoderInfo &coder = folder.Coders[i]; { - Byte mainByte = ReadByte(); + const Byte mainByte = ReadByte(); if ((mainByte & 0xC0) != 0) ThrowUnsupported(); - unsigned idSize = (mainByte & 0xF); + const unsigned idSize = (mainByte & 0xF); if (idSize > 8 || idSize > GetRem()) ThrowUnsupported(); const Byte *longID = GetPtr(); @@ -407,7 +455,9 @@ if ((mainByte & 0x10) != 0) { coder.NumStreams = ReadNum(); + // if (coder.NumStreams > k_Scan_NumCodersStreams_in_Folder_MAX) ThrowUnsupported(); /* numOutStreams = */ ReadNum(); + // if (ReadNum() != 1) // numOutStreams ThrowUnsupported(); } else { @@ -416,7 +466,7 @@ if ((mainByte & 0x20) != 0) { - CNum propsSize = ReadNum(); + const CNum propsSize = ReadNum(); coder.Props.Alloc((size_t)propsSize); ReadBytes((Byte *)coder.Props, (size_t)propsSize); } @@ -426,7 +476,7 @@ numInStreams += coder.NumStreams; } - UInt32 numBonds = numCoders - 1; + const UInt32 numBonds = numCoders - 1; folder.Bonds.SetSize(numBonds); for (i = 0; i < numBonds; i++) { @@ -437,7 +487,7 @@ if (numInStreams < numBonds) ThrowUnsupported(); - UInt32 numPackStreams = numInStreams - numBonds; + const UInt32 numPackStreams = numInStreams - numBonds; folder.PackStreams.SetSize(numPackStreams); if (numPackStreams == 1) @@ -458,7 +508,7 @@ void CFolders::ParseFolderInfo(unsigned folderIndex, CFolder &folder) const { - size_t startPos = FoCodersDataOffset[folderIndex]; + const size_t startPos = FoCodersDataOffset[folderIndex]; CInByte2 inByte; inByte.Init(CodersData + startPos, FoCodersDataOffset[folderIndex + 1] - startPos); inByte.ParseFolder(folder); @@ -473,8 +523,8 @@ if (!NameOffsets || !NamesBuf) return; - size_t offset = NameOffsets[index]; - size_t size = NameOffsets[index + 1] - offset; + const size_t offset = NameOffsets[index]; + const size_t size = NameOffsets[index + 1] - offset; if (size >= (1 << 28)) return; @@ -507,8 +557,8 @@ if (!NameOffsets || !NamesBuf) return S_OK; - size_t offset = NameOffsets[index]; - size_t size = NameOffsets[index + 1] - offset; + const size_t offset = NameOffsets[index]; + const size_t size = NameOffsets[index + 1] - offset; if (size >= (1 << 14)) return S_OK; @@ -530,7 +580,7 @@ #else */ - RINOK(PropVarEm_Alloc_Bstr(path, (unsigned)size - 1)); + RINOK(PropVarEm_Alloc_Bstr(path, (unsigned)size - 1)) wchar_t *s = path->bstrVal; const Byte *p = ((const Byte *)NamesBuf + offset * 2); // Utf16LE__To_WCHARs_Sep(p, size, s); @@ -601,7 +651,7 @@ { for (;;) { - UInt64 type = ReadID(); + const UInt64 type = ReadID(); if (type == id) return; if (type == NID::kEnd) @@ -613,7 +663,7 @@ void CInArchive::Read_UInt32_Vector(CUInt32DefVector &v) { - unsigned numItems = v.Defs.Size(); + const unsigned numItems = v.Defs.Size(); v.Vals.ClearAndSetSize(numItems); UInt32 *p = &v.Vals[0]; const bool *defs = &v.Defs[0]; @@ -634,12 +684,9 @@ } -#define k_Scan_NumCoders_MAX 64 -#define k_Scan_NumCodersStreams_in_Folder_MAX 64 - void CInArchive::ReadPackInfo(CFolders &f) { - CNum numPackStreams = ReadNum(); + const CNum numPackStreams = ReadNum(); WaitId(NID::kSize); f.PackPositions.Alloc(numPackStreams + 1); @@ -648,7 +695,7 @@ for (CNum i = 0; i < numPackStreams; i++) { f.PackPositions[i] = sum; - UInt64 packSize = ReadNumber(); + const UInt64 packSize = ReadNumber(); sum += packSize; if (sum < packSize) ThrowIncorrect(); @@ -676,7 +723,7 @@ CFolders &folders) { WaitId(NID::kFolder); - CNum numFolders = ReadNum(); + const CNum numFolders = ReadNum(); CNum numCodersOutStreams = 0; { @@ -704,18 +751,18 @@ folders.FoCodersDataOffset[fo] = (size_t)(_inByteBack->GetPtr() - startBufPtr); CNum numInStreams = 0; - CNum numCoders = inByte->ReadNum(); + const CNum numCoders = inByte->ReadNum(); if (numCoders == 0 || numCoders > k_Scan_NumCoders_MAX) ThrowUnsupported(); for (CNum ci = 0; ci < numCoders; ci++) { - Byte mainByte = inByte->ReadByte(); + const Byte mainByte = inByte->ReadByte(); if ((mainByte & 0xC0) != 0) ThrowUnsupported(); - unsigned idSize = (mainByte & 0xF); + const unsigned idSize = (mainByte & 0xF); if (idSize > 8) ThrowUnsupported(); if (idSize > inByte->GetRem()) @@ -744,18 +791,18 @@ if ((mainByte & 0x20) != 0) { - CNum propsSize = inByte->ReadNum(); + const CNum propsSize = inByte->ReadNum(); if (propsSize > inByte->GetRem()) ThrowEndOfData(); if (id == k_LZMA2 && propsSize == 1) { - Byte v = *_inByteBack->GetPtr(); + const Byte v = *_inByteBack->GetPtr(); if (folders.ParsedMethods.Lzma2Prop < v) folders.ParsedMethods.Lzma2Prop = v; } else if (id == k_LZMA && propsSize == 5) { - UInt32 dicSize = GetUi32(_inByteBack->GetPtr() + 1); + const UInt32 dicSize = GetUi32(_inByteBack->GetPtr() + 1); if (folders.ParsedMethods.LzmaDic < dicSize) folders.ParsedMethods.LzmaDic = dicSize; } @@ -771,7 +818,7 @@ else { UInt32 i; - CNum numBonds = numCoders - 1; + const CNum numBonds = numCoders - 1; if (numInStreams < numBonds) ThrowUnsupported(); @@ -796,7 +843,7 @@ if (numPackStreams != 1) for (i = 0; i < numPackStreams; i++) { - CNum index = inByte->ReadNum(); // PackStreams + const CNum index = inByte->ReadNum(); // PackStreams if (index >= numInStreams || StreamUsed[index]) ThrowUnsupported(); StreamUsed[index] = true; @@ -838,7 +885,7 @@ for (;;) { - UInt64 type = ReadID(); + const UInt64 type = ReadID(); if (type == NID::kEnd) return; if (type == NID::kCRC) @@ -882,19 +929,19 @@ { // v3.13 incorrectly worked with empty folders // v4.07: we check that folder is empty - CNum numSubstreams = folders.NumUnpackStreamsVector[i]; + const CNum numSubstreams = folders.NumUnpackStreamsVector[i]; if (numSubstreams == 0) continue; UInt64 sum = 0; for (CNum j = 1; j < numSubstreams; j++) { - UInt64 size = ReadNumber(); + const UInt64 size = ReadNumber(); unpackSizes.Add(size); sum += size; if (sum < size) ThrowIncorrect(); } - UInt64 folderUnpackSize = folders.GetFolderUnpackSize(i); + const UInt64 folderUnpackSize = folders.GetFolderUnpackSize(i); if (folderUnpackSize < sum) ThrowIncorrect(); unpackSizes.Add(folderUnpackSize - sum); @@ -907,7 +954,7 @@ { /* v9.26 - v9.29 incorrectly worked: if (folders.NumUnpackStreamsVector[i] == 0), it threw error */ - CNum val = folders.NumUnpackStreamsVector[i]; + const CNum val = folders.NumUnpackStreamsVector[i]; if (val > 1) ThrowIncorrect(); if (val == 1) @@ -918,7 +965,7 @@ unsigned numDigests = 0; for (i = 0; i < folders.NumFolders; i++) { - CNum numSubstreams = folders.NumUnpackStreamsVector[i]; + const CNum numSubstreams = folders.NumUnpackStreamsVector[i]; if (numSubstreams != 1 || !folders.FolderCRCs.ValidAndDefined(i)) numDigests += numSubstreams; } @@ -941,7 +988,7 @@ for (i = 0; i < folders.NumFolders; i++) { - CNum numSubstreams = folders.NumUnpackStreamsVector[i]; + const CNum numSubstreams = folders.NumUnpackStreamsVector[i]; if (numSubstreams == 1 && folders.FolderCRCs.ValidAndDefined(i)) { digests.Defs[k] = true; @@ -973,7 +1020,7 @@ unsigned k = 0; for (i = 0; i < folders.NumFolders; i++) { - CNum numSubstreams = folders.NumUnpackStreamsVector[i]; + const CNum numSubstreams = folders.NumUnpackStreamsVector[i]; if (numSubstreams == 1 && folders.FolderCRCs.ValidAndDefined(i)) { digests.Defs[k] = true; @@ -1069,7 +1116,7 @@ void CInArchive::ReadBoolVector2(unsigned numItems, CBoolVector &v) { - Byte allAreDefined = ReadByte(); + const Byte allAreDefined = ReadByte(); if (allAreDefined == 0) { ReadBoolVector(numItems, v); @@ -1106,7 +1153,7 @@ DECL_EXTERNAL_CODECS_LOC_VARS UInt64 baseOffset, UInt64 &dataOffset, CObjectVector &dataVector - _7Z_DECODER_CRYPRO_VARS_DECL + Z7_7Z_DECODER_CRYPRO_VARS_DECL ) { CFolders folders; @@ -1148,15 +1195,15 @@ NULL // **inStreamMainRes , dataAfterEnd_Error - _7Z_DECODER_CRYPRO_VARS - #if !defined(_7ZIP_ST) + Z7_7Z_DECODER_CRYPRO_VARS + #if !defined(Z7_ST) , false // mtMode , 1 // numThreads , 0 // memUsage #endif ); - RINOK(result); + RINOK(result) if (dataAfterEnd_Error) ThereIsHeaderError = true; @@ -1178,7 +1225,7 @@ HRESULT CInArchive::ReadHeader( DECL_EXTERNAL_CODECS_LOC_VARS CDbEx &db - _7Z_DECODER_CRYPRO_VARS_DECL + Z7_7Z_DECODER_CRYPRO_VARS_DECL ) { UInt64 type = ReadID(); @@ -1193,14 +1240,14 @@ if (type == NID::kAdditionalStreamsInfo) { - HRESULT result = ReadAndDecodePackedStreams( + const HRESULT result = ReadAndDecodePackedStreams( EXTERNAL_CODECS_LOC_VARS db.ArcInfo.StartPositionAfterHeader, db.ArcInfo.DataStartPosition2, dataVector - _7Z_DECODER_CRYPRO_VARS + Z7_7Z_DECODER_CRYPRO_VARS ); - RINOK(result); + RINOK(result) db.ArcInfo.DataStartPosition2 += db.ArcInfo.StartPositionAfterHeader; type = ReadID(); } @@ -1240,7 +1287,7 @@ const UInt64 type2 = ReadID(); if (type2 == NID::kEnd) break; - UInt64 size = ReadNumber(); + const UInt64 size = ReadNumber(); if (size > _inByteBack->GetRem()) ThrowIncorrect(); CStreamSwitch switchProp; @@ -1255,7 +1302,7 @@ { CStreamSwitch streamSwitch; streamSwitch.Set(this, &dataVector); - size_t rem = _inByteBack->GetRem(); + const size_t rem = _inByteBack->GetRem(); db.NamesBuf.Alloc(rem); ReadBytes(db.NamesBuf, rem); db.NameOffsets.Alloc(numFiles + 1); @@ -1471,7 +1518,7 @@ for (i = 0; i < Files.Size(); i++) { - bool emptyStream = !Files[i].HasStream; + const bool emptyStream = !Files[i].HasStream; if (indexInFolder == 0) { if (emptyStream) @@ -1528,7 +1575,7 @@ HRESULT CInArchive::ReadDatabase2( DECL_EXTERNAL_CODECS_LOC_VARS CDbEx &db - _7Z_DECODER_CRYPRO_VARS_DECL + Z7_7Z_DECODER_CRYPRO_VARS_DECL ) { db.Clear(); @@ -1548,22 +1595,22 @@ UInt32 nextHeaderCRC = Get32(_header + 28); #ifdef FORMAT_7Z_RECOVERY - UInt32 crcFromArc = Get32(_header + 8); + const UInt32 crcFromArc = Get32(_header + 8); if (crcFromArc == 0 && nextHeaderOffset == 0 && nextHeaderSize == 0 && nextHeaderCRC == 0) { UInt64 cur, fileSize; - RINOK(_stream->Seek(0, STREAM_SEEK_CUR, &cur)); + RINOK(InStream_GetPos(_stream, cur)) const unsigned kCheckSize = 512; Byte buf[kCheckSize]; - RINOK(_stream->Seek(0, STREAM_SEEK_END, &fileSize)); + RINOK(InStream_GetSize_SeekToEnd(_stream, fileSize)) const UInt64 rem = fileSize - cur; unsigned checkSize = kCheckSize; if (rem < kCheckSize) checkSize = (unsigned)(rem); if (checkSize < 3) return S_FALSE; - RINOK(_stream->Seek((Int64)(fileSize - checkSize), STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(_stream, buf, (size_t)checkSize)); + RINOK(InStream_SeekSet(_stream, fileSize - checkSize)) + RINOK(ReadStream_FALSE(_stream, buf, (size_t)checkSize)) if (buf[checkSize - 1] != 0) return S_FALSE; @@ -1580,7 +1627,7 @@ nextHeaderSize = checkSize - i; nextHeaderOffset = rem - nextHeaderSize; nextHeaderCRC = CrcCalc(buf + i, (size_t)nextHeaderSize); - RINOK(_stream->Seek((Int64)cur, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_stream, cur)) db.StartHeaderWasRecovered = true; } else @@ -1622,14 +1669,14 @@ db.UnexpectedEnd = true; return S_FALSE; } - RINOK(_stream->Seek((Int64)nextHeaderOffset, STREAM_SEEK_CUR, NULL)); + RINOK(_stream->Seek((Int64)nextHeaderOffset, STREAM_SEEK_CUR, NULL)) - size_t nextHeaderSize_t = (size_t)nextHeaderSize; + const size_t nextHeaderSize_t = (size_t)nextHeaderSize; if (nextHeaderSize_t != nextHeaderSize) return E_OUTOFMEMORY; CByteBuffer buffer2(nextHeaderSize_t); - RINOK(ReadStream_FALSE(_stream, buffer2, nextHeaderSize_t)); + RINOK(ReadStream_FALSE(_stream, buffer2, nextHeaderSize_t)) if (CrcCalc(buffer2, nextHeaderSize_t) != nextHeaderCRC) ThrowIncorrect(); @@ -1642,19 +1689,19 @@ CObjectVector dataVector; - UInt64 type = ReadID(); + const UInt64 type = ReadID(); if (type != NID::kHeader) { if (type != NID::kEncodedHeader) ThrowIncorrect(); - HRESULT result = ReadAndDecodePackedStreams( + const HRESULT result = ReadAndDecodePackedStreams( EXTERNAL_CODECS_LOC_VARS db.ArcInfo.StartPositionAfterHeader, db.ArcInfo.DataStartPosition2, dataVector - _7Z_DECODER_CRYPRO_VARS + Z7_7Z_DECODER_CRYPRO_VARS ); - RINOK(result); + RINOK(result) if (dataVector.Size() == 0) return S_OK; if (dataVector.Size() > 1) @@ -1672,7 +1719,7 @@ return ReadHeader( EXTERNAL_CODECS_LOC_VARS db - _7Z_DECODER_CRYPRO_VARS + Z7_7Z_DECODER_CRYPRO_VARS ); } @@ -1680,14 +1727,14 @@ HRESULT CInArchive::ReadDatabase( DECL_EXTERNAL_CODECS_LOC_VARS CDbEx &db - _7Z_DECODER_CRYPRO_VARS_DECL + Z7_7Z_DECODER_CRYPRO_VARS_DECL ) { try { - HRESULT res = ReadDatabase2( + const HRESULT res = ReadDatabase2( EXTERNAL_CODECS_LOC_VARS db - _7Z_DECODER_CRYPRO_VARS + Z7_7Z_DECODER_CRYPRO_VARS ); if (ThereIsHeaderError) db.ThereIsHeaderError = true; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zIn.h 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zIn.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zIn.h 2019-07-01 11:38:24.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zIn.h 2023-03-04 09:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // 7zIn.h -#ifndef __7Z_IN_H -#define __7Z_IN_H +#ifndef ZIP7_INC_7Z_IN_H +#define ZIP7_INC_7Z_IN_H #include "../../../Common/MyCom.h" @@ -22,12 +22,12 @@ We don't need to init isEncrypted and passwordIsDefined We must upgrade them only */ -#ifdef _NO_CRYPTO -#define _7Z_DECODER_CRYPRO_VARS_DECL -#define _7Z_DECODER_CRYPRO_VARS +#ifdef Z7_NO_CRYPTO +#define Z7_7Z_DECODER_CRYPRO_VARS_DECL +#define Z7_7Z_DECODER_CRYPRO_VARS #else -#define _7Z_DECODER_CRYPRO_VARS_DECL , ICryptoGetTextPassword *getTextPassword, bool &isEncrypted, bool &passwordIsDefined, UString &password -#define _7Z_DECODER_CRYPRO_VARS , getTextPassword, isEncrypted, passwordIsDefined, password +#define Z7_7Z_DECODER_CRYPRO_VARS_DECL , ICryptoGetTextPassword *getTextPassword, bool &isEncrypted, bool &passwordIsDefined, UString &password +#define Z7_7Z_DECODER_CRYPRO_VARS , getTextPassword, isEncrypted, passwordIsDefined, password #endif struct CParsedMethods @@ -418,17 +418,17 @@ DECL_EXTERNAL_CODECS_LOC_VARS UInt64 baseOffset, UInt64 &dataOffset, CObjectVector &dataVector - _7Z_DECODER_CRYPRO_VARS_DECL + Z7_7Z_DECODER_CRYPRO_VARS_DECL ); HRESULT ReadHeader( DECL_EXTERNAL_CODECS_LOC_VARS CDbEx &db - _7Z_DECODER_CRYPRO_VARS_DECL + Z7_7Z_DECODER_CRYPRO_VARS_DECL ); HRESULT ReadDatabase2( DECL_EXTERNAL_CODECS_LOC_VARS CDbEx &db - _7Z_DECODER_CRYPRO_VARS_DECL + Z7_7Z_DECODER_CRYPRO_VARS_DECL ); public: CInArchive(bool useMixerMT): @@ -442,7 +442,7 @@ HRESULT ReadDatabase( DECL_EXTERNAL_CODECS_LOC_VARS CDbEx &db - _7Z_DECODER_CRYPRO_VARS_DECL + Z7_7Z_DECODER_CRYPRO_VARS_DECL ); }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zItem.h 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zItem.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zItem.h 2021-01-25 09:26:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zItem.h 2023-05-09 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // 7zItem.h -#ifndef __7Z_ITEM_H -#define __7Z_ITEM_H +#ifndef ZIP7_INC_7Z_ITEM_H +#define ZIP7_INC_7Z_ITEM_H #include "../../../Common/MyBuffer.h" #include "../../../Common/MyString.h" @@ -36,7 +36,7 @@ struct CFolder { - CLASS_NO_COPY(CFolder) + Z7_CLASS_NO_COPY(CFolder) public: CObjArray2 Coders; CObjArray2 Bonds; @@ -129,6 +129,11 @@ bool CheckSize(unsigned size) const { return Defs.Size() == size || Defs.Size() == 0; } void SetItem(unsigned index, bool defined, UInt32 value); + void if_NonEmpty_FillResedue_with_false(unsigned numItems) + { + if (Defs.Size() != 0 && Defs.Size() < numItems) + SetItem(numItems - 1, false, 0); + } }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zOut.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zOut.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zOut.cpp 2021-04-02 16:46:07.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zOut.cpp 2023-03-29 17:00:00.000000000 +0000 @@ -14,16 +14,14 @@ namespace NArchive { namespace N7z { -HRESULT COutArchive::WriteSignature() +static void FillSignature(Byte *buf) { - Byte buf[8]; memcpy(buf, kSignature, kSignatureSize); buf[kSignatureSize] = kMajorVersion; buf[kSignatureSize + 1] = 4; - return WriteDirect(buf, 8); } -#ifdef _7Z_VOL +#ifdef Z7_7Z_VOL HRESULT COutArchive::WriteFinishSignature() { RINOK(WriteDirect(kFinishSignature, kSignatureSize)); @@ -49,15 +47,16 @@ HRESULT COutArchive::WriteStartHeader(const CStartHeader &h) { - Byte buf[24]; - SetUInt64(buf + 4, h.NextHeaderOffset); - SetUInt64(buf + 12, h.NextHeaderSize); - SetUInt32(buf + 20, h.NextHeaderCRC); - SetUInt32(buf, CrcCalc(buf + 4, 20)); - return WriteDirect(buf, 24); + Byte buf[32]; + FillSignature(buf); + SetUInt64(buf + 8 + 4, h.NextHeaderOffset); + SetUInt64(buf + 8 + 12, h.NextHeaderSize); + SetUInt32(buf + 8 + 20, h.NextHeaderCRC); + SetUInt32(buf + 8, CrcCalc(buf + 8 + 4, 20)); + return WriteDirect(buf, sizeof(buf)); } -#ifdef _7Z_VOL +#ifdef Z7_7Z_VOL HRESULT COutArchive::WriteFinishHeader(const CFinishHeader &h) { CCRC crc; @@ -75,15 +74,15 @@ } #endif -HRESULT COutArchive::Create(ISequentialOutStream *stream, bool endMarker) +HRESULT COutArchive::Create_and_WriteStartPrefix(ISequentialOutStream *stream /* , bool endMarker */) { Close(); - #ifdef _7Z_VOL + #ifdef Z7_7Z_VOL // endMarker = false; _endMarker = endMarker; #endif SeqStream = stream; - if (!endMarker) + // if (!endMarker) { SeqStream.QueryInterface(IID_IOutStream, &Stream); if (!Stream) @@ -91,8 +90,13 @@ return E_NOTIMPL; // endMarker = true; } + RINOK(Stream->Seek(0, STREAM_SEEK_CUR, &_signatureHeaderPos)) + Byte buf[32]; + FillSignature(buf); + memset(&buf[8], 0, 32 - 8); + return WriteDirect(buf, sizeof(buf)); } - #ifdef _7Z_VOL + #ifdef Z7_7Z_VOL if (endMarker) { /* @@ -101,17 +105,10 @@ sh.NextHeaderSize = (UInt32)(Int32)-1; sh.NextHeaderCRC = 0; WriteStartHeader(sh); + return S_OK; */ } - else #endif - { - if (!Stream) - return E_FAIL; - RINOK(WriteSignature()); - RINOK(Stream->Seek(0, STREAM_SEEK_CUR, &_prefixHeaderPos)); - } - return S_OK; } void COutArchive::Close() @@ -120,17 +117,6 @@ Stream.Release(); } -HRESULT COutArchive::SkipPrefixArchiveHeader() -{ - #ifdef _7Z_VOL - if (_endMarker) - return S_OK; - #endif - Byte buf[24]; - memset(buf, 0, 24); - return WriteDirect(buf, 24); -} - UInt64 COutArchive::GetPos() const { if (_countMode) @@ -216,7 +202,7 @@ return i; } -#ifdef _7Z_VOL +#ifdef Z7_7Z_VOL UInt32 COutArchive::GetVolHeadersSize(UInt64 dataSize, int nameLength, bool props) { UInt32 result = GetBigNumberSize(dataSize) * 2 + 41; @@ -515,14 +501,20 @@ outFolders.FolderUnpackCRCs.Defs.Add(true); outFolders.FolderUnpackCRCs.Vals.Add(CrcCalc(data, data.Size())); // outFolders.NumUnpackStreamsVector.Add(1); - UInt64 dataSize64 = data.Size(); - UInt64 unpackSize = data.Size(); - RINOK(encoder.Encode( + const UInt64 dataSize64 = data.Size(); + const UInt64 expectSize = data.Size(); + RINOK(encoder.Encode1( EXTERNAL_CODECS_LOC_VARS stream, // NULL, - &dataSize64, - folders.AddNew(), outFolders.CoderUnpackSizes, unpackSize, SeqStream, packSizes, NULL)) + &dataSize64, // inSizeForReduce + expectSize, + folders.AddNew(), + // outFolders.CoderUnpackSizes, unpackSize, + SeqStream, packSizes, NULL)) + if (!streamSpec->WasFinished()) + return E_FAIL; + encoder.Encode_Post(dataSize64, outFolders.CoderUnpackSizes); return S_OK; } @@ -833,15 +825,15 @@ { headerSize = 0; headerOffset = 0; - headerCRC = CrcCalc(0, 0); + headerCRC = CrcCalc(NULL, 0); } else { bool encodeHeaders = false; - if (options != 0) + if (options) if (options->IsEmpty()) - options = 0; - if (options != 0) + options = NULL; + if (options) if (options->PasswordIsDefined || headerOptions.CompressMainHeader) encodeHeaders = true; @@ -876,7 +868,7 @@ RINOK(EncodeStream( EXTERNAL_CODECS_LOC_VARS encoder, buf, - packSizes, folders, outFolders)); + packSizes, folders, outFolders)) _writeToStream = true; @@ -890,11 +882,11 @@ FOR_VECTOR (i, packSizes) headerOffset += packSizes[i]; } - RINOK(_outByte.Flush()); + RINOK(_outByte.Flush()) headerCRC = CRC_GET_DIGEST(_crc); headerSize = _outByte.GetProcessedSize(); } - #ifdef _7Z_VOL + #ifdef Z7_7Z_VOL if (_endMarker) { CFinishHeader h; @@ -910,14 +902,16 @@ } else #endif + if (Stream) { CStartHeader h; h.NextHeaderSize = headerSize; h.NextHeaderCRC = headerCRC; h.NextHeaderOffset = headerOffset; - RINOK(Stream->Seek((Int64)_prefixHeaderPos, STREAM_SEEK_SET, NULL)); + RINOK(Stream->Seek((Int64)_signatureHeaderPos, STREAM_SEEK_SET, NULL)) return WriteStartHeader(h); } + return S_OK; } void CUInt32DefVector::SetItem(unsigned index, bool defined, UInt32 value) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zOut.h 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zOut.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zOut.h 2016-12-18 09:41:49.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zOut.h 2023-03-04 09:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // 7zOut.h -#ifndef __7Z_OUT_H -#define __7Z_OUT_H +#ifndef ZIP7_INC_7Z_OUT_H +#define ZIP7_INC_7Z_OUT_H #include "7zCompressionMode.h" #include "7zEncode.h" @@ -14,6 +14,8 @@ namespace NArchive { namespace N7z { +const unsigned k_StartHeadersRewriteSize = 32; + class CWriteBufferLoc { Byte *_data; @@ -240,8 +242,6 @@ class COutArchive { - UInt64 _prefixHeaderPos; - HRESULT WriteDirect(const void *data, UInt32 size) { return WriteStream(SeqStream, data, size); } UInt64 GetPos() const; @@ -290,44 +290,39 @@ bool _countMode; bool _writeToStream; - size_t _countSize; - UInt32 _crc; - COutBuffer _outByte; - CWriteBufferLoc _outByte2; - - #ifdef _7Z_VOL + bool _useAlign; + #ifdef Z7_7Z_VOL bool _endMarker; #endif + UInt32 _crc; + size_t _countSize; + CWriteBufferLoc _outByte2; + COutBuffer _outByte; + UInt64 _signatureHeaderPos; + CMyComPtr Stream; - bool _useAlign; - - HRESULT WriteSignature(); - #ifdef _7Z_VOL + #ifdef Z7_7Z_VOL HRESULT WriteFinishSignature(); - #endif - HRESULT WriteStartHeader(const CStartHeader &h); - #ifdef _7Z_VOL HRESULT WriteFinishHeader(const CFinishHeader &h); #endif - CMyComPtr Stream; + HRESULT WriteStartHeader(const CStartHeader &h); + public: + CMyComPtr SeqStream; COutArchive() { _outByte.Create(1 << 16); } - CMyComPtr SeqStream; - HRESULT Create(ISequentialOutStream *stream, bool endMarker); + HRESULT Create_and_WriteStartPrefix(ISequentialOutStream *stream /* , bool endMarker */); void Close(); - HRESULT SkipPrefixArchiveHeader(); HRESULT WriteDatabase( DECL_EXTERNAL_CODECS_LOC_VARS const CArchiveDatabaseOut &db, const CCompressionMethodMode *options, const CHeaderOptions &headerOptions); - #ifdef _7Z_VOL + #ifdef Z7_7Z_VOL static UInt32 GetVolHeadersSize(UInt64 dataSize, int nameLength = 0, bool props = false); static UInt64 GetVolPureSize(UInt64 volSize, int nameLength = 0, bool props = false); #endif - }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zProperties.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zProperties.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zProperties.cpp 2015-09-28 13:09:56.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zProperties.cpp 2023-03-29 09:00:00.000000000 +0000 @@ -2,56 +2,63 @@ #include "StdAfx.h" -#include "7zProperties.h" -#include "7zHeader.h" #include "7zHandler.h" - -// #define _MULTI_PACK +#include "7zProperties.h" namespace NArchive { namespace N7z { struct CPropMap { - UInt32 FilePropID; - CStatProp StatProp; + Byte FilePropID; + // CStatProp StatProp; + VARTYPE vt; + UInt32 StatPropID; }; -static const CPropMap kPropMap[] = -{ - { NID::kName, { NULL, kpidPath, VT_BSTR } }, - { NID::kSize, { NULL, kpidSize, VT_UI8 } }, - { NID::kPackInfo, { NULL, kpidPackSize, VT_UI8 } }, - - #ifdef _MULTI_PACK - { 100, { "Pack0", kpidPackedSize0, VT_UI8 } }, - { 101, { "Pack1", kpidPackedSize1, VT_UI8 } }, - { 102, { "Pack2", kpidPackedSize2, VT_UI8 } }, - { 103, { "Pack3", kpidPackedSize3, VT_UI8 } }, - { 104, { "Pack4", kpidPackedSize4, VT_UI8 } }, - #endif +// #define STAT_PROP(name, id, vt) { name, id, vt } +#define STAT_PROP(name, id, vt) vt, id - { NID::kCTime, { NULL, kpidCTime, VT_FILETIME } }, - { NID::kMTime, { NULL, kpidMTime, VT_FILETIME } }, - { NID::kATime, { NULL, kpidATime, VT_FILETIME } }, - { NID::kWinAttrib, { NULL, kpidAttrib, VT_UI4 } }, - { NID::kStartPos, { NULL, kpidPosition, VT_UI8 } }, +#define STAT_PROP2(id, vt) STAT_PROP(NULL, id, vt) - { NID::kCRC, { NULL, kpidCRC, VT_UI4 } }, - -// { NID::kIsAux, { NULL, kpidIsAux, VT_BOOL } }, - { NID::kAnti, { NULL, kpidIsAnti, VT_BOOL } } +#define k_7z_id_Encrypted 97 +#define k_7z_id_Method 98 +#define k_7z_id_Block 99 - #ifndef _SFX - , - { 97, { NULL, kpidEncrypted, VT_BOOL } }, - { 98, { NULL, kpidMethod, VT_BSTR } }, - { 99, { NULL, kpidBlock, VT_UI4 } } +static const CPropMap kPropMap[] = +{ + { NID::kName, STAT_PROP2(kpidPath, VT_BSTR) }, + { NID::kSize, STAT_PROP2(kpidSize, VT_UI8) }, + { NID::kPackInfo, STAT_PROP2(kpidPackSize, VT_UI8) }, + + #ifdef Z7_7Z_SHOW_PACK_STREAMS_SIZES +#define k_7z_id_PackedSize0 100 + { k_7z_id_PackedSize0 + 0, STAT_PROP("Pack0", kpidPackedSize0, VT_UI8) }, + { k_7z_id_PackedSize0 + 1, STAT_PROP("Pack1", kpidPackedSize1, VT_UI8) }, + { k_7z_id_PackedSize0 + 2, STAT_PROP("Pack2", kpidPackedSize2, VT_UI8) }, + { k_7z_id_PackedSize0 + 3, STAT_PROP("Pack3", kpidPackedSize3, VT_UI8) }, + { k_7z_id_PackedSize0 + 4, STAT_PROP("Pack4", kpidPackedSize4, VT_UI8) }, + #endif + + { NID::kCTime, STAT_PROP2(kpidCTime, VT_FILETIME) }, + { NID::kMTime, STAT_PROP2(kpidMTime, VT_FILETIME) }, + { NID::kATime, STAT_PROP2(kpidATime, VT_FILETIME) }, + { NID::kWinAttrib, STAT_PROP2(kpidAttrib, VT_UI4) }, + { NID::kStartPos, STAT_PROP2(kpidPosition, VT_UI8) }, + + { NID::kCRC, STAT_PROP2(kpidCRC, VT_UI4) }, + // { NID::kIsAux, STAT_PROP2(kpidIsAux, VT_BOOL) }, + { NID::kAnti, STAT_PROP2(kpidIsAnti, VT_BOOL) } + + #ifndef Z7_SFX + , { k_7z_id_Encrypted, STAT_PROP2(kpidEncrypted, VT_BOOL) } + , { k_7z_id_Method, STAT_PROP2(kpidMethod, VT_BSTR) } + , { k_7z_id_Block, STAT_PROP2(kpidBlock, VT_UI4) } #endif }; static void CopyOneItem(CRecordVector &src, - CRecordVector &dest, UInt32 item) + CRecordVector &dest, const UInt32 item) { FOR_VECTOR (i, src) if (src[i] == item) @@ -62,7 +69,7 @@ } } -static void RemoveOneItem(CRecordVector &src, UInt32 item) +static void RemoveOneItem(CRecordVector &src, const UInt32 item) { FOR_VECTOR (i, src) if (src[i] == item) @@ -72,7 +79,7 @@ } } -static void InsertToHead(CRecordVector &dest, UInt32 item) +static void InsertToHead(CRecordVector &dest, const UInt32 item) { FOR_VECTOR (i, dest) if (dest[i] == item) @@ -89,7 +96,7 @@ { _fileInfoPopIDs.Clear(); - #ifdef _7Z_VOL + #ifdef Z7_7Z_VOL if (_volumes.Size() < 1) return; const CVolume &volume = _volumes.Front(); @@ -105,34 +112,31 @@ RemoveOneItem(fileInfoPopIDs, NID::kNtSecure); */ - COPY_ONE_ITEM(kName); - COPY_ONE_ITEM(kAnti); - COPY_ONE_ITEM(kSize); - COPY_ONE_ITEM(kPackInfo); - COPY_ONE_ITEM(kCTime); - COPY_ONE_ITEM(kMTime); - COPY_ONE_ITEM(kATime); - COPY_ONE_ITEM(kWinAttrib); - COPY_ONE_ITEM(kCRC); - COPY_ONE_ITEM(kComment); + COPY_ONE_ITEM(kName) + COPY_ONE_ITEM(kAnti) + COPY_ONE_ITEM(kSize) + COPY_ONE_ITEM(kPackInfo) + COPY_ONE_ITEM(kCTime) + COPY_ONE_ITEM(kMTime) + COPY_ONE_ITEM(kATime) + COPY_ONE_ITEM(kWinAttrib) + COPY_ONE_ITEM(kCRC) + COPY_ONE_ITEM(kComment) _fileInfoPopIDs += fileInfoPopIDs; - #ifndef _SFX - _fileInfoPopIDs.Add(97); - _fileInfoPopIDs.Add(98); - _fileInfoPopIDs.Add(99); + #ifndef Z7_SFX + _fileInfoPopIDs.Add(k_7z_id_Encrypted); + _fileInfoPopIDs.Add(k_7z_id_Method); + _fileInfoPopIDs.Add(k_7z_id_Block); #endif - #ifdef _MULTI_PACK - _fileInfoPopIDs.Add(100); - _fileInfoPopIDs.Add(101); - _fileInfoPopIDs.Add(102); - _fileInfoPopIDs.Add(103); - _fileInfoPopIDs.Add(104); + #ifdef Z7_7Z_SHOW_PACK_STREAMS_SIZES + for (unsigned i = 0; i < 5; i++) + _fileInfoPopIDs.Add(k_7z_id_PackedSize0 + i); #endif - #ifndef _SFX + #ifndef Z7_SFX InsertToHead(_fileInfoPopIDs, NID::kMTime); InsertToHead(_fileInfoPopIDs, NID::kPackInfo); InsertToHead(_fileInfoPopIDs, NID::kSize); @@ -140,25 +144,29 @@ #endif } -STDMETHODIMP CHandler::GetNumberOfProperties(UInt32 *numProps) +Z7_COM7F_IMF(CHandler::GetNumberOfProperties(UInt32 *numProps)) { *numProps = _fileInfoPopIDs.Size(); return S_OK; } -STDMETHODIMP CHandler::GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) +Z7_COM7F_IMF(CHandler::GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) { if (index >= _fileInfoPopIDs.Size()) return E_INVALIDARG; - UInt64 id = _fileInfoPopIDs[index]; - for (unsigned i = 0; i < ARRAY_SIZE(kPropMap); i++) + const UInt64 id = _fileInfoPopIDs[index]; + for (unsigned i = 0; i < Z7_ARRAY_SIZE(kPropMap); i++) { const CPropMap &pr = kPropMap[i]; if (pr.FilePropID == id) { + *propID = pr.StatPropID; + *varType = pr.vt; + /* const CStatProp &st = pr.StatProp; *propID = st.PropID; *varType = st.vt; + */ /* if (st.lpwstrName) *name = ::SysAllocString(st.lpwstrName); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zProperties.h 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zProperties.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zProperties.h 2008-08-06 08:30:47.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zProperties.h 2023-03-29 09:00:00.000000000 +0000 @@ -1,13 +1,16 @@ // 7zProperties.h -#ifndef __7Z_PROPERTIES_H -#define __7Z_PROPERTIES_H +#ifndef ZIP7_INC_7Z_PROPERTIES_H +#define ZIP7_INC_7Z_PROPERTIES_H #include "../../PropID.h" namespace NArchive { namespace N7z { +// #define Z7_7Z_SHOW_PACK_STREAMS_SIZES // for debug + +#ifdef Z7_7Z_SHOW_PACK_STREAMS_SIZES enum { kpidPackedSize0 = kpidUserDefined, @@ -16,6 +19,7 @@ kpidPackedSize3, kpidPackedSize4 }; +#endif }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zRegister.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zRegister.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zRegister.cpp 2022-05-04 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zRegister.cpp 2022-08-17 05:00:00.000000000 +0000 @@ -22,6 +22,6 @@ | NArcInfoFlags::kMTime_Default , TIME_PREC_TO_ARC_FLAGS_MASK(NFileTimeType::kWindows) | TIME_PREC_TO_ARC_FLAGS_TIME_DEFAULT(NFileTimeType::kWindows) - , NULL); + , NULL) }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zSpecStream.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zSpecStream.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zSpecStream.cpp 2012-11-17 06:57:34.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zSpecStream.cpp 2023-03-29 06:00:00.000000000 +0000 @@ -4,19 +4,28 @@ #include "7zSpecStream.h" -STDMETHODIMP CSequentialInStreamSizeCount2::Read(void *data, UInt32 size, UInt32 *processedSize) +/* +Z7_COM7F_IMF(CSequentialInStreamSizeCount2::Read(void *data, UInt32 size, UInt32 *processedSize)) { UInt32 realProcessedSize; - HRESULT result = _stream->Read(data, size, &realProcessedSize); + const HRESULT result = _stream->Read(data, size, &realProcessedSize); _size += realProcessedSize; if (processedSize) *processedSize = realProcessedSize; return result; } -STDMETHODIMP CSequentialInStreamSizeCount2::GetSubStreamSize(UInt64 subStream, UInt64 *value) +Z7_COM7F_IMF(CSequentialInStreamSizeCount2::GetSubStreamSize(UInt64 subStream, UInt64 *value)) { if (!_getSubStreamSize) return E_NOTIMPL; return _getSubStreamSize->GetSubStreamSize(subStream, value); } + +Z7_COM7F_IMF(CSequentialInStreamSizeCount2::GetNextInSubStream(UInt64 *streamIndexRes, ISequentialInStream **stream)) +{ + if (!_compressGetSubStreamSize) + return E_NOTIMPL; + return _compressGetSubStreamSize->GetNextInSubStream(streamIndexRes, stream); +} +*/ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zSpecStream.h 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zSpecStream.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zSpecStream.h 2014-12-21 15:31:05.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zSpecStream.h 2023-03-29 06:00:00.000000000 +0000 @@ -1,35 +1,49 @@ // 7zSpecStream.h -#ifndef __7Z_SPEC_STREAM_H -#define __7Z_SPEC_STREAM_H +#ifndef ZIP7_INC_7Z_SPEC_STREAM_H +#define ZIP7_INC_7Z_SPEC_STREAM_H #include "../../../Common/MyCom.h" #include "../../ICoder.h" -class CSequentialInStreamSizeCount2: +/* +#define Z7_COM_QI_ENTRY_AG_2(i, sub0, sub) else if (iid == IID_ ## i) \ + { if (!sub) RINOK(sub0->QueryInterface(IID_ ## i, (void **)&sub)) \ + { i *ti = this; *outObject = ti; } } + +class CSequentialInStreamSizeCount2 Z7_final: public ISequentialInStream, public ICompressGetSubStreamSize, + public ICompressInSubStreams, public CMyUnknownImp { + Z7_COM_QI_BEGIN2(ISequentialInStream) + Z7_COM_QI_ENTRY(ICompressGetSubStreamSize) + Z7_COM_QI_ENTRY_AG_2(ISequentialInStream, _stream, _compressGetSubStreamSize) + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(ISequentialInStream) + Z7_IFACE_COM7_IMP(ICompressGetSubStreamSize) + Z7_IFACE_COM7_IMP(ICompressInSubStreams) + CMyComPtr _stream; CMyComPtr _getSubStreamSize; + CMyComPtr _compressGetSubStreamSize; UInt64 _size; public: void Init(ISequentialInStream *stream) { _size = 0; _getSubStreamSize.Release(); + _compressGetSubStreamSize.Release(); _stream = stream; _stream.QueryInterface(IID_ICompressGetSubStreamSize, &_getSubStreamSize); + _stream.QueryInterface(IID_ICompressInSubStreams, &_compressGetSubStreamSize); } UInt64 GetSize() const { return _size; } - - MY_UNKNOWN_IMP2(ISequentialInStream, ICompressGetSubStreamSize) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - - STDMETHOD(GetSubStreamSize)(UInt64 subStream, UInt64 *value); }; +*/ #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zUpdate.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zUpdate.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zUpdate.cpp 2022-05-04 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zUpdate.cpp 2023-05-11 16:00:00.000000000 +0000 @@ -4,6 +4,8 @@ #include "../../../../C/CpuArch.h" +#include "../../../Common/MyLinux.h" +#include "../../../Common/StringToInt.h" #include "../../../Common/Wildcard.h" #include "../../Common/CreateCoder.h" @@ -24,24 +26,43 @@ namespace NArchive { namespace N7z { - #define k_X86 k_BCJ struct CFilterMode { UInt32 Id; - UInt32 Delta; - - CFilterMode(): Id(0), Delta(0) {} + UInt32 Delta; // required File Size alignment, if Id is not k_Delta. + // (Delta == 0) means unknown alignment + UInt32 Offset; // for k_ARM64 + // UInt32 AlignSizeOpt; // for k_ARM64 + + CFilterMode(): + Id(0), + Delta(0), + Offset(0) + // , AlignSizeOpt(0) + {} + + void ClearFilterMode() + { + Id = 0; + Delta = 0; + Offset = 0; + // AlignSizeOpt = 0; + } + // it sets Delta as Align value, if Id is exe filter + // in another cases it sets Delta = 0, that void SetDelta() { if (Id == k_IA64) Delta = 16; - else if (Id == k_ARM || Id == k_PPC || Id == k_SPARC) + else if (Id == k_ARM64 || Id == k_ARM || Id == k_PPC || Id == k_SPARC) Delta = 4; else if (Id == k_ARMT) Delta = 2; + else if (Id == k_BCJ || Id == k_BCJ2) + Delta = 1; // do we need it? else Delta = 0; } @@ -78,6 +99,7 @@ { case 0x014C: case 0x8664: filterId = k_X86; break; + case 0xAA64: filterId = k_ARM64; break; /* IMAGE_FILE_MACHINE_ARM 0x01C0 // ARM LE @@ -94,6 +116,7 @@ default: return 0; } + // const UInt32 numSections = GetUi16(p + 2); optHeaderSize = GetUi16(p + 16); if (optHeaderSize > (1 << 10)) return 0; @@ -109,6 +132,63 @@ return 0; } + /* + // Windows exe file sizes are not aligned for 4 KiB. + // So we can't use (CFilterMode::Offset != 0) in solid archives. + // So we just don't set Offset here. +#define NUM_SCAN_SECTIONS_MAX (1 << 6) +#define EXE_SECTION_OFFSET_MAX (1 << 27) +#define EXE_SECTION_SIZE_MIN (1 << 8) +#define EXE_SECTION_SIZE_MAX (1 << 27) +#define PE_SectHeaderSize 40 +#define PE_SECT_EXECUTE 0x20000000 + + if (numSections > NUM_SCAN_SECTIONS_MAX) + return 0; + + p += optHeaderSize; + // UInt32 numExeSections = 0; + // bool execute_finded = false; + // UInt32 sect_va = 0; + // UInt32 sect_size = 0; + // UInt32 sect_offset = 0; + + for (UInt32 i = 0; i < numSections + // && numExeSections < numSectionsMax + ; i++, p += PE_SectHeaderSize) + { + UInt32 characts, rawSize, offset; + if ((UInt32)(p - buf) + PE_SectHeaderSize > size) + return 0; + rawSize = GetUi32(p + 16); + offset = GetUi32(p + 20); + characts = GetUi32(p + 36); + if (rawSize >= EXE_SECTION_SIZE_MIN && + rawSize <= EXE_SECTION_SIZE_MAX && + offset <= EXE_SECTION_OFFSET_MAX && + // offset < limit && + offset > 0) + { + if ((characts & PE_SECT_EXECUTE) != 0) + { + // execute_finded = true; + // sect_va = GetUi32(p + 12); + // sect_size = rawSize; + // sect_offset = offset; + break; + } + } + } + + filterMode->Offset = 0; + if (filterId == k_ARM64) + { + // filterMode->AlignSizeOpt = (1 << 12); + // const UInt32 offs = (sect_va - sect_offset) & 0xFFF; + // if (offs != 0) + // filterMode->Offset = offs; // change it + } + */ filterMode->Id = filterId; return 1; } @@ -164,8 +244,9 @@ case 20: case 21: if (!be) return 0; filterId = k_PPC; break; case 40: if ( be) return 0; filterId = k_ARM; break; - - /* Some IA-64 ELF exacutable have size that is not aligned for 16 bytes. + case 183: if (be) return 0; filterId = k_ARM64; break; + + /* Some IA-64 ELF executables have size that is not aligned for 16 bytes. So we don't use IA-64 filter for IA-64 ELF */ // case 50: if ( be) return 0; filterId = k_IA64; break; @@ -192,6 +273,7 @@ #define MACH_MACHINE_PPC 18 #define MACH_MACHINE_PPC64 (MACH_ARCH_ABI64 | MACH_MACHINE_PPC) #define MACH_MACHINE_AMD64 (MACH_ARCH_ABI64 | MACH_MACHINE_386) +#define MACH_MACHINE_ARM64 (MACH_ARCH_ABI64 | MACH_MACHINE_ARM) static unsigned Parse_MACH(const Byte *buf, size_t size, CFilterMode *filterMode) { @@ -218,6 +300,7 @@ case MACH_MACHINE_SPARC: if (!be) return 0; filterId = k_SPARC; break; case MACH_MACHINE_PPC: case MACH_MACHINE_PPC64: if (!be) return 0; filterId = k_PPC; break; + case MACH_MACHINE_ARM64: if ( be) return 0; filterId = k_ARM64; break; default: return 0; } @@ -284,10 +367,15 @@ return False; } + +/* + filterMode->Delta will be set as: + = delta value : [1, 256] : for k_Delta + = 0 for another filters (branch filters) +*/ static BoolInt ParseFile(const Byte *buf, size_t size, CFilterMode *filterMode) { - filterMode->Id = 0; - filterMode->Delta = 0; + filterMode->ClearFilterMode(); if (Parse_EXE(buf, size, filterMode)) return True; if (Parse_ELF(buf, size, filterMode)) return True; @@ -315,18 +403,44 @@ else if (!m.Encrypted) return 1; - if (Id < m.Id) return -1; - if (Id > m.Id) return 1; + const UInt32 id1 = Id; + const UInt32 id2 = m.Id; + /* + // we can change the order to place k_ARM64 files close to another exe files + if (id1 <= k_SPARC && + id2 <= k_SPARC) + { + #define k_ARM64_FOR_SORT 0x3030901 + if (id1 == k_ARM64) id1 = k_ARM64_FOR_SORT; + if (id2 == k_ARM64) id2 = k_ARM64_FOR_SORT; + } + */ + if (id1 < id2) return -1; + if (id1 > id2) return 1; if (Delta < m.Delta) return -1; if (Delta > m.Delta) return 1; + if (Offset < m.Offset) return -1; + if (Offset > m.Offset) return 1; + + /* we don't go here, because GetGroup() + and operator ==(const CFilterMode2 &m) + add only unique CFilterMode2:: { Id, Delta, Offset, Encrypted } items. + */ + /* + if (GroupIndex < m.GroupIndex) return -1; + if (GroupIndex > m.GroupIndex) return 1; + */ return 0; } bool operator ==(const CFilterMode2 &m) const { - return Id == m.Id && Delta == m.Delta && Encrypted == m.Encrypted; + return Id == m.Id + && Delta == m.Delta + && Offset == m.Offset + && Encrypted == m.Encrypted; } }; @@ -367,6 +481,7 @@ { switch (m) { + case k_ARM64: case k_BCJ: case k_BCJ2: case k_ARM: @@ -383,8 +498,9 @@ CRecordVector &filters, const CFolderEx &f, bool extractFilter) { CFilterMode2 m; - m.Id = 0; - m.Delta = 0; + // m.Id = 0; + // m.Delta = 0; + // m.Offset = 0; m.Encrypted = f.IsEncrypted(); if (extractFilter) @@ -405,6 +521,9 @@ if (m.Id == k_BCJ2) m.Id = k_BCJ; m.SetDelta(); + if (m.Id == k_ARM64) + if (coder.Props.Size() == 4) + m.Offset = GetUi32(coder.Props); } } @@ -417,15 +536,15 @@ static HRESULT WriteRange(IInStream *inStream, ISequentialOutStream *outStream, UInt64 position, UInt64 size, ICompressProgressInfo *progress) { - RINOK(inStream->Seek((Int64)position, STREAM_SEEK_SET, 0)); + RINOK(InStream_SeekSet(inStream, position)) CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; - CMyComPtr inStreamLimited(streamSpec); + CMyComPtr inStreamLimited(streamSpec); streamSpec->SetStream(inStream); streamSpec->Init(size); NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder; CMyComPtr copyCoder = copyCoderSpec; - RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress)) return (copyCoderSpec->TotalSize == size ? S_OK : E_FAIL); } @@ -445,7 +564,7 @@ } */ -#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } +#define RINOZ(x) { const int _t_ = (x); if (_t_ != 0) return _t_; } #define RINOZ_COMP(a, b) RINOZ(MyCompare(a, b)) @@ -630,7 +749,7 @@ unsigned NamePos; unsigned ExtensionIndex; - CRefItem() {}; + CRefItem() {} CRefItem(UInt32 index, const CUpdateItem &ui, bool sortByType): UpdateItem(&ui), Index(index), @@ -710,16 +829,16 @@ // bool sortByType = *(bool *)param; const CSortParam *sortParam = (const CSortParam *)param; - bool sortByType = sortParam->SortByType; + const bool sortByType = sortParam->SortByType; if (sortByType) { - RINOZ_COMP(a1.ExtensionIndex, a2.ExtensionIndex); - RINOZ(CompareFileNames(u1.Name.Ptr(a1.ExtensionPos), u2.Name.Ptr(a2.ExtensionPos))); - RINOZ(CompareFileNames(u1.Name.Ptr(a1.NamePos), u2.Name.Ptr(a2.NamePos))); + RINOZ_COMP(a1.ExtensionIndex, a2.ExtensionIndex) + RINOZ(CompareFileNames(u1.Name.Ptr(a1.ExtensionPos), u2.Name.Ptr(a2.ExtensionPos))) + RINOZ(CompareFileNames(u1.Name.Ptr(a1.NamePos), u2.Name.Ptr(a2.NamePos))) if (!u1.MTimeDefined && u2.MTimeDefined) return 1; if (u1.MTimeDefined && !u2.MTimeDefined) return -1; - if (u1.MTimeDefined && u2.MTimeDefined) RINOZ_COMP(u1.MTime, u2.MTime); - RINOZ_COMP(u1.Size, u2.Size); + if (u1.MTimeDefined && u2.MTimeDefined) RINOZ_COMP(u1.MTime, u2.MTime) + RINOZ_COMP(u1.Size, u2.Size) } /* int par1 = a1.UpdateItem->ParentFolderIndex; @@ -765,9 +884,9 @@ } */ // RINOZ_COMP(a1.UpdateItem->ParentSortIndex, a2.UpdateItem->ParentSortIndex); - RINOK(CompareFileNames(u1.Name, u2.Name)); - RINOZ_COMP(a1.UpdateItem->IndexInClient, a2.UpdateItem->IndexInClient); - RINOZ_COMP(a1.UpdateItem->IndexInArchive, a2.UpdateItem->IndexInArchive); + RINOK(CompareFileNames(u1.Name, u2.Name)) + RINOZ_COMP(a1.UpdateItem->IndexInClient, a2.UpdateItem->IndexInClient) + RINOZ_COMP(a1.UpdateItem->IndexInArchive, a2.UpdateItem->IndexInArchive) return 0; } @@ -778,7 +897,7 @@ CRecordVector folderRefs; }; -static const char * const g_ExeExts[] = +static const char * const g_Exe_Exts[] = { "dll" , "exe" @@ -787,13 +906,64 @@ , "sys" }; -static bool IsExeExt(const wchar_t *ext) +static const char * const g_ExeUnix_Exts[] = +{ + "so" + , "dylib" +}; + +static bool IsExt_Exe(const wchar_t *ext) +{ + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Exe_Exts); i++) + if (StringsAreEqualNoCase_Ascii(ext, g_Exe_Exts[i])) + return true; + return false; +} + +/* +static bool IsExt_ExeUnix(const wchar_t *ext) { - for (unsigned i = 0; i < ARRAY_SIZE(g_ExeExts); i++) - if (StringsAreEqualNoCase_Ascii(ext, g_ExeExts[i])) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_ExeUnix_Exts); i++) + if (StringsAreEqualNoCase_Ascii(ext, g_ExeUnix_Exts[i])) return true; return false; } +*/ + +// we try to find "so" extension in such name: libstdc++.so.6.0.29 +static bool IsExt_ExeUnix_NumericAllowed(const UString &path) +{ + unsigned pos = path.Len(); + unsigned dotPos = pos; + for (;;) + { + if (pos == 0) + return false; + const wchar_t c = path[--pos]; + if (IS_PATH_SEPAR(c)) + return false; + if (c == '.') + { + const unsigned num = (dotPos - pos) - 1; + if (num < 1) + return false; + const wchar_t *cur = path.Ptr(pos + 1); + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_ExeUnix_Exts); i++) + { + const char *ext = g_ExeUnix_Exts[i]; + if (num == MyStringLen(ext)) + if (IsString1PrefixedByString2_NoCase_Ascii(cur, ext)) + return true; + } + const wchar_t *end; + ConvertStringToUInt32(cur, &end); + if ((size_t)(end - cur) != num) + return false; + dotPos = pos; + } + } +} + struct CAnalysis { @@ -802,6 +972,8 @@ bool ParseWav; bool ParseExe; + bool ParseExeUnix; + bool ParseNoExt; bool ParseAll; /* @@ -811,8 +983,10 @@ */ CAnalysis(): - ParseWav(true), + ParseWav(false), ParseExe(false), + ParseExeUnix(false), + ParseNoExt(false), ParseAll(false) /* , Need_ATime(false) @@ -829,32 +1003,46 @@ { filterMode.Id = 0; filterMode.Delta = 0; + filterMode.Offset = 0; CFilterMode filterModeTemp = filterMode; - int slashPos = ui.Name.ReverseFind_PathSepar(); - int dotPos = ui.Name.ReverseFind_Dot(); + const int slashPos = ui.Name.ReverseFind_PathSepar(); + const int dotPos = ui.Name.ReverseFind_Dot(); // if (dotPos > slashPos) { bool needReadFile = ParseAll; - + /* if (Callback) is not supported by client, + we still try to use file name extension to detect executable file */ bool probablyIsSameIsa = false; if (!needReadFile || !Callback) { - const wchar_t *ext; + const wchar_t *ext = NULL; if (dotPos > slashPos) ext = ui.Name.Ptr((unsigned)(dotPos + 1)); - else - ext = ui.Name.RightPtr(0); - - // p7zip uses the trick to store posix attributes in high 16 bits + // 7-zip stores posix attributes in high 16 bits and sets (0x8000) flag if (ui.Attrib & 0x8000) { - unsigned st_mode = ui.Attrib >> 16; - // st_mode = 00111; - if ((st_mode & 00111) && (ui.Size >= 2048)) + const unsigned st_mode = ui.Attrib >> 16; + /* note: executable ".so" can be without execute permission, + and symbolic link to such ".so" file is possible */ + // st_mode = 00111; // for debug + /* in Linux we expect such permissions: + 0755 : for most executables + 0644 : for some ".so" files + 0777 : in WSL for all files. + We can try to exclude some such 0777 cases from analysis, + if there is non-executable extension. + */ + + if ((st_mode & ( + MY_LIN_S_IXUSR | + MY_LIN_S_IXGRP | + MY_LIN_S_IXOTH)) != 0 + && MY_LIN_S_ISREG(st_mode) + && (ui.Size >= (1u << 11))) { #ifndef _WIN32 probablyIsSameIsa = true; @@ -863,36 +1051,45 @@ } } - if (IsExeExt(ext)) - { - needReadFile = true; - #ifdef _WIN32 - probablyIsSameIsa = true; - needReadFile = ParseExe; - #endif - } - else if (StringsAreEqualNoCase_Ascii(ext, "wav")) + if (!needReadFile) { - needReadFile = ParseWav; - } - /* - else if (!needReadFile && ParseUnixExt) - { - if (StringsAreEqualNoCase_Ascii(ext, "so") - || StringsAreEqualNoCase_Ascii(ext, "")) - - needReadFile = true; + if (!ext) + needReadFile = ParseNoExt; + else + { + bool isUnixExt = false; + if (ParseExeUnix) + isUnixExt = IsExt_ExeUnix_NumericAllowed(ui.Name); + if (isUnixExt) + { + needReadFile = true; + #ifndef _WIN32 + probablyIsSameIsa = true; + #endif + } + else if (IsExt_Exe(ext)) + { + needReadFile = ParseExe; + #ifdef _WIN32 + probablyIsSameIsa = true; + #endif + } + else if (StringsAreEqualNoCase_Ascii(ext, "wav")) + { + if (!needReadFile) + needReadFile = ParseWav; + } + } } - */ } - if (needReadFile && Callback) + if (needReadFile) { - if (Buffer.Size() != kAnalysisBufSize) - { - Buffer.Alloc(kAnalysisBufSize); - } + BoolInt parseRes = false; + if (Callback) { + if (Buffer.Size() != kAnalysisBufSize) + Buffer.Alloc(kAnalysisBufSize); CMyComPtr stream; HRESULT result = Callback->GetStream2(index, &stream, NUpdateNotifyOp::kAnalyze); if (result == S_OK && stream) @@ -908,40 +1105,60 @@ ATime_Defined = true; } */ - size_t size = kAnalysisBufSize; result = ReadStream(stream, Buffer, &size); stream.Release(); // RINOK(Callback->SetOperationResult2(index, NUpdate::NOperationResult::kOK)); if (result == S_OK) { - BoolInt parseRes = ParseFile(Buffer, size, &filterModeTemp); - if (parseRes && filterModeTemp.Delta == 0) - { - filterModeTemp.SetDelta(); - if (filterModeTemp.Delta != 0 && filterModeTemp.Id != k_Delta) - { - if (ui.Size % filterModeTemp.Delta != 0) - { - parseRes = false; - } - } - } - if (!parseRes) + parseRes = ParseFile(Buffer, size, &filterModeTemp); + } + } + } // Callback + else if (probablyIsSameIsa) + { + #ifdef MY_CPU_X86_OR_AMD64 + filterModeTemp.Id = k_X86; + #endif + #ifdef MY_CPU_ARM64 + filterModeTemp.Id = k_ARM64; + #endif + parseRes = true; + } + + if (parseRes + && filterModeTemp.Id != k_Delta + && filterModeTemp.Delta == 0) + { + /* ParseFile() sets (filterModeTemp.Delta == 0) for all + methods except of k_Delta. */ + // it's not k_Delta + // So we call SetDelta() to set Delta + filterModeTemp.SetDelta(); + if (filterModeTemp.Delta > 1) + { + /* If file Size is not aligned, then branch filter + will not work for next file in solid block. + Maybe we should allow filter for non-aligned-size file in non-solid archives ? + */ + if (ui.Size % filterModeTemp.Delta != 0) + parseRes = false; + // windows exe files are not aligned for 4 KiB. + /* + else if (filterModeTemp.Id == k_ARM64 && filterModeTemp.Offset != 0) + { + if (ui.Size % (1 << 12) != 0) { - filterModeTemp.Id = 0; - filterModeTemp.Delta = 0; + // If Size is not aligned for 4 KiB, then Offset will not work for next file in solid block. + // so we place such file in group with (Offset==0). + filterModeTemp.Offset = 0; } } + */ } } - } - else if ((needReadFile && !Callback) || probablyIsSameIsa) - { - #ifdef MY_CPU_X86_OR_AMD64 - if (probablyIsSameIsa) - filterModeTemp.Id = k_X86; - #endif + if (!parseRes) + filterModeTemp.ClearFilterMode(); } } @@ -1010,7 +1227,7 @@ mode.Methods.Add(m); mode.Methods.Add(m); - RINOK(AddBondForFilter(mode)); + RINOK(AddBondForFilter(mode)) CBond2 bond; bond.OutCoder = 0; bond.InCoder = methodIndex; bond.OutStream = 1; mode.Bonds.Add(bond); @@ -1024,7 +1241,7 @@ if (mode.Filter_was_Inserted) { const CMethodFull &m = mode.Methods[0]; - CMethodId id = m.Id; + const CMethodId id = m.Id; if (id == k_BCJ2) return AddBcj2Methods(mode); if (!m.IsSimpleCoder()) @@ -1039,7 +1256,7 @@ CMethodFull &m = mode.Methods.InsertNew(0); { - FOR_VECTOR(k, mode.Bonds) + FOR_VECTOR (k, mode.Bonds) { CBond2 &bond = mode.Bonds[k]; bond.InCoder++; @@ -1059,23 +1276,32 @@ GetMethodFull(filterMode.Id, 1, m); if (filterMode.Id == k_Delta) m.AddProp32(NCoderPropID::kDefaultProp, filterMode.Delta); + else if (filterMode.Id == k_ARM64) + { + // if (filterMode.Offset != 0) + m.AddProp32( + NCoderPropID::kDefaultProp, + // NCoderPropID::kBranchOffset, + filterMode.Offset); + } res = AddFilterBond(mode); int alignBits = -1; - if (filterMode.Id == k_Delta || filterMode.Delta != 0) - { - if (filterMode.Delta == 1) alignBits = 0; - else if (filterMode.Delta == 2) alignBits = 1; - else if (filterMode.Delta == 4) alignBits = 2; - else if (filterMode.Delta == 8) alignBits = 3; - else if (filterMode.Delta == 16) alignBits = 4; - } - else { - // alignBits = GetAlignForFilterMethod(filterMode.Id); + const UInt32 delta = filterMode.Delta; + if (delta == 0 || delta > 16) + { + // if (delta == 0) alignBits = GetAlignForFilterMethod(filterMode.Id); + } + else if ((delta & ((1 << 4) - 1)) == 0) alignBits = 4; + else if ((delta & ((1 << 3) - 1)) == 0) alignBits = 3; + else if ((delta & ((1 << 2) - 1)) == 0) alignBits = 2; + else if ((delta & ((1 << 1) - 1)) == 0) alignBits = 1; + // else alignBits = 0; + /* alignBits=0 is default mode for lzma/lzma2. + So we don't set alignBits=0 here. */ } - - if (res == S_OK && alignBits >= 0) + if (res == S_OK && alignBits > 0) { unsigned nextCoder = 1; if (!mode.Bonds.IsEmpty()) @@ -1135,13 +1361,13 @@ -class CRepackInStreamWithSizes: - public ISequentialInStream, - public ICompressGetSubStreamSize, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_2( + CRepackInStreamWithSizes + , ISequentialInStream + , ICompressGetSubStreamSize +) CMyComPtr _stream; - // UInt64 _size; + UInt64 _size; const CBoolVector *_extractStatuses; UInt32 _startIndex; public: @@ -1151,37 +1377,28 @@ { _startIndex = startIndex; _extractStatuses = extractStatuses; - // _size = 0; + _size = 0; _stream = stream; } - // UInt64 GetSize() const { return _size; } - - MY_UNKNOWN_IMP2(ISequentialInStream, ICompressGetSubStreamSize) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - - STDMETHOD(GetSubStreamSize)(UInt64 subStream, UInt64 *value); + UInt64 GetSize() const { return _size; } }; -STDMETHODIMP CRepackInStreamWithSizes::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CRepackInStreamWithSizes::Read(void *data, UInt32 size, UInt32 *processedSize)) { - return _stream->Read(data, size, processedSize); - /* UInt32 realProcessedSize; - HRESULT result = _stream->Read(data, size, &realProcessedSize); + const HRESULT result = _stream->Read(data, size, &realProcessedSize); _size += realProcessedSize; if (processedSize) *processedSize = realProcessedSize; return result; - */ } -STDMETHODIMP CRepackInStreamWithSizes::GetSubStreamSize(UInt64 subStream, UInt64 *value) +Z7_COM7F_IMF(CRepackInStreamWithSizes::GetSubStreamSize(UInt64 subStream, UInt64 *value)) { *value = 0; if (subStream >= _extractStatuses->Size()) return S_FALSE; // E_FAIL; - unsigned index = (unsigned)subStream; + const unsigned index = (unsigned)subStream; if ((*_extractStatuses)[index]) { const CFileItem &fi = _db->Files[_startIndex + index]; @@ -1212,7 +1429,7 @@ public: const CDbEx *_db; CMyComPtr _opCallback; - CMyComPtr _extractCallback; + CMyComPtr _extractCallback; HRESULT Init(UInt32 startIndex, const CBoolVector *extractStatuses); HRESULT CheckFinishedState() const { return (_currentIndex == _extractStatuses->Size()) ? S_OK: E_FAIL; } @@ -1241,7 +1458,7 @@ NEventIndexType::kInArcIndex, arcIndex, _needWrite ? NUpdateNotifyOp::kRepack : - NUpdateNotifyOp::kSkip)); + NUpdateNotifyOp::kSkip)) } _crc = CRC_INIT_VAL; @@ -1267,7 +1484,7 @@ { RINOK(_extractCallback->ReportExtractResult( NEventIndexType::kInArcIndex, arcIndex, - NExtract::NOperationResult::kCRCError)); + NExtract::NOperationResult::kCRCError)) } // return S_FALSE; return k_My_HRESULT_CRC_ERROR; @@ -1277,30 +1494,28 @@ { while (_currentIndex < _extractStatuses->Size() && _db->Files[_startIndex + _currentIndex].Size == 0) { - RINOK(OpenFile()); - RINOK(CloseFile()); + RINOK(OpenFile()) + RINOK(CloseFile()) } return S_OK; } -#ifndef _7ZIP_ST +#ifndef Z7_ST -class CFolderOutStream2: +class CFolderOutStream2 Z7_final: public CRepackStreamBase, public ISequentialOutStream, public CMyUnknownImp { + Z7_COM_UNKNOWN_IMP_0 + Z7_IFACE_COM7_IMP(ISequentialOutStream) public: CMyComPtr _stream; - - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); }; -STDMETHODIMP CFolderOutStream2::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CFolderOutStream2::Write(const void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -1322,22 +1537,22 @@ _rem -= cur; if (_rem == 0) { - RINOK(CloseFile()); - RINOK(ProcessEmptyFiles()); + RINOK(CloseFile()) + RINOK(ProcessEmptyFiles()) } - RINOK(result); + RINOK(result) if (cur == 0) break; continue; } - RINOK(ProcessEmptyFiles()); + RINOK(ProcessEmptyFiles()) if (_currentIndex == _extractStatuses->Size()) { // we don't support write cut here return E_FAIL; } - RINOK(OpenFile()); + RINOK(OpenFile()) } return S_OK; @@ -1349,18 +1564,19 @@ static const UInt32 kTempBufSize = 1 << 16; -class CFolderInStream2: +class CFolderInStream2 Z7_final: public CRepackStreamBase, public ISequentialInStream, public CMyUnknownImp { + Z7_COM_UNKNOWN_IMP_0 + Z7_IFACE_COM7_IMP(ISequentialInStream) + Byte *_buf; public: CMyComPtr _inStream; HRESULT Result; - MY_UNKNOWN_IMP - CFolderInStream2(): Result(S_OK) { @@ -1373,10 +1589,9 @@ } void Init() { Result = S_OK; } - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); }; -STDMETHODIMP CFolderInStream2::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CFolderInStream2::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -1397,7 +1612,7 @@ cur = kTempBufSize; } - HRESULT result = _inStream->Read(buf, cur, &cur); + const HRESULT result = _inStream->Read(buf, cur, &cur); _crc = CrcUpdate(_crc, buf, cur); _rem -= cur; @@ -1414,11 +1629,11 @@ if (_rem == 0) { - RINOK(CloseFile()); - RINOK(ProcessEmptyFiles()); + RINOK(CloseFile()) + RINOK(ProcessEmptyFiles()) } - RINOK(result); + RINOK(result) if (cur == 0) return E_FAIL; @@ -1426,20 +1641,20 @@ continue; } - RINOK(ProcessEmptyFiles()); + RINOK(ProcessEmptyFiles()) if (_currentIndex == _extractStatuses->Size()) { return S_OK; } - RINOK(OpenFile()); + RINOK(OpenFile()) } return S_OK; } -class CThreadDecoder - #ifndef _7ZIP_ST +class CThreadDecoder Z7_final + #ifndef Z7_ST : public CVirtThread #endif { @@ -1449,7 +1664,7 @@ CThreadDecoder(bool multiThreadMixer): Decoder(multiThreadMixer) { - #ifndef _7ZIP_ST + #ifndef Z7_ST if (multiThreadMixer) { MtMode = false; @@ -1463,7 +1678,7 @@ // send_UnpackSize = false; } - #ifndef _7ZIP_ST + #ifndef Z7_ST bool dataAfterEnd_Error; HRESULT Result; @@ -1479,31 +1694,39 @@ // bool send_UnpackSize; // UInt64 UnpackSize; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO CMyComPtr getTextPassword; #endif - DECL_EXTERNAL_CODECS_LOC_VARS2; + DECL_EXTERNAL_CODECS_LOC_VARS_DECL - #ifndef _7ZIP_ST + #ifndef Z7_ST bool MtMode; UInt32 NumThreads; #endif - ~CThreadDecoder() { CVirtThread::WaitThreadFinish(); } - virtual void Execute(); + ~CThreadDecoder() Z7_DESTRUCTOR_override + { + /* WaitThreadFinish() will be called in ~CVirtThread(). + But we need WaitThreadFinish() call before + destructors of this class members. + */ + CVirtThread::WaitThreadFinish(); + } +private: + virtual void Execute() Z7_override; #endif }; -#ifndef _7ZIP_ST +#ifndef Z7_ST void CThreadDecoder::Execute() { try { - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO bool isEncrypted = false; bool passwordIsDefined = false; UString password; @@ -1526,8 +1749,8 @@ NULL // *inStreamMainRes , dataAfterEnd_Error - _7Z_DECODER_CRYPRO_VARS - #ifndef _7ZIP_ST + Z7_7Z_DECODER_CRYPRO_VARS + #ifndef Z7_ST , MtMode, NumThreads, 0 // MemUsage #endif @@ -1548,20 +1771,17 @@ #endif -#ifndef _NO_CRYPTO +#ifndef Z7_NO_CRYPTO -class CCryptoGetTextPassword: - public ICryptoGetTextPassword, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + CCryptoGetTextPassword + , ICryptoGetTextPassword +) public: UString Password; - - MY_UNKNOWN_IMP - STDMETHOD(CryptoGetTextPassword)(BSTR *password); }; -STDMETHODIMP CCryptoGetTextPassword::CryptoGetTextPassword(BSTR *password) +Z7_COM7F_IMF(CCryptoGetTextPassword::CryptoGetTextPassword(BSTR *password)) { return StringToBstr(Password, password); } @@ -1585,58 +1805,70 @@ DECL_EXTERNAL_CODECS_LOC_VARS IInStream *inStream, const CDbEx *db, - const CObjectVector &updateItems, + CObjectVector &updateItems, // const CObjectVector &treeFolders, // const CUniqBlocks &secureBlocks, - COutArchive &archive, - CArchiveDatabaseOut &newDatabase, ISequentialOutStream *seqOutStream, IArchiveUpdateCallback *updateCallback, - const CUpdateOptions &options - #ifndef _NO_CRYPTO - , ICryptoGetTextPassword *getDecoderPassword - #endif - ) + const CUpdateOptions &options) { UInt64 numSolidFiles = options.NumSolidFiles; if (numSolidFiles == 0) numSolidFiles = 1; - CMyComPtr opCallback; - updateCallback->QueryInterface(IID_IArchiveUpdateCallbackFile, (void **)&opCallback); - - CMyComPtr extractCallback; - updateCallback->QueryInterface(IID_IArchiveExtractCallbackMessage, (void **)&extractCallback); + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveUpdateCallbackFile, + opCallback, updateCallback) + + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveExtractCallbackMessage2, + extractCallback, updateCallback) /* - CMyComPtr reportArcProp; - updateCallback->QueryInterface(IID_IArchiveUpdateCallbackArcProp, (void **)&reportArcProp); + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveUpdateCallbackArcProp, + reportArcProp, updateCallback) */ // size_t totalSecureDataSize = (size_t)secureBlocks.GetTotalSizeInBytes(); - /* - CMyComPtr outStream; - RINOK(seqOutStream->QueryInterface(IID_IOutStream, (void **)&outStream)); - if (!outStream) - return E_NOTIMPL; - */ - - UInt64 startBlockSize = db ? db->ArcInfo.StartPosition: 0; - if (startBlockSize > 0 && !options.RemoveSfxBlock) + CMyComPtr v_StreamSetRestriction; { - RINOK(WriteRange(inStream, seqOutStream, 0, startBlockSize, NULL)); + Z7_DECL_CMyComPtr_QI_FROM( + IOutStream, + outStream, seqOutStream) + if (!outStream) + return E_NOTIMPL; + const UInt64 sfxBlockSize = (db && !options.RemoveSfxBlock) ? + db->ArcInfo.StartPosition: 0; + seqOutStream->QueryInterface(IID_IStreamSetRestriction, (void **)&v_StreamSetRestriction); + if (v_StreamSetRestriction) + { + UInt64 offset = 0; + RINOK(outStream->Seek(0, STREAM_SEEK_CUR, &offset)) + RINOK(v_StreamSetRestriction->SetRestriction( + outStream ? offset + sfxBlockSize : 0, + outStream ? offset + sfxBlockSize + k_StartHeadersRewriteSize : 0)) + } + outStream.Release(); + if (sfxBlockSize != 0) + { + RINOK(WriteRange(inStream, seqOutStream, 0, sfxBlockSize, NULL)) + } } CIntArr fileIndexToUpdateIndexMap; UInt64 complexity = 0; UInt64 inSizeForReduce2 = 0; + + #ifndef Z7_NO_CRYPTO bool needEncryptedRepack = false; + #endif CRecordVector filters; CObjectVector groups; - #ifndef _7ZIP_ST + #ifndef Z7_ST bool thereAreRepacks = false; #endif @@ -1646,11 +1878,15 @@ const CCompressionMethodMode &method = *options.Method; FOR_VECTOR (i, method.Methods) + { + /* IsFilterMethod() knows only built-in codecs + FIXME: we should check IsFilter status for external filters too */ if (IsFilterMethod(method.Methods[i].Id)) { useFilters = false; break; } + } } if (db) @@ -1672,7 +1908,7 @@ { CNum indexInFolder = 0; CNum numCopyItems = 0; - CNum numUnpackStreams = db->NumUnpackStreamsVector[i]; + const CNum numUnpackStreams = db->NumUnpackStreamsVector[i]; UInt64 repackSize = 0; for (CNum fi = db->FolderStartFileIndex[i]; indexInFolder < numUnpackStreams; fi++) @@ -1684,7 +1920,7 @@ if (file.HasStream) { indexInFolder++; - int updateIndex = fileIndexToUpdateIndexMap[fi]; + const int updateIndex = fileIndexToUpdateIndexMap[fi]; if (updateIndex >= 0 && !updateItems[(unsigned)updateIndex].NewData) { numCopyItems++; @@ -1702,11 +1938,13 @@ CFolderEx f; db->ParseFolderEx(i, f); + #ifndef Z7_NO_CRYPTO const bool isEncrypted = f.IsEncrypted(); + #endif const bool needCopy = (numCopyItems == numUnpackStreams); const bool extractFilter = (useFilters || needCopy); - unsigned groupIndex = Get_FilterGroup_for_Folder(filters, f, extractFilter); + const unsigned groupIndex = Get_FilterGroup_for_Folder(filters, f, extractFilter); while (groupIndex >= groups.Size()) groups.AddNew(); @@ -1717,14 +1955,16 @@ complexity += db->GetFolderFullPackSize(i); else { - #ifndef _7ZIP_ST + #ifndef Z7_ST thereAreRepacks = true; #endif complexity += repackSize; if (inSizeForReduce2 < repackSize) inSizeForReduce2 = repackSize; + #ifndef Z7_NO_CRYPTO if (isEncrypted) needEncryptedRepack = true; + #endif } } } @@ -1749,13 +1989,13 @@ if (inSizeForReduce < inSizeForReduce2) inSizeForReduce = inSizeForReduce2; - RINOK(updateCallback->SetTotal(complexity)); + RINOK(updateCallback->SetTotal(complexity)) CLocalProgress *lps = new CLocalProgress; CMyComPtr progress = lps; lps->Init(updateCallback, true); - #ifndef _7ZIP_ST + #ifndef Z7_ST CStreamBinder sb; /* @@ -1769,13 +2009,13 @@ CThreadDecoder threadDecoder(options.MultiThreadMixer); - #ifndef _7ZIP_ST + #ifndef Z7_ST if (options.MultiThreadMixer && thereAreRepacks) { - #ifdef EXTERNAL_CODECS - threadDecoder.__externalCodecs = __externalCodecs; + #ifdef Z7_EXTERNAL_CODECS + threadDecoder._externalCodecs = _externalCodecs; #endif - WRes wres = threadDecoder.Create(); + const WRes wres = threadDecoder.Create(); if (wres != 0) return HRESULT_FROM_WIN32(wres); } @@ -1784,22 +2024,23 @@ { CAnalysis analysis; // analysis.Need_ATime = options.Need_ATime; - if (options.AnalysisLevel == 0) - { - analysis.ParseWav = false; - analysis.ParseExe = false; - analysis.ParseAll = false; - } - else + int analysisLevel = options.AnalysisLevel; + // (analysisLevel < 0) means default level (5) + if (analysisLevel < 0) + analysisLevel = 5; + if (analysisLevel != 0) { analysis.Callback = opCallback; - if (options.AnalysisLevel > 0) + analysis.ParseWav = true; + if (analysisLevel >= 5) { - analysis.ParseWav = true; - if (options.AnalysisLevel >= 7) + analysis.ParseExe = true; + analysis.ParseExeUnix = true; + // analysis.ParseNoExt = true; + if (analysisLevel >= 7) { - analysis.ParseExe = true; - if (options.AnalysisLevel >= 9) + analysis.ParseNoExt = true; + if (analysisLevel >= 9) analysis.ParseAll = true; } } @@ -1819,7 +2060,7 @@ if (useFilters) { // analysis.ATime_Defined = false; - RINOK(analysis.GetFilterGroup(i, ui, fm)); + RINOK(analysis.GetFilterGroup(i, ui, fm)) /* if (analysis.ATime_Defined) { @@ -1830,7 +2071,7 @@ } fm.Encrypted = method.PasswordIsDefined; - unsigned groupIndex = GetGroup(filters, fm); + const unsigned groupIndex = GetGroup(filters, fm); while (groupIndex >= groups.Size()) groups.AddNew(); groups[groupIndex].Indices.Add(i); @@ -1838,7 +2079,7 @@ } - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO CCryptoGetTextPassword *getPasswordSpec = NULL; CMyComPtr getTextPassword; @@ -1847,7 +2088,7 @@ getPasswordSpec = new CCryptoGetTextPassword; getTextPassword = getPasswordSpec; - #ifndef _7ZIP_ST + #ifndef Z7_ST threadDecoder.getTextPassword = getPasswordSpec; #endif @@ -1855,10 +2096,13 @@ getPasswordSpec->Password = options.Method->Password; else { + Z7_DECL_CMyComPtr_QI_FROM( + ICryptoGetTextPassword, + getDecoderPassword, updateCallback) if (!getDecoderPassword) return E_NOTIMPL; CMyComBSTR password; - RINOK(getDecoderPassword->CryptoGetTextPassword(&password)); + RINOK(getDecoderPassword->CryptoGetTextPassword(&password)) if (password) getPasswordSpec->Password = password; } @@ -1866,11 +2110,12 @@ #endif - // ---------- Compress ---------- - RINOK(archive.Create(seqOutStream, false)); - RINOK(archive.SkipPrefixArchiveHeader()); + COutArchive archive; + CArchiveDatabaseOut newDatabase; + + RINOK(archive.Create_and_WriteStartPrefix(seqOutStream)) /* CIntVector treeFolderToArcIndex; @@ -1973,7 +2218,6 @@ { // ---------- Sort Filters ---------- - FOR_VECTOR (i, filters) { filters[i].GroupIndex = i; @@ -1987,22 +2231,22 @@ CCompressionMethodMode method = *options.Method; { - HRESULT res = MakeExeMethod(method, filterMode, - #ifdef _7ZIP_ST + const HRESULT res = MakeExeMethod(method, filterMode, + #ifdef Z7_ST false #else options.MaxFilter && options.MultiThreadMixer #endif ); - RINOK(res); + RINOK(res) } if (filterMode.Encrypted) { if (!method.PasswordIsDefined) { - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO if (getPasswordSpec) method.Password = getPasswordSpec->Password; #endif @@ -2021,13 +2265,13 @@ const CSolidGroup &group = groups[filterMode.GroupIndex]; - FOR_VECTOR(folderRefIndex, group.folderRefs) + FOR_VECTOR (folderRefIndex, group.folderRefs) { const CFolderRepack &rep = group.folderRefs[folderRefIndex]; - unsigned folderIndex = rep.FolderIndex; + const unsigned folderIndex = rep.FolderIndex; - CNum numUnpackStreams = db->NumUnpackStreamsVector[folderIndex]; + const CNum numUnpackStreams = db->NumUnpackStreamsVector[folderIndex]; if (rep.NumCopyFiles == numUnpackStreams) { @@ -2035,7 +2279,7 @@ { RINOK(opCallback->ReportOperation( NEventIndexType::kBlockIndex, (UInt32)folderIndex, - NUpdateNotifyOp::kReplicate)); + NUpdateNotifyOp::kReplicate)) // ---------- Copy old solid block ---------- { @@ -2047,21 +2291,27 @@ indexInFolder++; RINOK(opCallback->ReportOperation( NEventIndexType::kInArcIndex, (UInt32)fi, - NUpdateNotifyOp::kReplicate)); + NUpdateNotifyOp::kReplicate)) } } } } - UInt64 packSize = db->GetFolderFullPackSize(folderIndex); + const UInt64 packSize = db->GetFolderFullPackSize(folderIndex); RINOK(WriteRange(inStream, archive.SeqStream, - db->GetFolderStreamPos(folderIndex, 0), packSize, progress)); + db->GetFolderStreamPos(folderIndex, 0), packSize, progress)) lps->ProgressOffset += packSize; - + + const unsigned folderIndex_New = newDatabase.Folders.Size(); CFolder &folder = newDatabase.Folders.AddNew(); + // v23.01: we copy FolderCrc, if FolderCrc was used + if (db->FolderCRCs.ValidAndDefined(folderIndex)) + newDatabase.FolderUnpackCRCs.SetItem(folderIndex_New, + true, db->FolderCRCs.Vals[folderIndex]); + db->ParseFolderInfo(folderIndex, folder); - CNum startIndex = db->FoStartPackStreamIndex[folderIndex]; - FOR_VECTOR(j, folder.PackStreams) + const CNum startIndex = db->FoStartPackStreamIndex[folderIndex]; + FOR_VECTOR (j, folder.PackStreams) { newDatabase.PackSizes.Add(db->GetStreamPackSize(startIndex + j)); // newDatabase.PackCRCsDefined.Add(db.PackCRCsDefined[startIndex + j]); @@ -2069,7 +2319,7 @@ } size_t indexStart = db->FoToCoderUnpackSizes[folderIndex]; - size_t indexEnd = db->FoToCoderUnpackSizes[folderIndex + 1]; + const size_t indexEnd = db->FoToCoderUnpackSizes[folderIndex + 1]; for (; indexStart < indexEnd; indexStart++) newDatabase.CoderUnpackSizes.Add(db->CoderUnpackSizes[indexStart]); } @@ -2108,7 +2358,7 @@ if (file.HasStream) { indexInFolder++; - int updateIndex = fileIndexToUpdateIndexMap[fi]; + const int updateIndex = fileIndexToUpdateIndexMap[fi]; if (updateIndex >= 0 && !updateItems[(unsigned)updateIndex].NewData) needExtract = true; // decodeSize += file.Size; @@ -2130,7 +2380,6 @@ unsigned startPackIndex = newDatabase.PackSizes.Size(); UInt64 curUnpackSize; { - CMyComPtr sbInStream; CRepackStreamBase *repackBase; CFolderInStream2 *FosSpec2 = NULL; @@ -2138,13 +2387,13 @@ CRepackInStreamWithSizes *inStreamSizeCountSpec = new CRepackInStreamWithSizes; CMyComPtr inStreamSizeCount = inStreamSizeCountSpec; { - #ifndef _7ZIP_ST + #ifndef Z7_ST if (options.MultiThreadMixer) { repackBase = threadDecoder.FosSpec; CMyComPtr sbOutStream; sb.CreateStreams2(sbInStream, sbOutStream); - RINOK(sb.Create_ReInit()); + RINOK(sb.Create_ReInit()) threadDecoder.FosSpec->_stream = sbOutStream; @@ -2164,7 +2413,7 @@ sbInStream = FosSpec2; repackBase = FosSpec2; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO bool isEncrypted = false; bool passwordIsDefined = false; UString password; @@ -2173,7 +2422,7 @@ CMyComPtr decodedStream; bool dataAfterEnd_Error = false; - HRESULT res = threadDecoder.Decoder.Decode( + const HRESULT res = threadDecoder.Decoder.Decode( EXTERNAL_CODECS_LOC_VARS inStream, db->ArcInfo.DataStartPosition, // db->GetFolderStreamPos(folderIndex, 0);, @@ -2187,15 +2436,15 @@ &decodedStream , dataAfterEnd_Error - _7Z_DECODER_CRYPRO_VARS - #ifndef _7ZIP_ST + Z7_7Z_DECODER_CRYPRO_VARS + #ifndef Z7_ST , false // mtMode , 1 // numThreads , 0 // memUsage #endif ); - RINOK(res); + RINOK(res) if (!decodedStream) return E_FAIL; @@ -2207,12 +2456,12 @@ repackBase->_extractCallback = extractCallback; UInt32 startIndex = db->FolderStartFileIndex[folderIndex]; - RINOK(repackBase->Init(startIndex, &extractStatuses)); + RINOK(repackBase->Init(startIndex, &extractStatuses)) inStreamSizeCountSpec->_db = db; inStreamSizeCountSpec->Init(sbInStream, startIndex, &extractStatuses); - #ifndef _7ZIP_ST + #ifndef Z7_ST if (options.MultiThreadMixer) { WRes wres = threadDecoder.Start(); @@ -2222,20 +2471,29 @@ #endif } - curUnpackSize = sizeToEncode; + // curUnpackSize = sizeToEncode; - HRESULT encodeRes = encoder.Encode( + HRESULT encodeRes = encoder.Encode1( EXTERNAL_CODECS_LOC_VARS inStreamSizeCount, // NULL, &inSizeForReduce, - newDatabase.Folders.AddNew(), newDatabase.CoderUnpackSizes, curUnpackSize, + sizeToEncode, // expectedDataSize + newDatabase.Folders.AddNew(), + // newDatabase.CoderUnpackSizes, curUnpackSize, archive.SeqStream, newDatabase.PackSizes, progress); if (encodeRes == k_My_HRESULT_CRC_ERROR) return E_FAIL; - #ifndef _7ZIP_ST + curUnpackSize = inStreamSizeCountSpec->GetSize(); + + if (encodeRes == S_OK) + { + encoder.Encode_Post(curUnpackSize, newDatabase.CoderUnpackSizes); + } + + #ifndef Z7_ST if (options.MultiThreadMixer) { // 16.00: hang was fixed : for case if decoding was not finished. @@ -2244,12 +2502,12 @@ sbInStream.Release(); { - WRes wres = threadDecoder.WaitExecuteFinish(); + const WRes wres = threadDecoder.WaitExecuteFinish(); if (wres != 0) return HRESULT_FROM_WIN32(wres); } - HRESULT decodeRes = threadDecoder.Result; + const HRESULT decodeRes = threadDecoder.Result; // if (res == k_My_HRESULT_CRC_ERROR) if (decodeRes == S_FALSE || threadDecoder.dataAfterEnd_Error) { @@ -2260,12 +2518,12 @@ // NEventIndexType::kBlockIndex, (UInt32)folderIndex, (decodeRes != S_OK ? NExtract::NOperationResult::kDataError : - NExtract::NOperationResult::kDataAfterEnd))); + NExtract::NOperationResult::kDataAfterEnd))) } if (decodeRes != S_OK) return E_FAIL; } - RINOK(decodeRes); + RINOK(decodeRes) if (encodeRes == S_OK) if (sb.ProcessedSize != sizeToEncode) encodeRes = E_FAIL; @@ -2279,15 +2537,15 @@ { RINOK(extractCallback->ReportExtractResult( NEventIndexType::kBlockIndex, (UInt32)folderIndex, - NExtract::NOperationResult::kDataError)); + NExtract::NOperationResult::kDataError)) } return E_FAIL; } - RINOK(FosSpec2->Result); + RINOK(FosSpec2->Result) } - RINOK(encodeRes); - RINOK(repackBase->CheckFinishedState()); + RINOK(encodeRes) + RINOK(repackBase->CheckFinishedState()) if (curUnpackSize != sizeToEncode) return E_FAIL; @@ -2306,7 +2564,7 @@ if (db->Files[fi].HasStream) { indexInFolder++; - int updateIndex = fileIndexToUpdateIndexMap[fi]; + const int updateIndex = fileIndexToUpdateIndexMap[fi]; if (updateIndex >= 0) { const CUpdateItem &ui = updateItems[(unsigned)updateIndex]; @@ -2343,13 +2601,13 @@ // ---------- Compress files to new solid blocks ---------- - unsigned numFiles = group.Indices.Size(); + const unsigned numFiles = group.Indices.Size(); if (numFiles == 0) continue; CRecordVector refItems; refItems.ClearAndSetSize(numFiles); // bool sortByType = (options.UseTypeSorting && isSoid); // numSolidFiles > 1 - bool sortByType = options.UseTypeSorting; + const bool sortByType = options.UseTypeSorting; unsigned i; @@ -2365,7 +2623,7 @@ for (i = 0; i < numFiles; i++) { - UInt32 index = refItems[i].Index; + const UInt32 index = refItems[i].Index; indices[i] = index; /* const CUpdateItem &ui = updateItems[index]; @@ -2395,8 +2653,8 @@ break; if (options.SolidExtension) { - int slashPos = ui.Name.ReverseFind_PathSepar(); - int dotPos = ui.Name.ReverseFind_Dot(); + const int slashPos = ui.Name.ReverseFind_PathSepar(); + const int dotPos = ui.Name.ReverseFind_Dot(); const wchar_t *ext = ui.Name.Ptr(dotPos <= slashPos ? ui.Name.Len() : (unsigned)(dotPos + 1)); if (numSubFiles == 0) prevExtension = ext; @@ -2408,7 +2666,7 @@ if (numSubFiles < 1) numSubFiles = 1; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) /* const unsigned folderIndex = newDatabase.NumUnpackStreamsVector.Size(); @@ -2431,31 +2689,45 @@ inStreamSpec->Need_ATime = options.Need_ATime; inStreamSpec->Need_MTime = options.Need_MTime; inStreamSpec->Need_Attrib = options.Need_Attrib; + // inStreamSpec->Need_Crc = options.Need_Crc; inStreamSpec->Init(updateCallback, &indices[i], numSubFiles); unsigned startPackIndex = newDatabase.PackSizes.Size(); - UInt64 curFolderUnpackSize = totalSize; + // UInt64 curFolderUnpackSize = totalSize; // curFolderUnpackSize = (UInt64)(Int64)-1; // for debug + const UInt64 expectedDataSize = totalSize; + + // const unsigned folderIndex_New = newDatabase.Folders.Size(); - RINOK(encoder.Encode( + RINOK(encoder.Encode1( EXTERNAL_CODECS_LOC_VARS solidInStream, // NULL, &inSizeForReduce, - newDatabase.Folders.AddNew(), newDatabase.CoderUnpackSizes, curFolderUnpackSize, - archive.SeqStream, newDatabase.PackSizes, progress)); + expectedDataSize, // expected size + newDatabase.Folders.AddNew(), + // newDatabase.CoderUnpackSizes, curFolderUnpackSize, + archive.SeqStream, newDatabase.PackSizes, progress)) if (!inStreamSpec->WasFinished()) return E_FAIL; + /* + if (inStreamSpec->Need_FolderCrc) + newDatabase.FolderUnpackCRCs.SetItem(folderIndex_New, + true, inStreamSpec->GetFolderCrc()); + */ + + const UInt64 curFolderUnpackSize = inStreamSpec->Get_TotalSize_for_Coder(); + encoder.Encode_Post(curFolderUnpackSize, newDatabase.CoderUnpackSizes); + UInt64 packSize = 0; // const UInt32 numStreams = newDatabase.PackSizes.Size() - startPackIndex; for (; startPackIndex < newDatabase.PackSizes.Size(); startPackIndex++) packSize += newDatabase.PackSizes[startPackIndex]; lps->OutSize += packSize; - lps->InSize += curFolderUnpackSize; // for () // newDatabase.PackCRCsDefined.Add(false); // newDatabase.PackCRCs.Add(0); @@ -2496,14 +2768,15 @@ // name += ".locked"; // for debug } + // if (inStreamSpec->Need_Crc) file.Crc = inStreamSpec->CRCs[subIndex]; file.Size = inStreamSpec->Sizes[subIndex]; procSize += file.Size; - // if (file.Size >= 0) // test purposes + // if (file.Size >= 0) // for debug: test purposes if (file.Size != 0) { - file.CrcDefined = true; + file.CrcDefined = true; // inStreamSpec->Need_Crc; file.HasStream = true; numUnpackStreams++; } @@ -2549,9 +2822,66 @@ newDatabase.AddFile(file, file2, name); } + /* + // for debug: + // we can write crc to folders area, if folder contains only one file + if (numUnpackStreams == 1 && numSubFiles == 1) + { + const CFileItem &file = newDatabase.Files.Back(); + if (file.CrcDefined) + newDatabase.FolderUnpackCRCs.SetItem(folderIndex_New, true, file.Crc); + } + */ + + /* // it's optional check to ensure that sizes are correct - if (procSize != curFolderUnpackSize) + if (inStreamSpec->TotalSize_for_Coder != curFolderUnpackSize) return E_FAIL; + */ + // if (inStreamSpec->AlignLog == 0) + { + if (procSize != curFolderUnpackSize) + return E_FAIL; + } + // else + { + /* + { + const CFolder &old = newDatabase.Folders.Back(); + CFolder &folder = newDatabase.Folders.AddNew(); + { + const unsigned numBonds = old.Bonds.Size(); + folder.Bonds.SetSize(numBonds + 1); + for (unsigned k = 0; k < numBonds; k++) + folder.Bonds[k] = old.Bonds[k]; + CBond &bond = folder.Bonds[numBonds]; + bond.PackIndex = 0; + bond.UnpackIndex = 0; + } + { + const unsigned numCoders = old.Coders.Size(); + folder.Coders.SetSize(numCoders + 1); + for (unsigned k = 0; k < numCoders; k++) + folder.Coders[k] = old.Coders[k]; + CCoderInfo &cod = folder.Coders[numCoders]; + cod.Props.Alloc(1); + cod.Props[0] = (Byte)inStreamSpec->AlignLog; + cod.NumStreams = 1; + } + { + const unsigned numPackStreams = old.Coders.Size(); + folder.Coders.SetSize(numPackStreams); + for (unsigned k = 0; k < numPackStreams; k++) + folder.PackStreams[k] = old.PackStreams[k]; + } + } + newDatabase.Folders.Delete(newDatabase.Folders.Size() - 2); + */ + } + + + lps->InSize += procSize; + // lps->InSize += curFolderUnpackSize; // numUnpackStreams = 0 is very bad case for locked files // v3.13 doesn't understand it. @@ -2561,7 +2891,7 @@ if (skippedSize != 0 && complexity >= skippedSize) { complexity -= skippedSize; - RINOK(updateCallback->SetTotal(complexity)); + RINOK(updateCallback->SetTotal(complexity)) } /* @@ -2604,7 +2934,7 @@ } } - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) /* fileIndexToUpdateIndexMap.ClearAndFree(); @@ -2634,10 +2964,26 @@ } } */ + + { + const unsigned numFolders = newDatabase.Folders.Size(); + if (newDatabase.NumUnpackStreamsVector.Size() != numFolders + || newDatabase.FolderUnpackCRCs.Defs.Size() > numFolders) + return E_FAIL; + newDatabase.FolderUnpackCRCs.if_NonEmpty_FillResedue_with_false(numFolders); + } + + updateItems.ClearAndFree(); newDatabase.ReserveDown(); if (opCallback) - RINOK(opCallback->ReportOperation(NEventIndexType::kNoIndex, (UInt32)(Int32)-1, NUpdateNotifyOp::kHeader)); + RINOK(opCallback->ReportOperation(NEventIndexType::kNoIndex, (UInt32)(Int32)-1, NUpdateNotifyOp::kHeader)) + + RINOK(archive.WriteDatabase(EXTERNAL_CODECS_LOC_VARS + newDatabase, options.HeaderMethod, options.HeaderOptions)) + + if (v_StreamSetRestriction) + RINOK(v_StreamSetRestriction->SetRestriction(0, 0)) return S_OK; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zUpdate.h 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zUpdate.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/7zUpdate.h 2022-02-06 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/7zUpdate.h 2023-05-11 16:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // 7zUpdate.h -#ifndef __7Z_UPDATE_H -#define __7Z_UPDATE_H +#ifndef ZIP7_INC_7Z_UPDATE_H +#define ZIP7_INC_7Z_UPDATE_H #include "../IArchive.h" @@ -9,7 +9,6 @@ #include "7zCompressionMode.h" #include "7zIn.h" -#include "7zOut.h" namespace NArchive { namespace N7z { @@ -95,8 +94,6 @@ bool MaxFilter; // use BCJ2 filter instead of BCJ int AnalysisLevel; - CHeaderOptions HeaderOptions; - UInt64 NumSolidFiles; UInt64 NumSolidBytes; bool SolidExtension; @@ -110,6 +107,9 @@ bool Need_ATime; bool Need_MTime; bool Need_Attrib; + // bool Need_Crc; + + CHeaderOptions HeaderOptions; CUpdateOptions(): Method(NULL), @@ -127,6 +127,7 @@ Need_ATime(false), Need_MTime(false), Need_Attrib(false) + // , Need_Crc(true) {} }; @@ -134,18 +135,12 @@ DECL_EXTERNAL_CODECS_LOC_VARS IInStream *inStream, const CDbEx *db, - const CObjectVector &updateItems, + CObjectVector &updateItems, // const CObjectVector &treeFolders, // treeFolders[0] is root // const CUniqBlocks &secureBlocks, - COutArchive &archive, - CArchiveDatabaseOut &newDatabase, ISequentialOutStream *seqOutStream, IArchiveUpdateCallback *updateCallback, - const CUpdateOptions &options - #ifndef _NO_CRYPTO - , ICryptoGetTextPassword *getDecoderPassword - #endif - ); + const CUpdateOptions &options); }} #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/makefile 7zip-23.01+dfsg/CPP/7zip/Archive/7z/makefile --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/makefile 2015-10-18 10:02:45.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/makefile 2023-04-04 20:00:00.000000000 +0000 @@ -1,11 +1,11 @@ PROG = 7z.dll DEF_FILE = ../Archive.def CFLAGS = $(CFLAGS) \ - -DEXTERNAL_CODECS \ + -DZ7_EXTERNAL_CODECS \ AR_OBJS = \ $O\ArchiveExports.obj \ - $O\DllExports.obj \ + $O\DllExports2.obj \ 7Z_OBJS = \ $O\7zCompressionMode.obj \ @@ -34,7 +34,6 @@ $O\Wildcard.obj \ WIN_OBJS = \ - $O\DLL.obj \ $O\FileDir.obj \ $O\FileFind.obj \ $O\FileIO.obj \ @@ -61,6 +60,7 @@ COMPRESS_OBJS = \ $O\CopyCoder.obj \ + $O\CodecExports.obj \ AR_COMMON_OBJS = \ $O\CoderMixer2.obj \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/7z/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Archive/7z/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/7z/StdAfx.h 2013-11-24 12:59:55.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/7z/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/ApfsHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/ApfsHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/ApfsHandler.cpp 2022-07-11 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/ApfsHandler.cpp 2023-04-07 10:00:00.000000000 +0000 @@ -12,9 +12,11 @@ #endif #include "../../../C/CpuArch.h" +#include "../../../C/Sha256.h" #include "../../Common/ComTry.h" #include "../../Common/IntToString.h" +#include "../../Common/MyBuffer2.h" #include "../../Common/MyLinux.h" #include "../../Common/UTFConvert.h" @@ -87,7 +89,8 @@ typedef UInt64 oid_t; typedef UInt64 xid_t; -typedef Int64 paddr_t; +// typedef Int64 paddr_t; +typedef UInt64 paddr_t_unsigned; #define G64o G64 #define G64x G64 @@ -140,8 +143,10 @@ #define OBJECT_TYPE_GBITMAP_BLOCK 0x1b #define OBJECT_TYPE_ER_RECOVERY_BLOCK 0x1c #define OBJECT_TYPE_SNAP_META_EXT 0x1d +*/ #define OBJECT_TYPE_INTEGRITY_META 0x1e #define OBJECT_TYPE_FEXT_TREE 0x1f +/* #define OBJECT_TYPE_RESERVED_20 0x20 #define OBJECT_TYPE_INVALID 0x0 @@ -152,8 +157,9 @@ #define OBJ_VIRTUAL 0x0 #define OBJ_EPHEMERAL 0x80000000 +*/ #define OBJ_PHYSICAL 0x40000000 - +/* #define OBJ_NOHEADER 0x20000000 #define OBJ_ENCRYPTED 0x10000000 #define OBJ_NONPERSISTENT 0x08000000 @@ -167,6 +173,8 @@ // #define MAX_CKSUM_SIZE 8 +static const unsigned k_obj_phys_Size = 0x20; + // obj_phys_t struct CPhys { @@ -183,10 +191,10 @@ void CPhys::Parse(const Byte *p) { // memcpy(cksum, p, MAX_CKSUM_SIZE); - G64o (8, oid); - G64x (0x10, xid); - G32 (0x18, type); - G32 (0x1C, subtype); + G64o (8, oid) + G64x (0x10, xid) + G32 (0x18, type) + G32 (0x1C, subtype) } #define NX_MAX_FILE_SYSTEMS 100 @@ -216,7 +224,9 @@ #define APFS_INCOMPAT_NORMALIZATION_INSENSITIVE (1 << 3) /* #define APFS_INCOMPAT_INCOMPLETE_RESTORE (1 << 4) +*/ #define APFS_INCOMPAT_SEALED_VOLUME (1 << 5) +/* #define APFS_INCOMPAT_RESERVED_40 (1 << 6) */ @@ -301,7 +311,7 @@ { for (unsigned i = 0; i < NX_MAX_FILE_SYSTEMS; i++) { - G64o (0xb8 + i * 8, fs_oid[i]); + G64o (0xb8 + i * 8, fs_oid[i]) } } }; @@ -369,17 +379,18 @@ if (!CheckFletcher64(p, kApfsHeaderSize)) return false; - G32 (0x24, block_size); + G32 (0x24, block_size) { - unsigned logSize = GetLogSize(block_size); + const unsigned logSize = GetLogSize(block_size); + // don't change it. Some code requires (block_size <= 16) if (logSize < 12 || logSize > 16) return false; block_size_Log = logSize; } - G64 (0x28, block_count); + G64 (0x28, block_count) - static const UInt64 kArcSize_MAX = (UInt64)1 << 62; + const UInt64 kArcSize_MAX = (UInt64)1 << 62; if (block_count > (kArcSize_MAX >> block_size_Log)) return false; @@ -402,10 +413,10 @@ G32 (0x94, xp_data_len); G64o (0x98, spaceman_oid); */ - G64o (0xa0, omap_oid); + G64o (0xa0, omap_oid) // G64o (0xa8, reaper_oid); // G32 (0xb0, test_type); - G32 (0xb4, max_file_systems); + G32 (0xb4, max_file_systems) if (max_file_systems > NX_MAX_FILE_SYSTEMS) return false; /* @@ -448,6 +459,87 @@ } +enum apfs_hash_type_t +{ + APFS_HASH_INVALID = 0, + APFS_HASH_SHA256 = 1, + APFS_HASH_SHA512_256 = 2, + APFS_HASH_SHA384 = 3, + APFS_HASH_SHA512 = 4, + + APFS_HASH_MIN = APFS_HASH_SHA256, + APFS_HASH_MAX = APFS_HASH_SHA512, + + APFS_HASH_DEFAULT = APFS_HASH_SHA256 +}; + +static unsigned GetHashSize(unsigned hashType) +{ + if (hashType > APFS_HASH_MAX) return 0; + if (hashType < APFS_HASH_MIN) return 0; + if (hashType == APFS_HASH_SHA256) return 32; + return hashType * 16; +} + +#define APFS_HASH_MAX_SIZE 64 + +static const char * const g_hash_types[] = +{ + NULL + , "SHA256" + , "SHA512_256" + , "SHA384" + , "SHA512" +}; + + +struct C_integrity_meta_phys +{ + // CPhys im_o; + // UInt32 im_version; + UInt32 im_flags; + // apfs_hash_type_t + UInt32 im_hash_type; + // UInt32 im_root_hash_offset; + // xid_t im_broken_xid; + // UInt64 im_reserved[9]; + + unsigned HashSize; + Byte Hash[APFS_HASH_MAX_SIZE]; + + bool Is_SHA256() const { return im_hash_type == APFS_HASH_SHA256; } + + C_integrity_meta_phys() + { + memset(this, 0, sizeof(*this)); + } + bool Parse(const Byte *p, size_t size, oid_t oid); +}; + +bool C_integrity_meta_phys::Parse(const Byte *p, size_t size, oid_t oid) +{ + CPhys o; + if (!CheckFletcher64(p, size)) + return false; + o.Parse(p); + if (o.GetType() != OBJECT_TYPE_INTEGRITY_META) + return false; + if (o.oid != oid) + return false; + // G32 (0x20, im_version); + G32 (0x24, im_flags) + G32 (0x28, im_hash_type) + UInt32 im_root_hash_offset; + G32 (0x2C, im_root_hash_offset) + // G64x (0x30, im_broken_xid); + const unsigned hashSize = GetHashSize(im_hash_type); + HashSize = hashSize; + if (im_root_hash_offset >= size || size - im_root_hash_offset < hashSize) + return false; + memcpy(Hash, p + im_root_hash_offset, hashSize); + return true; +} + struct C_omap_phys { @@ -485,7 +577,7 @@ G32 (0x28, tree_type); G32 (0x2C, snapshot_tree_type); */ - G64o (0x30, tree_oid); + G64o (0x30, tree_oid) /* G64o (0x38, snapshot_tree_oid); G64x (0x40, most_recent_snap); @@ -509,8 +601,8 @@ void Parse(const Byte *p) { - G16 (0, off); - G16 (2, len); + G16 (0, off) + G16 (2, len) } UInt32 GetEnd() const { return (UInt32)off + len; } bool CheckOverLimit(UInt32 limit) @@ -542,8 +634,8 @@ void Parse(const Byte *p) { - G16 (0, k); - G16 (2, v); + G16 (0, k) + G16 (2, v) } }; @@ -551,9 +643,9 @@ #define BTNODE_ROOT (1 << 0) #define BTNODE_LEAF (1 << 1) #define BTNODE_FIXED_KV_SIZE (1 << 2) -/* #define BTNODE_HASHED (1 << 3) #define BTNODE_NOHEADER (1 << 4) +/* #define BTNODE_CHECK_KOFF_INVAL (1 << 15) */ @@ -563,7 +655,7 @@ struct CBTreeNodePhys { // btn_ prefix - CPhys o; + CPhys ophys; UInt16 flags; UInt16 level; // the number of child levels below this node. 0 - for a leaf node, 1 for the immediate parent of a leaf node UInt32 nkeys; // The number of keys stored in this node. @@ -575,21 +667,35 @@ */ bool Is_FIXED_KV_SIZE() const { return (flags & BTNODE_FIXED_KV_SIZE) != 0; } + bool Is_NOHEADER() const { return (flags & BTNODE_NOHEADER) != 0; } + bool Is_HASHED() const { return (flags & BTNODE_HASHED) != 0; } - bool Parse(const Byte *p, size_t size) + bool Parse(const Byte *p, size_t size, bool noHeader = false) { - if (!CheckFletcher64(p, size)) - return false; - o.Parse(p); - G16 (0x20, flags); - G16 (0x22, level); - G32 (0x24, nkeys); + G16 (0x20, flags) + G16 (0x22, level) + G32 (0x24, nkeys) table_space.Parse(p + 0x28); /* free_space.Parse(p + 0x2C); key_free_list.Parse(p + 0x30); val_free_list.Parse(p + 0x34); */ + memset(&ophys, 0, sizeof(ophys)); + if (noHeader) + { + for (unsigned i = 0; i < k_obj_phys_Size; i++) + if (p[i] != 0) + return false; + } + else + { + if (!CheckFletcher64(p, size)) + return false; + ophys.Parse(p); + } + if (Is_NOHEADER() != noHeader) + return false; return true; } }; @@ -606,6 +712,7 @@ #define BTREE_KV_NONALIGNED (1 << 6) #define BTREE_HASHED (1 << 7) */ +#define BTREE_NOHEADER (1 << 8) /* BTREE_EPHEMERAL: The nodes in the B-tree use ephemeral object identifiers to link to child nodes @@ -624,10 +731,10 @@ void Parse(const Byte *p) { - G32 (0, flags); - G32 (4, node_size); - G32 (8, key_size); - G32 (12, val_size); + G32 (0, flags) + G32 (4, node_size) + G32 (8, key_size) + G32 (12, val_size) } }; @@ -643,14 +750,15 @@ bool Is_EPHEMERAL() const { return (fixed.flags & BTREE_EPHEMERAL) != 0; } bool Is_PHYSICAL() const { return (fixed.flags & BTREE_PHYSICAL) != 0; } + bool Is_NOHEADER() const { return (fixed.flags & BTREE_NOHEADER) != 0; } void Parse(const Byte *p) { fixed.Parse(p); - G32 (0x10, longest_key); - G32 (0x14, longest_val); - G64 (0x18, key_count); - G64 (0x20, node_count); + G32 (0x10, longest_key) + G32 (0x14, longest_val) + G64 (0x18, key_count) + G64 (0x20, node_count) } }; @@ -685,7 +793,7 @@ #define APFS_MODIFIED_NAMELEN 32 -#define sizeof__apfs_modified_by_t (APFS_MODIFIED_NAMELEN + 16); +#define sizeof_apfs_modified_by_t (APFS_MODIFIED_NAMELEN + 16) struct apfs_modified_by_t { @@ -697,8 +805,8 @@ { memcpy(id, p, APFS_MODIFIED_NAMELEN); p += APFS_MODIFIED_NAMELEN; - G64 (0, timestamp); - G64x (8, last_xid); + G64 (0, timestamp) + G64x (8, last_xid) } }; @@ -711,7 +819,7 @@ // apfs_ CPhys o; // UInt32 magic; - UInt32 fs_index; // e index of the object identifier for this volume's file system in the container's array of file systems. + UInt32 fs_index; // index of the object identifier for this volume's file system in the container's array of file systems. // UInt64 features; // UInt64 readonly_compatible_features; UInt64 incompatible_features; @@ -759,9 +867,11 @@ UInt64 cloneinfo_xid; oid_t snap_meta_ext_oid; CUuid volume_group_id; - oid_t integrity_meta_oid; - oid_t fext_tree_oid; - UInt32 fext_tree_type; + */ + oid_t integrity_meta_oid; // virtual object identifier of the integrity metadata object + oid_t fext_tree_oid; // virtual object identifier of the file extent tree. + UInt32 fext_tree_type; // The type of the file extent tree. + /* UInt32 reserved_type; oid_t reserved_oid; */ @@ -793,21 +903,21 @@ return false; // if (o.GetType() != OBJECT_TYPE_NX_SUPERBLOCK) return false; - G32 (0x24, fs_index); + G32 (0x24, fs_index) // G64 (0x28, features); // G64 (0x30, readonly_compatible_features); - G64 (0x38, incompatible_features); - G64 (0x40, unmount_time); + G64 (0x38, incompatible_features) + G64 (0x40, unmount_time) // G64 (0x48, fs_reserve_block_count); // G64 (0x50, fs_quota_block_count); - G64 (0x58, fs_alloc_count); + G64 (0x58, fs_alloc_count) // meta_crypto.Parse(p + 0x60); // G32 (0x74, root_tree_type); // G32 (0x78, extentref_tree_type); // G32 (0x7C, snap_meta_tree_type); - G64o (0x80, omap_oid); - G64o (0x88, root_tree_oid); + G64o (0x80, omap_oid) + G64o (0x88, root_tree_oid) /* G64o (0x90, extentref_tree_oid); G64o (0x98, snap_meta_tree_oid); @@ -815,23 +925,23 @@ G64o (0xa8, revert_to_sblock_oid); G64 (0xb0, next_obj_id); */ - G64 (0xb8, num_files); - G64 (0xc0, num_directories); - G64 (0xc8, num_symlinks); - G64 (0xd0, num_other_fsobjects); - G64 (0xd8, num_snapshots); - G64 (0xe0, total_blocks_alloced); - G64 (0xe8, total_blocks_freed); + G64 (0xb8, num_files) + G64 (0xc0, num_directories) + G64 (0xc8, num_symlinks) + G64 (0xd0, num_other_fsobjects) + G64 (0xd8, num_snapshots) + G64 (0xe0, total_blocks_alloced) + G64 (0xe8, total_blocks_freed) vol_uuid.SetFrom(p + 0xf0); - G64 (0x100, last_mod_time); - G64 (0x108, fs_flags); + G64 (0x100, last_mod_time) + G64 (0x108, fs_flags) p += 0x110; formatted_by.Parse(p); - p += sizeof__apfs_modified_by_t; + p += sizeof_apfs_modified_by_t; for (unsigned i = 0; i < APFS_MAX_HIST; i++) { modified_by[i].Parse(p); - p += sizeof__apfs_modified_by_t; + p += sizeof_apfs_modified_by_t; } memcpy(volname, p, APFS_VOLNAME_LEN); p += APFS_VOLNAME_LEN; @@ -845,9 +955,11 @@ G64 (0x20, cloneinfo_xid); G64o (0x28, snap_meta_ext_oid); volume_group_id.SetFrom(p + 0x30); - G64o (0x40, integrity_meta_oid); - G64o (0x48, fext_tree_oid); - G32 (0x50, fext_tree_type); + */ + G64o (0x40, integrity_meta_oid) + G64o (0x48, fext_tree_oid) + G32 (0x50, fext_tree_type) + /* G32 (0x54, reserved_type); G64o (0x58, reserved_oid); */ @@ -888,7 +1000,7 @@ { UInt64 obj_id_and_type; - void Parse(const Byte *p) { G64(0, obj_id_and_type); } + void Parse(const Byte *p) { G64(0, obj_id_and_type) } unsigned GetType() const { return (unsigned)(obj_id_and_type >> OBJ_TYPE_SHIFT); } UInt64 GetID() const { return obj_id_and_type & OBJ_ID_MASK; } }; @@ -918,9 +1030,9 @@ // uint8_t xfields[]; void Parse(const Byte *p) { - G64 (0, file_id); - G64 (8, date_added); - G16 (0x10, flags); + G64 (0, file_id) + G64 (8, date_added) + G16 (0x10, flags) } }; @@ -959,8 +1071,8 @@ #define UNIFIED_ID_SPACE_MARK 0x0800000000000000 */ -typedef enum -{ +//typedef enum +// { /* INODE_IS_APFS_PRIVATE = 0x00000001, INODE_MAINTAIN_DIR_STATS = 0x00000002, @@ -977,13 +1089,13 @@ INODE_PINNED_TO_MAIN = 0x00001000, INODE_PINNED_TO_TIER2 = 0x00002000, */ -INODE_HAS_RSRC_FORK = 0x00004000, +// INODE_HAS_RSRC_FORK = 0x00004000, /* INODE_NO_RSRC_FORK = 0x00008000, INODE_ALLOCATION_SPILLEDOVER = 0x00010000, INODE_FAST_PROMOTE = 0x00020000, */ -INODE_HAS_UNCOMPRESSED_SIZE = 0x00040000, +#define INODE_HAS_UNCOMPRESSED_SIZE 0x00040000 /* INODE_IS_PURGEABLE = 0x00080000, INODE_WANTS_TO_BE_PURGEABLE = 0x00100000, @@ -1001,8 +1113,8 @@ | INODE_HAS_FINDER_INFO \ | INODE_SNAPSHOT_COW_EXEMPTION), */ -} -j_inode_flags; +// } +// j_inode_flags; /* @@ -1063,24 +1175,24 @@ // bsd stat.h /* -#define MY__UF_SETTABLE 0x0000ffff // mask of owner changeable flags -#define MY__UF_NODUMP 0x00000001 // do not dump file -#define MY__UF_IMMUTABLE 0x00000002 // file may not be changed -#define MY__UF_APPEND 0x00000004 // writes to file may only append -#define MY__UF_OPAQUE 0x00000008 // directory is opaque wrt. union -#define MY__UF_NOUNLINK 0x00000010 // file entry may not be removed or renamed Not implement in MacOS -#define MY__UF_COMPRESSED 0x00000020 // file entry is compressed -#define MY__UF_TRACKED 0x00000040 // notify about file entry changes -#define MY__UF_DATAVAULT 0x00000080 // entitlement required for reading and writing -#define MY__UF_HIDDEN 0x00008000 // file entry is hidden - -#define MY__SF_SETTABLE 0xffff0000 // mask of superuser changeable flags -#define MY__SF_ARCHIVED 0x00010000 // file is archived -#define MY__SF_IMMUTABLE 0x00020000 // file may not be changed -#define MY__SF_APPEND 0x00040000 // writes to file may only append -#define MY__SF_RESTRICTED 0x00080000 // entitlement required for writing -#define MY__SF_NOUNLINK 0x00100000 // file entry may not be removed, renamed or used as mount point -#define MY__SF_SNAPSHOT 0x00200000 // snapshot inode +#define MY_UF_SETTABLE 0x0000ffff // mask of owner changeable flags +#define MY_UF_NODUMP 0x00000001 // do not dump file +#define MY_UF_IMMUTABLE 0x00000002 // file may not be changed +#define MY_UF_APPEND 0x00000004 // writes to file may only append +#define MY_UF_OPAQUE 0x00000008 // directory is opaque wrt. union +#define MY_UF_NOUNLINK 0x00000010 // file entry may not be removed or renamed Not implement in MacOS +#define MY_UF_COMPRESSED 0x00000020 // file entry is compressed +#define MY_UF_TRACKED 0x00000040 // notify about file entry changes +#define MY_UF_DATAVAULT 0x00000080 // entitlement required for reading and writing +#define MY_UF_HIDDEN 0x00008000 // file entry is hidden + +#define MY_SF_SETTABLE 0xffff0000 // mask of superuser changeable flags +#define MY_SF_ARCHIVED 0x00010000 // file is archived +#define MY_SF_IMMUTABLE 0x00020000 // file may not be changed +#define MY_SF_APPEND 0x00040000 // writes to file may only append +#define MY_SF_RESTRICTED 0x00080000 // entitlement required for writing +#define MY_SF_NOUNLINK 0x00100000 // file entry may not be removed, renamed or used as mount point +#define MY_SF_SNAPSHOT 0x00200000 // snapshot inode Not implement in MacOS */ @@ -1142,11 +1254,11 @@ void Parse(const Byte *p) { - G64 (0, size); - G64 (0x8, alloced_size); - G64 (0x10, default_crypto_id); - G64 (0x18, total_bytes_written); - G64 (0x20, total_bytes_read); + G64 (0, size) + G64 (0x8, alloced_size) + G64 (0x10, default_crypto_id) + G64 (0x18, total_bytes_written) + G64 (0x20, total_bytes_read) } }; @@ -1167,8 +1279,8 @@ void Parse(const Byte *p) { - G64 (0, len_and_flags); - G64 (0x8, phys_block_num); + G64 (0, len_and_flags) + G64 (0x8, phys_block_num) // G64 (0x10, crypto_id); } }; @@ -1180,12 +1292,14 @@ UInt64 len_and_flags; // The length must be a multiple of the block size defined by the nx_block_size field of nx_superblock_t. // There are currently no flags defined UInt64 phys_block_num; // The physical block address that the extent starts at + + UInt64 GetEndOffset() const { return logical_offset + EXTENT_GET_LEN(len_and_flags); } }; -typedef UInt32 MY__uid_t; -typedef UInt32 MY__gid_t; -typedef UInt16 MY__mode_t; +typedef UInt32 MY_uid_t; +typedef UInt32 MY_gid_t; +typedef UInt16 MY_mode_t; typedef enum @@ -1262,9 +1376,9 @@ // cp_key_class_t default_protection_class; UInt32 write_generation_counter; UInt32 bsd_flags; - MY__uid_t owner; - MY__gid_t group; - MY__mode_t mode; + MY_uid_t owner; + MY_gid_t group; + MY_mode_t mode; UInt16 pad1; UInt64 uncompressed_size; @@ -1376,32 +1490,32 @@ { CRecordVector Extents; // UInt32 NumLinks; - // CSmallNode(): NumLinks(0) {}; + // CSmallNode(): NumLinks(0) {} }; static const unsigned k_SizeOf_j_inode_val = 0x5c; void CNode::Parse(const Byte *p) { - G64 (0, parent_id); - G64 (0x8, private_id); - G64 (0x10, create_time); - G64 (0x18, mod_time); - G64 (0x20, change_time); - G64 (0x28, access_time); - G64 (0x30, internal_flags); + G64 (0, parent_id) + G64 (0x8, private_id) + G64 (0x10, create_time) + G64 (0x18, mod_time) + G64 (0x20, change_time) + G64 (0x28, access_time) + G64 (0x30, internal_flags) { - G32 (0x38, nchildren); + G32 (0x38, nchildren) // G32 (0x38, nlink); } // G32 (0x3c, default_protection_class); - G32 (0x40, write_generation_counter); - G32 (0x44, bsd_flags); - G32 (0x48, owner); - G32 (0x4c, group); - G16 (0x50, mode); + G32 (0x40, write_generation_counter) + G32 (0x44, bsd_flags) + G32 (0x48, owner) + G32 (0x4c, group) + G16 (0x50, mode) // G16 (0x52, pad1); - G64 (0x54, uncompressed_size); + G64 (0x54, uncompressed_size) } @@ -1414,10 +1528,10 @@ #ifdef APFS_SHOW_ALT_STREAMS unsigned AttrIndex; bool IsAltStream() const { return IsViDef(AttrIndex); } - unsigned GetAttrIndex() const { return AttrIndex; }; + unsigned GetAttrIndex() const { return AttrIndex; } #else // bool IsAltStream() const { return false; } - unsigned GetAttrIndex() const { return VI_MINUS1; }; + unsigned GetAttrIndex() const { return VI_MINUS1; } #endif }; @@ -1429,6 +1543,128 @@ }; +struct CHashChunk +{ + UInt64 lba; + UInt32 hashed_len; // the value is UInt16 + Byte hash[APFS_HASH_MAX_SIZE]; +}; + +typedef CRecordVector CStreamHashes; + + +Z7_CLASS_IMP_NOQIB_1( + COutStreamWithHash + , ISequentialOutStream +) + bool _hashError; + CAlignedBuffer1 _sha; + CMyComPtr _stream; + const CStreamHashes *_hashes; + unsigned _blockSizeLog; + unsigned _chunkIndex; + UInt32 _offsetInChunk; + // UInt64 _size; + + CSha256 *Sha() { return (CSha256 *)(void *)(Byte *)_sha; } +public: + COutStreamWithHash(): _sha(sizeof(CSha256)) {} + + void SetStream(ISequentialOutStream *stream) { _stream = stream; } + // void ReleaseStream() { _stream.Release(); } + void Init(const CStreamHashes *hashes, unsigned blockSizeLog) + { + _hashes = hashes; + _blockSizeLog = blockSizeLog; + _chunkIndex = 0; + _offsetInChunk = 0; + _hashError = false; + // _size = 0; + } + // UInt64 GetSize() const { return _size; } + bool FinalCheck(); +}; + + +static bool Sha256_Final_and_CheckDigest(CSha256 *sha256, const Byte *digest) +{ + MY_ALIGN (16) + UInt32 temp[SHA256_NUM_DIGEST_WORDS]; + Sha256_Final(sha256, (Byte *)temp); + return memcmp(temp, digest, SHA256_DIGEST_SIZE) == 0; +} + + +Z7_COM7F_IMF(COutStreamWithHash::Write(const void *data, UInt32 size, UInt32 *processedSize)) +{ + HRESULT result = S_OK; + if (_stream) + result = _stream->Write(data, size, &size); + if (processedSize) + *processedSize = size; + while (size != 0) + { + if (_hashError) + break; + if (_chunkIndex >= _hashes->Size()) + { + _hashError = true; + break; + } + if (_offsetInChunk == 0) + Sha256_Init(Sha()); + const CHashChunk &chunk = (*_hashes)[_chunkIndex]; + /* (_blockSizeLog <= 16) && chunk.hashed_len is 16-bit. + so we can use 32-bit chunkSize here */ + const UInt32 chunkSize = ((UInt32)chunk.hashed_len << _blockSizeLog); + const UInt32 rem = chunkSize - _offsetInChunk; + UInt32 cur = size; + if (cur > rem) + cur = (UInt32)rem; + Sha256_Update(Sha(), (const Byte *)data, cur); + data = (const void *)((const Byte *)data + cur); + size -= cur; + // _size += cur; + _offsetInChunk += cur; + if (chunkSize == _offsetInChunk) + { + if (!Sha256_Final_and_CheckDigest(Sha(), chunk.hash)) + _hashError = true; + _offsetInChunk = 0; + _chunkIndex++; + } + } + return result; +} + + +bool COutStreamWithHash::FinalCheck() +{ + if (_hashError) + return false; + + if (_offsetInChunk != 0) + { + const CHashChunk &chunk = (*_hashes)[_chunkIndex]; + { + const UInt32 chunkSize = ((UInt32)chunk.hashed_len << _blockSizeLog); + const UInt32 rem = chunkSize - _offsetInChunk; + Byte b = 0; + for (UInt32 i = 0; i < rem; i++) + Sha256_Update(Sha(), &b, 1); + } + if (!Sha256_Final_and_CheckDigest(Sha(), chunk.hash)) + _hashError = true; + _offsetInChunk = 0; + _chunkIndex++; + } + if (_chunkIndex != _hashes->Size()) + _hashError = true; + return !_hashError; +} + + + struct CVol { CObjectVector Nodes; @@ -1439,13 +1675,22 @@ CObjectVector SmallNodes; CRecordVector SmallNodeIDs; + CObjectVector FEXT_Nodes; + CRecordVector FEXT_NodeIDs; + + CObjectVector Hash_Vectors; + CRecordVector Hash_IDs; + unsigned StartRef2Index; // ref2_Index for Refs[0] item unsigned RootRef2Index; // ref2_Index of virtual root folder (Volume1) CApfs apfs; + C_integrity_meta_phys integrity; + bool NodeNotFound; bool ThereAreUnlinkedNodes; bool WrongInodeLink; bool UnsupportedFeature; + bool UnsupportedMethod; unsigned NumItems_In_PrivateDir; unsigned NumAltStreams; @@ -1468,6 +1713,7 @@ ThereAreUnlinkedNodes(false), WrongInodeLink(false), UnsupportedFeature(false), + UnsupportedMethod(false), NumItems_In_PrivateDir(0), NumAltStreams(0) {} @@ -1479,7 +1725,7 @@ const UInt64 s = apfsTime / 1000000000; const UInt32 ns = (UInt32)(apfsTime % 1000000000); ns100 = (ns % 100); - const UInt64 v = NWindows::NTime::UnixTime64_To_FileTime64(s) + ns / 100; + const UInt64 v = NWindows::NTime::UnixTime64_To_FileTime64((Int64)s) + ns / 100; ft.dwLowDateTime = (DWORD)v; ft.dwHighDateTime = (DWORD)(v >> 32); } @@ -1561,10 +1807,33 @@ AddComment_Name(s, "incompatible_features"); s += FlagsToString(g_APFS_INCOMPAT_Flags, - ARRAY_SIZE(g_APFS_INCOMPAT_Flags), + Z7_ARRAY_SIZE(g_APFS_INCOMPAT_Flags), (UInt32)apfs.incompatible_features); s.Add_LF(); + + if (apfs.integrity_meta_oid != 0) + { + /* + AddComment_Name(s, "im_version"); + s.Add_UInt32(integrity.im_version); + s.Add_LF(); + */ + AddComment_Name(s, "im_flags"); + s.Add_UInt32(integrity.im_flags); + s.Add_LF(); + AddComment_Name(s, "im_hash_type"); + const char *p = NULL; + if (integrity.im_hash_type < Z7_ARRAY_SIZE(g_hash_types)) + p = g_hash_types[integrity.im_hash_type]; + if (p) + s += p; + else + s.Add_UInt32(integrity.im_hash_type); + s.Add_LF(); + } + + // AddComment_UInt64(s, "reserve_block_count", apfs.fs_reserve_block_count, false); // AddComment_UInt64(s, "quota_block_count", apfs.fs_quota_block_count); AddComment_UInt64(s, "fs_alloc_count", apfs.fs_alloc_count); @@ -1583,7 +1852,7 @@ AddComment_Time(s, "unmounted", apfs.unmount_time); AddComment_Time(s, "last_modified", apfs.last_mod_time); AddComment_modified_by_t(s, "formatted_by", apfs.formatted_by); - for (unsigned i = 0; i < ARRAY_SIZE(apfs.modified_by); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(apfs.modified_by); i++) { const apfs_modified_by_t &v = apfs.modified_by[i]; if (v.last_xid == 0 && v.timestamp == 0 && v.id[0] == 0) @@ -1611,8 +1880,8 @@ xid_t xid; // The transaction identifier void Parse(const Byte *p) { - G64o (0, oid); - G64x (8, xid); + G64o (0, oid) + G64x (8, xid) } }; @@ -1620,7 +1889,9 @@ #define OMAP_VAL_DELETED (1 << 0) #define OMAP_VAL_SAVED (1 << 1) #define OMAP_VAL_ENCRYPTED (1 << 2) +*/ #define OMAP_VAL_NOHEADER (1 << 3) +/* #define OMAP_VAL_CRYPTO_GENERATION (1 << 4) */ @@ -1628,13 +1899,16 @@ { UInt32 flags; UInt32 size; - paddr_t paddr; + // paddr_t paddr; + paddr_t_unsigned paddr; + + bool IsFlag_NoHeader() const { return (flags & OMAP_VAL_NOHEADER) != 0; } void Parse(const Byte *p) { - G32 (0, flags); - G32 (4, size); - G64 (8, paddr); + G32 (0, flags) + G32 (4, size) + G64 (8, paddr) } }; @@ -1710,6 +1984,7 @@ bool HeadersError; bool ThereAreAltStreams; bool UnsupportedFeature; + bool UnsupportedMethod; CSuperBlock sb; @@ -1726,8 +2001,9 @@ void Clear() { HeadersError = false; - UnsupportedFeature = false; ThereAreAltStreams = false; + UnsupportedFeature = false; + UnsupportedMethod = false; ProgressVal_Cur = 0; ProgressVal_Prev = 0; @@ -1742,8 +2018,9 @@ HRESULT SeekReadBlock_FALSE(UInt64 oid, void *data); void GetItemPath(unsigned index, const CNode *inode, NWindows::NCOM::CPropVariant &path) const; - HRESULT ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel); - HRESULT ReadObjectMap(UInt64 oid, CObjectMap &map); + HRESULT ReadMap(UInt64 oid, bool noHeader, CVol *vol, const Byte *hash, + CMap &map, unsigned recurseLevel); + HRESULT ReadObjectMap(UInt64 oid, CVol *vol, CObjectMap &map); HRESULT OpenVolume(const CObjectMap &omap, const oid_t fs_oid); HRESULT Open2(); @@ -1766,14 +2043,14 @@ { if (ProgressVal_Cur - ProgressVal_Prev >= (1 << 22)) { - RINOK(OpenCallback->SetCompleted(NULL, &ProgressVal_Cur)); + RINOK(OpenCallback->SetCompleted(NULL, &ProgressVal_Cur)) ProgressVal_Prev = ProgressVal_Cur; } ProgressVal_Cur += sb.block_size; } if (oid == 0 || oid >= sb.block_count) return S_FALSE; - RINOK(OpenInStream->Seek(oid << sb.block_size_Log, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(OpenInStream, oid << sb.block_size_Log)) return ReadStream_FALSE(OpenInStream, data, sb.block_size); } @@ -1791,8 +2068,23 @@ } +static bool CheckHash(unsigned hashAlgo, const Byte *data, size_t size, const Byte *digest) +{ + if (hashAlgo == APFS_HASH_SHA256) + { + MY_ALIGN (16) + CSha256 sha; + Sha256_Init(&sha); + Sha256_Update(&sha, data, size); + return Sha256_Final_and_CheckDigest(&sha, digest); + } + return true; +} + -HRESULT CDatabase::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel) +HRESULT CDatabase::ReadMap(UInt64 oid, bool noHeader, + CVol *vol, const Byte *hash, + CMap &map, unsigned recurseLevel) { // is it allowed to use big number of levels ? if (recurseLevel > (1 << 10)) @@ -1809,12 +2101,16 @@ const Byte *buf; { CByteBuffer &buf2 = Buffers[recurseLevel]; - RINOK(SeekReadBlock_FALSE(oid, buf2)); + RINOK(SeekReadBlock_FALSE(oid, buf2)) buf = buf2; } + if (hash && vol) + if (!CheckHash(vol->integrity.im_hash_type, buf, blockSize, hash)) + return S_FALSE; + CBTreeNodePhys bt; - if (!bt.Parse(buf, blockSize)) + if (!bt.Parse(buf, blockSize, noHeader)) return S_FALSE; map.NumNodes++; @@ -1829,14 +2125,16 @@ - File-system records are sorted according to the rules listed in File-System Objects. */ - if (bt.o.subtype != map.Subtype) + if (!noHeader) + if (bt.ophys.subtype != map.Subtype) return S_FALSE; unsigned endLimit = blockSize; if (recurseLevel == 0) { - if (bt.o.GetType() != OBJECT_TYPE_BTREE) + if (!noHeader) + if (bt.ophys.GetType() != OBJECT_TYPE_BTREE) return S_FALSE; if ((bt.flags & BTNODE_ROOT) == 0) return S_FALSE; @@ -1850,6 +2148,8 @@ return S_FALSE; if (bti.Is_PHYSICAL() != map.IsPhysical) return S_FALSE; + if (bti.Is_NOHEADER() != noHeader) + return S_FALSE; // we don't allow volumes with big number of Keys const UInt32 kNumItemsMax = k_VectorSizeMax; if (map.bti.node_count > kNumItemsMax) @@ -1859,7 +2159,8 @@ } else { - if (bt.o.GetType() != OBJECT_TYPE_BTREE_NODE) + if (!noHeader) + if (bt.ophys.GetType() != OBJECT_TYPE_BTREE_NODE) return S_FALSE; if ((bt.flags & BTNODE_ROOT) != 0) return S_FALSE; @@ -1925,7 +2226,9 @@ const oid_t oidNext = Get64(p2); if (map.bti.Is_PHYSICAL()) { - RINOK(ReadMap(oidNext, map, recurseLevel + 1)); + RINOK(ReadMap(oidNext, noHeader, vol, + NULL, /* hash */ + map, recurseLevel + 1)) continue; } else @@ -1960,10 +2263,38 @@ continue; } { - if (a.v.off < 8 || a.v.len != 8) + if (a.v.len < 8) return S_FALSE; + + const Byte *hashNew = NULL; + oid_t oidNext = Get64(p2); + + if (bt.Is_HASHED()) + { + if (!vol) + return S_FALSE; + /* + struct btn_index_node_val { + oid_t binv_child_oid; + uint8_t binv_child_hash[BTREE_NODE_HASH_SIZE_MAX]; + }; + */ + /* (a.v.len == 40) is possible if Is_HASHED() + so there is hash (for example, 256-bit) after 64-bit id) */ + if (a.v.len != 8 + vol->integrity.HashSize) + return S_FALSE; + hashNew = p2 + 8; + /* we need to add root_tree_oid here, + but where it's defined in apfs specification ? */ + oidNext += vol->apfs.root_tree_oid; + } + else + { + if (a.v.len != 8) + return S_FALSE; + } + // value is only 64-bit for non leaf. - const oid_t oidNext = Get64(p2); if (map.bti.Is_PHYSICAL()) { @@ -1972,15 +2303,25 @@ // RINOK(ReadMap(oidNext, map, recurseLevel + 1)); // continue; } + /* + else if (map.bti.Is_EPHEMERAL()) + { + // Ephemeral objects are stored in memory while the container is mounted and in a checkpoint when the container isn't mounted + // the code was not tested: + return S_FALSE; + } + */ else { + /* nodes in the B-tree use virtual object identifiers to link to their child nodes. */ const int index = map.Omap.FindKey(oidNext); if (index == -1) return S_FALSE; const omap_val &ov = map.Omap.Vals[(unsigned)index]; if (ov.size != blockSize) // change it : it must be multiple of return S_FALSE; - RINOK(ReadMap(ov.paddr, map, recurseLevel + 1)); + RINOK(ReadMap(ov.paddr, ov.IsFlag_NoHeader(), vol, hashNew, + map, recurseLevel + 1)) continue; } } @@ -1996,19 +2337,23 @@ -HRESULT CDatabase::ReadObjectMap(UInt64 oid, CObjectMap &omap) +HRESULT CDatabase::ReadObjectMap(UInt64 oid, CVol *vol, CObjectMap &omap) { CByteBuffer buf; const size_t blockSize = sb.block_size; buf.Alloc(blockSize); - RINOK(SeekReadBlock_FALSE(oid, buf)); + RINOK(SeekReadBlock_FALSE(oid, buf)) C_omap_phys op; if (!op.Parse(buf, blockSize, oid)) return S_FALSE; CMap map; map.Subtype = OBJECT_TYPE_OMAP; map.IsPhysical = true; - RINOK(ReadMap(op.tree_oid, map, 0)); + RINOK(ReadMap(op.tree_oid, + false /* noHeader */, + vol, + NULL, /* hash */ + map, 0)) if (!omap.Parse(map.Pairs)) return S_FALSE; return S_OK; @@ -2022,7 +2367,7 @@ CSuperBlock2 sb2; { Byte buf[kApfsHeaderSize]; - RINOK(ReadStream_FALSE(OpenInStream, buf, kApfsHeaderSize)); + RINOK(ReadStream_FALSE(OpenInStream, buf, kApfsHeaderSize)) if (!sb.Parse(buf)) return S_FALSE; sb2.Parse(buf); @@ -2030,7 +2375,9 @@ { CObjectMap omap; - RINOK(ReadObjectMap(sb.omap_oid, omap)); + RINOK(ReadObjectMap(sb.omap_oid, + NULL, /* CVol */ + omap)) unsigned numRefs = 0; for (unsigned i = 0; i < sb.max_file_systems; i++) { @@ -2038,7 +2385,7 @@ if (oid == 0) continue; // for (unsigned k = 0; k < 1; k++) // for debug - RINOK(OpenVolume(omap, oid)); + RINOK(OpenVolume(omap, oid)) const unsigned a = Vols.Back().Refs.Size(); numRefs += a; if (numRefs < a) @@ -2104,7 +2451,7 @@ if (ov.size != blockSize) // change it : it must be multiple of return S_FALSE; buf.Alloc(blockSize); - RINOK(SeekReadBlock_FALSE(ov.paddr, buf)); + RINOK(SeekReadBlock_FALSE(ov.paddr, buf)) } CVol &vol = Vols.AddNew(); @@ -2113,14 +2460,107 @@ if (!apfs.Parse(buf, blockSize)) return S_FALSE; + if (apfs.fext_tree_oid != 0) + { + if ((apfs.incompatible_features & APFS_INCOMPAT_SEALED_VOLUME) == 0) + return S_FALSE; + if ((apfs.fext_tree_type & OBJ_PHYSICAL) == 0) + return S_FALSE; + if ((apfs.fext_tree_type & OBJECT_TYPE_MASK) != OBJECT_TYPE_BTREE) + return S_FALSE; + + CMap map2; + map2.Subtype = OBJECT_TYPE_FEXT_TREE; + map2.IsPhysical = true; + + RINOK(ReadMap(apfs.fext_tree_oid, + false /* noHeader */, + &vol, + NULL, /* hash */ + map2, 0)) + + UInt64 prevId = 1; + + FOR_VECTOR (i, map2.Pairs) + { + if (OpenCallback && (i & 0xffff) == 1) + { + const UInt64 numFiles = ProgressVal_NumFilesTotal + + (vol.Items.Size() + vol.Nodes.Size()) / 2; + RINOK(OpenCallback->SetCompleted(&numFiles, &ProgressVal_Cur)) + } + // The key half of a record from a file extent tree. + // struct fext_tree_key + const CKeyValPair &pair = map2.Pairs[i]; + if (pair.Key.Size() != 16) + return S_FALSE; + const Byte *p = pair.Key; + const UInt64 id = GetUi64(p); + if (id < prevId) + return S_FALSE; // IDs must be sorted + prevId = id; + + CExtent ext; + ext.logical_offset = GetUi64(p + 8); + { + if (pair.Val.Size() != 16) + return S_FALSE; + const Byte *p2 = pair.Val; + ext.len_and_flags = GetUi64(p2); + ext.phys_block_num = GetUi64(p2 + 8); + } + + PRF(printf("\n%6d: id=%6d logical_addr = %2d len_and_flags=%5x phys_block_num = %5d", + i, (unsigned)id, + (unsigned)ext.logical_offset, + (unsigned)ext.len_and_flags, + (unsigned)ext.phys_block_num)); + + if (vol.FEXT_NodeIDs.IsEmpty() || + vol.FEXT_NodeIDs.Back() != id) + { + vol.FEXT_NodeIDs.Add(id); + vol.FEXT_Nodes.AddNew(); + } + CRecordVector &extents = vol.FEXT_Nodes.Back().Extents; + if (!extents.IsEmpty()) + if (ext.logical_offset != extents.Back().GetEndOffset()) + return S_FALSE; + extents.Add(ext); + continue; + } + + PRF(printf("\n\n")); + } + /* For each volume, read the root file system tree's virtual object identifier from the apfs_root_tree_oid field, and then look it up in the volume object map indicated by the omap_oid field. */ CMap map; + ReadObjectMap(apfs.omap_oid, &vol, map.Omap); + + const Byte *hash_for_root = NULL; + + if (apfs.integrity_meta_oid != 0) + { + if ((apfs.incompatible_features & APFS_INCOMPAT_SEALED_VOLUME) == 0) + return S_FALSE; + const int index = map.Omap.FindKey(apfs.integrity_meta_oid); + if (index == -1) + return S_FALSE; + const omap_val &ov = map.Omap.Vals[(unsigned)index]; + if (ov.size != blockSize) + return S_FALSE; + RINOK(SeekReadBlock_FALSE(ov.paddr, buf)) + if (!vol.integrity.Parse(buf, blockSize, apfs.integrity_meta_oid)) + return S_FALSE; + if (vol.integrity.im_hash_type != 0) + hash_for_root = vol.integrity.Hash; + } + { - ReadObjectMap(apfs.omap_oid, map.Omap); const int index = map.Omap.FindKey(apfs.root_tree_oid); if (index == -1) return S_FALSE; @@ -2129,7 +2569,9 @@ return S_FALSE; map.Subtype = OBJECT_TYPE_FSTREE; map.IsPhysical = false; - RINOK(ReadMap(ov.paddr, map, 0)); + RINOK(ReadMap(ov.paddr, ov.IsFlag_NoHeader(), + &vol, hash_for_root, + map, 0)) } bool needParseAttr = false; @@ -2152,7 +2594,7 @@ if (OpenCallback) { const UInt64 numFiles = ProgressVal_NumFilesTotal + numApfsItems; - RINOK(OpenCallback->SetTotal(&numFiles, NULL)); + RINOK(OpenCallback->SetTotal(&numFiles, NULL)) } } @@ -2165,7 +2607,7 @@ { const UInt64 numFiles = ProgressVal_NumFilesTotal + (vol.Items.Size() + vol.Nodes.Size()) / 2; - RINOK(OpenCallback->SetCompleted(&numFiles, &ProgressVal_Cur)); + RINOK(OpenCallback->SetCompleted(&numFiles, &ProgressVal_Cur)) } const CKeyValPair &pair = map.Pairs[i]; @@ -2180,11 +2622,11 @@ return S_FALSE; // IDs must be sorted prevId = id; - PRF(printf("\n%6d: id=%6d type = %2d", i, (unsigned)id, type)); + PRF(printf("\n%6d: id=%6d type = %2d ", i, (unsigned)id, type)); if (type == APFS_TYPE_INODE) { - PRF(printf (" INODE")); + PRF(printf("INODE")); if (pair.Key.Size() != 8 || pair.Val.Size() < k_SizeOf_j_inode_val) return S_FALSE; @@ -2224,6 +2666,9 @@ UInt32 offset = 4 + (UInt32)xf_num_exts * 4; if (offset + xf_used_data != extraSize) return S_FALSE; + + PRF(printf(" parent_id = %d", (unsigned)inode.parent_id)); + for (unsigned k = 0; k < xf_num_exts; k++) { // struct x_field @@ -2336,7 +2781,7 @@ attr.Id = Get64(p4); attr.dstream.Parse(p4 + 8); attr.dstream_defined = true; - PRF(printf(" streamID=%d", (unsigned)attr.Id)); + PRF(printf(" streamID=%d streamSize=%d", (unsigned)attr.Id, (unsigned)attr.dstream.size)); } else { @@ -2386,7 +2831,7 @@ const UInt32 refcnt = Get32(pair.Val); // The data stream record can be deleted when its reference count reaches zero. - PRF(printf(" refcnt = %8d", (unsigned)refcnt)); + PRF(printf(" refcnt = %d", (unsigned)refcnt)); if (vol.NodeIDs.IsEmpty()) return S_FALSE; @@ -2407,6 +2852,7 @@ inode.refcnt_defined = true; if (inode.refcnt != (UInt32)inode.nlink) { + PRF(printf(" refcnt != nlink")); // is it possible ? // return S_FALSE; } @@ -2536,13 +2982,138 @@ if (id == PRIV_DIR_INO_NUM) vol.NumItems_In_PrivateDir++; - PRF(printf(" next=%6d flags=%2x %s", + PRF(printf(" DIR_REC next=%6d flags=%2x %s", (unsigned)item.Val.file_id, (unsigned)item.Val.flags, item.Name.Ptr())); continue; } - + + if (type == APFS_TYPE_FILE_INFO) + { + if (pair.Key.Size() != 16) + return S_FALSE; + // j_file_info_key + const UInt64 info_and_lba = Get64(p + 8); + + #define J_FILE_INFO_LBA_MASK 0x00ffffffffffffffUL + // #define J_FILE_INFO_TYPE_MASK 0xff00000000000000UL + #define J_FILE_INFO_TYPE_SHIFT 56 + #define APFS_FILE_INFO_DATA_HASH 1 + + const unsigned infoType = (unsigned)(info_and_lba >> J_FILE_INFO_TYPE_SHIFT); + // address is a paddr_t + const UInt64 lba = info_and_lba & J_FILE_INFO_LBA_MASK; + // j_file_data_hash_val_t + /* Use this field of the union if the type stored in the info_and_lba field of j_file_info_val_t is + APFS_FILE_INFO_DATA_HASH */ + if (infoType != APFS_FILE_INFO_DATA_HASH) + return S_FALSE; + if (pair.Val.Size() != 3 + vol.integrity.HashSize) + return S_FALSE; + /* + struct j_file_data_hash_val + { + UInt16 hashed_len; // The length, in blocks, of the data segment that was hashed. + UInt8 hash_size; // must be consistent with integrity_meta_phys_t::im_hash_type + UInt8 hash[0]; + } + */ + + const unsigned hash_size = pair.Val[2]; + if (hash_size != vol.integrity.HashSize) + return S_FALSE; + + CHashChunk hr; + hr.hashed_len = GetUi16(pair.Val); + if (hr.hashed_len == 0) + return S_FALSE; + memcpy(hr.hash, (const Byte *)pair.Val + 3, vol.integrity.HashSize); + // (hashed_len <= 4) : we have seen + hr.lba = lba; + + PRF(printf(" FILE_INFO lba = %6x, hashed_len=%6d", + (unsigned)lba, + (unsigned)hr.hashed_len)); + + if (vol.Hash_IDs.IsEmpty() || vol.Hash_IDs.Back() != id) + { + vol.Hash_Vectors.AddNew(); + vol.Hash_IDs.Add(id); + } + CStreamHashes &hashes = vol.Hash_Vectors.Back(); + if (hashes.Size() != 0) + { + const CHashChunk &hr_Back = hashes.Back(); + if (lba != hr_Back.lba + ((UInt64)hr_Back.hashed_len << sb.block_size_Log)) + return S_FALSE; + } + hashes.Add(hr); + continue; + } + + if (type == APFS_TYPE_SNAP_METADATA) + { + if (pair.Key.Size() != 8) + return S_FALSE; + PRF(printf(" SNAP_METADATA")); + // continue; + } + + /* SIBLING items are used, if there are more than one hard link to some inode + key : value + parent_id_1 DIR_REC : inode_id, name_1 + parent_id_2 DIR_REC : inode_id, name_2 + inode_id INODE : parent_id_1, name_1 + inode_id SIBLING_LINK sibling_id_1 : parent_id_1, name_1 + inode_id SIBLING_LINK sibling_id_2 : parent_id_2, name_2 + sibling_id_1 SIBLING_MAP : inode_id + sibling_id_2 SIBLING_MAP : inode_id + */ + + if (type == APFS_TYPE_SIBLING_LINK) + { + if (pair.Key.Size() != 16) + return S_FALSE; + if (pair.Val.Size() < 10 + 1) + return S_FALSE; + /* + // struct j_sibling_key + // The sibling's unique identifier. + // This value matches the object identifier for the sibling map record + const UInt64 sibling_id = Get64(p + 8); + // struct j_sibling_val + const Byte *v = pair.Val; + const UInt64 parent_id = Get64(v); // The object identifier for the inode that's the parent directory. + const unsigned name_len = Get16(v + 8); // len including the final null character + if (10 + name_len != pair.Val.Size()) + return S_FALSE; + if (v[10 + name_len - 1] != 0) + return S_FALSE; + AString name ((const char *)(v + 10)); + if (name.Len() != name_len - 1) + return S_FALSE; + PRF(printf(" SIBLING_LINK sibling_id = %6d : parent_id=%6d %s", + (unsigned)sibling_id, (unsigned)parent_id, name.Ptr())); + */ + continue; + } + + if (type == APFS_TYPE_SIBLING_MAP) + { + // struct j_sibling_map_key + // The object identifier in the header is the sibling's unique identifier + if (pair.Key.Size() != 8 || pair.Val.Size() != 8) + return S_FALSE; + /* + // j_sibling_map_val + // The inode number of the underlying file + const UInt64 file_id = Get64(pair.Val); + PRF(printf(" SIBLING_MAP : file_id = %d", (unsigned)file_id)); + */ + continue; + } + UnsupportedFeature = true; // return S_FALSE; } @@ -2596,7 +3167,7 @@ RINOK(OpenCallback->SetCompleted( &ProgressVal_NumFilesTotal, - &ProgressVal_Cur)); + &ProgressVal_Cur)) ProgressVal_Prev = ProgressVal_Cur; } } @@ -2623,7 +3194,7 @@ } else { - vol.UnsupportedFeature = true; + vol.UnsupportedMethod = true; } } } @@ -2635,6 +3206,8 @@ HeadersError = true; if (vol.UnsupportedFeature) UnsupportedFeature = true; + if (vol.UnsupportedMethod) + UnsupportedMethod = true; if (vol.NumAltStreams != 0) ThereAreAltStreams = true; @@ -2863,38 +3436,39 @@ -class CHandler: +Z7_class_CHandler_final: public IInArchive, public IArchiveGetRawProps, public IInArchiveGetStream, public CMyUnknownImp, public CDatabase { + Z7_IFACES_IMP_UNK_3( + IInArchive, + IArchiveGetRawProps, + IInArchiveGetStream) + CMyComPtr _stream; -public: - MY_UNKNOWN_IMP3(IInArchive, IArchiveGetRawProps, IInArchiveGetStream) - INTERFACE_IInArchive(;) - INTERFACE_IArchiveGetRawProps(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); + int FindHashIndex_for_Item(UInt32 index); }; -STDMETHODIMP CHandler::Open(IInStream *inStream, +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback *callback) + IArchiveOpenCallback *callback)) { COM_TRY_BEGIN Close(); OpenInStream = inStream; OpenCallback = callback; - RINOK(Open2()); + RINOK(Open2()) _stream = inStream; return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _stream.Release(); Clear(); @@ -2971,7 +3545,7 @@ } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -3006,6 +3580,7 @@ { UInt32 flags = 0; if (UnsupportedFeature) flags |= kpv_ErrorFlags_UnsupportedFeature; + if (UnsupportedMethod) flags |= kpv_ErrorFlags_UnsupportedMethod; if (flags != 0) prop = flags; break; @@ -3068,14 +3643,14 @@ } -STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) +Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps)) { *numProps = 0; return S_OK; } -STDMETHODIMP CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID) +Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID)) { *name = NULL; *propID = 0; @@ -3083,7 +3658,7 @@ } -STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType) +Z7_COM7F_IMF(CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType)) { *parentType = NParentType::kDir; @@ -3109,13 +3684,13 @@ } -STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) +Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType)) { *data = NULL; *dataSize = 0; *propType = 0; - UNUSED_VAR(index); - UNUSED_VAR(propID); + UNUSED_VAR(index) + UNUSED_VAR(propID) return S_OK; } @@ -3133,7 +3708,7 @@ s.Add_UInt64(id); if (!inode.PrimaryName.IsEmpty()) { - s += '.'; + s.Add_Dot(); UString s2; Utf8Name_to_InterName(inode.PrimaryName, s2); s += s2; @@ -3204,7 +3779,7 @@ -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -3509,8 +4084,8 @@ } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN const bool allFilesMode = (numItems == (UInt32)(Int32)-1); @@ -3527,7 +4102,7 @@ const UInt32 index = allFilesMode ? i : indices[i]; totalSize += GetSize(index); } - RINOK(extractCallback->SetTotal(totalSize)); + RINOK(extractCallback->SetTotal(totalSize)) } UInt64 currentTotalSize = 0, currentItemSize = 0; @@ -3541,11 +4116,14 @@ NHfs::CDecoder decoder; - for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize) + for (i = 0;; i++, currentTotalSize += currentItemSize) { lps->InSize = currentTotalSize; lps->OutSize = currentTotalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) + + if (i >= numItems) + break; const UInt32 index = allFilesMode ? i : indices[i]; const CRef2 &ref2 = Refs2[index]; @@ -3558,12 +4136,12 @@ const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) if (IsViNotDef(ref2.RefIndex)) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } @@ -3580,13 +4158,13 @@ if (isDir) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) int opRes = NExtract::NOperationResult::kDataError; if (IsViDef(ref.NodeIndex)) @@ -3643,10 +4221,31 @@ CMyComPtr inStream; if (GetStream(index, &inStream) == S_OK && inStream) { - RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); + COutStreamWithHash *hashStreamSpec = NULL; + CMyComPtr hashStream; + + if (vol.integrity.Is_SHA256()) + { + const int hashIndex = FindHashIndex_for_Item(index); + if (hashIndex != -1) + { + hashStreamSpec = new COutStreamWithHash; + hashStream = hashStreamSpec; + hashStreamSpec->SetStream(realOutStream); + hashStreamSpec->Init(&(vol.Hash_Vectors[(unsigned)hashIndex]), sb.block_size_Log); + } + } + + RINOK(copyCoder->Code(inStream, + hashStream ? hashStream : realOutStream, NULL, NULL, progress)) opRes = NExtract::NOperationResult::kDataError; if (copyCoderSpec->TotalSize == currentItemSize) + { opRes = NExtract::NOperationResult::kOK; + if (hashStream) + if (!hashStreamSpec->FinalCheck()) + opRes = NExtract::NOperationResult::kCRCError; + } else if (copyCoderSpec->TotalSize < currentItemSize) opRes = NExtract::NOperationResult::kUnexpectedEnd; } @@ -3654,21 +4253,61 @@ } realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = Refs2.Size(); return S_OK; } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +int CHandler::FindHashIndex_for_Item(UInt32 index) +{ + const CRef2 &ref2 = Refs2[index]; + const CVol &vol = Vols[ref2.VolIndex]; + if (IsViNotDef(ref2.RefIndex)) + return -1; + + const CRef &ref = vol.Refs[ref2.RefIndex]; + if (IsViNotDef(ref.NodeIndex)) + return -1; + const CNode &inode = vol.Nodes[ref.NodeIndex]; + + unsigned attrIndex = ref.GetAttrIndex(); + + if (IsViNotDef(attrIndex) + && !inode.dstream_defined + && inode.IsSymLink()) + { + attrIndex = inode.SymLinkIndex; + if (IsViNotDef(attrIndex)) + return -1; + } + + if (IsViDef(attrIndex)) + { + /* we have seen examples, where hash available for "com.apple.ResourceFork" stream. + these hashes for "com.apple.ResourceFork" stream are for unpacked data. + but the caller here needs packed data of stream. So we don't use hashes */ + return -1; + } + else + { + if (!inode.dstream_defined) + return -1; + const UInt64 id = vol.NodeIDs[ref.NodeIndex]; + return vol.Hash_IDs.FindInSorted(id); + } +} + + +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { *stream = NULL; @@ -3708,9 +4347,15 @@ return S_OK; } const int idIndex = vol.SmallNodeIDs.FindInSorted(attr.Id); - if (idIndex == -1) - return S_FALSE; - extents = &vol.SmallNodes[(unsigned)idIndex].Extents; + if (idIndex != -1) + extents = &vol.SmallNodes[(unsigned)idIndex].Extents; + else + { + const int fext_Index = vol.FEXT_NodeIDs.FindInSorted(attr.Id); + if (fext_Index == -1) + return S_FALSE; + extents = &vol.FEXT_Nodes[(unsigned)fext_Index].Extents; + } rem = attr.dstream.size; } else @@ -3720,16 +4365,21 @@ return S_FALSE; if (inode.IsDir()) return S_FALSE; + extents = &inode.Extents; if (inode.dstream_defined) { rem = inode.dstream.size; + if (inode.Extents.Size() == 0) + { + const int fext_Index = vol.FEXT_NodeIDs.FindInSorted(vol.NodeIDs[ref.NodeIndex]); + if (fext_Index != -1) + extents = &vol.FEXT_Nodes[(unsigned)fext_Index].Extents; + } } else { // return S_FALSE; // check it !!! How zero size files are stored with dstream_defined? } - - extents = &inode.Extents; } return GetStream2(_stream, extents, rem, stream); } @@ -3755,13 +4405,20 @@ HRESULT CDatabase::GetAttrStream_dstream( IInStream *apfsInStream, const CVol &vol, const CAttr &attr, ISequentialInStream **stream) { - const int idIndex = vol.SmallNodeIDs.FindInSorted(attr.Id); - if (idIndex == -1) - return S_FALSE; - return GetStream2(apfsInStream, - &vol.SmallNodes[(unsigned)idIndex].Extents, - attr.dstream.size, - stream); + const CRecordVector *extents; + { + const int idIndex = vol.SmallNodeIDs.FindInSorted(attr.Id); + if (idIndex != -1) + extents = &vol.SmallNodes[(unsigned)idIndex].Extents; + else + { + const int fext_Index = vol.FEXT_NodeIDs.FindInSorted(attr.Id); + if (fext_Index == -1) + return S_FALSE; + extents = &vol.FEXT_Nodes[(unsigned)fext_Index].Extents; + } + } + return GetStream2(apfsInStream, extents, attr.dstream.size, stream); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/ApmHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/ApmHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/ApmHandler.cpp 2021-01-24 16:10:36.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/ApmHandler.cpp 2023-03-27 18:00:00.000000000 +0000 @@ -71,8 +71,10 @@ } }; -class CHandler: public CHandlerCont +Z7_class_CHandler_final: public CHandlerCont { + Z7_IFACE_COM7_IMP(IInArchive_Cont) + CRecordVector _items; unsigned _blockSizeLog; UInt32 _numBlocks; @@ -82,16 +84,13 @@ HRESULT ReadTables(IInStream *stream); UInt64 BlocksToBytes(UInt32 i) const { return (UInt64)i << _blockSizeLog; } - virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const + virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const Z7_override { const CItem &item = _items[index]; pos = BlocksToBytes(item.StartBlock); size = BlocksToBytes(item.NumBlocks); return NExtract::NOperationResult::kOK; } - -public: - INTERFACE_IInArchive_Cont(;) }; static const UInt32 kSectorSize = 512; @@ -118,7 +117,7 @@ { Byte buf[kSectorSize]; { - RINOK(ReadStream_FALSE(stream, buf, kSectorSize)); + RINOK(ReadStream_FALSE(stream, buf, kSectorSize)) if (buf[0] != kSig0 || buf[1] != kSig1) return S_FALSE; UInt32 blockSize = Get16(buf + 2); @@ -136,14 +135,14 @@ unsigned numSkips = (unsigned)1 << (_blockSizeLog - 9); for (unsigned j = 1; j < numSkips; j++) { - RINOK(ReadStream_FALSE(stream, buf, kSectorSize)); + RINOK(ReadStream_FALSE(stream, buf, kSectorSize)) } UInt32 numBlocksInMap = 0; for (unsigned i = 0;;) { - RINOK(ReadStream_FALSE(stream, buf, kSectorSize)); + RINOK(ReadStream_FALSE(stream, buf, kSectorSize)) CItem item; @@ -167,7 +166,7 @@ _items.Add(item); for (unsigned j = 1; j < numSkips; j++) { - RINOK(ReadStream_FALSE(stream, buf, kSectorSize)); + RINOK(ReadStream_FALSE(stream, buf, kSectorSize)) } if (++i == numBlocksInMap) break; @@ -178,17 +177,17 @@ return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback * /* callback */) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback * /* callback */)) { COM_TRY_BEGIN Close(); - RINOK(ReadTables(stream)); + RINOK(ReadTables(stream)) _stream = stream; return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; _phySize = 0; @@ -220,7 +219,7 @@ return res; } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -244,7 +243,7 @@ } } if (mainIndex >= 0) - prop = (UInt32)mainIndex; + prop = (UInt32)(Int32)mainIndex; break; } case kpidClusterSize: prop = (UInt32)1 << _blockSizeLog; break; @@ -263,13 +262,13 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _items.Size(); return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -286,7 +285,7 @@ type = "hfs"; if (!type.IsEmpty()) { - s += '.'; + s.Add_Dot(); s += type; } prop = s; @@ -306,7 +305,7 @@ static const Byte k_Signature[] = { kSig0, kSig1 }; REGISTER_ARC_I( - "APM", "apm", 0, 0xD4, + "APM", "apm", NULL, 0xD4, k_Signature, 0, 0, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Archive2.def 7zip-23.01+dfsg/CPP/7zip/Archive/Archive2.def --- 7zip-22.01+dfsg/CPP/7zip/Archive/Archive2.def 2015-02-12 07:12:49.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Archive2.def 2023-04-03 10:00:00.000000000 +0000 @@ -17,3 +17,5 @@ SetLargePageMode PRIVATE SetCaseSensitive PRIVATE + + GetModuleProp PRIVATE diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Archive.def 7zip-23.01+dfsg/CPP/7zip/Archive/Archive.def --- 7zip-22.01+dfsg/CPP/7zip/Archive/Archive.def 2015-03-06 10:56:49.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Archive.def 2023-04-03 11:00:00.000000000 +0000 @@ -10,3 +10,5 @@ SetLargePageMode PRIVATE SetCaseSensitive PRIVATE + + GetModuleProp PRIVATE diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/ArchiveExports.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/ArchiveExports.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/ArchiveExports.cpp 2022-04-25 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/ArchiveExports.cpp 2023-03-23 11:00:00.000000000 +0000 @@ -10,7 +10,7 @@ #include "../Common/RegisterArc.h" -static const unsigned kNumArcsMax = 64; +static const unsigned kNumArcsMax = 72; static unsigned g_NumArcs = 0; static unsigned g_DefaultArcIndex = 0; static const CArcInfo *g_Arcs[kNumArcsMax]; @@ -24,9 +24,10 @@ g_DefaultArcIndex = g_NumArcs; g_Arcs[g_NumArcs++] = arcInfo; } + // else throw 1; } -DEFINE_GUID(CLSID_CArchiveHandler, +Z7_DEFINE_GUID(CLSID_CArchiveHandler, k_7zip_GUID_Data1, k_7zip_GUID_Data2, k_7zip_GUID_Data3_Common, @@ -36,7 +37,7 @@ static inline HRESULT SetPropStrFromBin(const char *s, unsigned size, PROPVARIANT *value) { - if ((value->bstrVal = ::SysAllocStringByteLen(s, size)) != 0) + if ((value->bstrVal = ::SysAllocStringByteLen(s, size)) != NULL) value->vt = VT_BSTR; return S_OK; } @@ -52,7 +53,7 @@ CLS_ARC_ID_ITEM(cls) = 0; if (cls != CLSID_CArchiveHandler) return -1; - Byte id = CLS_ARC_ID_ITEM(*clsid); + const Byte id = CLS_ARC_ID_ITEM(*clsid); for (unsigned i = 0; i < g_NumArcs; i++) if (g_Arcs[i]->Id == id) return (int)i; @@ -64,11 +65,11 @@ { COM_TRY_BEGIN { - int needIn = (*iid == IID_IInArchive); - int needOut = (*iid == IID_IOutArchive); + const int needIn = (*iid == IID_IInArchive); + const int needOut = (*iid == IID_IOutArchive); if (!needIn && !needOut) return E_NOINTERFACE; - int formatIndex = FindFormatCalssId(clsid); + const int formatIndex = FindFormatCalssId(clsid); if (formatIndex < 0) return CLASS_E_CLASSNOTAVAILABLE; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/ArHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/ArHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/ArHandler.cpp 2022-04-30 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/ArHandler.cpp 2023-03-27 18:00:00.000000000 +0000 @@ -56,10 +56,8 @@ */ static const unsigned kSignatureLen = 8; - -#define SIGNATURE { '!', '<', 'a', 'r', 'c', 'h', '>', 0x0A } - -static const Byte kSignature[kSignatureLen] = SIGNATURE; +static const Byte kSignature[kSignatureLen] = + { '!', '<', 'a', 'r', 'c', 'h', '>', 0x0A }; static const unsigned kNameSize = 16; static const unsigned kTimeSize = 12; @@ -136,16 +134,16 @@ HRESULT Open(IInStream *inStream); HRESULT SkipData(UInt64 dataSize) { - return m_Stream->Seek(dataSize + (dataSize & 1), STREAM_SEEK_CUR, &Position); + return m_Stream->Seek((Int64)(dataSize + (dataSize & 1)), STREAM_SEEK_CUR, &Position); } }; HRESULT CInArchive::Open(IInStream *inStream) { SubType = kSubType_None; - RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &Position)); + RINOK(InStream_GetPos(inStream, Position)) char signature[kSignatureLen]; - RINOK(ReadStream_FALSE(inStream, signature, kSignatureLen)); + RINOK(ReadStream_FALSE(inStream, signature, kSignatureLen)) Position += kSignatureLen; if (memcmp(signature, kSignature, kSignatureLen) != 0) return S_FALSE; @@ -215,7 +213,7 @@ size_t processedSize = sizeof(header); item.HeaderPos = Position; item.HeaderSize = kHeaderSize; - RINOK(ReadStream(m_Stream, header, &processedSize)); + RINOK(ReadStream(m_Stream, header, &processedSize)) if (processedSize != sizeof(header)) return S_OK; if (header[kHeaderSize - 2] != 0x60 || @@ -235,7 +233,7 @@ cur[3] != 0) { // BSD variant - RIF(DecimalToNumber32(cur + 3, kNameSize - 3 , longNameLen)); + RIF(DecimalToNumber32(cur + 3, kNameSize - 3 , longNameLen)) if (longNameLen >= (1 << 12)) longNameLen = 0; } @@ -247,11 +245,11 @@ } cur += kNameSize; - RIF(DecimalToNumber32(cur, kTimeSize, item.MTime)); cur += kTimeSize; - RIF(DecimalToNumber32(cur, kUserSize, item.User)); cur += kUserSize; - RIF(DecimalToNumber32(cur, kUserSize, item.Group)); cur += kUserSize; - RIF(OctalToNumber32(cur, kModeSize, item.Mode)); cur += kModeSize; - RIF(DecimalToNumber(cur, kSizeSize, item.Size)); cur += kSizeSize; + RIF(DecimalToNumber32(cur, kTimeSize, item.MTime)) cur += kTimeSize; + RIF(DecimalToNumber32(cur, kUserSize, item.User)) cur += kUserSize; + RIF(DecimalToNumber32(cur, kUserSize, item.Group)) cur += kUserSize; + RIF(OctalToNumber32(cur, kModeSize, item.Mode)) cur += kModeSize; + RIF(DecimalToNumber(cur, kSizeSize, item.Size)) cur += kSizeSize; if (longNameLen != 0 && longNameLen <= item.Size) { @@ -260,7 +258,7 @@ char *s = item.Name.GetBuf(longNameLen); HRESULT res = ReadStream(m_Stream, s, &processedSize); item.Name.ReleaseBuf_CalcLen(longNameLen); - RINOK(res); + RINOK(res) if (processedSize != longNameLen) return S_OK; item.Size -= longNameLen; @@ -272,11 +270,10 @@ return S_OK; } -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_CHandler_IInArchive_1( + IInArchiveGetStream +) CObjectVector _items; CMyComPtr _stream; Int32 _mainSubfile; @@ -289,7 +286,6 @@ unsigned _numLibFiles; AString _errorMessage; bool _isArc; - void UpdateErrorMessage(const char *s); @@ -298,10 +294,6 @@ int FindItem(UInt32 offset) const; HRESULT AddFunc(UInt32 offset, const Byte *data, size_t size, size_t &pos); HRESULT ParseLibSymbols(IInStream *stream, unsigned fileIndex); -public: - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); }; void CHandler::UpdateErrorMessage(const char *s) @@ -342,11 +334,11 @@ const CItem &item = _items[fileIndex]; if (item.Size > ((UInt32)1 << 30)) return S_FALSE; - RINOK(stream->Seek(item.GetDataPos(), STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, item.GetDataPos())) const size_t size = (size_t)item.Size; CByteArr p(size); - RINOK(ReadStream_FALSE(stream, p, size)); + RINOK(ReadStream_FALSE(stream, p, size)) for (i = 0; i < _items.Size(); i++) { @@ -365,15 +357,15 @@ { if (pos >= size) return S_FALSE; - char c = p[pos]; + const Byte c = p[pos]; if (c == 0 || c == 0x0A) break; pos++; } - item2.Name.SetFrom((const char *)(p + start), pos - start); + item2.Name.SetFrom((const char *)(p + start), (unsigned)(pos - start)); } - _longNames_FileIndex = fileIndex; + _longNames_FileIndex = (int)fileIndex; return S_OK; } @@ -399,7 +391,7 @@ if (item.SameNameIndex < 0) continue; char sz[32]; - ConvertUInt32ToString(item.SameNameIndex + 1, sz); + ConvertUInt32ToString((unsigned)item.SameNameIndex + 1, sz); unsigned len = MyStringLen(sz); sz[len++] = '.'; sz[len] = 0; @@ -412,10 +404,10 @@ unsigned left = 0, right = _items.Size(); while (left != right) { - unsigned mid = (left + right) / 2; - UInt64 midVal = _items[mid].HeaderPos; + const unsigned mid = (left + right) / 2; + const UInt64 midVal = _items[mid].HeaderPos; if (offset == midVal) - return mid; + return (int)mid; if (offset < midVal) right = mid; else @@ -426,7 +418,7 @@ HRESULT CHandler::AddFunc(UInt32 offset, const Byte *data, size_t size, size_t &pos) { - int fileIndex = FindItem(offset); + const int fileIndex = FindItem(offset); if (fileIndex < (int)0) return S_FALSE; @@ -439,7 +431,7 @@ while (data[i++] != 0); AString &s = _libFiles[_numLibFiles]; - const AString &name = _items[fileIndex].Name; + const AString &name = _items[(unsigned)fileIndex].Name; s += name; if (!name.IsEmpty() && name.Back() == '/') s.DeleteBack(); @@ -463,35 +455,35 @@ if (item.Size > ((UInt32)1 << 30) || item.Size < 4) return S_OK; - RINOK(stream->Seek(item.GetDataPos(), STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, item.GetDataPos())) size_t size = (size_t)item.Size; CByteArr p(size); - RINOK(ReadStream_FALSE(stream, p, size)); + RINOK(ReadStream_FALSE(stream, p, size)) size_t pos = 0; if (item.Name != "/") { - // __.SYMDEF parsing (BSD) + // "__.SYMDEF" parsing (BSD) unsigned be; for (be = 0; be < 2; be++) { - UInt32 tableSize = Get32(p, be); + const UInt32 tableSize = Get32(p, be); pos = 4; if (size - pos < tableSize || (tableSize & 7) != 0) continue; size_t namesStart = pos + tableSize; - UInt32 namesSize = Get32(p + namesStart, be); + const UInt32 namesSize = Get32(p + namesStart, be); namesStart += 4; if (namesStart > size || namesStart + namesSize != size) continue; - UInt32 numSymbols = tableSize >> 3; + const UInt32 numSymbols = tableSize >> 3; UInt32 i; for (i = 0; i < numSymbols; i++, pos += 8) { size_t namePos = Get32(p + pos, be); - UInt32 offset = Get32(p + pos + 4, be); + const UInt32 offset = Get32(p + pos + 4, be); if (AddFunc(offset, p + namesStart, namesSize, namePos) != S_OK) break; } @@ -509,7 +501,7 @@ else if (_numLibFiles == 0) { // archive symbol table (GNU) - UInt32 numSymbols = GetBe32(p); + const UInt32 numSymbols = GetBe32(p); pos = 4; if (numSymbols > (size - pos) / 4) return S_FALSE; @@ -517,15 +509,15 @@ for (UInt32 i = 0; i < numSymbols; i++) { - UInt32 offset = GetBe32(p + 4 + i * 4); - RINOK(AddFunc(offset, p, size, pos)); + const UInt32 offset = GetBe32(p + 4 + i * 4); + RINOK(AddFunc(offset, p, size, pos)) } _type = kType_ALib; } else { // Second linker file (Microsoft .lib) - UInt32 numMembers = GetUi32(p); + const UInt32 numMembers = GetUi32(p); pos = 4; if (numMembers > (size - pos) / 4) return S_FALSE; @@ -533,7 +525,7 @@ if (size - pos < 4) return S_FALSE; - UInt32 numSymbols = GetUi32(p + pos); + const UInt32 numSymbols = GetUi32(p + pos); pos += 4; if (numSymbols > (size - pos) / 2) return S_FALSE; @@ -543,48 +535,47 @@ for (UInt32 i = 0; i < numSymbols; i++) { // index is 1-based. So 32-bit numSymbols field works as item[0] - UInt32 index = GetUi16(p + indexStart + i * 2); + const UInt32 index = GetUi16(p + indexStart + i * 2); if (index == 0 || index > numMembers) return S_FALSE; - UInt32 offset = GetUi32(p + index * 4); - RINOK(AddFunc(offset, p, size, pos)); + const UInt32 offset = GetUi32(p + index * 4); + RINOK(AddFunc(offset, p, size, pos)) } _type = kType_Lib; } // size can be 2-byte aligned in linux files if (pos != size && pos + (pos & 1) != size) return S_FALSE; - item.TextFileIndex = _numLibFiles++; + item.TextFileIndex = (int)(_numLibFiles++); return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *stream, +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback *callback) + IArchiveOpenCallback *callback)) { COM_TRY_BEGIN { Close(); - UInt64 fileSize = 0; - RINOK(stream->Seek(0, STREAM_SEEK_END, &fileSize)); - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); + UInt64 fileSize; + RINOK(InStream_AtBegin_GetSize(stream, fileSize)) CInArchive arc; - RINOK(arc.Open(stream)); + RINOK(arc.Open(stream)) if (callback) { - RINOK(callback->SetTotal(NULL, &fileSize)); - UInt64 numFiles = _items.Size(); - RINOK(callback->SetCompleted(&numFiles, &arc.Position)); + RINOK(callback->SetTotal(NULL, &fileSize)) + const UInt64 numFiles = _items.Size(); + RINOK(callback->SetCompleted(&numFiles, &arc.Position)) } CItem item; for (;;) { bool filled; - RINOK(arc.GetNextItem(item, filled)); + RINOK(arc.GetNextItem(item, filled)) if (!filled) break; _items.Add(item); @@ -592,7 +583,7 @@ if (callback && (_items.Size() & 0xFF) == 0) { UInt64 numFiles = _items.Size(); - RINOK(callback->SetCompleted(&numFiles, &arc.Position)); + RINOK(callback->SetCompleted(&numFiles, &arc.Position)) } } @@ -610,7 +601,7 @@ if (ParseLongNames(stream) != S_OK) UpdateErrorMessage("Long file names parsing error"); if (_longNames_FileIndex >= 0) - _items.Delete(_longNames_FileIndex); + _items.Delete((unsigned)_longNames_FileIndex); if (!_items.IsEmpty() && _items[0].Name == "debian-binary") { @@ -651,7 +642,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; _phySize = 0; @@ -672,13 +663,13 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _items.Size(); return S_OK; } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -711,7 +702,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -749,11 +740,11 @@ COM_TRY_END } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _items.Size(); if (numItems == 0) @@ -785,23 +776,23 @@ for (i = 0; i < numItems; i++) { lps->InSize = lps->OutSize = currentTotalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - Int32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; const CItem &item = _items[index]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) currentTotalSize += (item.TextFileIndex >= 0) ? (UInt64)_libFiles[(unsigned)item.TextFileIndex].Len() : item.Size; if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) if (testMode) { - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } bool isOk = true; @@ -809,25 +800,25 @@ { const AString &f = _libFiles[(unsigned)item.TextFileIndex]; if (realOutStream) - RINOK(WriteStream(realOutStream, f, f.Len())); + RINOK(WriteStream(realOutStream, f, f.Len())) } else { - RINOK(_stream->Seek(item.GetDataPos(), STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_stream, item.GetDataPos())) streamSpec->Init(item.Size); - RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)) isOk = (copyCoderSpec->TotalSize == item.Size); } realOutStream.Release(); RINOK(extractCallback->SetOperationResult(isOk ? NExtract::NOperationResult::kOK: - NExtract::NOperationResult::kDataError)); + NExtract::NOperationResult::kDataError)) } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN const CItem &item = _items[index]; @@ -843,7 +834,7 @@ } REGISTER_ARC_I( - "Ar", "ar a deb udeb lib", 0, 0xEC, + "Ar", "ar a deb udeb lib", NULL, 0xEC, kSignature, 0, 0, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/ArjHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/ArjHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/ArjHandler.cpp 2022-02-14 07:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/ArjHandler.cpp 2023-03-27 17:00:00.000000000 +0000 @@ -31,10 +31,11 @@ static const UInt32 kWindowSize = 1 << 15; // must be >= (1 << 14) -class CCoder: - public ICompressCoder, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_NOQIB_1( + CCoder + , ICompressCoder +) CLzOutWindow _outWindow; NBitm::CDecoder _inBitStream; @@ -50,16 +51,13 @@ HRESULT CodeReal(UInt64 outSize, ICompressProgressInfo *progress); public: - MY_UNKNOWN_IMP - bool FinishMode; - CCoder(): FinishMode(false) {} - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); + CCoder(): FinishMode(false) {} UInt64 GetInputProcessedSize() const { return _inBitStream.GetProcessedSize(); } }; + HRESULT CCoder::CodeReal(UInt64 rem, ICompressProgressInfo *progress) { const UInt32 kStep = 1 << 20; @@ -76,7 +74,7 @@ UInt64 packSize = _inBitStream.GetProcessedSize(); UInt64 pos = _outWindow.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &pos)); + RINOK(progress->SetRatioInfo(&packSize, &pos)) next = 0; if (rem > kStep) next = rem - kStep; @@ -152,8 +150,8 @@ -STDMETHODIMP CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress)) { try { @@ -367,10 +365,10 @@ // LastChapter = p[29]; unsigned pos = headerSize; unsigned size1 = size - pos; - RINOK(ReadString(p + pos, size1, Name)); + RINOK(ReadString(p + pos, size1, Name)) pos += size1; size1 = size - pos; - RINOK(ReadString(p + pos, size1, Comment)); + RINOK(ReadString(p + pos, size1, Comment)) pos += size1; return S_OK; } @@ -477,10 +475,10 @@ unsigned pos = headerSize; unsigned size1 = size - pos; - RINOK(ReadString(p + pos, size1, Name)); + RINOK(ReadString(p + pos, size1, Name)) pos += size1; size1 = size - pos; - RINOK(ReadString(p + pos, size1, Comment)); + RINOK(ReadString(p + pos, size1, Comment)) pos += size1; return S_OK; @@ -570,7 +568,7 @@ if (extendedInfo) extendedInfo->Size += _blockSize; - READ_STREAM(_block, readSize); + READ_STREAM(_block, readSize) if (Get32(_block + _blockSize) != CrcCalc(_block, _blockSize)) { if (extendedInfo) @@ -591,28 +589,28 @@ for (UInt32 i = 0;; i++) { bool filled; - RINOK(ReadBlock(filled, &extendedInfo)); + RINOK(ReadBlock(filled, &extendedInfo)) if (!filled) return S_OK; if (Callback && (i & 0xFF) == 0) - RINOK(Callback->SetCompleted(&NumFiles, &Processed)); + RINOK(Callback->SetCompleted(&NumFiles, &Processed)) } } HRESULT CArc::Open() { bool filled; - RINOK(ReadBlock(filled, NULL)); // (extendedInfo = NULL) + RINOK(ReadBlock(filled, NULL)) // (extendedInfo = NULL) if (!filled) return S_FALSE; - RINOK(Header.Parse(_block, _blockSize)); + RINOK(Header.Parse(_block, _blockSize)) IsArc = true; return SkipExtendedHeaders(ExtendedInfo); } HRESULT CArc::GetNextItem(CItem &item, bool &filled) { - RINOK(ReadBlock(filled, NULL)); // (extendedInfo = NULL) + RINOK(ReadBlock(filled, NULL)) // (extendedInfo = NULL) if (!filled) return S_OK; filled = false; @@ -627,23 +625,18 @@ extraData = GetUi32(_block + pos); */ - RINOK(SkipExtendedHeaders(item.ExtendedInfo)); + RINOK(SkipExtendedHeaders(item.ExtendedInfo)) filled = true; return S_OK; } -class CHandler: - public IInArchive, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_CHandler_IInArchive_0 + CObjectVector _items; CMyComPtr _stream; UInt64 _phySize; CArc _arc; -public: - MY_UNKNOWN_IMP1(IInArchive) - - INTERFACE_IInArchive(;) HRESULT Open2(IInStream *inStream, IArchiveOpenCallback *callback); }; @@ -696,7 +689,7 @@ prop = MultiByteToUnicodeString(s, CP_OEMCP); } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -717,7 +710,7 @@ case k_ErrorType_UnexpectedEnd: v |= kpv_ErrorFlags_UnexpectedEnd; break; case k_ErrorType_Corrupted: v |= kpv_ErrorFlags_HeadersError; break; case k_ErrorType_OK: - default: + // default: break; } prop = v; @@ -730,13 +723,13 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _items.Size(); return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -766,16 +759,15 @@ { Close(); - UInt64 endPos = 0; - RINOK(inStream->Seek(0, STREAM_SEEK_END, &endPos)); - RINOK(inStream->Seek(0, STREAM_SEEK_SET, NULL)); + UInt64 endPos; + RINOK(InStream_AtBegin_GetSize(inStream, endPos)) _arc.Stream = inStream; _arc.Callback = callback; _arc.NumFiles = 0; _arc.Processed = 0; - RINOK(_arc.Open()); + RINOK(_arc.Open()) _phySize = _arc.Processed; if (_arc.Header.ArchiveSize != 0) @@ -787,7 +779,7 @@ bool filled; _arc.Error = k_ErrorType_OK; - RINOK(_arc.GetNextItem(item, filled)); + RINOK(_arc.GetNextItem(item, filled)) if (_arc.Error != k_ErrorType_OK) break; @@ -811,20 +803,20 @@ break; } - RINOK(inStream->Seek(pos, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(inStream, pos)) _arc.NumFiles = _items.Size(); _arc.Processed = pos; if (callback && (_items.Size() & 0xFF) == 0) { - RINOK(callback->SetCompleted(&_arc.NumFiles, &_arc.Processed)); + RINOK(callback->SetCompleted(&_arc.NumFiles, &_arc.Processed)) } } return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *inStream, - const UInt64 * /* maxCheckStartPosition */, IArchiveOpenCallback *callback) +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, + const UInt64 * /* maxCheckStartPosition */, IArchiveOpenCallback *callback)) { COM_TRY_BEGIN HRESULT res; @@ -840,7 +832,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _arc.Close(); _phySize = 0; @@ -849,12 +841,12 @@ return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN UInt64 totalUnpacked = 0, totalPacked = 0; - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _items.Size(); if (numItems == 0) @@ -892,24 +884,24 @@ { lps->InSize = totalPacked; lps->OutSize = totalUnpacked; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) curUnpacked = curPacked = 0; CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - Int32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; const CItem &item = _items[index]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) if (item.IsDir()) { // if (!testMode) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) } continue; } @@ -917,7 +909,7 @@ if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) curUnpacked = item.Size; curPacked = item.PackSize; @@ -930,8 +922,7 @@ inStreamSpec->Init(item.PackSize); - UInt64 pos; - _stream->Seek(item.DataPosition, STREAM_SEEK_SET, &pos); + RINOK(InStream_SeekSet(_stream, item.DataPosition)) HRESULT result = S_OK; Int32 opRes = NExtract::NOperationResult::kOK; @@ -990,7 +981,7 @@ opRes = NExtract::NOperationResult::kDataError; else { - RINOK(result); + RINOK(result) opRes = (outStreamSpec->GetCRC() == item.FileCRC) ? NExtract::NOperationResult::kOK: NExtract::NOperationResult::kCRCError; @@ -998,7 +989,7 @@ } outStream.Release(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } } @@ -1009,7 +1000,7 @@ static const Byte k_Signature[] = { kSig0, kSig1 }; REGISTER_ARC_I( - "Arj", "arj", 0, 4, + "Arj", "arj", NULL, 4, k_Signature, 0, 0, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Base64Handler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Base64Handler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Base64Handler.cpp 2021-01-22 19:47:01.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Base64Handler.cpp 2023-03-27 17:00:00.000000000 +0000 @@ -207,7 +207,7 @@ { if (size == 0) return p; - UInt32 c = k_Base64Table[(Byte)(*p++)]; + const UInt32 c = k_Base64Table[(Byte)(*p++)]; size--; if (c == k_Code_Space) continue; @@ -225,7 +225,7 @@ for (;;) { - UInt32 c = k_Base64Table[(Byte)(*src++)]; + const UInt32 c = k_Base64Table[(Byte)(*src++)]; if (c < 64) { @@ -266,7 +266,7 @@ for (;;) { - Byte c = k_Base64Table[(Byte)(*src++)]; + const Byte c = k_Base64Table[(Byte)(*src++)]; if (c == k_Code_Space) continue; if (c == k_Code_Zero) @@ -279,18 +279,13 @@ namespace NArchive { namespace NBase64 { -class CHandler: - public IInArchive, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_0 + bool _isArc; UInt64 _phySize; size_t _size; EBase64Res _sres; CByteBuffer _data; -public: - MY_UNKNOWN_IMP1(IInArchive) - INTERFACE_IInArchive(;) }; static const Byte kProps[] = @@ -302,13 +297,13 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps_NO_Table -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = 1; return S_OK; } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { NWindows::NCOM::CPropVariant prop; switch (propID) @@ -328,7 +323,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)) { // COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -349,22 +344,22 @@ while (size != 0) { const UInt32 kBlockSize = ((UInt32)1 << 24); - UInt32 curSize = (size < kBlockSize) ? (UInt32)size : kBlockSize; + const UInt32 curSize = (size < kBlockSize) ? (UInt32)size : kBlockSize; UInt32 processedSizeLoc; - RINOK(stream->Read(data, curSize, &processedSizeLoc)); + RINOK(stream->Read(data, curSize, &processedSizeLoc)) if (processedSizeLoc == 0) return E_FAIL; data = (void *)((Byte *)data + processedSizeLoc); size -= processedSizeLoc; bytes += processedSizeLoc; const UInt64 files = 1; - RINOK(openCallback->SetCompleted(&files, &bytes)); + RINOK(openCallback->SetCompleted(&files, &bytes)) } return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *openCallback) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *openCallback)) { COM_TRY_BEGIN { @@ -373,7 +368,7 @@ const unsigned kStartSize = 1 << 12; _data.Alloc(kStartSize); size_t size = kStartSize; - RINOK(ReadStream(stream, _data, &size)); + RINOK(ReadStream(stream, _data, &size)) UInt32 isArcRes = IsArc_Base64(_data, size); if (isArcRes == k_IsArc_Res_NO) return S_FALSE; @@ -381,7 +376,7 @@ _isArc = true; UInt64 packSize64; - RINOK(stream->Seek(0, STREAM_SEEK_END, &packSize64)); + RINOK(InStream_GetSize_SeekToEnd(stream, packSize64)) if (packSize64 == 0) return S_FALSE; @@ -393,16 +388,16 @@ for (;;) { - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, 0)) _data.Alloc(curSize); - RINOK(ReadStream_OpenProgress(stream, _data, curSize, openCallback)); + RINOK(ReadStream_OpenProgress(stream, _data, curSize, openCallback)) const Byte *srcEnd; Byte *dest; _sres = Base64ToBin(_data, curSize, &srcEnd, &dest); - _size = dest - _data; - size_t mainSize = srcEnd - _data; + _size = (size_t)(dest - _data); + const size_t mainSize = (size_t)(srcEnd - _data); _phySize = mainSize; if (_sres == k_Base64_RES_UnexpectedChar) break; @@ -431,7 +426,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _phySize = 0; _size = 0; @@ -442,19 +437,16 @@ } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); - if (allFilesMode) - numItems = 1; if (numItems == 0) return S_OK; - if (numItems != 1 || *indices != 0) + if (numItems != (UInt32)(Int32)-1 && (numItems != 1 || indices[0] != 0)) return E_INVALIDARG; - RINOK(extractCallback->SetTotal(_size)); + RINOK(extractCallback->SetTotal(_size)) CLocalProgress *lps = new CLocalProgress; CMyComPtr progress = lps; @@ -462,14 +454,14 @@ { lps->InSize = lps->OutSize = 0; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(0, &realOutStream, askMode)) if (!testMode && !realOutStream) return S_OK; @@ -478,7 +470,7 @@ if (realOutStream) { - RINOK(WriteStream(realOutStream, (const Byte *)_data, _size)); + RINOK(WriteStream(realOutStream, (const Byte *)_data, _size)) realOutStream.Release(); } @@ -492,7 +484,7 @@ opRes = NExtract::NOperationResult::kDataError; } - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } lps->InSize = _phySize; @@ -503,9 +495,11 @@ } REGISTER_ARC_I_NO_SIG( - "Base64", "b64", 0, 0xC5, + "Base64", "b64", NULL, 0xC5, 0, - NArcInfoFlags::kKeepName | NArcInfoFlags::kStartOpen | NArcInfoFlags::kByExtOnlyOpen, + NArcInfoFlags::kKeepName + | NArcInfoFlags::kStartOpen + | NArcInfoFlags::kByExtOnlyOpen, IsArc_Base64) }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Bz2Handler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Bz2Handler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Bz2Handler.cpp 2022-04-30 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Bz2Handler.cpp 2023-03-27 17:00:00.000000000 +0000 @@ -20,13 +20,11 @@ namespace NArchive { namespace NBz2 { -class CHandler: - public IInArchive, - public IArchiveOpenSeq, - public IOutArchive, - public ISetProperties, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_3( + IArchiveOpenSeq, + IOutArchive, + ISetProperties +) CMyComPtr _stream; CMyComPtr _seqStream; @@ -46,19 +44,6 @@ UInt64 _numBlocks; CSingleMethodProps _props; - -public: - MY_UNKNOWN_IMP4( - IInArchive, - IArchiveOpenSeq, - IOutArchive, - ISetProperties) - INTERFACE_IInArchive(;) - INTERFACE_IOutArchive(;) - STDMETHOD(OpenSeq)(ISequentialInStream *stream); - STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps); - - CHandler() { } }; static const Byte kProps[] = @@ -76,7 +61,7 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; switch (propID) @@ -88,7 +73,7 @@ case kpidErrorFlags: { UInt32 v = 0; - if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;; + if (!_isArc) v |= kpv_ErrorFlags_IsNotArc; if (_needMoreInput) v |= kpv_ErrorFlags_UnexpectedEnd; if (_dataAfterEnd) v |= kpv_ErrorFlags_DataAfterEnd; prop = v; @@ -98,13 +83,13 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = 1; return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; switch (propID) @@ -133,13 +118,13 @@ } } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *)) { COM_TRY_BEGIN Close(); { Byte buf[kSignatureCheckSize]; - RINOK(ReadStream_FALSE(stream, buf, kSignatureCheckSize)); + RINOK(ReadStream_FALSE(stream, buf, kSignatureCheckSize)) if (IsArc_BZip2(buf, kSignatureCheckSize) == k_IsArc_Res_NO) return S_FALSE; _isArc = true; @@ -152,7 +137,7 @@ } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { Close(); _isArc = true; @@ -160,7 +145,7 @@ return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; _needSeekToStart = false; @@ -180,8 +165,8 @@ } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN if (numItems == 0) @@ -193,10 +178,10 @@ extractCallback->SetTotal(_packSize); CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(0, &realOutStream, askMode)) if (!testMode && !realOutStream) return S_OK; @@ -206,7 +191,7 @@ { if (!_stream) return E_FAIL; - RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(_stream)) } else _needSeekToStart = true; @@ -216,8 +201,8 @@ NCompress::NBZip2::CDecoder *decoderSpec = new NCompress::NBZip2::CDecoder; CMyComPtr decoder = decoderSpec; - #ifndef _7ZIP_ST - RINOK(decoderSpec->SetNumberOfThreads(_props._numThreads)); + #ifndef Z7_ST + RINOK(decoderSpec->SetNumberOfThreads(_props._numThreads)) #endif CDummyOutStream *outStreamSpec = new CDummyOutStream; @@ -240,7 +225,7 @@ lps->InSize = 0; lps->OutSize = 0; - HRESULT result = decoderSpec->Code(_seqStream, outStream, NULL, NULL, progress); + HRESULT result = decoder->Code(_seqStream, outStream, NULL, NULL, progress); if (result != S_FALSE && result != S_OK) return result; @@ -352,12 +337,13 @@ { { CMyComPtr fileInStream; - RINOK(updateCallback->GetStream(0, &fileInStream)); + RINOK(updateCallback->GetStream(0, &fileInStream)) if (!fileInStream) return S_FALSE; { - CMyComPtr streamGetSize; - fileInStream.QueryInterface(IID_IStreamGetSize, &streamGetSize); + Z7_DECL_CMyComPtr_QI_FROM( + IStreamGetSize, + streamGetSize, fileInStream) if (streamGetSize) { UInt64 size; @@ -365,15 +351,15 @@ unpackSize = size; } } - RINOK(updateCallback->SetTotal(unpackSize)); + RINOK(updateCallback->SetTotal(unpackSize)) CLocalProgress *localProgressSpec = new CLocalProgress; CMyComPtr localProgress = localProgressSpec; localProgressSpec->Init(updateCallback, true); { NCompress::NBZip2::CEncoder *encoderSpec = new NCompress::NBZip2::CEncoder; CMyComPtr encoder = encoderSpec; - RINOK(props.SetCoderProps(encoderSpec, NULL)); - RINOK(encoder->Code(fileInStream, outStream, NULL, NULL, localProgress)); + RINOK(props.SetCoderProps(encoderSpec, NULL)) + RINOK(encoder->Code(fileInStream, outStream, NULL, NULL, localProgress)) /* if (reportArcProp) { @@ -386,37 +372,42 @@ return updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK); } -STDMETHODIMP CHandler::GetFileTimeType(UInt32 *timeType) +Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *timeType)) { *timeType = GET_FileTimeType_NotDefined_for_GetFileTimeType; // *timeType = NFileTimeType::kUnix; return S_OK; } -STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, - IArchiveUpdateCallback *updateCallback) +Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, + IArchiveUpdateCallback *updateCallback)) { COM_TRY_BEGIN if (numItems != 1) return E_INVALIDARG; + { + Z7_DECL_CMyComPtr_QI_FROM( + IStreamSetRestriction, + setRestriction, outStream) + if (setRestriction) + RINOK(setRestriction->SetRestriction(0, 0)) + } + Int32 newData, newProps; UInt32 indexInArchive; if (!updateCallback) return E_FAIL; - RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProps, &indexInArchive)); + RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProps, &indexInArchive)) - /* - CMyComPtr reportArcProp; - updateCallback->QueryInterface(IID_IArchiveUpdateCallbackArcProp, (void **)&reportArcProp); - */ + // Z7_DECL_CMyComPtr_QI_FROM(IArchiveUpdateCallbackArcProp, reportArcProp, updateCallback) if (IntToBool(newProps)) { { NCOM::CPropVariant prop; - RINOK(updateCallback->GetProperty(0, kpidIsDir, &prop)); + RINOK(updateCallback->GetProperty(0, kpidIsDir, &prop)) if (prop.vt != VT_EMPTY) if (prop.vt != VT_BOOL || prop.boolVal != VARIANT_FALSE) return E_INVALIDARG; @@ -428,14 +419,14 @@ UInt64 size; { NCOM::CPropVariant prop; - RINOK(updateCallback->GetProperty(0, kpidSize, &prop)); + RINOK(updateCallback->GetProperty(0, kpidSize, &prop)) if (prop.vt != VT_UI8) return E_INVALIDARG; size = prop.uhVal.QuadPart; } CMethodProps props2 = _props; - #ifndef _7ZIP_ST + #ifndef Z7_ST props2.AddProp_NumThreads(_props._numThreads); #endif @@ -449,8 +440,9 @@ CMyComPtr progress = lps; lps->Init(updateCallback, true); - CMyComPtr opCallback; - updateCallback->QueryInterface(IID_IArchiveUpdateCallbackFile, (void **)&opCallback); + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveUpdateCallbackFile, + opCallback, updateCallback) if (opCallback) { RINOK(opCallback->ReportOperation( @@ -459,7 +451,7 @@ } if (_stream) - RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(_stream)) return NCompress::CopyStream(_stream, outStream, progress); @@ -468,7 +460,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) +Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps)) { return _props.SetProperties(names, values, numProps); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabBlockInStream.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabBlockInStream.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabBlockInStream.cpp 2015-08-31 06:53:06.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabBlockInStream.cpp 2023-01-28 17:00:00.000000000 +0000 @@ -18,7 +18,7 @@ { if (!_buf) _buf = (Byte *)::MyAlloc(kBlockSize); - return _buf != 0; + return _buf != NULL; } CCabBlockInStream::~CCabBlockInStream() @@ -60,7 +60,7 @@ unpackSize = GetUi16(header + 6); if (packSize > kBlockSize - _size) return S_FALSE; - RINOK(ReadStream_FALSE(stream, _buf + _size, packSize)); + RINOK(ReadStream_FALSE(stream, _buf + _size, packSize)) if (MsZip) { @@ -82,7 +82,7 @@ return S_OK; } -STDMETHODIMP CCabBlockInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CCabBlockInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (size != 0) { diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabBlockInStream.h 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabBlockInStream.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabBlockInStream.h 2015-09-11 13:22:25.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabBlockInStream.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // CabBlockInStream.h -#ifndef __CAB_BLOCK_IN_STREAM_H -#define __CAB_BLOCK_IN_STREAM_H +#ifndef ZIP7_INC_CAB_BLOCK_IN_STREAM_H +#define ZIP7_INC_CAB_BLOCK_IN_STREAM_H #include "../../../Common/MyCom.h" #include "../../IStream.h" @@ -9,10 +9,10 @@ namespace NArchive { namespace NCab { -class CCabBlockInStream: - public ISequentialInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + CCabBlockInStream + , ISequentialInStream +) Byte *_buf; UInt32 _size; UInt32 _pos; @@ -21,9 +21,7 @@ UInt32 ReservedSize; // < 256 bool MsZip; - MY_UNKNOWN_IMP - - CCabBlockInStream(): _buf(0), ReservedSize(0), MsZip(false) {} + CCabBlockInStream(): _buf(NULL), ReservedSize(0), MsZip(false) {} ~CCabBlockInStream(); bool Create(); @@ -34,8 +32,6 @@ UInt32 GetPackSizeAvail() const { return _size - _pos; } const Byte *GetData() const { return _buf + _pos; } - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabHandler.cpp 2022-02-14 07:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabHandler.cpp 2023-03-26 12:00:00.000000000 +0000 @@ -32,9 +32,9 @@ namespace NArchive { namespace NCab { -// #define _CAB_DETAILS +// #define CAB_DETAILS -#ifdef _CAB_DETAILS +#ifdef CAB_DETAILS enum { kpidBlockReal = kpidUserDefined @@ -49,7 +49,7 @@ kpidAttrib, kpidMethod, kpidBlock - #ifdef _CAB_DETAILS + #ifdef CAB_DETAILS , // kpidBlockReal, // L"BlockReal", kpidOffset, @@ -83,7 +83,7 @@ static void SetMethodName(char *s, unsigned method, unsigned param) { - if (method < ARRAY_SIZE(kMethods)) + if (method < Z7_ARRAY_SIZE(kMethods)) { s = MyStpCpy(s, kMethods[method]); if (method != NHeader::NMethod::kLZX && @@ -95,7 +95,7 @@ ConvertUInt32ToString(method, s); } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -267,7 +267,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -305,7 +305,7 @@ if (realFolderIndex >= 0) { const CFolder &folder = db.Folders[(unsigned)realFolderIndex]; - char s[kMethodNameBufSize];; + char s[kMethodNameBufSize]; SetMethodName(s, folder.GetMethod(), folder.MethodMinor); prop = s; } @@ -314,7 +314,7 @@ case kpidBlock: prop.Set_Int32((Int32)m_Database.GetFolderIndex(&mvItem)); break; - #ifdef _CAB_DETAILS + #ifdef CAB_DETAILS // case kpidBlockReal: prop = (UInt32)item.FolderIndex; break; case kpidOffset: prop = (UInt32)item.Offset; break; @@ -327,9 +327,9 @@ COM_TRY_END } -STDMETHODIMP CHandler::Open(IInStream *inStream, +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 *maxCheckStartPosition, - IArchiveOpenCallback *callback) + IArchiveOpenCallback *callback)) { COM_TRY_BEGIN Close(); @@ -418,7 +418,7 @@ if (callback) { - RINOK(callback->SetCompleted(&numItems, NULL)); + RINOK(callback->SetCompleted(&numItems, NULL)) } nextStream = NULL; @@ -471,7 +471,7 @@ startVolName_was_Requested = true; { NCOM::CPropVariant prop; - RINOK(openVolumeCallback->GetProperty(kpidName, &prop)); + RINOK(openVolumeCallback->GetProperty(kpidName, &prop)) if (prop.vt == VT_BSTR) startVolName = prop.bstrVal; } @@ -520,7 +520,7 @@ return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _errorMessage.Empty(); _isArc = false; @@ -534,15 +534,11 @@ return S_OK; } -class CFolderOutStream: - public ISequentialOutStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); -private: +Z7_CLASS_IMP_NOQIB_1( + CFolderOutStream + , ISequentialOutStream +) const CMvDatabaseEx *m_Database; const CRecordVector *m_ExtractStatuses; @@ -681,10 +677,10 @@ while (NumIdenticalFiles && !(*m_ExtractStatuses)[m_CurrentIndex]) { CMyComPtr stream; - RINOK(m_ExtractCallback->GetStream(m_StartIndex + m_CurrentIndex, &stream, NExtract::NAskMode::kSkip)); + RINOK(m_ExtractCallback->GetStream(m_StartIndex + m_CurrentIndex, &stream, NExtract::NAskMode::kSkip)) if (stream) return E_FAIL; - RINOK(m_ExtractCallback->PrepareOperation(NExtract::NAskMode::kSkip)); + RINOK(m_ExtractCallback->PrepareOperation(NExtract::NAskMode::kSkip)) m_CurrentIndex++; m_FileIsOpen = true; CloseFile(); @@ -692,11 +688,11 @@ } } - Int32 askMode = (*m_ExtractStatuses)[m_CurrentIndex] ? (m_TestMode ? + Int32 askMode = (*m_ExtractStatuses)[m_CurrentIndex] ? m_TestMode ? NExtract::NAskMode::kTest : - NExtract::NAskMode::kExtract) : + NExtract::NAskMode::kExtract : NExtract::NAskMode::kSkip; - RINOK(m_ExtractCallback->GetStream(m_StartIndex + m_CurrentIndex, &m_RealOutStream, askMode)); + RINOK(m_ExtractCallback->GetStream(m_StartIndex + m_CurrentIndex, &m_RealOutStream, askMode)) if (!m_RealOutStream && !m_TestMode) askMode = NExtract::NAskMode::kSkip; return m_ExtractCallback->PrepareOperation(askMode); @@ -716,14 +712,14 @@ return S_OK; HRESULT result = OpenFile(); m_RealOutStream.Release(); - RINOK(result); - RINOK(m_ExtractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(result) + RINOK(m_ExtractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) } return S_OK; } -HRESULT CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { // (data == NULL) means Error_Data for solid folder flushing COM_TRY_BEGIN @@ -777,7 +773,7 @@ if (m_RemainFileSize == 0) { - RINOK(CloseFile()); + RINOK(CloseFile()) while (NumIdenticalFiles) { @@ -789,14 +785,14 @@ if (!TempBuf && TempBufMode && m_RealOutStream) { - RINOK(CloseFileWithResOp(NExtract::NOperationResult::kUnsupportedMethod)); + RINOK(CloseFileWithResOp(NExtract::NOperationResult::kUnsupportedMethod)) } else { - RINOK(CloseFile()); + RINOK(CloseFile()) } - RINOK(result); + RINOK(result) } TempBufMode = false; @@ -842,7 +838,7 @@ if (fileOffset == m_PosInFolder) { - RINOK(OpenFile()); + RINOK(OpenFile()) m_FileIsOpen = true; m_CurrentIndex++; m_IsOk = true; @@ -860,11 +856,11 @@ { if (!NeedMoreWrite()) { - CMyComPtr callbackMessage; - m_ExtractCallback.QueryInterface(IID_IArchiveExtractCallbackMessage, &callbackMessage); + CMyComPtr callbackMessage; + m_ExtractCallback.QueryInterface(IID_IArchiveExtractCallbackMessage2, &callbackMessage); if (callbackMessage) { - RINOK(callbackMessage->ReportExtractResult(NEventIndexType::kBlockIndex, folderIndex, NExtract::NOperationResult::kDataError)); + RINOK(callbackMessage->ReportExtractResult(NEventIndexType::kBlockIndex, folderIndex, NExtract::NOperationResult::kDataError)) } return S_OK; } @@ -878,7 +874,7 @@ if (size > remain) size = (UInt32)remain; UInt32 processedSizeLocal = 0; - RINOK(Write(NULL, size, &processedSizeLocal)); + RINOK(Write(NULL, size, &processedSizeLocal)) } } @@ -891,19 +887,18 @@ if (result != S_FALSE && result != S_OK) return result; m_RealOutStream.Release(); - RINOK(m_ExtractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)); + RINOK(m_ExtractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)) m_CurrentIndex++; } return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testModeSpec, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testModeSpec, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = m_Database.Items.Size(); if (numItems == 0) @@ -964,45 +959,45 @@ { lps->OutSize = totalUnPacked; lps->InSize = totalPacked; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) if (i >= numItems) break; - unsigned index = allFilesMode ? i : indices[i]; + const unsigned index = allFilesMode ? i : indices[i]; const CMvItem &mvItem = m_Database.Items[index]; const CDatabaseEx &db = m_Database.Volumes[mvItem.VolumeIndex]; - unsigned itemIndex = mvItem.ItemIndex; + const unsigned itemIndex = mvItem.ItemIndex; const CItem &item = db.Items[itemIndex]; i++; if (item.IsDir()) { - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; CMyComPtr realOutStream; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) + RINOK(extractCallback->PrepareOperation(askMode)) realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } - int folderIndex = m_Database.GetFolderIndex(&mvItem); + const int folderIndex = m_Database.GetFolderIndex(&mvItem); if (folderIndex < 0) { // If we need previous archive - Int32 askMode= testMode ? + const Int32 askMode= testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; CMyComPtr realOutStream; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) + RINOK(extractCallback->PrepareOperation(askMode)) realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kDataError)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kDataError)) continue; } @@ -1017,12 +1012,12 @@ for (; i < numItems; i++) { - unsigned indexNext = allFilesMode ? i : indices[i]; + const unsigned indexNext = allFilesMode ? i : indices[i]; const CMvItem &mvItem2 = m_Database.Items[indexNext]; const CItem &item2 = m_Database.Volumes[mvItem2.VolumeIndex].Items[mvItem2.ItemIndex]; if (item2.IsDir()) continue; - int newFolderIndex = m_Database.GetFolderIndex(&mvItem2); + const int newFolderIndex = m_Database.GetFolderIndex(&mvItem2); if (newFolderIndex != folderIndex) break; @@ -1086,11 +1081,11 @@ if (res == E_INVALIDARG) { - RINOK(cabFolderOutStream->Unsupported()); + RINOK(cabFolderOutStream->Unsupported()) totalUnPacked += curUnpack; continue; } - RINOK(res); + RINOK(res) { unsigned volIndex = mvItem.VolumeIndex; @@ -1115,7 +1110,7 @@ if (bl == 0) { cabBlockInStreamSpec->ReservedSize = db2.ArcInfo.GetDataBlockReserveSize(); - RINOK(db2.Stream->Seek((Int64)(db2.StartPosition + folder2.DataStart), STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(db2.Stream, db2.StartPosition + folder2.DataStart)) } if (bl == folder2.NumDataBlocks) @@ -1146,7 +1141,7 @@ res = cabBlockInStreamSpec->PreRead(db2.Stream, packSize, unpackSize); if (res == S_FALSE) break; - RINOK(res); + RINOK(res) keepInputBuffer = (unpackSize == 0); if (keepInputBuffer) continue; @@ -1156,7 +1151,7 @@ lps->OutSize = totalUnPacked2; lps->InSize = totalPacked; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) const UInt32 kBlockSizeMax = (1 << 15); @@ -1230,7 +1225,7 @@ if (res != S_OK) { if (res != S_FALSE) - RINOK(res); + RINOK(res) break; } @@ -1239,13 +1234,13 @@ if (res == S_OK) { - RINOK(cabFolderOutStream->WriteEmptyFiles()); + RINOK(cabFolderOutStream->WriteEmptyFiles()) } } if (res != S_OK || cabFolderOutStream->NeedMoreWrite()) { - RINOK(cabFolderOutStream->FlushCorrupted((unsigned)folderIndex2)); + RINOK(cabFolderOutStream->FlushCorrupted((unsigned)folderIndex2)) } totalUnPacked += curUnpack; @@ -1257,7 +1252,7 @@ } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = m_Database.Items.Size(); return S_OK; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabHandler.h 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabHandler.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabHandler.h 2013-11-02 15:57:53.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabHandler.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // CabHandler.h -#ifndef __CAB_HANDLER_H -#define __CAB_HANDLER_H +#ifndef ZIP7_INC_CAB_HANDLER_H +#define ZIP7_INC_CAB_HANDLER_H #include "../../../Common/MyCom.h" @@ -12,16 +12,8 @@ namespace NArchive { namespace NCab { -class CHandler: - public IInArchive, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP1(IInArchive) +Z7_CLASS_IMP_CHandler_IInArchive_0 - INTERFACE_IInArchive(;) - -private: CMvDatabaseEx m_Database; UString _errorMessage; bool _isArc; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabHeader.h 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabHeader.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabHeader.h 2015-02-10 08:17:38.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabHeader.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Archive/CabHeader.h -#ifndef __ARCHIVE_CAB_HEADER_H -#define __ARCHIVE_CAB_HEADER_H +#ifndef ZIP7_INC_ARCHIVE_CAB_HEADER_H +#define ZIP7_INC_ARCHIVE_CAB_HEADER_H #include "../../../Common/MyTypes.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabIn.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabIn.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabIn.cpp 2021-01-25 15:17:41.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabIn.cpp 2023-01-19 09:00:00.000000000 +0000 @@ -76,9 +76,9 @@ const Byte *Signature; UInt32 SignatureSize; - UInt32 _HeaderSize; - UInt32 _AlignSize; - UInt32 _BufUseCapacity; + UInt32 _headerSize; + UInt32 _alignSize; + UInt32 _bufUseCapacity; ISequentialInStream *Stream; UInt64 Processed; // Global offset of start of Buf @@ -87,10 +87,10 @@ UInt32 GetTotalCapacity(UInt32 basicSize, UInt32 headerSize) { - _HeaderSize = headerSize; - for (_AlignSize = (1 << 5); _AlignSize < _HeaderSize; _AlignSize <<= 1); - _BufUseCapacity = basicSize + _AlignSize; - return _BufUseCapacity + 16; + _headerSize = headerSize; + for (_alignSize = (1 << 5); _alignSize < _headerSize; _alignSize <<= 1); + _bufUseCapacity = basicSize + _alignSize; + return _bufUseCapacity + 16; } /* @@ -108,7 +108,7 @@ { Buf[End] = Signature[0]; // it's for fast search; - while (End - Pos >= _HeaderSize) + while (End - Pos >= _headerSize) { const Byte *p = Buf + Pos; Byte b = Signature[0]; @@ -118,9 +118,9 @@ if (*p == b) { break; } p++; } Pos = (UInt32)(p - Buf); - if (End - Pos < _HeaderSize) + if (End - Pos < _headerSize) { - Pos = End - _HeaderSize + 1; + Pos = End - _headerSize + 1; break; } UInt32 i; @@ -130,28 +130,28 @@ Pos++; } - if (Pos >= _AlignSize) + if (Pos >= _alignSize) { - UInt32 num = (Pos & ~(_AlignSize - 1)); + UInt32 num = (Pos & ~(_alignSize - 1)); Processed += num; Pos -= num; End -= num; memmove(Buf, Buf + num, End); } - UInt32 rem = _BufUseCapacity - End; + UInt32 rem = _bufUseCapacity - End; if (SearchLimit) { if (Processed + Pos > *SearchLimit) return S_FALSE; - UInt64 rem2 = *SearchLimit - (Processed + End) + _HeaderSize; + UInt64 rem2 = *SearchLimit - (Processed + End) + _headerSize; if (rem > rem2) rem = (UInt32)rem2; } UInt32 processedSize; - if (Processed == 0 && rem == _BufUseCapacity - _HeaderSize) - rem -= _AlignSize; // to make reads more aligned. - RINOK(Stream->Read(Buf + End, rem, &processedSize)); + if (Processed == 0 && rem == _bufUseCapacity - _headerSize) + rem -= _alignSize; // to make reads more aligned. + RINOK(Stream->Read(Buf + End, rem, &processedSize)) if (processedSize == 0) return S_FALSE; End += processedSize; @@ -189,7 +189,7 @@ HeaderError = false; db.Clear(); - RINOK(db.Stream->Seek(0, STREAM_SEEK_CUR, &db.StartPosition)); + RINOK(InStream_GetPos(db.Stream, db.StartPosition)) // UInt64 temp = db.StartPosition; CByteBuffer buffer; @@ -201,12 +201,12 @@ // for (int iii = 0; iii < 10000; iii++) { - // db.StartPosition = temp; RINOK(db.Stream->Seek(db.StartPosition, STREAM_SEEK_SET, NULL)); + // db.StartPosition = temp; RINOK(InStream_SeekSet(db.Stream, db.StartPosition)) const UInt32 kMainHeaderSize = 32; Byte header[kMainHeaderSize]; const UInt32 kBufSize = 1 << 15; - RINOK(ReadStream_FALSE(db.Stream, header, kMainHeaderSize)); + RINOK(ReadStream_FALSE(db.Stream, header, kMainHeaderSize)) if (memcmp(header, NHeader::kMarker, NHeader::kMarkerSize) == 0 && ai.Parse(header)) { limitedStreamSpec = new CLimitedSequentialInStream; @@ -216,7 +216,7 @@ buffer.Alloc(kBufSize); memcpy(buffer, header, kMainHeaderSize); UInt32 numProcessedBytes; - RINOK(limitedStream->Read(buffer + kMainHeaderSize, kBufSize - kMainHeaderSize, &numProcessedBytes)); + RINOK(limitedStream->Read(buffer + kMainHeaderSize, kBufSize - kMainHeaderSize, &numProcessedBytes)) _inBuffer.SetBuf(buffer, (UInt32)kBufSize, kMainHeaderSize + numProcessedBytes, kMainHeaderSize); } else @@ -241,7 +241,7 @@ for (;;) { - RINOK(finder.Find()); + RINOK(finder.Find()) if (ai.Parse(finder.Buf + finder.Pos)) { db.StartPosition = finder.Processed + finder.Pos; @@ -311,7 +311,7 @@ { // printf("\n!!! Seek Error !!!!\n"); // fflush(stdout); - RINOK(db.Stream->Seek((Int64)(db.StartPosition + ai.FileHeadersOffset), STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(db.Stream, db.StartPosition + ai.FileHeadersOffset)) limitedStreamSpec->Init(ai.Size - ai.FileHeadersOffset); _inBuffer.Init(); } @@ -357,7 +357,7 @@ -#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } +#define RINOZ(x) { int _tt_ = (x); if (_tt_ != 0) return _tt_; } static int CompareMvItems(const CMvItem *p1, const CMvItem *p2, void *param) { @@ -365,17 +365,17 @@ const CDatabaseEx &db1 = mvDb.Volumes[p1->VolumeIndex]; const CDatabaseEx &db2 = mvDb.Volumes[p2->VolumeIndex]; const CItem &item1 = db1.Items[p1->ItemIndex]; - const CItem &item2 = db2.Items[p2->ItemIndex];; + const CItem &item2 = db2.Items[p2->ItemIndex]; bool isDir1 = item1.IsDir(); bool isDir2 = item2.IsDir(); if (isDir1 && !isDir2) return -1; if (isDir2 && !isDir1) return 1; int f1 = mvDb.GetFolderIndex(p1); int f2 = mvDb.GetFolderIndex(p2); - RINOZ(MyCompare(f1, f2)); - RINOZ(MyCompare(item1.Offset, item2.Offset)); - RINOZ(MyCompare(item1.Size, item2.Size)); - RINOZ(MyCompare(p1->VolumeIndex, p2->VolumeIndex)); + RINOZ(MyCompare(f1, f2)) + RINOZ(MyCompare(item1.Offset, item2.Offset)) + RINOZ(MyCompare(item1.Size, item2.Size)) + RINOZ(MyCompare(p1->VolumeIndex, p2->VolumeIndex)) return MyCompare(p1->ItemIndex, p2->ItemIndex); } @@ -387,7 +387,7 @@ const CDatabaseEx &db1 = Volumes[p1->VolumeIndex]; const CDatabaseEx &db2 = Volumes[p2->VolumeIndex]; const CItem &item1 = db1.Items[p1->ItemIndex]; - const CItem &item2 = db2.Items[p2->ItemIndex];; + const CItem &item2 = db2.Items[p2->ItemIndex]; return GetFolderIndex(p1) == GetFolderIndex(p2) && item1.Offset == item2.Offset && item1.Size == item2.Size diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabIn.h 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabIn.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabIn.h 2021-01-25 15:08:45.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabIn.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Archive/CabIn.h -#ifndef __ARCHIVE_CAB_IN_H -#define __ARCHIVE_CAB_IN_H +#ifndef ZIP7_INC_ARCHIVE_CAB_IN_H +#define ZIP7_INC_ARCHIVE_CAB_IN_H #include "../../../Common/MyBuffer.h" #include "../../../Common/MyCom.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabItem.h 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabItem.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabItem.h 2021-01-25 15:07:17.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabItem.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Archive/CabItem.h -#ifndef __ARCHIVE_CAB_ITEM_H -#define __ARCHIVE_CAB_ITEM_H +#ifndef ZIP7_INC_ARCHIVE_CAB_ITEM_H +#define ZIP7_INC_ARCHIVE_CAB_ITEM_H #include "../../../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabRegister.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabRegister.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/CabRegister.cpp 2015-03-25 12:05:36.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/CabRegister.cpp 2022-12-20 16:00:00.000000000 +0000 @@ -10,7 +10,7 @@ namespace NCab { REGISTER_ARC_I( - "Cab", "cab", 0, 8, + "Cab", "cab", NULL, 8, NHeader::kMarker, 0, NArcInfoFlags::kFindSignature, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Cab/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Cab/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Chm/ChmHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Chm/ChmHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Chm/ChmHandler.cpp 2020-09-28 09:26:08.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Chm/ChmHandler.cpp 2023-03-26 13:00:00.000000000 +0000 @@ -27,9 +27,9 @@ namespace NArchive { namespace NChm { -// #define _CHM_DETAILS +// #define CHM_DETAILS -#ifdef _CHM_DETAILS +#ifdef CHM_DETAILS enum { @@ -45,7 +45,7 @@ kpidMethod, kpidBlock - #ifdef _CHM_DETAILS + #ifdef CHM_DETAILS , L"Section", kpidSection, kpidOffset @@ -63,7 +63,7 @@ IMP_IInArchive_ArcProps_NO_Table -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { // COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -97,7 +97,7 @@ // COM_TRY_END } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -160,7 +160,7 @@ prop = m_Database.GetFolder(index); break; - #ifdef _CHM_DETAILS + #ifdef CHM_DETAILS case kpidSection: prop = (UInt32)item.Section; break; case kpidOffset: prop = (UInt32)item.Offset; break; @@ -173,34 +173,10 @@ COM_TRY_END } -/* -class CProgressImp: public CProgressVirt -{ - CMyComPtr _callback; -public: - STDMETHOD(SetTotal)(const UInt64 *numFiles); - STDMETHOD(SetCompleted)(const UInt64 *numFiles); - CProgressImp(IArchiveOpenCallback *callback): _callback(callback) {}; -}; - -STDMETHODIMP CProgressImp::SetTotal(const UInt64 *numFiles) -{ - if (_callback) - return _callback->SetCompleted(numFiles, NULL); - return S_OK; -} -STDMETHODIMP CProgressImp::SetCompleted(const UInt64 *numFiles) -{ - if (_callback) - return _callback->SetCompleted(numFiles, NULL); - return S_OK; -} -*/ - -STDMETHODIMP CHandler::Open(IInStream *inStream, +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 *maxCheckStartPosition, - IArchiveOpenCallback * /* openArchiveCallback */) + IArchiveOpenCallback * /* openArchiveCallback */)) { COM_TRY_BEGIN Close(); @@ -208,13 +184,13 @@ { CInArchive archive(_help2); // CProgressImp progressImp(openArchiveCallback); - HRESULT res = archive.Open(inStream, maxCheckStartPosition, m_Database); + const HRESULT res = archive.Open(inStream, maxCheckStartPosition, m_Database); if (!archive.IsArc) m_ErrorFlags |= kpv_ErrorFlags_IsNotArc; if (archive.HeadersError) m_ErrorFlags |= kpv_ErrorFlags_HeadersError; if (archive.UnexpectedEnd) m_ErrorFlags |= kpv_ErrorFlags_UnexpectedEnd; if (archive.UnsupportedFeature) m_ErrorFlags |= kpv_ErrorFlags_UnsupportedFeature; - RINOK(res); + RINOK(res) /* if (m_Database.LowLevel) return S_FALSE; @@ -229,7 +205,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { m_ErrorFlags = 0; m_Database.Clear(); @@ -237,15 +213,22 @@ return S_OK; } -class CChmFolderOutStream: - public ISequentialOutStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP +Z7_CLASS_IMP_NOQIB_1( + CChmFolderOutStream + , ISequentialOutStream +) + bool m_TestMode; + bool m_IsOk; + bool m_FileIsOpen; + const CFilesDatabase *m_Database; + CMyComPtr m_ExtractCallback; + CMyComPtr m_RealOutStream; + UInt64 m_RemainFileSize; + HRESULT OpenFile(); + HRESULT WriteEmptyFiles(); HRESULT Write2(const void *data, UInt32 size, UInt32 *processedSize, bool isOK); - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); +public: UInt64 m_FolderSize; UInt64 m_PosInFolder; @@ -255,19 +238,6 @@ unsigned m_CurrentIndex; unsigned m_NumFiles; -private: - const CFilesDatabase *m_Database; - CMyComPtr m_ExtractCallback; - bool m_TestMode; - - bool m_IsOk; - bool m_FileIsOpen; - UInt64 m_RemainFileSize; - CMyComPtr m_RealOutStream; - - HRESULT OpenFile(); - HRESULT WriteEmptyFiles(); -public: void Init( const CFilesDatabase *database, IArchiveExtractCallback *extractCallback, @@ -290,12 +260,12 @@ HRESULT CChmFolderOutStream::OpenFile() { - Int32 askMode = (*m_ExtractStatuses)[m_CurrentIndex] ? (m_TestMode ? + Int32 askMode = (*m_ExtractStatuses)[m_CurrentIndex] ? m_TestMode ? NExtract::NAskMode::kTest : - NExtract::NAskMode::kExtract) : + NExtract::NAskMode::kExtract : NExtract::NAskMode::kSkip; m_RealOutStream.Release(); - RINOK(m_ExtractCallback->GetStream(m_StartIndex + m_CurrentIndex, &m_RealOutStream, askMode)); + RINOK(m_ExtractCallback->GetStream(m_StartIndex + m_CurrentIndex, &m_RealOutStream, askMode)) if (!m_RealOutStream && !m_TestMode) askMode = NExtract::NAskMode::kSkip; return m_ExtractCallback->PrepareOperation(askMode); @@ -307,13 +277,13 @@ return S_OK; for (; m_CurrentIndex < m_NumFiles; m_CurrentIndex++) { - UInt64 fileSize = m_Database->GetFileSize(m_StartIndex + m_CurrentIndex); + const UInt64 fileSize = m_Database->GetFileSize(m_StartIndex + m_CurrentIndex); if (fileSize != 0) return S_OK; - HRESULT result = OpenFile(); + const HRESULT result = OpenFile(); m_RealOutStream.Release(); - RINOK(result); - RINOK(m_ExtractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(result) + RINOK(m_ExtractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) } return S_OK; } @@ -358,7 +328,7 @@ RINOK(m_ExtractCallback->SetOperationResult( m_IsOk ? NExtract::NOperationResult::kOK: - NExtract::NOperationResult::kDataError)); + NExtract::NOperationResult::kDataError)) m_FileIsOpen = false; } if (realProcessed > 0) @@ -395,7 +365,7 @@ if (fileOffset == m_PosInSection) { - RINOK(OpenFile()); + RINOK(OpenFile()) m_FileIsOpen = true; m_CurrentIndex++; m_IsOk = true; @@ -406,7 +376,7 @@ return WriteEmptyFiles(); } -STDMETHODIMP CChmFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CChmFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { return Write2(data, size, processedSize, true); } @@ -423,7 +393,7 @@ { UInt32 size = (UInt32)MyMin(maxSize - m_PosInFolder, (UInt64)kBufferSize); UInt32 processedSizeLocal = 0; - RINOK(Write2(buffer, size, &processedSizeLocal, false)); + RINOK(Write2(buffer, size, &processedSizeLocal, false)) if (processedSizeLocal == 0) return S_OK; } @@ -431,11 +401,11 @@ } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testModeSpec, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testModeSpec, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = m_Database.NewFormat ? 1: @@ -479,13 +449,13 @@ lps->InSize = currentTotalSize; // Change it lps->OutSize = currentTotalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr realOutStream; - Int32 askMode= testMode ? + const Int32 askMode= testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - Int32 index = allFilesMode ? i : indices[i]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + const UInt32 index = allFilesMode ? i : indices[i]; + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) if (m_Database.NewFormat) { @@ -496,9 +466,9 @@ if (!testMode) { UInt32 size = m_Database.NewFormatString.Len(); - RINOK(WriteStream(realOutStream, (const char *)m_Database.NewFormatString, size)); + RINOK(WriteStream(realOutStream, (const char *)m_Database.NewFormatString, size)) } - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } @@ -508,27 +478,27 @@ if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) if (item.Section != 0) { - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)) continue; } if (testMode) { - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } - RINOK(m_Stream->Seek(m_Database.ContentOffset + item.Offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(m_Stream, m_Database.ContentOffset + item.Offset)) streamSpec->Init(item.Size); - RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)) realOutStream.Release(); RINOK(extractCallback->SetOperationResult((copyCoderSpec->TotalSize == item.Size) ? NExtract::NOperationResult::kOK: - NExtract::NOperationResult::kDataError)); + NExtract::NOperationResult::kDataError)) } return S_OK; } @@ -537,7 +507,7 @@ for (i = 0; i < numItems; i++) { - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; const CItem &item = m_Database.Items[m_Database.Indices[index]]; const UInt64 sectionIndex = item.Section; if (item.IsDir() || item.Size == 0) @@ -564,11 +534,11 @@ } } - RINOK(extractCallback->SetTotal(currentTotalSize)); + RINOK(extractCallback->SetTotal(currentTotalSize)) NCompress::NLzx::CDecoder *lzxDecoderSpec = NULL; CMyComPtr lzxDecoder; - CChmFolderOutStream *chmFolderOutStream = 0; + CChmFolderOutStream *chmFolderOutStream = NULL; CMyComPtr outStream; currentTotalSize = 0; @@ -579,7 +549,7 @@ for (i = 0;;) { - RINOK(extractCallback->SetCompleted(¤tTotalSize)); + RINOK(extractCallback->SetCompleted(¤tTotalSize)) if (i >= numItems) break; @@ -595,10 +565,10 @@ if (item.IsDir()) { CMyComPtr realOutStream; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) + RINOK(extractCallback->PrepareOperation(askMode)) realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } @@ -608,21 +578,21 @@ if (item.Size == 0 || sectionIndex == 0) { CMyComPtr realOutStream; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) Int32 opRes = NExtract::NOperationResult::kOK; if (!testMode && item.Size != 0) { - RINOK(m_Stream->Seek(m_Database.ContentOffset + item.Offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(m_Stream, m_Database.ContentOffset + item.Offset)) streamSpec->Init(item.Size); - RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)) if (copyCoderSpec->TotalSize != item.Size) opRes = NExtract::NOperationResult::kDataError; } realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) currentTotalSize += item.Size; continue; } @@ -631,11 +601,11 @@ { // we must report error here; CMyComPtr realOutStream; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kHeadersError)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kHeadersError)) continue; } @@ -644,11 +614,11 @@ if (!section.IsLzx()) { CMyComPtr realOutStream; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)) continue; } @@ -671,7 +641,7 @@ UInt64 folderIndex = m_Database.GetFolder(index); const UInt64 compressedPos = m_Database.ContentOffset + section.Offset; - RINOK(lzxDecoderSpec->SetParams_and_Alloc(lzxInfo.GetNumDictBits())); + RINOK(lzxDecoderSpec->SetParams_and_Alloc(lzxInfo.GetNumDictBits())) const CItem *lastItem = &item; extractStatuses.Clear(); @@ -679,7 +649,7 @@ for (;; folderIndex++) { - RINOK(extractCallback->SetCompleted(¤tTotalSize)); + RINOK(extractCallback->SetCompleted(¤tTotalSize)) UInt64 startPos = lzxInfo.GetFolderPos(folderIndex); UInt64 finishPos = lastItem->Offset + lastItem->Size; @@ -702,7 +672,7 @@ const CItem &nextItem = m_Database.Items[m_Database.Indices[nextIndex]]; if (nextItem.Section != sectionIndex) break; - UInt64 nextFolderIndex = m_Database.GetFolder(nextIndex); + const UInt64 nextFolderIndex = m_Database.GetFolder(nextIndex); if (nextFolderIndex != folderIndex) break; for (index++; index < nextIndex; index++) @@ -734,7 +704,7 @@ for (UInt32 b = 0; b < numBlocks; b++) { UInt64 completedSize = currentTotalSize + chmFolderOutStream->m_PosInSection - startPos; - RINOK(extractCallback->SetCompleted(&completedSize)); + RINOK(extractCallback->SetCompleted(&completedSize)) UInt64 bCur = startBlock + b; if (bCur >= rt.ResetOffsets.Size()) return E_FAIL; @@ -744,7 +714,7 @@ // chm writes full blocks. So we don't need to use reduced size for last block - RINOK(m_Stream->Seek(compressedPos + offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(m_Stream, compressedPos + offset)) streamSpec->SetStream(m_Stream); streamSpec->Init(compressedSize); @@ -777,7 +747,7 @@ } catch(...) { - RINOK(chmFolderOutStream->FlushCorrupted(unPackSize)); + RINOK(chmFolderOutStream->FlushCorrupted(unPackSize)) } currentTotalSize += folderSize; @@ -790,9 +760,9 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { - *numItems = m_Database.NewFormat ? 1: + *numItems = m_Database.NewFormat ? 1: (m_Database.LowLevel ? m_Database.Items.Size(): m_Database.Indices.Size()); @@ -805,7 +775,7 @@ REGISTER_ARC_I_CLS( CHandler(false), - "Chm", "chm chi chq chw", 0, 0xE9, + "Chm", "chm chi chq chw", NULL, 0xE9, k_Signature, 0, 0, @@ -819,7 +789,7 @@ REGISTER_ARC_I_CLS( CHandler(true), - "Hxs", "hxs hxi hxr hxq hxw lit", 0, 0xCE, + "Hxs", "hxs hxi hxr hxq hxw lit", NULL, 0xCE, k_Signature, 0, NArcInfoFlags::kFindSignature, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Chm/ChmHandler.h 7zip-23.01+dfsg/CPP/7zip/Archive/Chm/ChmHandler.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Chm/ChmHandler.h 2013-11-03 07:12:40.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Chm/ChmHandler.h 2023-03-26 12:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ChmHandler.h -#ifndef __ARCHIVE_CHM_HANDLER_H -#define __ARCHIVE_CHM_HANDLER_H +#ifndef ZIP7_INC_ARCHIVE_CHM_HANDLER_H +#define ZIP7_INC_ARCHIVE_CHM_HANDLER_H #include "../../../Common/MyCom.h" @@ -12,22 +12,14 @@ namespace NArchive { namespace NChm { -class CHandler: - public IInArchive, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP1(IInArchive) - - INTERFACE_IInArchive(;) - - bool _help2; - CHandler(bool help2): _help2(help2) {} +Z7_CLASS_IMP_CHandler_IInArchive_0 -private: CFilesDatabase m_Database; CMyComPtr m_Stream; + bool _help2; UInt32 m_ErrorFlags; +public: + CHandler(bool help2): _help2(help2) {} }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Chm/ChmIn.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Chm/ChmIn.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Chm/ChmIn.cpp 2021-04-18 08:30:29.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Chm/ChmIn.cpp 2023-01-19 10:00:00.000000000 +0000 @@ -10,6 +10,7 @@ #include "../../../Common/UTFConvert.h" #include "../../Common/LimitedStreams.h" +#include "../../Common/StreamUtils.h" #include "ChmIn.h" @@ -217,7 +218,7 @@ HRESULT CInArchive::ReadChunk(IInStream *inStream, UInt64 pos, UInt64 size) { - RINOK(inStream->Seek(pos, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(inStream, pos)) CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; CMyComPtr limitedStream(streamSpec); streamSpec->SetStream(inStream); @@ -350,7 +351,7 @@ return S_FALSE; if (offset == offsetLimit) break; - RINOK(ReadDirEntry(database)); + RINOK(ReadDirEntry(database)) numItems++; } @@ -570,7 +571,7 @@ } else { - RINOK(ReadDirEntry(database)); + RINOK(ReadDirEntry(database)) } numItems++; } @@ -616,7 +617,7 @@ return s; } -#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } +#define RINOZ(x) { int _tt_ = (x); if (_tt_ != 0) return _tt_; } static int CompareFiles(const unsigned *p1, const unsigned *p2, void *param) { @@ -634,9 +635,9 @@ } else { - RINOZ(MyCompare(item1.Section, item2.Section)); - RINOZ(MyCompare(item1.Offset, item2.Offset)); - RINOZ(MyCompare(item1.Size, item2.Size)); + RINOZ(MyCompare(item1.Section, item2.Section)) + RINOZ(MyCompare(item1.Offset, item2.Offset)) + RINOZ(MyCompare(item1.Size, item2.Size)) } return MyCompare(*p1, *p2); } @@ -705,7 +706,7 @@ { { // The NameList file - RINOK(DecompressStream(inStream, database, (AString)kNameList)); + RINOK(DecompressStream(inStream, database, (AString)kNameList)) /* UInt16 length = */ ReadUInt16(); UInt16 numSections = ReadUInt16(); for (unsigned i = 0; i < numSections; i++) @@ -740,7 +741,7 @@ if (database.Help2Format) { // Transform List - RINOK(DecompressStream(inStream, database, transformPrefix + kTransformList)); + RINOK(DecompressStream(inStream, database, transformPrefix + kTransformList)) if ((_chunkSize & 0xF) != 0) return S_FALSE; unsigned numGuids = (unsigned)(_chunkSize / 0x10); @@ -762,7 +763,7 @@ { // Control Data - RINOK(DecompressStream(inStream, database, sectionPrefix + kControlData)); + RINOK(DecompressStream(inStream, database, sectionPrefix + kControlData)) FOR_VECTOR (mi, section.Methods) { @@ -781,19 +782,19 @@ { // There is bug in VC6, if we use function call as parameter for inline function - UInt32 val32 = ReadUInt32(); - int n = GetLog(val32); + const UInt32 val32 = ReadUInt32(); + const int n = GetLog(val32); if (n < 0 || n > 16) return S_FALSE; - li.ResetIntervalBits = n; + li.ResetIntervalBits = (unsigned)n; } { - UInt32 val32 = ReadUInt32(); - int n = GetLog(val32); + const UInt32 val32 = ReadUInt32(); + const int n = GetLog(val32); if (n < 0 || n > 16) return S_FALSE; - li.WindowSizeBits = n; + li.WindowSizeBits = (unsigned)n; } li.CacheSize = ReadUInt32(); @@ -812,7 +813,7 @@ { // SpanInfo - RINOK(DecompressStream(inStream, database, sectionPrefix + kSpanInfo)); + RINOK(DecompressStream(inStream, database, sectionPrefix + kSpanInfo)) section.UncompressedSize = ReadUInt64(); } @@ -824,7 +825,7 @@ { // ResetTable; RINOK(DecompressStream(inStream, database, transformPrefix + - method.GetGuidString() + kResetTable)); + method.GetGuidString() + kResetTable)) CResetTable &rt = method.LzxInfo.ResetTable; if (_chunkSize < 4) @@ -906,7 +907,7 @@ database.Help2Format = _help2; const UInt32 chmVersion = 3; - RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &database.StartPosition)); + RINOK(InStream_GetPos(inStream, database.StartPosition)) if (!_inBuffer.Create(1 << 14)) return E_OUTOFMEMORY; @@ -942,7 +943,7 @@ } database.StartPosition += _inBuffer.GetProcessedSize() - kSignatureSize; - RINOK(OpenHelp2(inStream, database)); + RINOK(OpenHelp2(inStream, database)) if (database.NewFormat) return S_OK; } @@ -952,7 +953,7 @@ return S_FALSE; if (ReadUInt32() != chmVersion) return S_FALSE; - RINOK(OpenChm(inStream, database)); + RINOK(OpenChm(inStream, database)) } @@ -969,7 +970,7 @@ database.HighLevelClear(); return S_OK; } - RINOK(res); + RINOK(res) if (!database.CheckSectionRefs()) HeadersError = true; database.LowLevel = false; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Chm/ChmIn.h 7zip-23.01+dfsg/CPP/7zip/Archive/Chm/ChmIn.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Chm/ChmIn.h 2022-07-14 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Chm/ChmIn.h 2023-01-19 10:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Archive/ChmIn.h -#ifndef __ARCHIVE_CHM_IN_H -#define __ARCHIVE_CHM_IN_H +#ifndef ZIP7_INC_ARCHIVE_CHM_IN_H +#define ZIP7_INC_ARCHIVE_CHM_IN_H #include "../../../Common/MyBuffer.h" #include "../../../Common/MyString.h" @@ -59,7 +59,7 @@ { FOR_VECTOR (i, Items) if (Items[i].Name == name) - return i; + return (int)i; return -1; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Chm/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Archive/Chm/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Chm/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Chm/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/ComHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/ComHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/ComHandler.cpp 2021-03-25 16:20:10.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/ComHandler.cpp 2023-03-27 17:00:00.000000000 +0000 @@ -26,8 +26,8 @@ namespace NArchive { namespace NCom { -#define SIGNATURE { 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1 } -static const Byte kSignature[] = SIGNATURE; +static const Byte kSignature[] = + { 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1 }; enum EType { @@ -120,6 +120,7 @@ Int32 MainSubfile; UInt64 PhySize; + UInt64 PhySize_Aligned; EType Type; bool IsNotArcType() const @@ -129,10 +130,12 @@ Type != k_Type_Msp; } - void UpdatePhySize(UInt64 val) + void UpdatePhySize(UInt64 val, UInt64 val_Aligned) { if (PhySize < val) PhySize = val; + if (PhySize_Aligned < val_Aligned) + PhySize_Aligned = val_Aligned; } HRESULT ReadSector(IInStream *inStream, Byte *buf, unsigned sectorSizeBits, UInt32 sid); HRESULT ReadIDs(IInStream *inStream, Byte *buf, unsigned sectorSizeBits, UInt32 sid, UInt32 *dest); @@ -165,14 +168,15 @@ HRESULT CDatabase::ReadSector(IInStream *inStream, Byte *buf, unsigned sectorSizeBits, UInt32 sid) { - UpdatePhySize(((UInt64)sid + 2) << sectorSizeBits); - RINOK(inStream->Seek((((UInt64)sid + 1) << sectorSizeBits), STREAM_SEEK_SET, NULL)); + const UInt64 end = ((UInt64)sid + 2) << sectorSizeBits; + UpdatePhySize(end, end); + RINOK(InStream_SeekSet(inStream, (((UInt64)sid + 1) << sectorSizeBits))) return ReadStream_FALSE(inStream, buf, (size_t)1 << sectorSizeBits); } HRESULT CDatabase::ReadIDs(IInStream *inStream, Byte *buf, unsigned sectorSizeBits, UInt32 sid, UInt32 *dest) { - RINOK(ReadSector(inStream, buf, sectorSizeBits, sid)); + RINOK(ReadSector(inStream, buf, sectorSizeBits, sid)) UInt32 sectorSize = (UInt32)1 << sectorSizeBits; for (UInt32 t = 0; t < sectorSize; t += 4) *dest++ = Get32(buf + t); @@ -205,6 +209,7 @@ void CDatabase::Clear() { PhySize = 0; + PhySize_Aligned = 0; Fat.Free(); MiniSids.Free(); @@ -227,14 +232,14 @@ CRef ref; ref.Parent = parent; ref.Did = did; - int index = Refs.Add(ref); + const unsigned index = Refs.Add(ref); if (Refs.Size() > Items.Size()) return S_FALSE; - RINOK(AddNode(parent, item.LeftDid)); - RINOK(AddNode(parent, item.RightDid)); + RINOK(AddNode(parent, item.LeftDid)) + RINOK(AddNode(parent, item.RightDid)) if (item.IsDir()) { - RINOK(AddNode(index, item.SonDid)); + RINOK(AddNode((int)index, item.SonDid)) } return S_OK; } @@ -244,11 +249,11 @@ UString res; for (unsigned i = 0; i < s.Len(); i++) { - wchar_t c = s[i]; - if (c < 0x20) + const wchar_t c = s[i]; + if ((unsigned)(int)c < 0x20) { res += '['; - res.Add_UInt32(c); + res.Add_UInt32((UInt32)(unsigned)(int)c); res += ']'; } else @@ -360,7 +365,7 @@ if (!s.IsEmpty()) s.InsertAtFront(WCHAR_PATH_SEPARATOR); s.Insert(0, ConvertName(item.Name)); - index = ref.Parent; + index = (unsigned)ref.Parent; } return s; } @@ -371,11 +376,11 @@ bool isLargeStream = (index == 0 || IsLargeStream(item.Size)); if (!isLargeStream) return S_OK; - unsigned bsLog = isLargeStream ? SectorSizeBits : MiniSectorSizeBits; + const unsigned bsLog = isLargeStream ? SectorSizeBits : MiniSectorSizeBits; // streamSpec->Size = item.Size; - UInt32 clusterSize = (UInt32)1 << bsLog; - UInt64 numClusters64 = (item.Size + clusterSize - 1) >> bsLog; + const UInt32 clusterSize = (UInt32)1 << bsLog; + const UInt64 numClusters64 = (item.Size + clusterSize - 1) >> bsLog; if (numClusters64 >= ((UInt32)1 << 31)) return S_FALSE; UInt32 sid = item.Sid; @@ -389,7 +394,13 @@ { if (sid >= FatSize) return S_FALSE; - UpdatePhySize(((UInt64)sid + 2) << bsLog); + UInt64 end = ((UInt64)sid + 1) << bsLog; + const UInt64 end_Aligned = end + clusterSize; + if (size < clusterSize) + end += size; + else + end = end_Aligned; + UpdatePhySize(end, end_Aligned); sid = Fat[sid]; } if (size <= clusterSize) @@ -415,8 +426,8 @@ const UInt32 kHeaderSize = 512; Byte p[kHeaderSize]; PhySize = kHeaderSize; - RINOK(ReadStream_FALSE(inStream, p, kHeaderSize)); - if (memcmp(p, kSignature, ARRAY_SIZE(kSignature)) != 0) + RINOK(ReadStream_FALSE(inStream, p, kHeaderSize)) + if (memcmp(p, kSignature, Z7_ARRAY_SIZE(kSignature)) != 0) return S_FALSE; if (Get16(p + 0x1A) > 4) // majorVer return S_FALSE; @@ -461,7 +472,7 @@ UInt32 sid = Get32(p + 0x44); for (UInt32 s = 0; s < numSectorsForBat; s++) { - RINOK(ReadIDs(inStream, sect, sectorSizeBits, sid, bat + i)); + RINOK(ReadIDs(inStream, sect, sectorSizeBits, sid, bat + i)) i += numSidsInSec - 1; sid = bat[i]; } @@ -474,7 +485,7 @@ { if (j >= numBatItems) return S_FALSE; - RINOK(ReadIDs(inStream, sect, sectorSizeBits, bat[j], Fat + i)); + RINOK(ReadIDs(inStream, sect, sectorSizeBits, bat[j], Fat + i)) } FatSize = numFatItems = i; } @@ -490,7 +501,7 @@ UInt32 sid = Get32(p + 0x3C); // short-sector table SID for (i = 0; i < numMatItems; i += numSidsInSec) { - RINOK(ReadIDs(inStream, sect, sectorSizeBits, sid, Mat + i)); + RINOK(ReadIDs(inStream, sect, sectorSizeBits, sid, Mat + i)) if (sid >= numFatItems) return S_FALSE; sid = Fat[sid]; @@ -511,7 +522,7 @@ if (used[sid]) return S_FALSE; used[sid] = 1; - RINOK(ReadSector(inStream, sect, sectorSizeBits, sid)); + RINOK(ReadSector(inStream, sect, sectorSizeBits, sid)) for (UInt32 i = 0; i < sectSize; i += 128) { CItem item; @@ -563,7 +574,7 @@ } } - RINOK(AddNode(-1, root.SonDid)); + RINOK(AddNode(-1, root.SonDid)) unsigned numCabs = 0; @@ -584,7 +595,7 @@ ) { numCabs++; - MainSubfile = i; + MainSubfile = (int)i; } } } @@ -599,6 +610,17 @@ } } { + if (PhySize != PhySize_Aligned) + { + /* some msi (in rare cases) have unaligned size of archive, + where there is no padding data after payload data in last cluster of archive */ + UInt64 fileSize; + RINOK(InStream_GetSize_SeekToEnd(inStream, fileSize)) + if (PhySize != fileSize) + PhySize = PhySize_Aligned; + } + } + { FOR_VECTOR (t, Items) { const CItem &item = Items[t]; @@ -634,17 +656,11 @@ return S_OK; } -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_1( + IInArchiveGetStream +) CMyComPtr _stream; CDatabase _db; -public: - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); }; static const Byte kProps[] = @@ -666,7 +682,7 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -684,7 +700,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -705,9 +721,9 @@ COM_TRY_END } -STDMETHODIMP CHandler::Open(IInStream *inStream, +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openArchiveCallback */) + IArchiveOpenCallback * /* openArchiveCallback */)) { COM_TRY_BEGIN Close(); @@ -722,18 +738,18 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _db.Clear(); _stream.Release(); return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _db.Refs.Size(); if (numItems == 0) @@ -746,7 +762,7 @@ if (!item.IsDir()) totalSize += item.Size; } - RINOK(extractCallback->SetTotal(totalSize)); + RINOK(extractCallback->SetTotal(totalSize)) UInt64 totalPackSize; totalSize = totalPackSize = 0; @@ -762,20 +778,20 @@ { lps->InSize = totalPackSize; lps->OutSize = totalSize; - RINOK(lps->SetCur()); - Int32 index = allFilesMode ? i : indices[i]; + RINOK(lps->SetCur()) + const UInt32 index = allFilesMode ? i : indices[i]; const CItem &item = _db.Items[_db.Refs[index].Did]; CMyComPtr outStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - RINOK(extractCallback->GetStream(index, &outStream, askMode)); + RINOK(extractCallback->GetStream(index, &outStream, askMode)) if (item.IsDir()) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } @@ -784,7 +800,7 @@ if (!testMode && !outStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) Int32 res = NExtract::NOperationResult::kDataError; CMyComPtr inStream; HRESULT hres = GetStream(index, &inStream); @@ -794,45 +810,45 @@ res = NExtract::NOperationResult::kUnsupportedMethod; else { - RINOK(hres); + RINOK(hres) if (inStream) { - RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)) if (copyCoderSpec->TotalSize == item.Size) res = NExtract::NOperationResult::kOK; } } outStream.Release(); - RINOK(extractCallback->SetOperationResult(res)); + RINOK(extractCallback->SetOperationResult(res)) } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _db.Refs.Size(); return S_OK; } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN - *stream = 0; - UInt32 itemIndex = _db.Refs[index].Did; + *stream = NULL; + const UInt32 itemIndex = _db.Refs[index].Did; const CItem &item = _db.Items[itemIndex]; CClusterInStream *streamSpec = new CClusterInStream; CMyComPtr streamTemp = streamSpec; streamSpec->Stream = _stream; streamSpec->StartOffset = 0; - bool isLargeStream = (itemIndex == 0 || _db.IsLargeStream(item.Size)); - int bsLog = isLargeStream ? _db.SectorSizeBits : _db.MiniSectorSizeBits; + const bool isLargeStream = (itemIndex == 0 || _db.IsLargeStream(item.Size)); + const unsigned bsLog = isLargeStream ? _db.SectorSizeBits : _db.MiniSectorSizeBits; streamSpec->BlockSizeLog = bsLog; streamSpec->Size = item.Size; - UInt32 clusterSize = (UInt32)1 << bsLog; - UInt64 numClusters64 = (item.Size + clusterSize - 1) >> bsLog; + const UInt32 clusterSize = (UInt32)1 << bsLog; + const UInt64 numClusters64 = (item.Size + clusterSize - 1) >> bsLog; if (numClusters64 >= ((UInt32)1 << 31)) return E_NOTIMPL; streamSpec->Vector.ClearAndReserve((unsigned)numClusters64); @@ -864,14 +880,14 @@ } if (sid != NFatID::kEndOfChain) return S_FALSE; - RINOK(streamSpec->InitAndSeek()); + RINOK(streamSpec->InitAndSeek()) *stream = streamTemp.Detach(); return S_OK; COM_TRY_END } REGISTER_ARC_I( - "Compound", "msi msp doc xls ppt", 0, 0xE5, + "Compound", "msi msp doc xls ppt", NULL, 0xE5, kSignature, 0, 0, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/CoderMixer2.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Common/CoderMixer2.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/CoderMixer2.cpp 2021-03-07 09:01:09.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/CoderMixer2.cpp 2023-04-05 10:00:00.000000000 +0000 @@ -6,7 +6,7 @@ #ifdef USE_MIXER_ST -STDMETHODIMP CSequentialInStreamCalcSize::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CSequentialInStreamCalcSize::Read(void *data, UInt32 size, UInt32 *processedSize)) { UInt32 realProcessed = 0; HRESULT result = S_OK; @@ -21,7 +21,7 @@ } -STDMETHODIMP COutStreamCalcSize::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(COutStreamCalcSize::Write(const void *data, UInt32 size, UInt32 *processedSize)) { HRESULT result = S_OK; if (_stream) @@ -32,7 +32,7 @@ return result; } -STDMETHODIMP COutStreamCalcSize::OutStreamFinish() +Z7_COM7F_IMF(COutStreamCalcSize::OutStreamFinish()) { HRESULT result = S_OK; if (_stream) @@ -73,7 +73,7 @@ if (getInStreamProcessedSize) { UInt64 processed; - RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&processed)); + RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&processed)) if (processed != (UInt64)(Int64)-1) { const UInt64 size = PackSizes[0]; @@ -97,7 +97,7 @@ if (!PackSizePointers[i]) continue; UInt64 processed; - RINOK(getInStreamProcessedSize2->GetInStreamProcessedSize2(i, &processed)); + RINOK(getInStreamProcessedSize2->GetInStreamProcessedSize2(i, &processed)) if (processed != (UInt64)(Int64)-1) { const UInt64 size = PackSizes[i]; @@ -343,13 +343,11 @@ { IUnknown *unk = (cod.Coder ? (IUnknown *)cod.Coder : (IUnknown *)cod.Coder2); { - CMyComPtr s; - unk->QueryInterface(IID_ISequentialInStream, (void**)&s); + Z7_DECL_CMyComPtr_QI_FROM(ISequentialInStream, s, unk) c2.CanRead = (s != NULL); } { - CMyComPtr s; - unk->QueryInterface(IID_ISequentialOutStream, (void**)&s); + Z7_DECL_CMyComPtr_QI_FROM(ISequentialOutStream, s, unk) c2.CanWrite = (s != NULL); } } @@ -382,8 +380,8 @@ if (!seqInStream) return E_NOTIMPL; - UInt32 numInStreams = EncodeMode ? 1 : coder.NumStreams; - UInt32 startIndex = EncodeMode ? coderIndex : _bi.Coder_to_Stream[coderIndex]; + const UInt32 numInStreams = EncodeMode ? 1 : coder.NumStreams; + const UInt32 startIndex = EncodeMode ? coderIndex : _bi.Coder_to_Stream[coderIndex]; bool isSet = false; @@ -394,8 +392,8 @@ if (setStream) { CMyComPtr seqInStream2; - RINOK(GetInStream(inStreams, /* inSizes, */ startIndex + 0, &seqInStream2)); - RINOK(setStream->SetInStream(seqInStream2)); + RINOK(GetInStream(inStreams, /* inSizes, */ startIndex + 0, &seqInStream2)) + RINOK(setStream->SetInStream(seqInStream2)) isSet = true; } } @@ -410,8 +408,8 @@ for (UInt32 i = 0; i < numInStreams; i++) { CMyComPtr seqInStream2; - RINOK(GetInStream(inStreams, /* inSizes, */ startIndex + i, &seqInStream2)); - RINOK(setStream2->SetInStream2(i, seqInStream2)); + RINOK(GetInStream(inStreams, /* inSizes, */ startIndex + i, &seqInStream2)) + RINOK(setStream2->SetInStream2(i, seqInStream2)) } } @@ -451,7 +449,7 @@ return E_INVALIDARG; RINOK(GetInStream2(inStreams, /* inSizes, */ - _bi.Bonds[(unsigned)bond].Get_OutIndex(EncodeMode), &seqInStream)); + _bi.Bonds[(unsigned)bond].Get_OutIndex(EncodeMode), &seqInStream)) while (_binderStreams.Size() <= (unsigned)bond) _binderStreams.AddNew(); @@ -504,7 +502,7 @@ if (bond < 0) return E_INVALIDARG; - UInt32 inStreamIndex = _bi.Bonds[(unsigned)bond].Get_InIndex(EncodeMode); + const UInt32 inStreamIndex = _bi.Bonds[(unsigned)bond].Get_InIndex(EncodeMode); UInt32 coderIndex = inStreamIndex; UInt32 coderStreamIndex = 0; @@ -523,8 +521,8 @@ if (!seqOutStream) return E_NOTIMPL; - UInt32 numOutStreams = EncodeMode ? coder.NumStreams : 1; - UInt32 startIndex = EncodeMode ? _bi.Coder_to_Stream[coderIndex]: coderIndex; + const UInt32 numOutStreams = EncodeMode ? coder.NumStreams : 1; + const UInt32 startIndex = EncodeMode ? _bi.Coder_to_Stream[coderIndex]: coderIndex; bool isSet = false; @@ -535,8 +533,8 @@ if (setOutStream) { CMyComPtr seqOutStream2; - RINOK(GetOutStream(outStreams, /* outSizes, */ startIndex + 0, &seqOutStream2)); - RINOK(setOutStream->SetOutStream(seqOutStream2)); + RINOK(GetOutStream(outStreams, /* outSizes, */ startIndex + 0, &seqOutStream2)) + RINOK(setOutStream->SetOutStream(seqOutStream2)) isSet = true; } } @@ -552,8 +550,8 @@ for (UInt32 i = 0; i < numOutStreams; i++) { CMyComPtr seqOutStream2; - RINOK(GetOutStream(outStreams, startIndex + i, &seqOutStream2)); - RINOK(setStream2->SetOutStream2(i, seqOutStream2)); + RINOK(GetOutStream(outStreams, startIndex + i, &seqOutStream2)) + RINOK(setStream2->SetOutStream2(i, seqOutStream2)) } */ } @@ -616,7 +614,7 @@ if (bond < 0) return E_INVALIDARG; - UInt32 inStreamIndex = _bi.Bonds[(unsigned)bond].Get_InIndex(EncodeMode); + const UInt32 inStreamIndex = _bi.Bonds[(unsigned)bond].Get_InIndex(EncodeMode); UInt32 coderIndex = inStreamIndex; UInt32 coderStreamIndex = 0; @@ -639,8 +637,8 @@ { CCoder &coder = _coders[coderIndex]; - UInt32 numOutStreams = EncodeMode ? coder.NumStreams : 1; - UInt32 startIndex = EncodeMode ? _bi.Coder_to_Stream[coderIndex]: coderIndex; + const UInt32 numOutStreams = EncodeMode ? coder.NumStreams : 1; + const UInt32 startIndex = EncodeMode ? _bi.Coder_to_Stream[coderIndex]: coderIndex; HRESULT res = S_OK; for (unsigned i = 0; i < numOutStreams; i++) @@ -671,7 +669,7 @@ if (coder.NumStreams != 1) break; - UInt32 st = _bi.Coder_to_Stream[ci]; + const UInt32 st = _bi.Coder_to_Stream[ci]; if (_bi.IsStream_in_PackStreams(st)) break; const int bond = _bi.FindBond_for_PackStream(st); @@ -706,32 +704,32 @@ dataAfterEnd_Error = false; _binderStreams.Clear(); - unsigned ci = MainCoderIndex; + const unsigned ci = MainCoderIndex; const CCoder &mainCoder = _coders[MainCoderIndex]; CObjectVector< CMyComPtr > seqInStreams; CObjectVector< CMyComPtr > seqOutStreams; - UInt32 numInStreams = EncodeMode ? 1 : mainCoder.NumStreams; - UInt32 numOutStreams = !EncodeMode ? 1 : mainCoder.NumStreams; + const UInt32 numInStreams = EncodeMode ? 1 : mainCoder.NumStreams; + const UInt32 numOutStreams = !EncodeMode ? 1 : mainCoder.NumStreams; - UInt32 startInIndex = EncodeMode ? ci : _bi.Coder_to_Stream[ci]; - UInt32 startOutIndex = !EncodeMode ? ci : _bi.Coder_to_Stream[ci]; + const UInt32 startInIndex = EncodeMode ? ci : _bi.Coder_to_Stream[ci]; + const UInt32 startOutIndex = !EncodeMode ? ci : _bi.Coder_to_Stream[ci]; UInt32 i; for (i = 0; i < numInStreams; i++) { CMyComPtr seqInStream; - RINOK(GetInStream(inStreams, /* inSizes, */ startInIndex + i, &seqInStream)); + RINOK(GetInStream(inStreams, /* inSizes, */ startInIndex + i, &seqInStream)) seqInStreams.Add(seqInStream); } for (i = 0; i < numOutStreams; i++) { CMyComPtr seqOutStream; - RINOK(GetOutStream(outStreams, /* outSizes, */ startOutIndex + i, &seqOutStream)); + RINOK(GetOutStream(outStreams, /* outSizes, */ startOutIndex + i, &seqOutStream)) seqOutStreams.Add(seqOutStream); } @@ -755,15 +753,19 @@ CMyComPtr initEncoder; coder.QueryInterface(IID_ICompressInitEncoder, (void **)&initEncoder); if (initEncoder) - RINOK(initEncoder->InitEncoder()); + { + RINOK(initEncoder->InitEncoder()) + } } else { CMyComPtr setOutStreamSize; coder.QueryInterface(IID_ICompressSetOutStreamSize, (void **)&setOutStreamSize); if (setOutStreamSize) + { RINOK(setOutStreamSize->SetOutStreamSize( - EncodeMode ? coder.PackSizePointers[0] : coder.UnpackSizePointer)); + EncodeMode ? coder.PackSizePointers[0] : coder.UnpackSizePointer)) + } } } @@ -811,7 +813,7 @@ for (i = 0; i < _coders.Size(); i++) { - RINOK(_coders[i].CheckDataAfterEnd(dataAfterEnd_Error /*, InternalPackSizeError */)); + RINOK(_coders[i].CheckDataAfterEnd(dataAfterEnd_Error /*, InternalPackSizeError */)) } return S_OK; @@ -834,7 +836,7 @@ coder.QueryInterface(IID_ICompressSetOutStreamSize, (void **)&setOutStreamSize); if (setOutStreamSize) { - RINOK(setOutStreamSize->SetOutStreamSize(coder.UnpackSizePointer)); + RINOK(setOutStreamSize->SetOutStreamSize(coder.UnpackSizePointer)) } } @@ -919,7 +921,7 @@ _streamBinders.Clear(); FOR_VECTOR (i, _bi.Bonds) { - // RINOK(_streamBinders.AddNew().CreateEvents()); + // RINOK(_streamBinders.AddNew().CreateEvents()) _streamBinders.AddNew(); } return S_OK; @@ -946,7 +948,7 @@ { FOR_VECTOR (i, _streamBinders) { - RINOK(_streamBinders[i].Create_ReInit()); + RINOK(_streamBinders[i].Create_ReInit()) } return S_OK; } @@ -986,8 +988,8 @@ UInt32 j; - unsigned numInStreams = EncodeMode ? 1 : csi.NumStreams; - unsigned numOutStreams = EncodeMode ? csi.NumStreams : 1; + const unsigned numInStreams = EncodeMode ? 1 : csi.NumStreams; + const unsigned numOutStreams = EncodeMode ? csi.NumStreams : 1; coderInfo.InStreams.Clear(); for (j = 0; j < numInStreams; j++) @@ -1102,8 +1104,8 @@ if (wres != 0) return HRESULT_FROM_WIN32(wres); - RINOK(ReturnIfError(E_ABORT)); - RINOK(ReturnIfError(E_OUTOFMEMORY)); + RINOK(ReturnIfError(E_ABORT)) + RINOK(ReturnIfError(E_OUTOFMEMORY)) for (i = 0; i < _coders.Size(); i++) { @@ -1115,7 +1117,7 @@ return result; } - RINOK(ReturnIfError(S_FALSE)); + RINOK(ReturnIfError(S_FALSE)) for (i = 0; i < _coders.Size(); i++) { @@ -1126,7 +1128,7 @@ for (i = 0; i < _coders.Size(); i++) { - RINOK(_coders[i].CheckDataAfterEnd(dataAfterEnd_Error /* , InternalPackSizeError */)); + RINOK(_coders[i].CheckDataAfterEnd(dataAfterEnd_Error /* , InternalPackSizeError */)) } return S_OK; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/CoderMixer2.h 7zip-23.01+dfsg/CPP/7zip/Archive/Common/CoderMixer2.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/CoderMixer2.h 2021-01-24 16:19:15.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/CoderMixer2.h 2023-04-05 10:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // CoderMixer2.h -#ifndef __CODER_MIXER2_H -#define __CODER_MIXER2_H +#ifndef ZIP7_INC_CODER_MIXER2_H +#define ZIP7_INC_CODER_MIXER2_H #include "../../../Common/MyCom.h" #include "../../../Common/MyVector.h" @@ -10,11 +10,11 @@ #include "../../Common/CreateCoder.h" -#ifdef _7ZIP_ST +#ifdef Z7_ST #define USE_MIXER_ST #else #define USE_MIXER_MT - #ifndef _SFX + #ifndef Z7_SFX #define USE_MIXER_ST #endif #endif @@ -28,18 +28,13 @@ #ifdef USE_MIXER_ST -class CSequentialInStreamCalcSize: - public ISequentialInStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP1(ISequentialInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); -private: +Z7_CLASS_IMP_COM_1( + CSequentialInStreamCalcSize + , ISequentialInStream +) + bool _wasFinished; CMyComPtr _stream; UInt64 _size; - bool _wasFinished; public: void SetStream(ISequentialInStream *stream) { _stream = stream; } void Init() @@ -53,19 +48,14 @@ }; -class COutStreamCalcSize: - public ISequentialOutStream, - public IOutStreamFinish, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_2( + COutStreamCalcSize + , ISequentialOutStream + , IOutStreamFinish +) CMyComPtr _stream; UInt64 _size; public: - MY_UNKNOWN_IMP2(ISequentialOutStream, IOutStreamFinish) - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(OutStreamFinish)(); - void SetStream(ISequentialOutStream *stream) { _stream = stream; } void ReleaseStream() { _stream.Release(); } void Init() { _size = 0; } @@ -122,7 +112,7 @@ bool SetUnpackCoder() { bool isOk = false; - FOR_VECTOR(i, Coders) + FOR_VECTOR (i, Coders) { if (FindBond_for_UnpackStream(i) < 0) { @@ -142,7 +132,7 @@ int FindStream_in_PackStreams(UInt32 streamIndex) const { - FOR_VECTOR(i, PackStreams) + FOR_VECTOR (i, PackStreams) if (PackStreams[i] == streamIndex) return (int)i; return -1; @@ -189,11 +179,12 @@ class CCoder { - CLASS_NO_COPY(CCoder); + Z7_CLASS_NO_COPY(CCoder) public: CMyComPtr Coder; CMyComPtr Coder2; UInt32 NumStreams; + bool Finish; UInt64 UnpackSize; const UInt64 *UnpackSizePointer; @@ -201,8 +192,6 @@ CRecordVector PackSizes; CRecordVector PackSizePointers; - bool Finish; - CCoder(): Finish(false) {} void SetCoderInfo(const UInt64 *unpackSize, const UInt64 * const *packSizes, bool finish); @@ -251,7 +240,7 @@ // , InternalPackSizeError(false) {} - virtual ~CMixer() {}; + virtual ~CMixer() {} /* Sequence of calling: @@ -323,7 +312,8 @@ public CMixer, public CMyUnknownImp { - CLASS_NO_COPY(CMixerST) + Z7_COM_UNKNOWN_IMP_0 + Z7_CLASS_NO_COPY(CMixerST) HRESULT GetInStream2(ISequentialInStream * const *inStreams, /* const UInt64 * const *inSizes, */ UInt32 outStreamIndex, ISequentialInStream **inStreamRes); @@ -340,23 +330,21 @@ CObjectVector _binderStreams; - MY_UNKNOWN_IMP - CMixerST(bool encodeMode); - ~CMixerST(); + ~CMixerST() Z7_DESTRUCTOR_override; - virtual void AddCoder(const CCreatedCoder &cod); - virtual CCoder &GetCoder(unsigned index); - virtual void SelectMainCoder(bool useFirst); - virtual HRESULT ReInit2(); - virtual void SetCoderInfo(unsigned coderIndex, const UInt64 *unpackSize, const UInt64 * const *packSizes, bool finish) + virtual void AddCoder(const CCreatedCoder &cod) Z7_override; + virtual CCoder &GetCoder(unsigned index) Z7_override; + virtual void SelectMainCoder(bool useFirst) Z7_override; + virtual HRESULT ReInit2() Z7_override; + virtual void SetCoderInfo(unsigned coderIndex, const UInt64 *unpackSize, const UInt64 * const *packSizes, bool finish) Z7_override { _coders[coderIndex].SetCoderInfo(unpackSize, packSizes, finish); } virtual HRESULT Code( ISequentialInStream * const *inStreams, ISequentialOutStream * const *outStreams, ICompressProgressInfo *progress, - bool &dataAfterEnd_Error); - virtual UInt64 GetBondStreamSize(unsigned bondIndex) const; + bool &dataAfterEnd_Error) Z7_override; + virtual UInt64 GetBondStreamSize(unsigned bondIndex) const Z7_override; HRESULT GetMainUnpackStream( ISequentialInStream * const *inStreams, @@ -372,12 +360,12 @@ class CCoderMT: public CCoder, public CVirtThread { - CLASS_NO_COPY(CCoderMT) + Z7_CLASS_NO_COPY(CCoderMT) CRecordVector InStreamPointers; CRecordVector OutStreamPointers; private: - void Execute(); + virtual void Execute() Z7_override; public: bool EncodeMode; HRESULT Result; @@ -397,7 +385,7 @@ class CReleaser { - CLASS_NO_COPY(CReleaser) + Z7_CLASS_NO_COPY(CReleaser) CCoderMT &_c; public: CReleaser(CCoderMT &c): _c(c) {} @@ -405,7 +393,14 @@ }; CCoderMT(): EncodeMode(false) {} - virtual ~CCoderMT() { CVirtThread::WaitThreadFinish(); } + ~CCoderMT() Z7_DESTRUCTOR_override + { + /* WaitThreadFinish() will be called in ~CVirtThread(). + But we need WaitThreadFinish() call before CCoder destructor, + and before destructors of this class members. + */ + CVirtThread::WaitThreadFinish(); + } void Code(ICompressProgressInfo *progress); }; @@ -416,32 +411,31 @@ public CMixer, public CMyUnknownImp { - CLASS_NO_COPY(CMixerMT) + Z7_COM_UNKNOWN_IMP_0 + Z7_CLASS_NO_COPY(CMixerMT) CObjectVector _streamBinders; HRESULT Init(ISequentialInStream * const *inStreams, ISequentialOutStream * const *outStreams); HRESULT ReturnIfError(HRESULT code); - // virtual ~CMixerMT() {}; + // virtual ~CMixerMT() {} public: CObjectVector _coders; - MY_UNKNOWN_IMP - - virtual HRESULT SetBindInfo(const CBindInfo &bindInfo); - virtual void AddCoder(const CCreatedCoder &cod); - virtual CCoder &GetCoder(unsigned index); - virtual void SelectMainCoder(bool useFirst); - virtual HRESULT ReInit2(); - virtual void SetCoderInfo(unsigned coderIndex, const UInt64 *unpackSize, const UInt64 * const *packSizes, bool finish) + virtual HRESULT SetBindInfo(const CBindInfo &bindInfo) Z7_override; + virtual void AddCoder(const CCreatedCoder &cod) Z7_override; + virtual CCoder &GetCoder(unsigned index) Z7_override; + virtual void SelectMainCoder(bool useFirst) Z7_override; + virtual HRESULT ReInit2() Z7_override; + virtual void SetCoderInfo(unsigned coderIndex, const UInt64 *unpackSize, const UInt64 * const *packSizes, bool finish) Z7_override { _coders[coderIndex].SetCoderInfo(unpackSize, packSizes, finish); } virtual HRESULT Code( ISequentialInStream * const *inStreams, ISequentialOutStream * const *outStreams, ICompressProgressInfo *progress, - bool &dataAfterEnd_Error); - virtual UInt64 GetBondStreamSize(unsigned bondIndex) const; + bool &dataAfterEnd_Error) Z7_override; + virtual UInt64 GetBondStreamSize(unsigned bondIndex) const Z7_override; CMixerMT(bool encodeMode): CMixer(encodeMode) {} }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/DummyOutStream.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Common/DummyOutStream.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/DummyOutStream.cpp 2012-09-19 11:36:06.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/DummyOutStream.cpp 2023-01-28 17:00:00.000000000 +0000 @@ -4,7 +4,7 @@ #include "DummyOutStream.h" -STDMETHODIMP CDummyOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CDummyOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { UInt32 realProcessedSize = size; HRESULT res = S_OK; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/DummyOutStream.h 7zip-23.01+dfsg/CPP/7zip/Archive/Common/DummyOutStream.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/DummyOutStream.h 2013-01-17 08:10:30.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/DummyOutStream.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,24 +1,22 @@ // DummyOutStream.h -#ifndef __DUMMY_OUT_STREAM_H -#define __DUMMY_OUT_STREAM_H +#ifndef ZIP7_INC_DUMMY_OUT_STREAM_H +#define ZIP7_INC_DUMMY_OUT_STREAM_H #include "../../../Common/MyCom.h" #include "../../IStream.h" -class CDummyOutStream: - public ISequentialOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + CDummyOutStream + , ISequentialOutStream +) CMyComPtr _stream; UInt64 _size; public: void SetStream(ISequentialOutStream *outStream) { _stream = outStream; } void ReleaseStream() { _stream.Release(); } void Init() { _size = 0; } - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); UInt64 GetSize() const { return _size; } }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/FindSignature.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Common/FindSignature.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/FindSignature.cpp 2015-08-01 09:18:35.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/FindSignature.cpp 2023-04-05 08:00:00.000000000 +0000 @@ -16,7 +16,7 @@ { resPos = 0; CByteBuffer byteBuffer2(signatureSize); - RINOK(ReadStream_FALSE(stream, byteBuffer2, signatureSize)); + RINOK(ReadStream_FALSE(stream, byteBuffer2, signatureSize)) if (memcmp(byteBuffer2, signature, signatureSize) == 0) return S_OK; @@ -29,23 +29,23 @@ resPos = 1; for (;;) { - if (limit != NULL) + if (limit) if (resPos > *limit) return S_FALSE; do { - UInt32 numReadBytes = kBufferSize - numPrevBytes; + const UInt32 numReadBytes = kBufferSize - numPrevBytes; UInt32 processedSize; - RINOK(stream->Read(buffer + numPrevBytes, numReadBytes, &processedSize)); + RINOK(stream->Read(buffer + numPrevBytes, numReadBytes, &processedSize)) numPrevBytes += processedSize; if (processedSize == 0) return S_FALSE; } while (numPrevBytes < signatureSize); - UInt32 numTests = numPrevBytes - signatureSize + 1; + const UInt32 numTests = numPrevBytes - signatureSize + 1; for (UInt32 pos = 0; pos < numTests; pos++) { - Byte b = signature[0]; + const Byte b = signature[0]; for (; buffer[pos] != b && pos < numTests; pos++); if (pos == numTests) break; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/FindSignature.h 7zip-23.01+dfsg/CPP/7zip/Archive/Common/FindSignature.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/FindSignature.h 2015-08-01 09:18:35.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/FindSignature.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // FindSignature.h -#ifndef __FIND_SIGNATURE_H -#define __FIND_SIGNATURE_H +#ifndef ZIP7_INC_FIND_SIGNATURE_H +#define ZIP7_INC_FIND_SIGNATURE_H #include "../../IStream.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/HandlerOut.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Common/HandlerOut.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/HandlerOut.cpp 2022-05-10 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/HandlerOut.cpp 2023-05-07 15:00:00.000000000 +0000 @@ -88,7 +88,7 @@ if (name.IsPrefixedBy_Ascii_NoCase("mt")) { - #ifndef _7ZIP_ST + #ifndef Z7_ST _numThreads = _numProcessors; _numThreads_WasForced = false; hres = ParseMtProp2(name.Ptr(2), value, _numThreads, _numThreads_WasForced); @@ -112,7 +112,7 @@ } -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY static void SetMethodProp32(CMethodProps &m, PROPID propID, UInt32 value) { @@ -127,7 +127,7 @@ SetMethodProp32(oneMethodInfo, NCoderPropID::kLevel, (UInt32)level); } -#ifndef _7ZIP_ST +#ifndef Z7_ST static void SetMethodProp32_Replace(CMethodProps &m, PROPID propID, UInt32 value) { @@ -151,7 +151,7 @@ SetMethodProp32_Replace(oneMethodInfo, NCoderPropID::kNumThreads, numThreads); } -#endif // _7ZIP_ST +#endif // Z7_ST void CMultiMethodProps::InitMulti() @@ -189,7 +189,7 @@ { name.Delete(0, 2); UInt32 v = 9; - RINOK(ParsePropToUInt32(name, value, v)); + RINOK(ParsePropToUInt32(name, value, v)) _analysisLevel = (int)v; return S_OK; } @@ -208,13 +208,13 @@ } UInt32 number; - unsigned index = ParseStringToUInt32(name, number); - UString realName = name.Ptr(index); + const unsigned index = ParseStringToUInt32(name, number); + const UString realName = name.Ptr(index); if (index == 0) { if (name.IsEqualTo("f")) { - HRESULT res = PROPVARIANT_to_bool(value, _autoFilter); + const HRESULT res = PROPVARIANT_to_bool(value, _autoFilter); if (res == S_OK) return res; if (value.vt != VT_BSTR) @@ -224,7 +224,7 @@ number = 0; } if (number > 64) - return E_FAIL; + return E_INVALIDARG; for (unsigned j = _methods.Size(); j <= number; j++) _methods.AddNew(); return _methods[number].ParseMethodFromPROPVARIANT(realName, value); @@ -250,7 +250,7 @@ if (name.IsPrefixedBy_Ascii_NoCase("x")) { UInt32 a = 9; - RINOK(ParsePropToUInt32(name.Ptr(1), value, a)); + RINOK(ParsePropToUInt32(name.Ptr(1), value, a)) _level = a; AddProp_Level(a); // processed = true; @@ -264,7 +264,7 @@ return S_OK; } } - RINOK(ParseMethodFromPROPVARIANT(name, value)); + RINOK(ParseMethodFromPROPVARIANT(name, value)) return S_OK; } @@ -275,7 +275,7 @@ for (UInt32 i = 0; i < numProps; i++) { - RINOK(SetProperty(names[i], values[i])); + RINOK(SetProperty(names[i], values[i])) } return S_OK; @@ -286,7 +286,7 @@ static HRESULT PROPVARIANT_to_BoolPair(const PROPVARIANT &prop, CBoolPair &dest) { - RINOK(PROPVARIANT_to_bool(prop, dest.Val)); + RINOK(PROPVARIANT_to_bool(prop, dest.Val)) dest.Def = true; return S_OK; } @@ -300,7 +300,7 @@ if (name.IsPrefixedBy_Ascii_NoCase("tp")) { UInt32 v = 0; - RINOK(ParsePropToUInt32(name.Ptr(2), prop, v)); + RINOK(ParsePropToUInt32(name.Ptr(2), prop, v)) Prec = v; return S_OK; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/HandlerOut.h 7zip-23.01+dfsg/CPP/7zip/Archive/Common/HandlerOut.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/HandlerOut.h 2022-05-10 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/HandlerOut.h 2023-01-30 18:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // HandlerOut.h -#ifndef __HANDLER_OUT_H -#define __HANDLER_OUT_H +#ifndef ZIP7_INC_HANDLER_OUT_H +#define ZIP7_INC_HANDLER_OUT_H #include "../../../Windows/System.h" @@ -17,7 +17,7 @@ void InitCommon() { // _Write_MTime = true; - #ifndef _7ZIP_ST + #ifndef Z7_ST _numProcessors = _numThreads = NWindows::NSystem::GetNumberOfProcessors(); _numThreads_WasForced = false; #endif @@ -46,7 +46,7 @@ } public: - #ifndef _7ZIP_ST + #ifndef Z7_ST UInt32 _numThreads; UInt32 _numProcessors; bool _numThreads_WasForced; @@ -63,7 +63,7 @@ }; -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY class CMultiMethodProps: public CCommonMethodProps { @@ -80,7 +80,7 @@ void SetGlobalLevelTo(COneMethodInfo &oneMethodInfo) const; - #ifndef _7ZIP_ST + #ifndef Z7_ST static void SetMethodThreadsTo_IfNotFinded(CMethodProps &props, UInt32 numThreads); static void SetMethodThreadsTo_Replace(CMethodProps &props, UInt32 numThreads); #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/InStreamWithCRC.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Common/InStreamWithCRC.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/InStreamWithCRC.cpp 2014-12-23 07:43:17.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/InStreamWithCRC.cpp 2023-01-28 17:00:00.000000000 +0000 @@ -4,22 +4,33 @@ #include "InStreamWithCRC.h" -STDMETHODIMP CSequentialInStreamWithCRC::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CSequentialInStreamWithCRC::Read(void *data, UInt32 size, UInt32 *processedSize)) { UInt32 realProcessed = 0; HRESULT result = S_OK; - if (_stream) - result = _stream->Read(data, size, &realProcessed); - _size += realProcessed; - if (size != 0 && realProcessed == 0) - _wasFinished = true; - _crc = CrcUpdate(_crc, data, realProcessed); + if (size != 0) + { + if (_stream) + result = _stream->Read(data, size, &realProcessed); + _size += realProcessed; + if (realProcessed == 0) + _wasFinished = true; + else + _crc = CrcUpdate(_crc, data, realProcessed); + } if (processedSize) *processedSize = realProcessed; return result; } -STDMETHODIMP CInStreamWithCRC::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CSequentialInStreamWithCRC::GetSize(UInt64 *size)) +{ + *size = _fullSize; + return S_OK; +} + + +Z7_COM7F_IMF(CInStreamWithCRC::Read(void *data, UInt32 size, UInt32 *processedSize)) { UInt32 realProcessed = 0; HRESULT result = S_OK; @@ -36,7 +47,7 @@ return result; } -STDMETHODIMP CInStreamWithCRC::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CInStreamWithCRC::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { if (seekOrigin != STREAM_SEEK_SET || offset != 0) return E_FAIL; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/InStreamWithCRC.h 7zip-23.01+dfsg/CPP/7zip/Archive/Common/InStreamWithCRC.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/InStreamWithCRC.h 2010-05-15 09:55:50.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/InStreamWithCRC.h 2023-04-05 08:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // InStreamWithCRC.h -#ifndef __IN_STREAM_WITH_CRC_H -#define __IN_STREAM_WITH_CRC_H +#ifndef ZIP7_INC_IN_STREAM_WITH_CRC_H +#define ZIP7_INC_IN_STREAM_WITH_CRC_H #include "../../../../C/7zCrc.h" @@ -9,26 +9,29 @@ #include "../../IStream.h" -class CSequentialInStreamWithCRC: - public ISequentialInStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); -private: +Z7_CLASS_IMP_NOQIB_2( + CSequentialInStreamWithCRC + , ISequentialInStream + , IStreamGetSize +) CMyComPtr _stream; UInt64 _size; UInt32 _crc; bool _wasFinished; + UInt64 _fullSize; public: - void SetStream(ISequentialInStream *stream) { _stream = stream; } + + CSequentialInStreamWithCRC(): + _fullSize((UInt64)(Int64)-1) + {} + + void SetStream(ISequentialInStream *stream) { _stream = stream; } + void SetFullSize(UInt64 fullSize) { _fullSize = fullSize; } void Init() { _size = 0; - _wasFinished = false; _crc = CRC_INIT_VAL; + _wasFinished = false; } void ReleaseStream() { _stream.Release(); } UInt32 GetCRC() const { return CRC_GET_DIGEST(_crc); } @@ -36,22 +39,19 @@ bool WasFinished() const { return _wasFinished; } }; -class CInStreamWithCRC: - public IInStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP1(IInStream) - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); -private: +Z7_CLASS_IMP_COM_1( + CInStreamWithCRC, + IInStream +) + Z7_IFACE_COM7_IMP(ISequentialInStream) + CMyComPtr _stream; UInt64 _size; UInt32 _crc; // bool _wasFinished; public: - void SetStream(IInStream *stream) { _stream = stream; } + void SetStream(IInStream *stream) { _stream = stream; } void Init() { _size = 0; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/ItemNameUtils.h 7zip-23.01+dfsg/CPP/7zip/Archive/Common/ItemNameUtils.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/ItemNameUtils.h 2022-01-09 18:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/ItemNameUtils.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Archive/Common/ItemNameUtils.h -#ifndef __ARCHIVE_ITEM_NAME_UTILS_H -#define __ARCHIVE_ITEM_NAME_UTILS_H +#ifndef ZIP7_INC_ARCHIVE_ITEM_NAME_UTILS_H +#define ZIP7_INC_ARCHIVE_ITEM_NAME_UTILS_H #include "../../../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/MultiStream.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Common/MultiStream.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/MultiStream.cpp 2021-01-24 16:26:59.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/MultiStream.cpp 2023-04-05 08:00:00.000000000 +0000 @@ -4,7 +4,7 @@ #include "MultiStream.h" -STDMETHODIMP CMultiStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CMultiStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -23,10 +23,7 @@ else if (_pos >= m.GlobalOffset + m.Size) left = mid + 1; else - { - _streamIndex = mid; break; - } mid = (left + right) / 2; } _streamIndex = mid; @@ -36,12 +33,14 @@ UInt64 localPos = _pos - s.GlobalOffset; if (localPos != s.LocalPos) { - RINOK(s.Stream->Seek((Int64)localPos, STREAM_SEEK_SET, &s.LocalPos)); + RINOK(s.Stream->Seek((Int64)localPos, STREAM_SEEK_SET, &s.LocalPos)) } - UInt64 rem = s.Size - localPos; - if (size > rem) - size = (UInt32)rem; - HRESULT result = s.Stream->Read(data, size, &size); + { + const UInt64 rem = s.Size - localPos; + if (size > rem) + size = (UInt32)rem; + } + const HRESULT result = s.Stream->Read(data, size, &size); _pos += size; s.LocalPos += size; if (processedSize) @@ -49,7 +48,7 @@ return result; } -STDMETHODIMP CMultiStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CMultiStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { @@ -72,6 +71,9 @@ public ISequentialOutStream, public CMyUnknownImp { + Z7_COM_UNKNOWN_IMP_0 + Z7_IFACE_COM7_IMP(ISequentialOutStream) + unsigned _volIndex; UInt64 _volSize; UInt64 _curPos; @@ -80,8 +82,6 @@ CCRC _crc; public: - MY_UNKNOWN_IMP - CFileItem _file; CUpdateOptions _options; CMyComPtr VolumeCallback; @@ -98,7 +98,6 @@ } HRESULT Flush(); - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); }; HRESULT COutVolumeStream::Flush() @@ -107,7 +106,7 @@ { _file.UnPackSize = _curPos; _file.FileCRC = _crc.GetDigest(); - RINOK(WriteVolumeHeader(_archive, _file, _options)); + RINOK(WriteVolumeHeader(_archive, _file, _options)) _archive.Close(); _volumeStream.Release(); _file.StartPos += _file.UnPackSize; @@ -117,7 +116,10 @@ */ /* -STDMETHODIMP COutMultiStream::Write(const void *data, UInt32 size, UInt32 *processedSize) + +#include "../../../Common/Defs.h" + +Z7_COM7F_IMF(COutMultiStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -126,8 +128,8 @@ if (_streamIndex >= Streams.Size()) { CSubStreamInfo subStream; - RINOK(VolumeCallback->GetVolumeSize(Streams.Size(), &subStream.Size)); - RINOK(VolumeCallback->GetVolumeStream(Streams.Size(), &subStream.Stream)); + RINOK(VolumeCallback->GetVolumeSize(Streams.Size(), &subStream.Size)) + RINOK(VolumeCallback->GetVolumeStream(Streams.Size(), &subStream.Stream)) subStream.Pos = 0; Streams.Add(subStream); continue; @@ -142,15 +144,15 @@ if (_offsetPos != subStream.Pos) { CMyComPtr outStream; - RINOK(subStream.Stream.QueryInterface(IID_IOutStream, &outStream)); - RINOK(outStream->Seek(_offsetPos, STREAM_SEEK_SET, NULL)); + RINOK(subStream.Stream.QueryInterface(IID_IOutStream, &outStream)) + RINOK(outStream->Seek((Int64)_offsetPos, STREAM_SEEK_SET, NULL)) subStream.Pos = _offsetPos; } - UInt32 curSize = (UInt32)MyMin((UInt64)size, subStream.Size - subStream.Pos); + const UInt32 curSize = (UInt32)MyMin((UInt64)size, subStream.Size - subStream.Pos); UInt32 realProcessed; - RINOK(subStream.Stream->Write(data, curSize, &realProcessed)); - data = (void *)((Byte *)data + realProcessed); + RINOK(subStream.Stream->Write(data, curSize, &realProcessed)) + data = (const void *)((const Byte *)data + realProcessed); size -= realProcessed; subStream.Pos += realProcessed; _offsetPos += realProcessed; @@ -170,7 +172,7 @@ return S_OK; } -STDMETHODIMP COutMultiStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(COutMultiStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { @@ -181,11 +183,11 @@ } if (offset < 0) return HRESULT_WIN32_ERROR_NEGATIVE_SEEK; - _absPos = offset; + _absPos = (UInt64)offset; _offsetPos = _absPos; _streamIndex = 0; if (newPosition) - *newPosition = offset; + *newPosition = (UInt64)offset; return S_OK; } */ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/MultiStream.h 7zip-23.01+dfsg/CPP/7zip/Archive/Common/MultiStream.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/MultiStream.h 2014-12-31 13:40:43.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/MultiStream.h 2023-04-05 08:00:00.000000000 +0000 @@ -1,20 +1,23 @@ // MultiStream.h -#ifndef __MULTI_STREAM_H -#define __MULTI_STREAM_H +#ifndef ZIP7_INC_MULTI_STREAM_H +#define ZIP7_INC_MULTI_STREAM_H #include "../../../Common/MyCom.h" #include "../../../Common/MyVector.h" #include "../../IStream.h" +#include "../../Archive/IArchive.h" -class CMultiStream: - public IInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CMultiStream + , IInStream +) + Z7_IFACE_COM7_IMP(ISequentialInStream) + + unsigned _streamIndex; UInt64 _pos; UInt64 _totalLength; - unsigned _streamIndex; public: @@ -24,12 +27,12 @@ UInt64 Size; UInt64 GlobalOffset; UInt64 LocalPos; - CSubStreamInfo(): Size(0), GlobalOffset(0), LocalPos(0) {} }; - + + CMyComPtr updateCallbackFile; CObjectVector Streams; - + HRESULT Init() { UInt64 total = 0; @@ -37,26 +40,27 @@ { CSubStreamInfo &s = Streams[i]; s.GlobalOffset = total; - total += Streams[i].Size; - RINOK(s.Stream->Seek(0, STREAM_SEEK_CUR, &s.LocalPos)); + total += s.Size; + s.LocalPos = 0; + { + // it was already set to start + // RINOK(InStream_GetPos(s.Stream, s.LocalPos)); + } } _totalLength = total; _pos = 0; _streamIndex = 0; return S_OK; } - - MY_UNKNOWN_IMP1(IInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); }; /* -class COutMultiStream: - public IOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + COutMultiStream, + IOutStream +) + Z7_IFACE_COM7_IMP(ISequentialOutStream) + unsigned _streamIndex; // required stream UInt64 _offsetPos; // offset from start of _streamIndex index UInt64 _absPos; @@ -78,11 +82,6 @@ _absPos = 0; _length = 0; } - - MY_UNKNOWN_IMP1(IOutStream) - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); }; */ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp 2009-03-14 10:28:56.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp 2023-01-28 17:00:00.000000000 +0000 @@ -4,7 +4,7 @@ #include "OutStreamWithCRC.h" -STDMETHODIMP COutStreamWithCRC::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(COutStreamWithCRC::Write(const void *data, UInt32 size, UInt32 *processedSize)) { HRESULT result = S_OK; if (_stream) @@ -12,7 +12,7 @@ if (_calculate) _crc = CrcUpdate(_crc, data, size); _size += size; - if (processedSize != NULL) + if (processedSize) *processedSize = size; return result; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/OutStreamWithCRC.h 7zip-23.01+dfsg/CPP/7zip/Archive/Common/OutStreamWithCRC.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/OutStreamWithCRC.h 2012-02-12 06:06:54.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/OutStreamWithCRC.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // OutStreamWithCRC.h -#ifndef __OUT_STREAM_WITH_CRC_H -#define __OUT_STREAM_WITH_CRC_H +#ifndef ZIP7_INC_OUT_STREAM_WITH_CRC_H +#define ZIP7_INC_OUT_STREAM_WITH_CRC_H #include "../../../../C/7zCrc.h" @@ -9,17 +9,15 @@ #include "../../IStream.h" -class COutStreamWithCRC: - public ISequentialOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + COutStreamWithCRC + , ISequentialOutStream +) CMyComPtr _stream; UInt64 _size; UInt32 _crc; bool _calculate; public: - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); void SetStream(ISequentialOutStream *stream) { _stream = stream; } void ReleaseStream() { _stream.Release(); } void Init(bool calculate = true) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/OutStreamWithSha1.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Common/OutStreamWithSha1.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/OutStreamWithSha1.cpp 2019-08-29 11:00:55.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/OutStreamWithSha1.cpp 2023-01-28 17:00:00.000000000 +0000 @@ -4,7 +4,7 @@ #include "OutStreamWithSha1.h" -STDMETHODIMP COutStreamWithSha1::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(COutStreamWithSha1::Write(const void *data, UInt32 size, UInt32 *processedSize)) { HRESULT result = S_OK; if (_stream) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/OutStreamWithSha1.h 7zip-23.01+dfsg/CPP/7zip/Archive/Common/OutStreamWithSha1.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/OutStreamWithSha1.h 2021-01-26 11:47:10.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/OutStreamWithSha1.h 2023-02-10 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // OutStreamWithSha1.h -#ifndef __OUT_STREAM_WITH_SHA1_H -#define __OUT_STREAM_WITH_SHA1_H +#ifndef ZIP7_INC_OUT_STREAM_WITH_SHA1_H +#define ZIP7_INC_OUT_STREAM_WITH_SHA1_H #include "../../../../C/Sha1.h" @@ -10,23 +10,19 @@ #include "../../IStream.h" -class COutStreamWithSha1: - public ISequentialOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + COutStreamWithSha1 + , ISequentialOutStream +) CMyComPtr _stream; UInt64 _size; // CSha1 _sha; bool _calculate; - CAlignedBuffer _sha; + CAlignedBuffer1 _sha; CSha1 *Sha() { return (CSha1 *)(void *)(Byte *)_sha; } public: - MY_UNKNOWN_IMP - COutStreamWithSha1(): _sha(sizeof(CSha1)) {} - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); void SetStream(ISequentialOutStream *stream) { _stream = stream; } void ReleaseStream() { _stream.Release(); } void Init(bool calculate = true) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/ParseProperties.h 7zip-23.01+dfsg/CPP/7zip/Archive/Common/ParseProperties.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/ParseProperties.h 2011-02-06 08:34:40.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/ParseProperties.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,6 +1,6 @@ // ParseProperties.h -#ifndef __PARSE_PROPERTIES_H -#define __PARSE_PROPERTIES_H +#ifndef ZIP7_INC_PARSE_PROPERTIES_H +#define ZIP7_INC_PARSE_PROPERTIES_H #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Common/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Archive/Common/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Common/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Common/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/CpioHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/CpioHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/CpioHandler.cpp 2022-02-14 07:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/CpioHandler.cpp 2023-03-22 15:00:00.000000000 +0000 @@ -44,41 +44,6 @@ static const unsigned k_RecordSize_Max = k_HexRecord_Size; - /* - struct CBinRecord - { - unsigned short c_magic; - short c_dev; - unsigned short c_ino; - unsigned short c_mode; - unsigned short c_uid; - unsigned short c_gid; - unsigned short c_nlink; - short c_rdev; - unsigned short c_mtimes[2]; - unsigned short c_namesize; - unsigned short c_filesizes[2]; - }; - - struct CHexRecord - { - char Magic[6]; - char inode[8]; - char Mode[8]; - char UID[8]; - char GID[8]; - char nlink[8]; - char mtime[8]; - char Size[8]; // must be 0 for FIFOs and directories - char DevMajor[8]; - char DevMinor[8]; - char RDevMajor[8]; //only valid for chr and blk special files - char RDevMinor[8]; //only valid for chr and blk special files - char NameSize[8]; // count includes terminating NUL in pathname - char ChkSum[8]; // 0 for "new" portable format; for CRC format the sum of all the bytes in the file - }; -*/ - enum EType { k_Type_BinLe, @@ -99,114 +64,159 @@ struct CItem { - AString Name; UInt32 inode; + unsigned MainIndex_ForInode; UInt32 Mode; - UInt32 UID; - UInt32 GID; - UInt64 Size; UInt32 MTime; - - UInt32 NumLinks; UInt32 DevMajor; UInt32 DevMinor; + UInt64 Size; + AString Name; + UInt32 NumLinks; + UInt32 UID; + UInt32 GID; UInt32 RDevMajor; UInt32 RDevMinor; UInt32 ChkSum; - UInt32 Align; + UInt32 AlignMask; EType Type; UInt32 HeaderSize; UInt64 HeaderPos; + CByteBuffer Data; // for symlink + + + UInt32 GetAlignedSize(UInt32 size) const + { + return (size + AlignMask) & ~(UInt32)AlignMask; + } + + UInt64 GetPackSize() const + { + const UInt64 alignMask64 = AlignMask; + return (Size + alignMask64) & ~(UInt64)alignMask64; + } + + bool IsSame_inode_Dev(const CItem &item) const + { + return inode == item.inode + && DevMajor == item.DevMajor + && DevMinor == item.DevMinor; + } + bool IsBin() const { return Type == k_Type_BinLe || Type == k_Type_BinBe; } bool IsCrcFormat() const { return Type == k_Type_HexCrc; } bool IsDir() const { return MY_LIN_S_ISDIR(Mode); } + bool Is_SymLink() const { return MY_LIN_S_ISLNK(Mode); } bool IsTrailer() const { return strcmp(Name, kName_TRAILER) == 0; } UInt64 GetDataPosition() const { return HeaderPos + HeaderSize; } }; + enum EErrorType { k_ErrorType_OK, + k_ErrorType_BadSignature, k_ErrorType_Corrupted, k_ErrorType_UnexpectedEnd }; + struct CInArchive { + EErrorType errorType; ISequentialInStream *Stream; UInt64 Processed; + CItem item; HRESULT Read(void *data, size_t *size); - HRESULT GetNextItem(CItem &item, EErrorType &errorType); + HRESULT GetNextItem(); }; HRESULT CInArchive::Read(void *data, size_t *size) { - HRESULT res = ReadStream(Stream, data, size); + const HRESULT res = ReadStream(Stream, data, size); Processed += *size; return res; } -static bool ReadHex(const Byte *p, UInt32 &resVal) + +static bool CheckOctRecord(const Byte *p) +{ + for (unsigned i = 6; i < k_OctRecord_Size; i++) + { + const Byte c = p[i]; + if (c < '0' || c > '7') + return false; + } + return true; +} + +static bool CheckHexRecord(const Byte *p) +{ + for (unsigned i = 6; i < k_HexRecord_Size; i++) + { + const Byte c = p[i]; + if ((c < '0' || c > '9') && + (c < 'A' || c > 'F') && + (c < 'a' || c > 'f')) + return false; + } + return true; +} + +static UInt32 ReadHex(const Byte *p) { char sz[16]; memcpy(sz, p, 8); sz[8] = 0; const char *end; - resVal = ConvertHexStringToUInt32(sz, &end); - return (unsigned)(end - sz) == 8; + return ConvertHexStringToUInt32(sz, &end); } -static bool ReadOct6(const Byte *p, UInt32 &resVal) +static UInt32 ReadOct6(const Byte *p) { char sz[16]; memcpy(sz, p, 6); sz[6] = 0; const char *end; - resVal = ConvertOctStringToUInt32(sz, &end); - return (unsigned)(end - sz) == 6; + return ConvertOctStringToUInt32(sz, &end); } -static bool ReadOct11(const Byte *p, UInt64 &resVal) +static UInt64 ReadOct11(const Byte *p) { char sz[16]; memcpy(sz, p, 11); sz[11] = 0; const char *end; - resVal = ConvertOctStringToUInt64(sz, &end); - return (unsigned)(end - sz) == 11; + return ConvertOctStringToUInt64(sz, &end); } -#define READ_HEX(y) { if (!ReadHex(p2, y)) return S_OK; p2 += 8; } -#define READ_OCT_6(y) { if (!ReadOct6(p2, y)) return S_OK; p2 += 6; } -#define READ_OCT_11(y) { if (!ReadOct11(p2, y)) return S_OK; p2 += 11; } - -static UInt32 GetAlignedSize(UInt32 size, UInt32 align) -{ - while ((size & (align - 1)) != 0) - size++; - return size; -} - -static UInt16 Get16(const Byte *p, bool be) { if (be) return GetBe16(p); return GetUi16(p); } -static UInt32 Get32(const Byte *p, bool be) { return ((UInt32)Get16(p, be) << 16) + Get16(p + 2, be); } - -#define G16(offs, v) v = Get16(p + (offs), be) -#define G32(offs, v) v = Get32(p + (offs), be) +#define READ_HEX( y, dest) dest = ReadHex (p + 6 + (y) * 8); +#define READ_OCT_6( y, dest) dest = ReadOct6 (p + 6 + (y)); +#define READ_OCT_11( y, dest) dest = ReadOct11(p + 6 + (y)); + +#define Get32spec(p) (((UInt32)GetUi16(p) << 16) + GetUi16(p + 2)) +#define G16(offs, v) v = GetUi16(p + (offs)) +#define G32(offs, v) v = Get32spec(p + (offs)) static const unsigned kNameSizeMax = 1 << 12; + API_FUNC_static_IsArc IsArc_Cpio(const Byte *p, size_t size) { if (size < k_BinRecord_Size) return k_IsArc_Res_NEED_MORE; + UInt32 namePos; UInt32 nameSize; - UInt32 numLinks; + UInt32 mode; + UInt32 rDevMinor; + UInt32 rDevMajor = 0; + if (p[0] == '0') { if (p[1] != '7' || @@ -214,94 +224,120 @@ p[3] != '7' || p[4] != '0') return k_IsArc_Res_NO; - if (p[5] == '7') + if (p[5] == kMagicOct) { if (size < k_OctRecord_Size) return k_IsArc_Res_NEED_MORE; - for (unsigned i = 6; i < k_OctRecord_Size; i++) - { - char c = p[i]; - if (c < '0' || c > '7') - return k_IsArc_Res_NO; - } - ReadOct6(p + 6 * 6, numLinks); - ReadOct6(p + 8 * 6 + 11, nameSize); + if (!CheckOctRecord(p)) + return k_IsArc_Res_NO; + READ_OCT_6 (2 * 6, mode) + READ_OCT_6 (6 * 6, rDevMinor) + READ_OCT_6 (7 * 6 + 11, nameSize) + namePos = k_OctRecord_Size; } - else if (p[5] == '1' || p[5] == '2') + else if (p[5] == kMagicHex || p[5] == kMagicHexCrc) { if (size < k_HexRecord_Size) return k_IsArc_Res_NEED_MORE; - for (unsigned i = 6; i < k_HexRecord_Size; i++) - { - char c = p[i]; - if ((c < '0' || c > '9') && - (c < 'A' || c > 'F') && - (c < 'a' || c > 'f')) - return k_IsArc_Res_NO; - } - ReadHex(p + 6 + 4 * 8, numLinks); - ReadHex(p + 6 + 11 * 8, nameSize); + if (!CheckHexRecord(p)) + return k_IsArc_Res_NO; + READ_HEX (1, mode) + READ_HEX (9, rDevMajor) + READ_HEX (10, rDevMinor) + READ_HEX (11, nameSize) + namePos = k_HexRecord_Size; } else return k_IsArc_Res_NO; } else { - UInt32 rDevMinor; if (p[0] == kMagicBin0 && p[1] == kMagicBin1) { - numLinks = GetUi16(p + 12); + mode = GetUi16(p + 6); rDevMinor = GetUi16(p + 14); nameSize = GetUi16(p + 20); } else if (p[0] == kMagicBin1 && p[1] == kMagicBin0) { - numLinks = GetBe16(p + 12); + mode = GetBe16(p + 6); rDevMinor = GetBe16(p + 14); nameSize = GetBe16(p + 20); } else return k_IsArc_Res_NO; + namePos = k_BinRecord_Size; + } - if (rDevMinor != 0) - return k_IsArc_Res_NO; - if (nameSize > (1 << 8)) + if (mode >= (1 << 16)) + return k_IsArc_Res_NO; + + if (rDevMajor != 0 || + rDevMinor != 0) + { + if (!MY_LIN_S_ISCHR(mode) && + !MY_LIN_S_ISBLK(mode)) return k_IsArc_Res_NO; } - // 20.03: some cpio files have (numLinks == 0). - // if (numLinks == 0) return k_IsArc_Res_NO; - if (numLinks >= (1 << 10)) - return k_IsArc_Res_NO; + + // nameSize must include the null byte if (nameSize == 0 || nameSize > kNameSizeMax) return k_IsArc_Res_NO; + { + unsigned lim = namePos + nameSize - 1; + if (lim >= size) + lim = (unsigned)size; + else if (p[lim] != 0) + return k_IsArc_Res_NO; + for (unsigned i = namePos; i < lim; i++) + if (p[i] == 0) + return k_IsArc_Res_NO; + } + return k_IsArc_Res_YES; } } + #define READ_STREAM(_dest_, _size_) \ { size_t processed = (_size_); RINOK(Read(_dest_, &processed)); \ if (processed != (_size_)) { errorType = k_ErrorType_UnexpectedEnd; return S_OK; } } -HRESULT CInArchive::GetNextItem(CItem &item, EErrorType &errorType) +HRESULT CInArchive::GetNextItem() { - errorType = k_ErrorType_Corrupted; + errorType = k_ErrorType_BadSignature; Byte p[k_RecordSize_Max]; READ_STREAM(p, k_BinRecord_Size) UInt32 nameSize; + UInt32 namePos; + + /* we try to reduce probability of false detection, + so we check some fields for unuxpected values */ if (p[0] != '0') { - bool be; - if (p[0] == kMagicBin0 && p[1] == kMagicBin1) { be = false; item.Type = k_Type_BinLe; } - else if (p[0] == kMagicBin1 && p[1] == kMagicBin0) { be = true; item.Type = k_Type_BinBe; } - else return S_FALSE; + if (p[0] == kMagicBin0 && p[1] == kMagicBin1) { item.Type = k_Type_BinLe; } + else if (p[0] == kMagicBin1 && p[1] == kMagicBin0) + { + for (unsigned i = 2; i < k_BinRecord_Size; i += 2) + { + const Byte b = p[i]; + p[i] = p[i + 1]; + p[i + 1] = b; + } + item.Type = k_Type_BinBe; + } + else + return S_OK; + + errorType = k_ErrorType_Corrupted; - item.Align = 2; + item.AlignMask = 2 - 1; item.DevMajor = 0; - item.RDevMajor =0; + item.RDevMajor = 0; item.ChkSum = 0; G16(2, item.DevMinor); @@ -315,13 +351,7 @@ G16(20, nameSize); G32(22, item.Size); - /* - if (item.RDevMinor != 0) - return S_FALSE; - */ - - item.HeaderSize = GetAlignedSize(nameSize + k_BinRecord_Size, item.Align); - nameSize = item.HeaderSize - k_BinRecord_Size; + namePos = k_BinRecord_Size; } else { @@ -329,104 +359,131 @@ p[2] != '0' || p[3] != '7' || p[4] != '0') - return S_FALSE; + return S_OK; if (p[5] == kMagicOct) { + errorType = k_ErrorType_Corrupted; + item.Type = k_Type_Oct; READ_STREAM(p + k_BinRecord_Size, k_OctRecord_Size - k_BinRecord_Size) - item.Align = 1; + item.AlignMask = 1 - 1; item.DevMajor = 0; item.RDevMajor = 0; + item.ChkSum = 0; + + if (!CheckOctRecord(p)) + return S_OK; - const Byte *p2 = p + 6; - READ_OCT_6(item.DevMinor); - READ_OCT_6(item.inode); - READ_OCT_6(item.Mode); - READ_OCT_6(item.UID); - READ_OCT_6(item.GID); - READ_OCT_6(item.NumLinks); - READ_OCT_6(item.RDevMinor); + READ_OCT_6 (0, item.DevMinor) + READ_OCT_6 (1 * 6, item.inode) + READ_OCT_6 (2 * 6, item.Mode) + READ_OCT_6 (3 * 6, item.UID) + READ_OCT_6 (4 * 6, item.GID) + READ_OCT_6 (5 * 6, item.NumLinks) + READ_OCT_6 (6 * 6, item.RDevMinor) { UInt64 mTime64; - READ_OCT_11(mTime64); + READ_OCT_11 (7 * 6, mTime64) item.MTime = 0; - if (mTime64 < (UInt32)(Int32)-1) + if (mTime64 <= (UInt32)(Int32)-1) item.MTime = (UInt32)mTime64; } - READ_OCT_6(nameSize); - READ_OCT_11(item.Size); // ????? - item.HeaderSize = GetAlignedSize(nameSize + k_OctRecord_Size, item.Align); - nameSize = item.HeaderSize - k_OctRecord_Size; + READ_OCT_6 (7 * 6 + 11, nameSize) + READ_OCT_11 (8 * 6 + 11, item.Size) // ????? + + namePos = k_OctRecord_Size; } else { - if (p[5] == kMagicHex) - item.Type = k_Type_Hex; - else if (p[5] == kMagicHexCrc) - item.Type = k_Type_HexCrc; - else - return S_FALSE; + if (p[5] == kMagicHex) item.Type = k_Type_Hex; + else if (p[5] == kMagicHexCrc) item.Type = k_Type_HexCrc; + else return S_OK; + + errorType = k_ErrorType_Corrupted; READ_STREAM(p + k_BinRecord_Size, k_HexRecord_Size - k_BinRecord_Size) - item.Align = 4; + if (!CheckHexRecord(p)) + return S_OK; + + item.AlignMask = 4 - 1; + READ_HEX (0, item.inode) + READ_HEX (1, item.Mode) + READ_HEX (2, item.UID) + READ_HEX (3, item.GID) + READ_HEX (4, item.NumLinks) + READ_HEX (5, item.MTime) + READ_HEX (6, item.Size) + READ_HEX (7, item.DevMajor) + READ_HEX (8, item.DevMinor) + READ_HEX (9, item.RDevMajor) + READ_HEX (10, item.RDevMinor) + READ_HEX (11, nameSize) + READ_HEX (12, item.ChkSum) - const Byte *p2 = p + 6; - READ_HEX(item.inode); - READ_HEX(item.Mode); - READ_HEX(item.UID); - READ_HEX(item.GID); - READ_HEX(item.NumLinks); - READ_HEX(item.MTime); - { - UInt32 size32; - READ_HEX(size32); - item.Size = size32; - } - READ_HEX(item.DevMajor); - READ_HEX(item.DevMinor); - READ_HEX(item.RDevMajor); - READ_HEX(item.RDevMinor); - READ_HEX(nameSize); - READ_HEX(item.ChkSum); - if (nameSize >= kNameSizeMax) + if (item.Type == k_Type_Hex && item.ChkSum != 0) return S_OK; - item.HeaderSize = GetAlignedSize(nameSize + k_HexRecord_Size, item.Align); - nameSize = item.HeaderSize - k_HexRecord_Size; + + namePos = k_HexRecord_Size; } } - if (nameSize > kNameSizeMax) - return S_FALSE; - if (nameSize == 0 || nameSize >= kNameSizeMax) + + if (item.Mode >= (1 << 16)) return S_OK; - char *s = item.Name.GetBuf(nameSize); - size_t processedSize = nameSize; - RINOK(Read(s, &processedSize)); - item.Name.ReleaseBuf_CalcLen(nameSize); - if (processedSize != nameSize) + + if (item.RDevMinor != 0 || + item.RDevMajor != 0) + { + if (!MY_LIN_S_ISCHR(item.Mode) && + !MY_LIN_S_ISBLK(item.Mode)) + return S_OK; + } + + // Size must be 0 for FIFOs and directories + if (item.IsDir() || MY_LIN_S_ISFIFO(item.Mode)) + if (item.Size != 0) + return S_OK; + + // nameSize must include the null byte + if (nameSize == 0 || nameSize > kNameSizeMax) + return S_OK; + item.HeaderSize = item.GetAlignedSize(namePos + nameSize); + const UInt32 rem = item.HeaderSize - namePos; + char *s = item.Name.GetBuf(rem); + size_t processedSize = rem; + RINOK(Read(s, &processedSize)) + if (processedSize != rem) { + item.Name.ReleaseBuf_SetEnd(0); errorType = k_ErrorType_UnexpectedEnd; return S_OK; } + bool pad_error = false; + for (size_t i = nameSize; i < processedSize; i++) + if (s[i] != 0) + pad_error = true; + item.Name.ReleaseBuf_CalcLen(nameSize); + if (item.Name.Len() + 1 != nameSize || pad_error) + return S_OK; errorType = k_ErrorType_OK; return S_OK; } -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public CMyUnknownImp -{ + + +Z7_CLASS_IMP_CHandler_IInArchive_1( + IInArchiveGetStream +) CObjectVector _items; CMyComPtr _stream; UInt64 _phySize; - EType _Type; + EType _type; EErrorType _error; bool _isArc; -public: - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); + bool _moreThanOneHardLinks_Error; + bool _numLinks_Error; + bool _pad_Error; + bool _symLink_Error; }; static const Byte kArcProps[] = @@ -439,22 +496,35 @@ kpidPath, kpidIsDir, kpidSize, + kpidPackSize, kpidMTime, kpidPosixAttrib, - kpidLinks + kpidLinks, + kpidINode, + kpidUserId, + kpidGroupId, + kpidDevMajor, + kpidDevMinor, + kpidDeviceMajor, + kpidDeviceMinor, + kpidChecksum, + kpidSymLink, + kpidStreamId, // for debug + kpidOffset }; IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; switch (propID) { - case kpidSubType: prop = k_Types[(unsigned)_Type]; break; + case kpidSubType: prop = k_Types[(unsigned)_type]; break; case kpidPhySize: prop = _phySize; break; + case kpidINode: prop = true; break; case kpidErrorFlags: { UInt32 v = 0; @@ -463,14 +533,28 @@ switch (_error) { case k_ErrorType_UnexpectedEnd: v |= kpv_ErrorFlags_UnexpectedEnd; break; - case k_ErrorType_Corrupted: v |= kpv_ErrorFlags_HeadersError; break; + case k_ErrorType_Corrupted: v |= kpv_ErrorFlags_HeadersError; break; case k_ErrorType_OK: - default: + case k_ErrorType_BadSignature: + // default: break; } prop = v; break; } + case kpidWarningFlags: + { + UInt32 v = 0; + if (_moreThanOneHardLinks_Error) + v |= kpv_ErrorFlags_UnsupportedFeature; // kpv_ErrorFlags_HeadersError + if (_numLinks_Error + || _pad_Error + || _symLink_Error) + v |= kpv_ErrorFlags_HeadersError; + if (v != 0) + prop = v; + break; + } } prop.Detach(value); return S_OK; @@ -478,22 +562,43 @@ } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback) +static int CompareItems(const unsigned *p1, const unsigned *p2, void *param) +{ + const CObjectVector &items = *(const CObjectVector *)param; + const unsigned index1 = *p1; + const unsigned index2 = *p2; + const CItem &i1 = items[index1]; + const CItem &i2 = items[index2]; + if (i1.DevMajor < i2.DevMajor) return -1; + if (i1.DevMajor > i2.DevMajor) return 1; + if (i1.DevMinor < i2.DevMinor) return -1; + if (i1.DevMinor > i2.DevMinor) return 1; + if (i1.inode < i2.inode) return -1; + if (i1.inode > i2.inode) return 1; + if (i1.IsDir()) + { + if (!i2.IsDir()) + return -1; + } + else if (i2.IsDir()) + return 1; + return MyCompare(index1, index2); +} + + +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback)) { COM_TRY_BEGIN { Close(); - UInt64 endPos = 0; - - RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos)); - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); + UInt64 endPos; + RINOK(InStream_AtBegin_GetSize(stream, endPos)) if (callback) { - RINOK(callback->SetTotal(NULL, &endPos)); + RINOK(callback->SetTotal(NULL, &endPos)) } - _items.Clear(); CInArchive arc; arc.Stream = stream; @@ -501,70 +606,98 @@ for (;;) { - CItem item; + CItem &item = arc.item; item.HeaderPos = arc.Processed; - HRESULT result = arc.GetNextItem(item, _error); - if (result == S_FALSE) - return S_FALSE; - if (result != S_OK) - return S_FALSE; + + RINOK(arc.GetNextItem()) + + _error = arc.errorType; + if (_error != k_ErrorType_OK) { - if (_error == k_ErrorType_Corrupted) + if (_error == k_ErrorType_BadSignature || + _error == k_ErrorType_Corrupted) arc.Processed = item.HeaderPos; break; } + if (_items.IsEmpty()) - _Type = item.Type; + _type = item.Type; else if (_items.Back().Type != item.Type) { _error = k_ErrorType_Corrupted; arc.Processed = item.HeaderPos; break; } + if (item.IsTrailer()) break; + item.MainIndex_ForInode = _items.Size(); _items.Add(item); + const UInt64 dataSize = item.GetPackSize(); + arc.Processed += dataSize; + if (arc.Processed > endPos) { - // archive.SkipDataRecords(item.Size, item.Align); - UInt64 dataSize = item.Size; - UInt32 align = item.Align; - while ((dataSize & (align - 1)) != 0) - dataSize++; - - // _error = k_ErrorType_UnexpectedEnd; break; - - arc.Processed += dataSize; - if (arc.Processed > endPos) + _error = k_ErrorType_UnexpectedEnd; + break; + } + + if (item.Is_SymLink() && dataSize <= (1 << 12) && item.Size != 0) + { + size_t cur = (size_t)dataSize; + CByteBuffer buf; + buf.Alloc(cur); + RINOK(ReadStream(stream, buf, &cur)) + if (cur != dataSize) { _error = k_ErrorType_UnexpectedEnd; break; } - - UInt64 newPostion; - RINOK(stream->Seek(dataSize, STREAM_SEEK_CUR, &newPostion)); - if (arc.Processed != newPostion) + size_t i; + + for (i = (size_t)item.Size; i < dataSize; i++) + if (buf[i] != 0) + break; + if (i != dataSize) + _pad_Error = true; + + for (i = 0; i < (size_t)item.Size; i++) + if (buf[i] == 0) + break; + if (i != (size_t)item.Size) + _symLink_Error = true; + else + _items.Back().Data.CopyFrom(buf, (size_t)item.Size); + } + else if (dataSize != 0) + { + UInt64 newPos; + RINOK(stream->Seek((Int64)dataSize, STREAM_SEEK_CUR, &newPos)) + if (arc.Processed != newPos) return E_FAIL; } - if (callback && (_items.Size() & 0xFF) == 0) + if (callback && (_items.Size() & 0xFFF) == 0) { - UInt64 numFiles = _items.Size(); - RINOK(callback->SetCompleted(&numFiles, &item.HeaderPos)); + const UInt64 numFiles = _items.Size(); + RINOK(callback->SetCompleted(&numFiles, &item.HeaderPos)) } } + _phySize = arc.Processed; + } + + { if (_error != k_ErrorType_OK) { + // we try to reduce probability of false detection if (_items.Size() == 0) return S_FALSE; + // bin file uses small signature. So we do additional check for single item case. if (_items.Size() == 1 && _items[0].IsBin()) - { - // probably it's false detected archive. So we return error return S_FALSE; - } } else { @@ -574,16 +707,15 @@ const unsigned kTailSize_MAX = 1 << 9; Byte buf[kTailSize_MAX]; - unsigned pos = (unsigned)arc.Processed & (kTailSize_MAX - 1); + unsigned pos = (unsigned)_phySize & (kTailSize_MAX - 1); if (pos != 0) // use this check to support 512 bytes alignment only for (;;) { - unsigned rem = kTailSize_MAX - pos; + const unsigned rem = kTailSize_MAX - pos; size_t processed = rem; - RINOK(ReadStream(stream, buf + pos, &processed)); + RINOK(ReadStream(stream, buf + pos, &processed)) if (processed != rem) break; - for (; pos < kTailSize_MAX && buf[pos] == 0; pos++) {} if (pos != kTailSize_MAX) @@ -596,32 +728,134 @@ break; } } + } + + { + /* there was such cpio archive example with hard links: + { + all hard links (same dev/inode) are stored in neighboring items, and + (item.Size == 0) for non last hard link items + (item.Size != 0) for last hard link item + } + but here we sort items by (dev/inode) to support cases + where hard links (same dev/inode) are not stored in neighboring items. + + // note: some cpio files have (numLinks == 0) ?? + */ + + CUIntVector indices; + { + const unsigned numItems = _items.Size(); + indices.ClearAndSetSize(numItems); + if (numItems != 0) + { + unsigned *vals = &indices[0]; + for (unsigned i = 0; i < numItems; i++) + vals[i] = i; + indices.Sort(CompareItems, (void *)&_items); + } + } + + /* Note: if cpio archive (maybe incorrect) contains + more then one non empty streams with identical inode number, + we want to extract all such data streams too. + + So we place items with identical inode to groups: + all items in group will have same MainIndex_ForInode, + that is index of last item in group with (Size != 0). + Another (non last) items in group have (Size == 0). + If there are another hard links with same inode number + after (Size != 0) item, we place them to another next group(s). + + Check it: maybe we should use single group for items + with identical inode instead, and ignore some extra data streams ? + */ - _isArc = true; - _stream = stream; + for (unsigned i = 0; i < indices.Size();) + { + unsigned k; + { + const CItem &item_Base = _items[indices[i]]; + + if (item_Base.IsDir()) + { + i++; + continue; + } + + if (i != 0) + { + const CItem &item_Prev = _items[indices[i - 1]]; + if (!item_Prev.IsDir()) + if (item_Base.IsSame_inode_Dev(item_Prev)) + _moreThanOneHardLinks_Error = true; + } + + if (item_Base.Size != 0) + { + if (item_Base.NumLinks != 1) + _numLinks_Error = true; + i++; + continue; + } + + for (k = i + 1; k < indices.Size();) + { + const CItem &item = _items[indices[k]]; + if (item.IsDir()) + break; + if (!item.IsSame_inode_Dev(item_Base)) + break; + k++; + if (item.Size != 0) + break; + } + } + + const unsigned numLinks = k - i; + for (;;) + { + CItem &item = _items[indices[i]]; + if (item.NumLinks != numLinks) + _numLinks_Error = true; + if (++i == k) + break; + // if (item.Size == 0) + item.MainIndex_ForInode = indices[k - 1]; + } + } } + + _isArc = true; + _stream = stream; + return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::Close() + +Z7_COM7F_IMF(CHandler::Close()) { _items.Clear(); _stream.Release(); _phySize = 0; - _Type = k_Type_BinLe; + _type = k_Type_BinLe; _isArc = false; + _moreThanOneHardLinks_Error = false; + _numLinks_Error = false; + _pad_Error = false; + _symLink_Error = false; _error = k_ErrorType_OK; return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _items.Size(); return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -645,10 +879,15 @@ break; } case kpidIsDir: prop = item.IsDir(); break; + case kpidSize: + prop = (UInt64)_items[item.MainIndex_ForInode].Size; + break; + case kpidPackSize: - prop = (UInt64)item.Size; + prop = (UInt64)item.GetPackSize(); break; + case kpidMTime: { if (item.MTime != 0) @@ -656,28 +895,69 @@ break; } case kpidPosixAttrib: prop = item.Mode; break; + case kpidINode: prop = item.inode; break; + case kpidStreamId: + if (!item.IsDir()) + prop = (UInt32)item.MainIndex_ForInode; + break; + case kpidDevMajor: prop = (UInt32)item.DevMajor; break; + case kpidDevMinor: prop = (UInt32)item.DevMinor; break; + + case kpidUserId: prop = item.UID; break; + case kpidGroupId: prop = item.GID; break; + + case kpidSymLink: + if (item.Is_SymLink() && item.Data.Size() != 0) + { + AString s; + s.SetFrom_CalcLen((const char *)(const void *)(const Byte *)item.Data, (unsigned)item.Data.Size()); + if (s.Len() == item.Data.Size()) + { + UString u; + bool needConvert = true; + #ifdef _WIN32 + // if ( + ConvertUTF8ToUnicode(item.Name, u); + // ) + needConvert = false; + #endif + if (needConvert) + u = MultiByteToUnicodeString(s, CP_OEMCP); + prop = u; + } + } + break; + case kpidLinks: prop = item.NumLinks; break; - /* - case kpidinode: prop = item.inode; break; - case kpidiChkSum: prop = item.ChkSum; break; - */ + case kpidDeviceMajor: + // if (item.RDevMajor != 0) + prop = (UInt32)item.RDevMajor; + break; + case kpidDeviceMinor: + // if (item.RDevMinor != 0) + prop = (UInt32)item.RDevMinor; + break; + case kpidChecksum: + if (item.IsCrcFormat()) + prop = item.ChkSum; + break; + case kpidOffset: prop = item.GetDataPosition(); break; } prop.Detach(value); return S_OK; COM_TRY_END } -class COutStreamWithSum: - public ISequentialOutStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_NOQIB_1( + COutStreamWithSum + , ISequentialOutStream +) CMyComPtr _stream; UInt64 _size; UInt32 _crc; bool _calculate; public: - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); void SetStream(ISequentialOutStream *stream) { _stream = stream; } void ReleaseStream() { _stream.Release(); } void Init(bool calculate = true) @@ -692,7 +972,7 @@ UInt32 GetCRC() const { return _crc; } }; -STDMETHODIMP COutStreamWithSum::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(COutStreamWithSum::Write(const void *data, UInt32 size, UInt32 *processedSize)) { HRESULT result = S_OK; if (_stream) @@ -709,11 +989,11 @@ return result; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _items.Size(); if (numItems == 0) @@ -721,11 +1001,14 @@ UInt64 totalSize = 0; UInt32 i; for (i = 0; i < numItems; i++) - totalSize += _items[allFilesMode ? i : indices[i]].Size; - extractCallback->SetTotal(totalSize); + { + const UInt32 index = allFilesMode ? i : indices[i]; + const CItem &item2 = _items[index]; + const CItem &item = _items[item2.MainIndex_ForInode]; + totalSize += item.Size; + } + RINOK(extractCallback->SetTotal(totalSize)) - UInt64 currentTotalSize = 0; - NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder(); CMyComPtr copyCoder = copyCoderSpec; @@ -740,22 +1023,32 @@ COutStreamWithSum *outStreamSumSpec = new COutStreamWithSum; CMyComPtr outStreamSum(outStreamSumSpec); - for (i = 0; i < numItems; i++) + UInt64 total_PackSize = 0; + UInt64 total_UnpackSize = 0; + + for (i = 0;; i++) { - lps->InSize = lps->OutSize = currentTotalSize; - RINOK(lps->SetCur()); + lps->InSize = total_PackSize; + lps->OutSize = total_UnpackSize; + RINOK(lps->SetCur()) + if (i >= numItems) + break; CMyComPtr outStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - Int32 index = allFilesMode ? i : indices[i]; - const CItem &item = _items[index]; - RINOK(extractCallback->GetStream(index, &outStream, askMode)); - currentTotalSize += item.Size; - if (item.IsDir()) + const UInt32 index = allFilesMode ? i : indices[i]; + const CItem &item2 = _items[index]; + const CItem &item = _items[item2.MainIndex_ForInode]; + RINOK(extractCallback->GetStream(index, &outStream, askMode)) + + total_PackSize += item2.GetPackSize(); + total_UnpackSize += item.Size; + + if (item2.IsDir()) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } if (!testMode && !outStream) @@ -764,10 +1057,10 @@ outStreamSumSpec->SetStream(outStream); outStream.Release(); - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(_stream->Seek(item.GetDataPosition(), STREAM_SEEK_SET, NULL)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(InStream_SeekSet(_stream, item.GetDataPosition())) streamSpec->Init(item.Size); - RINOK(copyCoder->Code(inStream, outStreamSum, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStream, outStreamSum, NULL, NULL, progress)) outStreamSumSpec->ReleaseStream(); Int32 res = NExtract::NOperationResult::kDataError; if (copyCoderSpec->TotalSize == item.Size) @@ -776,16 +1069,17 @@ if (item.IsCrcFormat() && item.ChkSum != outStreamSumSpec->GetCRC()) res = NExtract::NOperationResult::kCRCError; } - RINOK(extractCallback->SetOperationResult(res)); + RINOK(extractCallback->SetOperationResult(res)) } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN - const CItem &item = _items[index]; + const CItem &item2 = _items[index]; + const CItem &item = _items[item2.MainIndex_ForInode]; return CreateLimitedInStream(_stream, item.GetDataPosition(), item.Size, stream); COM_TRY_END } @@ -796,7 +1090,7 @@ 2, kMagicBin1, kMagicBin0 }; REGISTER_ARC_I( - "Cpio", "cpio", 0, 0xED, + "Cpio", "cpio", NULL, 0xED, k_Signature, 0, NArcInfoFlags::kMultiSignature, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/CramfsHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/CramfsHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/CramfsHandler.cpp 2016-05-14 11:47:41.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/CramfsHandler.cpp 2023-03-26 12:00:00.000000000 +0000 @@ -25,9 +25,8 @@ namespace NArchive { namespace NCramfs { -#define SIGNATURE { 'C','o','m','p','r','e','s','s','e','d',' ','R','O','M','F','S' } - -static const Byte kSignature[] = SIGNATURE; +static const Byte kSignature[] = + { 'C','o','m','p','r','e','s','s','e','d',' ','R','O','M','F','S' }; static const UInt32 kArcSizeMax = (256 + 16) << 20; static const UInt32 kNumFilesMax = (1 << 19); @@ -114,7 +113,7 @@ if (be) return (p[8] & 0xFC); else - return (p[8] & 0x3F) << 2; + return ((UInt32)p[8] & (UInt32)0x3F) << 2; } static UInt32 GetOffset(const Byte *p, bool be) @@ -145,7 +144,7 @@ bool Parse(const Byte *p) { - if (memcmp(p + 16, kSignature, ARRAY_SIZE(kSignature)) != 0) + if (memcmp(p + 16, kSignature, Z7_ARRAY_SIZE(kSignature)) != 0) return false; switch (GetUi32(p)) { @@ -169,11 +168,11 @@ unsigned GetMethod() const { return (unsigned)(Flags >> k_Flags_Method_Shift) & k_Flags_Method_Mask; } }; -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public CMyUnknownImp -{ + + +Z7_CLASS_IMP_CHandler_IInArchive_1( + IInArchiveGetStream +) CRecordVector _items; CMyComPtr _stream; Byte *_data; @@ -205,8 +204,8 @@ HRESULT OpenDir(int parent, UInt32 baseOffsetBase, unsigned level); HRESULT Open2(IInStream *inStream); - AString GetPath(int index) const; - bool GetPackSize(int index, UInt32 &res) const; + AString GetPath(unsigned index) const; + bool GetPackSize(unsigned index, UInt32 &res) const; void Free(); UInt32 GetNumBlocks(UInt32 size) const @@ -221,11 +220,8 @@ } public: - CHandler(): _data(0) {} + CHandler(): _data(NULL) {} ~CHandler() { Free(); } - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); HRESULT ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize); }; @@ -291,7 +287,7 @@ unsigned endIndex = _items.Size(); for (unsigned i = startIndex; i < endIndex; i++) { - RINOK(OpenDir(i, _items[i].Offset, level + 1)); + RINOK(OpenDir((int)i, _items[i].Offset, level + 1)) } return S_OK; } @@ -299,7 +295,7 @@ HRESULT CHandler::Open2(IInStream *inStream) { Byte buf[kHeaderSize]; - RINOK(ReadStream_FALSE(inStream, buf, kHeaderSize)); + RINOK(ReadStream_FALSE(inStream, buf, kHeaderSize)) if (!_h.Parse(buf)) return S_FALSE; _method = k_Flags_Method_ZLIB; @@ -319,18 +315,18 @@ else { UInt64 size; - RINOK(inStream->Seek(0, STREAM_SEEK_END, &size)); + RINOK(InStream_GetSize_SeekToEnd(inStream, size)) if (size > kArcSizeMax) size = kArcSizeMax; _h.Size = (UInt32)size; - RINOK(inStream->Seek(kHeaderSize, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(inStream, kHeaderSize)) } _data = (Byte *)MidAlloc(_h.Size); - if (_data == 0) + if (!_data) return E_OUTOFMEMORY; memcpy(_data, buf, kHeaderSize); size_t processed = _h.Size - kHeaderSize; - RINOK(ReadStream(inStream, _data + kHeaderSize, &processed)); + RINOK(ReadStream(inStream, _data + kHeaderSize, &processed)) if (processed < kNodeSize) return S_FALSE; _size = kHeaderSize + (UInt32)processed; @@ -340,7 +336,7 @@ _errorFlags = kpv_ErrorFlags_UnexpectedEnd; else { - SetUi32(_data + 0x20, 0); + SetUi32(_data + 0x20, 0) if (CrcCalc(_data, _h.Size) != _h.Crc) { _errorFlags = kpv_ErrorFlags_HeadersError; @@ -351,7 +347,7 @@ _items.ClearAndReserve(_h.NumFiles - 1); } - RINOK(OpenDir(-1, kHeaderSize, 0)); + RINOK(OpenDir(-1, kHeaderSize, 0)) if (!_h.IsVer2()) { @@ -389,22 +385,23 @@ return S_OK; } -AString CHandler::GetPath(int index) const +AString CHandler::GetPath(unsigned index) const { unsigned len = 0; - int indexMem = index; - do + unsigned indexMem = index; + for (;;) { const CItem &item = _items[index]; - index = item.Parent; const Byte *p = _data + item.Offset; unsigned size = GetNameLen(p, _h.be); p += kNodeSize; unsigned i; for (i = 0; i < size && p[i]; i++); len += i + 1; + index = (unsigned)item.Parent; + if (item.Parent < 0) + break; } - while (index >= 0); len--; AString path; @@ -413,7 +410,6 @@ for (;;) { const CItem &item = _items[index]; - index = item.Parent; const Byte *p = _data + item.Offset; unsigned size = GetNameLen(p, _h.be); p += kNodeSize; @@ -421,41 +417,42 @@ for (i = 0; i < size && p[i]; i++); dest -= i; memcpy(dest, p, i); - if (index < 0) + index = (unsigned)item.Parent; + if (item.Parent < 0) break; *(--dest) = CHAR_PATH_SEPARATOR; } return path; } -bool CHandler::GetPackSize(int index, UInt32 &res) const +bool CHandler::GetPackSize(unsigned index, UInt32 &res) const { res = 0; const CItem &item = _items[index]; const Byte *p = _data + item.Offset; - bool be = _h.be; - UInt32 offset = GetOffset(p, be); + const bool be = _h.be; + const UInt32 offset = GetOffset(p, be); if (offset < kHeaderSize) return false; - UInt32 numBlocks = GetNumBlocks(GetSize(p, be)); + const UInt32 numBlocks = GetNumBlocks(GetSize(p, be)); if (numBlocks == 0) return true; - UInt32 start = offset + numBlocks * 4; + const UInt32 start = offset + numBlocks * 4; if (start > _size) return false; - UInt32 end = Get32(_data + start - 4); + const UInt32 end = Get32(_data + start - 4); if (end < start) return false; res = end - start; return true; } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback * /* callback */) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback * /* callback */)) { COM_TRY_BEGIN { Close(); - RINOK(Open2(stream)); + RINOK(Open2(stream)) _isArc = true; _stream = stream; } @@ -466,10 +463,10 @@ void CHandler::Free() { MidFree(_data); - _data = 0; + _data = NULL; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; _phySize = 0; @@ -481,13 +478,13 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _items.Size(); return S_OK; } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -523,7 +520,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -554,7 +551,7 @@ class CCramfsInStream: public CCachedInStream { - HRESULT ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize); + HRESULT ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize) Z7_override; public: CHandler *Handler; }; @@ -626,16 +623,16 @@ } _inStreamSpec->Init(_data + start, inSize); _outStreamSpec->Init(dest, blockSize); - RINOK(_zlibDecoder->Code(_inStream, _outStream, NULL, NULL, NULL)); + RINOK(_zlibDecoder->Code(_inStream, _outStream, NULL, NULL, NULL)) return (inSize == _zlibDecoderSpec->GetInputProcessedSize() && _outStreamSpec->GetPos() == blockSize) ? S_OK : S_FALSE; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _items.Size(); if (numItems == 0) @@ -665,20 +662,20 @@ { lps->InSize = totalPackSize; lps->OutSize = totalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr outStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; const CItem &item = _items[index]; - RINOK(extractCallback->GetStream(index, &outStream, askMode)); + RINOK(extractCallback->GetStream(index, &outStream, askMode)) const Byte *p = _data + item.Offset; if (IsDir(p, be)) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } UInt32 curSize = GetSize(p, be); @@ -689,7 +686,7 @@ if (!testMode && !outStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) UInt32 offset = GetOffset(p, be); if (offset < kHeaderSize) @@ -705,7 +702,7 @@ res = NExtract::NOperationResult::kUnsupportedMethod; else { - RINOK(hres); + RINOK(hres) { hres = copyCoder->Code(inSeqStream, outStream, NULL, NULL, progress); if (hres == S_OK) @@ -720,14 +717,14 @@ } } } - RINOK(extractCallback->SetOperationResult(res)); + RINOK(extractCallback->SetOperationResult(res)) } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN @@ -778,7 +775,7 @@ } REGISTER_ARC_I( - "CramFS", "cramfs", 0, 0xD3, + "CramFS", "cramfs", NULL, 0xD3, kSignature, 16, 0, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/DeflateProps.h 7zip-23.01+dfsg/CPP/7zip/Archive/DeflateProps.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/DeflateProps.h 2011-01-27 10:53:18.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/DeflateProps.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,6 +1,6 @@ // DeflateProps.h -#ifndef __DEFLATE_PROPS_H -#define __DEFLATE_PROPS_H +#ifndef ZIP7_INC_DEFLATE_PROPS_H +#define ZIP7_INC_DEFLATE_PROPS_H #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/DllExports2.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/DllExports2.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/DllExports2.cpp 2022-04-30 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/DllExports2.cpp 2023-03-23 18:00:00.000000000 +0000 @@ -3,10 +3,9 @@ #include "StdAfx.h" #include "../../Common/MyWindows.h" - #include "../../Common/MyInitGuid.h" -#if defined(_7ZIP_LARGE_PAGES) +#if defined(Z7_LARGE_PAGES) #include "../../../C/Alloc.h" #endif @@ -29,6 +28,7 @@ #define NT_CHECK_FAIL_ACTION return FALSE; #endif +static HINSTANCE g_hInstance; extern "C" @@ -53,7 +53,7 @@ { // OutputDebugStringA("7z.dll DLL_PROCESS_ATTACH"); g_hInstance = (HINSTANCE)hInstance; - NT_CHECK; + NT_CHECK } /* if (dwReason == DLL_PROCESS_DETACH) @@ -80,7 +80,7 @@ #endif // _WIN32 -DEFINE_GUID(CLSID_CArchiveHandler, +Z7_DEFINE_GUID(CLSID_CArchiveHandler, k_7zip_GUID_Data1, k_7zip_GUID_Data2, k_7zip_GUID_Data3_Common, @@ -94,7 +94,7 @@ STDAPI CreateObject(const GUID *clsid, const GUID *iid, void **outObject) { // COM_TRY_BEGIN - *outObject = 0; + *outObject = NULL; if (*iid == IID_ICompressCoder || *iid == IID_ICompressCoder2 || *iid == IID_ICompressFilter) @@ -108,7 +108,7 @@ STDAPI SetLargePageMode(); STDAPI SetLargePageMode() { - #if defined(_7ZIP_LARGE_PAGES) + #if defined(Z7_LARGE_PAGES) #ifdef _WIN32 SetLargePageSize(); #endif @@ -143,7 +143,7 @@ } */ -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS CExternalCodecs g_ExternalCodecs; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/DllExports.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/DllExports.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/DllExports.cpp 2015-03-06 10:54:22.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/DllExports.cpp 2023-06-15 04:00:00.000000000 +0000 @@ -2,10 +2,11 @@ #include "StdAfx.h" -#if defined(_7ZIP_LARGE_PAGES) +#if defined(Z7_LARGE_PAGES) #include "../../../C/Alloc.h" #endif +#include "../../Common/MyWindows.h" #include "../../Common/MyInitGuid.h" #include "../../Common/ComTry.h" @@ -20,22 +21,23 @@ #include "IArchive.h" +static HINSTANCE g_hInstance; #define NT_CHECK_FAIL_ACTION return FALSE; -extern "C" -BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/) +extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/); +extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/) { if (dwReason == DLL_PROCESS_ATTACH) { g_hInstance = hInstance; - NT_CHECK; + NT_CHECK } return TRUE; } -DEFINE_GUID(CLSID_CArchiveHandler, +Z7_DEFINE_GUID(CLSID_CArchiveHandler, k_7zip_GUID_Data1, k_7zip_GUID_Data2, k_7zip_GUID_Data3_Common, @@ -50,7 +52,7 @@ STDAPI SetLargePageMode() { - #if defined(_7ZIP_LARGE_PAGES) + #if defined(Z7_LARGE_PAGES) SetLargePageSize(); #endif return S_OK; @@ -64,7 +66,7 @@ return S_OK; } -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS CExternalCodecs g_ExternalCodecs; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/DmgHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/DmgHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/DmgHandler.cpp 2022-07-15 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/DmgHandler.cpp 2023-03-27 17:00:00.000000000 +0000 @@ -85,7 +85,7 @@ Type = Get32(p); NumBits = Get32(p + 4); memcpy(Data, p + 8, kChecksumSize_Max); -}; +} struct CFile { @@ -132,11 +132,9 @@ }; -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_1( + IInArchiveGetStream +) CMyComPtr _inStream; CObjectVector _files; bool _masterCrcError; @@ -156,10 +154,6 @@ bool ParseBlob(const CByteBuffer &data); HRESULT Open2(IInStream *stream); HRESULT Extract(IInStream *stream); -public: - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); }; // that limit can be increased, if there are such dmg files @@ -248,7 +242,7 @@ { false, NULL, "Patches" } }; -static const unsigned kNumAppleNames = ARRAY_SIZE(k_Names); +static const unsigned kNumAppleNames = Z7_ARRAY_SIZE(k_Names); static const Byte kProps[] = { @@ -270,7 +264,7 @@ kpidComment }; -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -313,19 +307,19 @@ if (appleName.IsFs) { numFS++; - mainIndex = i; + mainIndex = (int)i; } break; } } if (n == kNumAppleNames) { - mainIndex = i; + mainIndex = (int)i; numUnknown++; } } if (numFS + numUnknown == 1) - prop = (UInt32)mainIndex; + prop = (UInt32)(Int32)mainIndex; break; } case kpidWarning: @@ -448,7 +442,7 @@ { const CXmlItem &si = item.SubItems[i]; if (si.IsTagged("key") && si.GetSubString() == key && item.SubItems[i + 1].IsTagged(nextTag)) - return i + 1; + return (int)(i + 1); } return -1; } @@ -467,7 +461,7 @@ static inline bool IsKoly(const Byte *p) { - return memcmp(p, k_Signature, ARRAY_SIZE(k_Signature)) == 0; + return memcmp(p, k_Signature, Z7_ARRAY_SIZE(k_Signature)) == 0; /* if (Get32(p) != 0x6B6F6C79) // "koly" signature return false; @@ -486,7 +480,7 @@ if (size != pair.Len) return E_OUTOFMEMORY; buf.Alloc(size); - RINOK(stream->Seek(_startPos + pair.Offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, _startPos + pair.Offset)) return ReadStream_FALSE(stream, buf, size); } @@ -564,14 +558,11 @@ */ _dataStartOffset = 0; - RINOK(stream->Seek(0, STREAM_SEEK_CUR, &_startPos)); - - UInt64 fileSize = 0; - RINOK(stream->Seek(0, STREAM_SEEK_END, &fileSize)); - RINOK(stream->Seek(_startPos, STREAM_SEEK_SET, NULL)); + UInt64 fileSize; + RINOK(InStream_GetPos_GetSize(stream, _startPos, fileSize)) Byte buf[HEADER_SIZE]; - RINOK(ReadStream_FALSE(stream, buf, HEADER_SIZE)); + RINOK(ReadStream_FALSE(stream, buf, HEADER_SIZE)) UInt64 headerPos; bool startKolyMode = false; @@ -595,8 +586,8 @@ if (headerPos < HEADER_SIZE) return S_FALSE; headerPos -= HEADER_SIZE; - RINOK(stream->Seek(headerPos, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(stream, buf, HEADER_SIZE)); + RINOK(InStream_SeekSet(stream, headerPos)) + RINOK(ReadStream_FALSE(stream, buf, HEADER_SIZE)) if (!IsKoly(buf)) return S_FALSE; } @@ -674,7 +665,7 @@ #else CByteBuffer blobBuf; #endif - RINOK(ReadData(stream, blobPair, blobBuf)); + RINOK(ReadData(stream, blobPair, blobBuf)) if (!ParseBlob(blobBuf)) _headersError = true; } @@ -704,7 +695,7 @@ CByteBuffer rsrcBuf; #endif - RINOK(ReadData(stream, rsrcPair, rsrcBuf)); + RINOK(ReadData(stream, rsrcPair, rsrcBuf)) const Byte *p = rsrcBuf; UInt32 headSize = Get32(p + 0); @@ -803,7 +794,7 @@ { CFile &file = _files.AddNew(); file.Name = name; - RINOK(file.Parse(pBlock + 4, blockSize)); + RINOK(file.Parse(pBlock + 4, blockSize)) } #ifdef DMG_SHOW_RAW @@ -844,12 +835,12 @@ if (size != xmlPair.Len) return S_FALSE; - RINOK(stream->Seek(_startPos + xmlPair.Offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, _startPos + xmlPair.Offset)) CXml xml; { CObjArray xmlStr(size + 1); - RINOK(ReadStream_FALSE(stream, xmlStr, size)); + RINOK(ReadStream_FALSE(stream, xmlStr, size)) xmlStr[size] = 0; // if (strlen(xmlStr) != size) return S_FALSE; if (!xml.Parse(xmlStr)) @@ -916,7 +907,7 @@ if (name) file.Name = *name; } - RINOK(file.Parse(rawBuf, destLen)); + RINOK(file.Parse(rawBuf, destLen)) } } @@ -941,9 +932,9 @@ return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *stream, +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openArchiveCallback */) + IArchiveOpenCallback * /* openArchiveCallback */)) { COM_TRY_BEGIN { @@ -956,7 +947,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _phySize = 0; _inStream.Release(); @@ -970,7 +961,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _files.Size() #ifdef DMG_SHOW_RAW @@ -984,7 +975,7 @@ #define RAW_PREFIX "raw" STRING_PATH_SEPARATOR #endif -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -1054,7 +1045,7 @@ if (pos1 >= 0) { pos1++; - int pos2 = item.Name.Find(')', pos1); + const int pos2 = item.Name.Find(')', pos1); if (pos2 >= 0) { subName.SetFrom(item.Name.Ptr(pos1), pos2 - pos1); @@ -1082,7 +1073,7 @@ } UString name2; ConvertUTF8ToUnicode(subName, name2); - name += '.'; + name.Add_Dot(); name += name2; } else @@ -1111,10 +1102,11 @@ COM_TRY_END } -class CAdcDecoder: - public ICompressCoder, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_NOQIB_1( + CAdcDecoder + , ICompressCoder +) CLzOutWindow m_OutWindowStream; CInBuffer m_InStream; @@ -1126,7 +1118,7 @@ } */ - class CCoderReleaser + class CCoderReleaser Z7_final { CAdcDecoder *m_Coder; public: @@ -1142,18 +1134,12 @@ friend class CCoderReleaser; public: - MY_UNKNOWN_IMP - - STDMETHOD(CodeReal)(ISequentialInStream *inStream, - ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, - ICompressProgressInfo *progress); - - STDMETHOD(Code)(ISequentialInStream *inStream, + HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); }; -STDMETHODIMP CAdcDecoder::CodeReal(ISequentialInStream *inStream, +HRESULT CAdcDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) { @@ -1178,7 +1164,7 @@ if (pos > nextLimit && progress) { UInt64 packSize = m_InStream.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &pos)); + RINOK(progress->SetRatioInfo(&packSize, &pos)) nextLimit += kStep; } Byte b; @@ -1231,9 +1217,9 @@ return m_OutWindowStream.Flush(); } -STDMETHODIMP CAdcDecoder::Code(ISequentialInStream *inStream, +Z7_COM7F_IMF(CAdcDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, - ICompressProgressInfo *progress) + ICompressProgressInfo *progress)) { try { return CodeReal(inStream, outStream, inSize, outSize, progress);} catch(const CInBufferException &e) { return e.ErrorCode; } @@ -1247,11 +1233,11 @@ -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _files.Size(); if (numItems == 0) @@ -1309,17 +1295,17 @@ lps->OutSize = currentUnpTotal; currentPackSize = 0; currentUnpSize = 0; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - UInt32 index = allFilesMode ? i : indices[i]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + const UInt32 index = allFilesMode ? i : indices[i]; + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) COutStreamWithCRC *outCrcStreamSpec = new COutStreamWithCRC; @@ -1359,7 +1345,7 @@ { lps->InSize = currentPackTotal + packPos; lps->OutSize = currentUnpTotal + unpPos; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) const CBlock &block = item.Blocks[j]; if (!block.ThereAreDataInBlock()) @@ -1372,7 +1358,7 @@ break; } - RINOK(_inStream->Seek(_startPos + _dataStartOffset + item.StartPos + block.PackPos, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_inStream, _startPos + _dataStartOffset + item.StartPos + block.PackPos)) streamSpec->Init(block.PackSize); bool realMethod = true; outStreamSpec->Init(block.UnpSize); @@ -1453,7 +1439,7 @@ { UInt64 rem = outStreamSpec->GetRem(); UInt32 size = (UInt32)MyMin(rem, (UInt64)kZeroBufSize); - RINOK(WriteStream(outStream, zeroBuf, size)); + RINOK(WriteStream(outStream, zeroBuf, size)) } } } @@ -1466,7 +1452,7 @@ } } outStream.Release(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } return S_OK; @@ -1480,10 +1466,13 @@ CByteBuffer Buf; }; -class CInStream: - public IInStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_COM_1( + CInStream + , IInStream +) + Z7_IFACE_COM7_IMP(ISequentialInStream) + UInt64 _virtPos; int _latestChunk; int _latestBlock; @@ -1530,11 +1519,6 @@ outStream = outStreamSpec; return S_OK; } - - MY_UNKNOWN_IMP1(IInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); }; @@ -1553,7 +1537,7 @@ } } -STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { COM_TRY_BEGIN @@ -1571,7 +1555,7 @@ if (_latestBlock >= 0) { - const CBlock &block = File->Blocks[_latestBlock]; + const CBlock &block = File->Blocks[(unsigned)_latestBlock]; if (_virtPos < block.UnpPos || (_virtPos - block.UnpPos) >= block.UnpSize) _latestBlock = -1; } @@ -1590,7 +1574,7 @@ break; if (i != _chunks.Size()) - _latestChunk = i; + _latestChunk = (int)i; else { const unsigned kNumChunksMax = 128; @@ -1620,7 +1604,7 @@ outStreamSpec->Init(chunk.Buf, (size_t)block.UnpSize); - RINOK(Stream->Seek(_startPos + File->StartPos + block.PackPos, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(Stream, _startPos + File->StartPos + block.PackPos)) limitedStreamSpec->Init(block.PackSize); HRESULT res = S_OK; @@ -1681,17 +1665,17 @@ return res; if (block.Type != METHOD_COPY && outStreamSpec->GetPos() != block.UnpSize) return E_FAIL; - chunk.BlockIndex = blockIndex; - _latestChunk = chunkIndex; + chunk.BlockIndex = (int)blockIndex; + _latestChunk = (int)chunkIndex; } _chunks[_latestChunk].AccessMark = _accessMark++; } - _latestBlock = blockIndex; + _latestBlock = (int)blockIndex; } - const CBlock &block = File->Blocks[_latestBlock]; + const CBlock &block = File->Blocks[(unsigned)_latestBlock]; const UInt64 offset = _virtPos - block.UnpPos; const UInt64 rem = block.UnpSize - offset; if (size > rem) @@ -1701,7 +1685,7 @@ if (block.Type == METHOD_COPY) { - RINOK(Stream->Seek(_startPos + File->StartPos + block.PackPos + offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(Stream, _startPos + File->StartPos + block.PackPos + offset)) res = Stream->Read(data, size, &size); } else if (block.IsZeroMethod()) @@ -1717,7 +1701,7 @@ COM_TRY_END } -STDMETHODIMP CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { @@ -1728,13 +1712,13 @@ } if (offset < 0) return HRESULT_WIN32_ERROR_NEGATIVE_SEEK; - _virtPos = offset; + _virtPos = (UInt64)offset; if (newPosition) - *newPosition = offset; + *newPosition = (UInt64)offset; return S_OK; } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN @@ -1769,7 +1753,7 @@ spec->Stream = _inStream; spec->Size = spec->File->Size; - RINOK(spec->InitAndSeek(_startPos + _dataStartOffset)); + RINOK(spec->InitAndSeek(_startPos + _dataStartOffset)) *stream = specStream.Detach(); return S_OK; @@ -1777,7 +1761,7 @@ } REGISTER_ARC_I( - "Dmg", "dmg", 0, 0xE4, + "Dmg", "dmg", NULL, 0xE4, k_Signature, 0, NArcInfoFlags::kBackwardOpen | diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/ElfHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/ElfHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/ElfHandler.cpp 2021-01-26 09:45:18.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/ElfHandler.cpp 2023-03-27 17:00:00.000000000 +0000 @@ -156,18 +156,22 @@ #define PT_PHDR 6 -static const char * const g_SegnmentTypes[] = +static const CUInt32PCharPair g_SegnmentTypes[] = { - "Unused" - , "Loadable segment" - , "Dynamic linking tables" - , "Program interpreter path name" - , "Note section" - , "SHLIB" - , "Program header table" - , "TLS" + { 0, "Unused" }, + { 1, "Loadable segment" }, + { 2, "Dynamic linking tables" }, + { 3, "Program interpreter path name" }, + { 4, "Note section" }, + { 5, "SHLIB" }, + { 6, "Program header table" }, + { 7, "TLS" }, + { 0x6474e550, "GNU_EH_FRAME" }, + { 0x6474e551, "GNU_STACK" }, + { 0x6474e552, "GNU_RELRO" } }; + static const char * const g_SegmentFlags[] = { "Execute" @@ -271,6 +275,7 @@ { 16, "PREINIT_ARRAY" }, { 17, "GROUP" }, { 18, "SYMTAB_SHNDX" }, + { 0x6ffffff5, "GNU_ATTRIBUTES" }, { 0x6ffffff6, "GNU_HASH" }, { 0x6ffffffd, "GNU_verdef" }, @@ -654,11 +659,9 @@ -class CHandler: - public IInArchive, - public IArchiveAllowTail, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_1( + IArchiveAllowTail +) CRecordVector _segments; CRecordVector _sections; CByteBuffer _namesData; @@ -671,10 +674,6 @@ void GetSectionName(UInt32 index, NCOM::CPropVariant &prop, bool showNULL) const; HRESULT Open2(IInStream *stream); public: - MY_UNKNOWN_IMP2(IInArchive, IArchiveAllowTail) - INTERFACE_IInArchive(;) - STDMETHOD(AllowTail)(Int32 allowTail); - CHandler(): _allowTail(false) {} }; @@ -683,7 +682,7 @@ if (index >= _sections.Size()) return; const CSection §ion = _sections[index]; - UInt32 offset = section.Name; + const UInt32 offset = section.Name; if (index == SHN_UNDEF /* && section.Type == SHT_NULL && offset == 0 */) { if (showNULL) @@ -732,7 +731,7 @@ IMP_IInArchive_Props_WITH_NAME IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -747,27 +746,27 @@ case kpidCpu: { AString s; - if (_header.Machine < ARRAY_SIZE(g_Machines)) + if (_header.Machine < Z7_ARRAY_SIZE(g_Machines)) { const char *name = g_Machines[_header.Machine]; if (name) s = name; } if (s.IsEmpty()) - s = TypePairToString(g_MachinePairs, ARRAY_SIZE(g_MachinePairs), _header.Machine); + s = TypePairToString(g_MachinePairs, Z7_ARRAY_SIZE(g_MachinePairs), _header.Machine); UInt32 flags = _header.Flags; if (flags != 0) { s.Add_Space(); if (_header.Machine == k_Machine_ARM) { - s += FlagsToString(g_ARM_Flags, ARRAY_SIZE(g_ARM_Flags), flags & (((UInt32)1 << 24) - 1)); + s += FlagsToString(g_ARM_Flags, Z7_ARRAY_SIZE(g_ARM_Flags), flags & (((UInt32)1 << 24) - 1)); s += " ABI:"; s.Add_UInt32(flags >> 24); } else if (_header.Machine == k_Machine_MIPS) { - UInt32 ver = flags >> 28; + const UInt32 ver = flags >> 28; s += "v"; s.Add_UInt32(ver); flags &= (((UInt32)1 << 28) - 1); @@ -781,7 +780,7 @@ flags &= ~((UInt32)7 << 12); s.Add_Space(); - s += FlagsToString(g_MIPS_Flags, ARRAY_SIZE(g_MIPS_Flags), flags); + s += FlagsToString(g_MIPS_Flags, Z7_ARRAY_SIZE(g_MIPS_Flags), flags); } else { @@ -822,7 +821,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -843,7 +842,7 @@ case kpidSize: case kpidPackSize: prop = (UInt64)item.Size; break; case kpidVirtualSize: prop = (UInt64)item.VSize; break; - case kpidType: TYPE_TO_PROP(g_SegnmentTypes, item.Type, prop); break; + case kpidType: PAIR_TO_PROP(g_SegnmentTypes, item.Type, prop); break; case kpidCharacts: FLAGS_TO_PROP(g_SegmentFlags, item.Flags, prop); break; } @@ -875,7 +874,7 @@ { const UInt32 kStartSize = kHeaderSize64; Byte h[kStartSize]; - RINOK(ReadStream_FALSE(stream, h, kStartSize)); + RINOK(ReadStream_FALSE(stream, h, kStartSize)) if (h[0] != 0x7F || h[1] != 'E' || h[2] != 'L' || h[3] != 'F') return S_FALSE; if (!_header.Parse(h)) @@ -894,14 +893,14 @@ if (_header.NumSegments != 0) { if (_header.ProgOffset > (UInt64)1 << 60) return S_FALSE; - RINOK(stream->Seek(_header.ProgOffset, STREAM_SEEK_SET, NULL)); - size_t size = (size_t)_header.SegmentEntrySize * _header.NumSegments; + RINOK(InStream_SeekSet(stream, _header.ProgOffset)) + const size_t size = (size_t)_header.SegmentEntrySize * _header.NumSegments; CByteArr buf(size); - RINOK(ReadStream_FALSE(stream, buf, size)); + RINOK(ReadStream_FALSE(stream, buf, size)) - UInt64 total = _header.ProgOffset + size; + const UInt64 total = _header.ProgOffset + size; if (_totalSize < total) _totalSize = total; @@ -923,12 +922,12 @@ if (_header.NumSections != 0) { if (_header.SectOffset > (UInt64)1 << 60) return S_FALSE; - RINOK(stream->Seek(_header.SectOffset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, _header.SectOffset)) size_t size = (size_t)_header.SectionEntrySize * _header.NumSections; CByteArr buf(size); - RINOK(ReadStream_FALSE(stream, buf, size)); + RINOK(ReadStream_FALSE(stream, buf, size)) UInt64 total = _header.SectOffset + size; if (_totalSize < total) @@ -957,14 +956,14 @@ if (_header.NamesSectIndex < _sections.Size()) { const CSection § = _sections[_header.NamesSectIndex]; - UInt64 size = sect.GetSize(); + const UInt64 size = sect.GetSize(); if (size != 0 && size < ((UInt64)1 << 31) && (Int64)sect.Offset >= 0) { _namesData.Alloc((size_t)size); - RINOK(stream->Seek(sect.Offset, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(stream, _namesData, (size_t)size)); + RINOK(InStream_SeekSet(stream, sect.Offset)) + RINOK(ReadStream_FALSE(stream, _namesData, (size_t)size)) } } @@ -979,7 +978,7 @@ if (!_allowTail) { UInt64 fileSize; - RINOK(stream->Seek(0, STREAM_SEEK_END, &fileSize)); + RINOK(InStream_GetSize_SeekToEnd(stream, fileSize)) if (fileSize > _totalSize) return S_FALSE; } @@ -987,19 +986,19 @@ return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *inStream, +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openArchiveCallback */) + IArchiveOpenCallback * /* openArchiveCallback */)) { COM_TRY_BEGIN Close(); - RINOK(Open2(inStream)); + RINOK(Open2(inStream)) _inStream = inStream; return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _totalSize = 0; _headersError = false; @@ -1011,17 +1010,17 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _segments.Size() + _sections.Size(); return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _segments.Size() + _sections.Size(); if (numItems == 0) @@ -1030,7 +1029,7 @@ UInt32 i; for (i = 0; i < numItems; i++) { - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; totalSize += (index < _segments.Size()) ? _segments[index].Size : _sections[index - _segments.Size()].GetSize(); @@ -1054,11 +1053,11 @@ for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize) { lps->InSize = lps->OutSize = currentTotalSize; - RINOK(lps->SetCur()); - Int32 askMode = testMode ? + RINOK(lps->SetCur()) + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; UInt64 offset; if (index < _segments.Size()) { @@ -1074,24 +1073,24 @@ } CMyComPtr outStream; - RINOK(extractCallback->GetStream(index, &outStream, askMode)); + RINOK(extractCallback->GetStream(index, &outStream, askMode)) if (!testMode && !outStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(_inStream->Seek(offset, STREAM_SEEK_SET, NULL)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(InStream_SeekSet(_inStream, offset)) streamSpec->Init(currentItemSize); - RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)) outStream.Release(); RINOK(extractCallback->SetOperationResult(copyCoderSpec->TotalSize == currentItemSize ? NExtract::NOperationResult::kOK: - NExtract::NOperationResult::kDataError)); + NExtract::NOperationResult::kDataError)) } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::AllowTail(Int32 allowTail) +Z7_COM7F_IMF(CHandler::AllowTail(Int32 allowTail)) { _allowTail = IntToBool(allowTail); return S_OK; @@ -1100,7 +1099,7 @@ static const Byte k_Signature[] = { 0x7F, 'E', 'L', 'F' }; REGISTER_ARC_I( - "ELF", "elf", 0, 0xDE, + "ELF", "elf", NULL, 0xDE, k_Signature, 0, NArcInfoFlags::kPreArc, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/ExtHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/ExtHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/ExtHandler.cpp 2022-04-30 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/ExtHandler.cpp 2023-03-27 17:00:00.000000000 +0000 @@ -353,7 +353,7 @@ { for (unsigned i = 0; i < 32; i++) if (((UInt32)1 << i) == num) - return i; + return (int)i; return -1; } @@ -371,8 +371,8 @@ if (GetUi16(p + 0x38) != 0xEF53) return false; - LE_32 (0x18, BlockBits); - LE_32 (0x1C, ClusterBits); + LE_32 (0x18, BlockBits) + LE_32 (0x1C, ClusterBits) if (ClusterBits != 0 && BlockBits != ClusterBits) return false; @@ -381,22 +381,22 @@ return false; BlockBits += 10; - LE_32 (0x00, NumInodes); - LE_32 (0x04, NumBlocks); + LE_32 (0x00, NumInodes) + LE_32 (0x04, NumBlocks) // LE_32 (0x08, NumBlocksSuper); - LE_32 (0x0C, NumFreeBlocks); - LE_32 (0x10, NumFreeInodes); + LE_32 (0x0C, NumFreeBlocks) + LE_32 (0x10, NumFreeInodes) if (NumInodes < 2 || NumInodes <= NumFreeInodes) return false; UInt32 FirstDataBlock; - LE_32 (0x14, FirstDataBlock); + LE_32 (0x14, FirstDataBlock) if (FirstDataBlock != (unsigned)(BlockBits == 10 ? 1 : 0)) return false; - LE_32 (0x20, BlocksPerGroup); - LE_32 (0x24, ClustersPerGroup); + LE_32 (0x20, BlocksPerGroup) + LE_32 (0x24, ClustersPerGroup) if (BlocksPerGroup != ClustersPerGroup) return false; @@ -408,13 +408,13 @@ // return false; } - LE_32 (0x28, InodesPerGroup); + LE_32 (0x28, InodesPerGroup) if (InodesPerGroup < 1 || InodesPerGroup > NumInodes) return false; - LE_32 (0x2C, MountTime); - LE_32 (0x30, WriteTime); + LE_32 (0x2C, MountTime) + LE_32 (0x30, WriteTime) // LE_16 (0x34, NumMounts); // LE_16 (0x36, NumMountsMax); @@ -423,10 +423,10 @@ // LE_16 (0x3C, Errors); // LE_16 (0x3E, MinorRevLevel); - LE_32 (0x40, LastCheckTime); + LE_32 (0x40, LastCheckTime) // LE_32 (0x44, CheckInterval); - LE_32 (0x48, CreatorOs); - LE_32 (0x4C, RevLevel); + LE_32 (0x48, CreatorOs) + LE_32 (0x4C, RevLevel) // LE_16 (0x50, DefResUid); // LE_16 (0x52, DefResGid); @@ -436,8 +436,8 @@ if (!IsOldRev()) { - LE_32 (0x54, FirstInode); - LE_16 (0x58, InodeSize); + LE_32 (0x54, FirstInode) + LE_16 (0x58, InodeSize) if (FirstInode < k_INODE_GOOD_OLD_FIRST) return false; if (InodeSize > ((UInt32)1 << BlockBits) @@ -446,10 +446,10 @@ return false; } - LE_16 (0x5A, BlockGroupNr); - LE_32 (0x5C, FeatureCompat); - LE_32 (0x60, FeatureIncompat); - LE_32 (0x64, FeatureRoCompat); + LE_16 (0x5A, BlockGroupNr) + LE_32 (0x5C, FeatureCompat) + LE_32 (0x60, FeatureIncompat) + LE_32 (0x64, FeatureRoCompat) memcpy(Uuid, p + 0x68, sizeof(Uuid)); memcpy(VolName, p + 0x78, sizeof(VolName)); @@ -457,24 +457,24 @@ // LE_32 (0xC8, BitmapAlgo); - LE_32 (0xE0, JournalInode); + LE_32 (0xE0, JournalInode) - LE_16 (0xFE, GdSize); + LE_16 (0xFE, GdSize) - LE_32 (0x108, CTime); + LE_32 (0x108, CTime) if (Is64Bit()) { - HI_32(0x150, NumBlocks); + HI_32(0x150, NumBlocks) // HI_32(0x154, NumBlocksSuper); - HI_32(0x158, NumFreeBlocks); + HI_32(0x158, NumFreeBlocks) } if (NumBlocks >= (UInt64)1 << (63 - BlockBits)) return false; - LE_16(0x15C, MinExtraISize); + LE_16(0x15C, MinExtraISize) // LE_16(0x15E, WantExtraISize); // LE_32(0x160, Flags); // LE_16(0x164, RaidStride); @@ -484,7 +484,7 @@ // LogGroupsPerFlex = p[0x174]; // ChecksumType = p[0x175]; - LE_64 (0x178, WrittenKB); + LE_64 (0x178, WrittenKB) // LE_32(0x194, ErrorCount); // LE_32(0x198, ErrorTime); @@ -525,32 +525,32 @@ void CGroupDescriptor::Parse(const Byte *p, unsigned size) { - LE_32 (0x00, BlockBitmap); - LE_32 (0x04, InodeBitmap); - LE_32 (0x08, InodeTable); - LE_16 (0x0C, NumFreeBlocks); - LE_16 (0x0E, NumFreeInodes); - LE_16 (0x10, DirCount); - LE_16 (0x12, Flags); - LE_32 (0x14, ExcludeBitmap); - LE_16 (0x18, BlockBitmap_Checksum); - LE_16 (0x1A, InodeBitmap_Checksum); - LE_16 (0x1C, UnusedCount); - LE_16 (0x1E, Checksum); + LE_32 (0x00, BlockBitmap) + LE_32 (0x04, InodeBitmap) + LE_32 (0x08, InodeTable) + LE_16 (0x0C, NumFreeBlocks) + LE_16 (0x0E, NumFreeInodes) + LE_16 (0x10, DirCount) + LE_16 (0x12, Flags) + LE_32 (0x14, ExcludeBitmap) + LE_16 (0x18, BlockBitmap_Checksum) + LE_16 (0x1A, InodeBitmap_Checksum) + LE_16 (0x1C, UnusedCount) + LE_16 (0x1E, Checksum) if (size >= 64) { p += 0x20; - HI_32 (0x00, BlockBitmap); - HI_32 (0x04, InodeBitmap); - HI_32 (0x08, InodeTable); - HI_16 (0x0C, NumFreeBlocks); - HI_16 (0x0E, NumFreeInodes); - HI_16 (0x10, DirCount); - HI_16 (0x12, UnusedCount); // instead of Flags - HI_32 (0x14, ExcludeBitmap); - HI_16 (0x18, BlockBitmap_Checksum); - HI_16 (0x1A, InodeBitmap_Checksum); + HI_32 (0x00, BlockBitmap) + HI_32 (0x04, InodeBitmap) + HI_32 (0x08, InodeTable) + HI_16 (0x0C, NumFreeBlocks) + HI_16 (0x0E, NumFreeInodes) + HI_16 (0x10, DirCount) + HI_16 (0x12, UnusedCount) // instead of Flags + HI_32 (0x14, ExcludeBitmap) + HI_16 (0x18, BlockBitmap_Checksum) + HI_16 (0x1A, InodeBitmap_Checksum) // HI_16 (0x1C, Reserved); } } @@ -567,9 +567,9 @@ bool Parse(const Byte *p) { - LE_16 (0x02, NumEntries); - LE_16 (0x04, MaxEntries); - LE_16 (0x06, Depth); + LE_16 (0x02, NumEntries) + LE_16 (0x04, MaxEntries) + LE_16 (0x06, Depth) // LE_32 (0x08, Generation); return Get16(p) == 0xF30A; // magic } @@ -582,8 +582,8 @@ void Parse(const Byte *p) { - LE_32 (0x00, VirtBlock); - LE_32 (0x04, PhyLeaf); + LE_32 (0x00, VirtBlock) + LE_32 (0x04, PhyLeaf) PhyLeaf |= (((UInt64)Get16(p + 8)) << 32); // unused 16-bit field (at offset 0x0A) can be not zero in some cases. Why? } @@ -601,17 +601,17 @@ void Parse(const Byte *p) { - LE_32 (0x00, VirtBlock); - LE_16 (0x04, Len); + LE_32 (0x00, VirtBlock) + LE_16 (0x04, Len) IsInited = true; if (Len > (UInt32)0x8000) { IsInited = false; Len = (UInt16)(Len - (UInt32)0x8000); } - LE_32 (0x08, PhyStart); + LE_32 (0x08, PhyStart) UInt16 hi; - LE_16 (0x06, hi); + LE_16 (0x06, hi) PhyStart |= ((UInt64)hi << 32); } }; @@ -627,7 +627,7 @@ struct CNode { Int32 ParentNode; // in _refs[], -1 if not dir - int ItemIndex; // in _items[] + int ItemIndex; // in _items[] , (set as >=0 only for if (IsDir()) int SymLinkIndex; // in _symLinks[] int DirIndex; // in _dirs[] @@ -655,7 +655,7 @@ ParentNode(-1), ItemIndex(-1), SymLinkIndex(-1), - DirIndex(0), + DirIndex(-1), NumLinksCalced(0) {} @@ -679,18 +679,18 @@ ChangeTime.Extra = 0; // DTime.Extra = 0; - LE_16 (0x00, Mode); - LE_16 (0x02, Uid); - LE_32 (0x04, FileSize); - LE_32 (0x08, ATime.Val); - LE_32 (0x0C, ChangeTime.Val); - LE_32 (0x10, MTime.Val); + LE_16 (0x00, Mode) + LE_16 (0x02, Uid) + LE_32 (0x04, FileSize) + LE_32 (0x08, ATime.Val) + LE_32 (0x0C, ChangeTime.Val) + LE_32 (0x10, MTime.Val) // LE_32 (0x14, DTime.Val); - LE_16 (0x18, Gid); - LE_16 (0x1A, NumLinks); + LE_16 (0x18, Gid) + LE_16 (0x1A, NumLinks) - LE_32 (0x1C, NumBlocks); - LE_32 (0x20, Flags); + LE_32 (0x1C, NumBlocks) + LE_32 (0x20, Flags) // LE_32 (0x24, Union osd1); memcpy(Block, p + 0x28, kNodeBlockFieldSize); @@ -700,7 +700,7 @@ { UInt32 highSize; - LE_32 (0x6C, highSize); // In ext2/3 this field was named i_dir_acl + LE_32 (0x6C, highSize) // In ext2/3 this field was named i_dir_acl if (IsRegular()) // do we need that check ? FileSize |= ((UInt64)highSize << 32); @@ -718,11 +718,11 @@ // ext4: UInt32 numBlocksHigh; - LE_16 (0x74, numBlocksHigh); + LE_16 (0x74, numBlocksHigh) NumBlocks |= (UInt64)numBlocksHigh << 32; - HI_16 (0x74 + 4, Uid); - HI_16 (0x74 + 6, Gid); + HI_16 (0x74 + 4, Uid) + HI_16 (0x74 + 6, Gid) /* UInt32 checksum; LE_16 (0x74 + 8, checksum); @@ -737,19 +737,19 @@ // InodeSize is power of 2, so the following check is not required: // if (_h.InodeSize < 128 + 2) return false; UInt16 extra_isize; - LE_16 (0x80, extra_isize); + LE_16 (0x80, extra_isize) if (128 + extra_isize > _h.InodeSize) return false; if (extra_isize >= 0x1C) { // UInt16 checksumUpper; // LE_16 (0x82, checksumUpper); - LE_32 (0x84, ChangeTime.Extra); - LE_32 (0x88, MTime.Extra); - LE_32 (0x8C, ATime.Extra); - LE_32 (0x90, CTime.Val); - LE_32 (0x94, CTime.Extra); - // LE_32 (0x98, VersionHi); + LE_32 (0x84, ChangeTime.Extra) + LE_32 (0x88, MTime.Extra) + LE_32 (0x8C, ATime.Extra) + LE_32 (0x90, CTime.Val) + LE_32 (0x94, CTime.Extra) + // LE_32 (0x98, VersionHi) } } @@ -786,7 +786,6 @@ bool IsDir() const { return Type == k_Type_DIR; } // bool IsNotDir() const { return Type != k_Type_DIR && Type != k_Type_UNKNOWN; } - }; @@ -794,14 +793,12 @@ static const unsigned kNumTreeLevelsMax = 6; // must be >= 3 -class CHandler: - public IInArchive, - public IArchiveGetRawProps, - public IInArchiveGetStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_2( + IArchiveGetRawProps, + IInArchiveGetStream +) CObjectVector _items; - CIntVector _refs; + CIntVector _refs; // iNode -> (index in _nodes). if (_refs[iNode] < 0), that node is not filled CRecordVector _nodes; CObjectVector _dirs; // each CUIntVector contains indexes in _items[] only for dir items; AStringVector _symLinks; @@ -871,16 +868,6 @@ void GetPath(unsigned index, AString &s) const; bool GetPackSize(unsigned index, UInt64 &res) const; - -public: - CHandler() {} - ~CHandler() {} - - MY_UNKNOWN_IMP3(IInArchive, IArchiveGetRawProps, IInArchiveGetStream) - - INTERFACE_IInArchive(;) - INTERFACE_IArchiveGetRawProps(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); }; @@ -892,7 +879,7 @@ PRF(printf("\n\n========= node = %5d size = %5d", (unsigned)iNodeDir, (unsigned)size)); CNode &nodeDir = _nodes[_refs[iNodeDir]]; - nodeDir.DirIndex = _dirs.Size(); + nodeDir.DirIndex = (int)_dirs.Size(); CUIntVector &dir = _dirs.AddNew(); int parentNode = -1; @@ -905,11 +892,11 @@ if (size < 8) return S_FALSE; UInt32 iNode; - LE_32 (0x00, iNode); + LE_32 (0x00, iNode) unsigned recLen; - LE_16 (0x04, recLen); - unsigned nameLen = p[6]; - Byte type = p[7]; + LE_16 (0x04, recLen) + const unsigned nameLen = p[6]; + const Byte type = p[7]; if (recLen > size) return S_FALSE; @@ -926,7 +913,7 @@ else if (type != 0) return S_FALSE; - item.ParentNode = iNodeDir; + item.ParentNode = (int)iNodeDir; item.Node = iNode; item.Name.SetFrom_CalcLen((const char *)(p + 8), nameLen); @@ -958,14 +945,14 @@ continue; } - int nodeIndex = _refs[iNode]; + const int nodeIndex = _refs[iNode]; if (nodeIndex < 0) return S_FALSE; CNode &node = _nodes[nodeIndex]; if (_h.IsThereFileType() && type != 0) { - if (type >= ARRAY_SIZE(k_TypeToMode)) + if (type >= Z7_ARRAY_SIZE(k_TypeToMode)) return S_FALSE; if (k_TypeToMode[type] != (node.Mode & MY_LIN_S_IFMT)) return S_FALSE; @@ -996,10 +983,10 @@ if (iNode == iNodeDir && iNode != k_INODE_ROOT) return S_FALSE; - parentNode = iNode; + parentNode = (int)iNode; if (nodeDir.ParentNode < 0) - nodeDir.ParentNode = iNode; + nodeDir.ParentNode = (int)iNode; else if ((unsigned)nodeDir.ParentNode != iNode) return S_FALSE; @@ -1016,12 +1003,12 @@ if (node.IsDir()) { if (node.ParentNode < 0) - node.ParentNode = iNodeDir; + node.ParentNode = (int)iNodeDir; else if ((unsigned)node.ParentNode != iNodeDir) return S_FALSE; const unsigned itemIndex = _items.Size(); dir.Add(itemIndex); - node.ItemIndex = itemIndex; + node.ItemIndex = (int)itemIndex; } _items.Add(item); @@ -1034,6 +1021,13 @@ } +static int CompareItemsNames(const unsigned *p1, const unsigned *p2, void *param) +{ + const CObjectVector &items = *(const CObjectVector *)param; + return strcmp(items[*p1].Name, items[*p2].Name); +} + + int CHandler::FindTargetItem_for_SymLink(unsigned iNode, const AString &path) const { unsigned pos = 0; @@ -1054,7 +1048,7 @@ while (pos != path.Len()) { const CNode &node = _nodes[_refs[iNode]]; - int slash = path.Find('/', pos); + const int slash = path.Find('/', pos); if (slash < 0) { @@ -1063,8 +1057,8 @@ } else { - s.SetFrom(path.Ptr(pos), slash - pos); - pos = slash + 1; + s.SetFrom(path.Ptr(pos), (unsigned)slash - pos); + pos = (unsigned)slash + 1; } if (s[0] == '.') @@ -1077,7 +1071,7 @@ return -1; if (iNode == k_INODE_ROOT) return -1; - iNode = node.ParentNode; + iNode = (unsigned)node.ParentNode; continue; } } @@ -1087,6 +1081,7 @@ const CUIntVector &dir = _dirs[node.DirIndex]; + /* for (unsigned i = 0;; i++) { if (i >= dir.Size()) @@ -1098,6 +1093,26 @@ break; } } + */ + + unsigned left = 0, right = dir.Size(); + for (;;) + { + if (left == right) + return -1; + const unsigned mid = (unsigned)(((size_t)left + (size_t)right) / 2); + const CItem &item = _items[dir[mid]]; + const int comp = strcmp(s, item.Name); + if (comp == 0) + { + iNode = item.Node; + break; + } + if (comp < 0) + right = mid; + else + left = mid + 1; + } } return _nodes[_refs[iNode]].ItemIndex; @@ -1110,7 +1125,7 @@ return S_FALSE; if (((size + ((size_t)1 << _h.BlockBits) - 1) >> _h.BlockBits) > _h.NumBlocks - block) return S_FALSE; - RINOK(inStream->Seek((UInt64)block << _h.BlockBits, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(inStream, (UInt64)block << _h.BlockBits)) _totalRead += size; return ReadStream_FALSE(inStream, data, size); } @@ -1123,7 +1138,7 @@ { { Byte buf[kHeaderSize]; - RINOK(ReadStream_FALSE(inStream, buf, kHeaderSize)); + RINOK(ReadStream_FALSE(inStream, buf, kHeaderSize)) if (!_h.Parse(buf + kHeaderDataOffset)) return S_FALSE; if (_h.BlockGroupNr != 0) @@ -1135,7 +1150,7 @@ unsigned numGroups; { - UInt64 numGroups64 = _h.GetNumGroups(); + const UInt64 numGroups64 = _h.GetNumGroups(); if (numGroups64 > (UInt32)1 << 31) return S_FALSE; numGroups = (unsigned)numGroups64; @@ -1154,11 +1169,11 @@ if (_openCallback) { - RINOK(_openCallback->SetTotal(NULL, &_phySize)); + RINOK(_openCallback->SetTotal(NULL, &_phySize)) } UInt64 fileSize = 0; - RINOK(inStream->Seek(0, STREAM_SEEK_END, &fileSize)); + RINOK(InStream_GetSize_SeekToEnd(inStream, fileSize)) CRecordVector groups; @@ -1166,18 +1181,18 @@ // ---------- Read groups ---------- CByteBuffer gdBuf; - size_t gdBufSize = (size_t)numGroups << gdBits; + const size_t gdBufSize = (size_t)numGroups << gdBits; if ((gdBufSize >> gdBits) != numGroups) return S_FALSE; gdBuf.Alloc(gdBufSize); - RINOK(SeekAndRead(inStream, (_h.BlockBits <= 10 ? 2 : 1), gdBuf, gdBufSize)); + RINOK(SeekAndRead(inStream, (_h.BlockBits <= 10 ? 2 : 1), gdBuf, gdBufSize)) for (unsigned i = 0; i < numGroups; i++) { CGroupDescriptor gd; const Byte *p = gdBuf + ((size_t)i << gdBits); - unsigned gd_Size = (unsigned)1 << gdBits; + const unsigned gd_Size = (unsigned)1 << gdBits; gd.Parse(p, gd_Size); if (_h.UseMetadataChecksum()) @@ -1188,7 +1203,7 @@ { UInt32 crc = Crc16Calc(_h.Uuid, sizeof(_h.Uuid)); Byte i_le[4]; - SetUi32(i_le, i); + SetUi32(i_le, i) crc = Crc16Update(crc, i_le, 4); crc = Crc16Update(crc, p, 32 - 2); if (gd_Size != 32) @@ -1250,8 +1265,8 @@ PRF(printf("\n\ng%6d block = %6x\n", gi, (unsigned)gd.InodeTable)); - RINOK(SeekAndRead(inStream, gd.InodeBitmap, nodesMap, blockSize)); - RINOK(SeekAndRead(inStream, gd.InodeTable, nodesData, nodesDataSize)); + RINOK(SeekAndRead(inStream, gd.InodeBitmap, nodesMap, blockSize)) + RINOK(SeekAndRead(inStream, gd.InodeTable, nodesData, nodesDataSize)) unsigned numEmpty_in_Map = 0; @@ -1300,7 +1315,7 @@ _refs.Add(-1); } - _refs.Add(_nodes.Add(node)); + _refs.Add((int)_nodes.Add(node)); } @@ -1336,7 +1351,7 @@ FOR_VECTOR (i, _refs) { - int nodeIndex = _refs[i]; + const int nodeIndex = _refs[i]; { if (nodeIndex < 0) continue; @@ -1344,7 +1359,7 @@ if (!node.IsDir()) continue; } - RINOK(ExtractNode(nodeIndex, dataBuf)); + RINOK(ExtractNode((unsigned)nodeIndex, dataBuf)) if (dataBuf.Size() == 0) { // _headersError = true; @@ -1352,12 +1367,12 @@ } else { - RINOK(ParseDir(dataBuf, dataBuf.Size(), i)); + RINOK(ParseDir(dataBuf, dataBuf.Size(), i)) } - RINOK(CheckProgress()); + RINOK(CheckProgress()) } - int ref = _refs[k_INODE_ROOT]; + const int ref = _refs[k_INODE_ROOT]; if (ref < 0 || _nodes[ref].ParentNode != k_INODE_ROOT) return S_FALSE; } @@ -1423,7 +1438,7 @@ for (;;) { - int nodeIndex = _refs[c]; + const int nodeIndex = _refs[c]; if (nodeIndex < 0) return S_FALSE; CNode &node = _nodes[nodeIndex]; @@ -1435,12 +1450,12 @@ break; } - UsedByNode[c] = i; + UsedByNode[c] = (int)i; if (node.ParentNode < 0 || node.ParentNode == k_INODE_ROOT) break; if ((unsigned)node.ParentNode == i) return S_FALSE; - c = node.ParentNode; + c = (unsigned)node.ParentNode; } } } @@ -1454,7 +1469,7 @@ unsigned i; for (i = 0; i < _refs.Size(); i++) { - int nodeIndex = _refs[i]; + const int nodeIndex = _refs[i]; if (nodeIndex < 0) continue; CNode &node = _nodes[nodeIndex]; @@ -1462,32 +1477,37 @@ continue; if (node.FileSize > ((UInt32)1 << 14)) continue; - if (ExtractNode(nodeIndex, data) == S_OK && data.Size() != 0) + if (ExtractNode((unsigned)nodeIndex, data) == S_OK && data.Size() != 0) { s.SetFrom_CalcLen((const char *)(const Byte *)data, (unsigned)data.Size()); if (s.Len() == data.Size()) - node.SymLinkIndex = _symLinks.Add(s); - RINOK(CheckProgress()); + node.SymLinkIndex = (int)_symLinks.Add(s); + RINOK(CheckProgress()) } } + for (i = 0; i < _dirs.Size(); i++) + { + _dirs[i].Sort(CompareItemsNames, (void *)&_items); + } + unsigned prev = 0; unsigned complex = 0; for (i = 0; i < _items.Size(); i++) { CItem &item = _items[i]; - int sym = _nodes[_refs[item.Node]].SymLinkIndex; + const int sym = _nodes[_refs[item.Node]].SymLinkIndex; if (sym >= 0 && item.ParentNode >= 0) { - item.SymLinkItemIndex = FindTargetItem_for_SymLink(item.ParentNode, _symLinks[sym]); + item.SymLinkItemIndex = FindTargetItem_for_SymLink((unsigned)item.ParentNode, _symLinks[sym]); if (_openCallback) { complex++; if (complex - prev >= (1 << 10)) { - RINOK(CheckProgress2()); prev = complex; + RINOK(CheckProgress2()) } } } @@ -1502,7 +1522,7 @@ FOR_VECTOR (i, _refs) { - int nodeIndex = _refs[i]; + const int nodeIndex = _refs[i]; if (nodeIndex < 0) continue; const CNode &node = _nodes[nodeIndex]; @@ -1523,7 +1543,7 @@ if (i < _h.FirstInode) { - if (item.Node < ARRAY_SIZE(k_SysInode_Names)) + if (item.Node < Z7_ARRAY_SIZE(k_SysInode_Names)) item.Name = k_SysInode_Names[item.Node]; useSys = true; } @@ -1538,16 +1558,16 @@ } if (useSys) - _auxSysIndex = _auxItems.Add((AString)"[SYS]"); + _auxSysIndex = (int)_auxItems.Add((AString)"[SYS]"); if (useUnknown) - _auxUnknownIndex = _auxItems.Add((AString)"[UNKNOWN]"); + _auxUnknownIndex = (int)_auxItems.Add((AString)"[UNKNOWN]"); } return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback)) { COM_TRY_BEGIN { @@ -1590,7 +1610,7 @@ } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _totalRead = 0; _totalReadPrev = 0; @@ -1652,7 +1672,7 @@ const CNode &node = _nodes[_refs[item.ParentNode]]; if (node.ItemIndex < 0) return; - index = node.ItemIndex; + index = (unsigned)node.ItemIndex; if (s.Len() > ((UInt32)1 << 16)) { @@ -1707,7 +1727,7 @@ } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _items.Size() + _auxItems.Size(); return S_OK; @@ -1797,7 +1817,7 @@ PropVariant_SetFrom_UnixTime(prop, val); } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN @@ -1869,7 +1889,7 @@ case kpidErrorFlags: { UInt32 v = 0; - if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;; + if (!_isArc) v |= kpv_ErrorFlags_IsNotArc; if (_linksError) v |= kpv_ErrorFlags_HeadersError; if (_headersError) v |= kpv_ErrorFlags_HeadersError; if (!_stream && v == 0 && _isArc) @@ -1903,22 +1923,22 @@ }; */ -STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) +Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps)) { - // *numProps = ARRAY_SIZE(kRawProps); + // *numProps = Z7_ARRAY_SIZE(kRawProps); *numProps = 0; return S_OK; } -STDMETHODIMP CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID) +Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID)) { // *propID = kRawProps[index]; *propID = 0; - *name = 0; + *name = NULL; return S_OK; } -STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType) +Z7_COM7F_IMF(CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType)) { *parentType = NParentType::kDir; *parent = (UInt32)(Int32)-1; @@ -1930,22 +1950,22 @@ if (item.ParentNode < 0) { - int aux = GetParentAux(item); + const int aux = GetParentAux(item); if (aux >= 0) - *parent = _items.Size() + aux; + *parent = _items.Size() + (unsigned)aux; } else { - int itemIndex = _nodes[_refs[item.ParentNode]].ItemIndex; + const int itemIndex = _nodes[_refs[item.ParentNode]].ItemIndex; if (itemIndex >= 0) - *parent = itemIndex; + *parent = (unsigned)itemIndex; } return S_OK; } -STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) +Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType)) { *data = NULL; *dataSize = 0; @@ -2017,7 +2037,7 @@ } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -2094,7 +2114,7 @@ case kpidPosixAttrib: { /* - if (node.Type != 0 && node.Type < ARRAY_SIZE(k_TypeToMode)) + if (node.Type != 0 && node.Type < Z7_ARRAY_SIZE(k_TypeToMode)) prop = (UInt32)(node.Mode & 0xFFF) | k_TypeToMode[node.Type]; */ prop = (UInt32)(node.Mode); @@ -2137,10 +2157,8 @@ } -class CClusterInStream2: - public IInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_IInStream(CClusterInStream2 +) UInt64 _virtPos; UInt64 _physPos; UInt32 _curRem; @@ -2150,7 +2168,7 @@ CMyComPtr Stream; CRecordVector Vector; - HRESULT SeekToPhys() { return Stream->Seek(_physPos, STREAM_SEEK_SET, NULL); } + HRESULT SeekToPhys() { return InStream_SeekSet(Stream, _physPos); } HRESULT InitAndSeek() { @@ -2164,15 +2182,10 @@ } return S_OK; } - - MY_UNKNOWN_IMP2(ISequentialInStream, IInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); }; -STDMETHODIMP CClusterInStream2::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CClusterInStream2::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -2209,7 +2222,7 @@ if (newPos != _physPos) { _physPos = newPos; - RINOK(SeekToPhys()); + RINOK(SeekToPhys()) } _curRem = blockSize - offsetInBlock; @@ -2229,7 +2242,7 @@ return res; } -STDMETHODIMP CClusterInStream2::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CClusterInStream2::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { @@ -2242,17 +2255,16 @@ return HRESULT_WIN32_ERROR_NEGATIVE_SEEK; if (_virtPos != (UInt64)offset) _curRem = 0; - _virtPos = offset; + _virtPos = (UInt64)offset; if (newPosition) - *newPosition = offset; + *newPosition = (UInt64)offset; return S_OK; } -class CExtInStream: - public IInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_IInStream( + CExtInStream +) UInt64 _virtPos; UInt64 _phyPos; public: @@ -2261,21 +2273,15 @@ CMyComPtr Stream; CRecordVector Extents; - CExtInStream() {} - HRESULT StartSeek() { _virtPos = 0; _phyPos = 0; - return Stream->Seek(_phyPos, STREAM_SEEK_SET, NULL); + return InStream_SeekSet(Stream, _phyPos); } - - MY_UNKNOWN_IMP2(ISequentialInStream, IInStream) - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); }; -STDMETHODIMP CExtInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CExtInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -2328,18 +2334,18 @@ return S_OK; } - UInt64 phyBlock = extent.PhyStart + bo; - UInt64 phy = (phyBlock << BlockBits) + offset; + const UInt64 phyBlock = extent.PhyStart + bo; + const UInt64 phy = (phyBlock << BlockBits) + offset; if (phy != _phyPos) { - RINOK(Stream->Seek(phy, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(Stream, phy)) _phyPos = phy; } UInt32 realProcessSize = 0; - HRESULT res = Stream->Read(data, size, &realProcessSize); + const HRESULT res = Stream->Read(data, size, &realProcessSize); _phyPos += realProcessSize; _virtPos += realProcessSize; @@ -2350,7 +2356,7 @@ } -STDMETHODIMP CExtInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CExtInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { @@ -2361,9 +2367,9 @@ } if (offset < 0) return HRESULT_WIN32_ERROR_NEGATIVE_SEEK; - _virtPos = offset; + _virtPos = (UInt64)offset; if (newPosition) - *newPosition = offset; + *newPosition = (UInt64)offset; return S_OK; } @@ -2377,7 +2383,7 @@ PRF2(printf("\n level = %d, block = %7d", level, (unsigned)block)); - RINOK(SeekAndRead(_stream, block, tempBuf, blockSize)); + RINOK(SeekAndRead(_stream, block, tempBuf, blockSize)) const Byte *p = tempBuf; size_t num = (size_t)1 << (_h.BlockBits - 2); @@ -2408,7 +2414,7 @@ return S_FALSE; } - RINOK(FillFileBlocks2(val, level - 1, numBlocks, blocks)); + RINOK(FillFileBlocks2(val, level - 1, numBlocks, blocks)) continue; } @@ -2464,7 +2470,7 @@ return S_FALSE; } - RINOK(FillFileBlocks2(val, level, numBlocks, blocks)); + RINOK(FillFileBlocks2(val, level, numBlocks, blocks)) } return S_OK; @@ -2560,8 +2566,8 @@ if (!UpdateExtents(extents, e.VirtBlock)) return S_FALSE; - RINOK(SeekAndRead(_stream, e.PhyLeaf, tempBuf, blockSize)); - RINOK(FillExtents(tempBuf, blockSize, extents, eth.Depth)); + RINOK(SeekAndRead(_stream, e.PhyLeaf, tempBuf, blockSize)) + RINOK(FillExtents(tempBuf, blockSize, extents, eth.Depth)) } return S_OK; @@ -2610,7 +2616,7 @@ streamSpec->Size = node.FileSize; streamSpec->Stream = _stream; - RINOK(FillExtents(node.Block, kNodeBlockFieldSize, streamSpec->Extents, -1)); + RINOK(FillExtents(node.Block, kNodeBlockFieldSize, streamSpec->Extents, -1)) UInt32 end = 0; if (!streamSpec->Extents.IsEmpty()) @@ -2621,7 +2627,7 @@ // return S_FALSE; } - RINOK(streamSpec->StartSeek()); + RINOK(streamSpec->StartSeek()) } else { @@ -2648,7 +2654,7 @@ } const unsigned specBits = (node.IsFlags_HUGE() ? 0 : _h.BlockBits - 9); - const UInt32 specMask = ((UInt32)1 << specBits) - 1;; + const UInt32 specMask = ((UInt32)1 << specBits) - 1; if ((node.NumBlocks & specMask) != 0) return S_FALSE; const UInt64 numBlocks64_from_header = node.NumBlocks >> specBits; @@ -2670,7 +2676,7 @@ streamSpec->Size = node.FileSize; streamSpec->Stream = _stream; - RINOK(FillFileBlocks(node.Block, numBlocks, streamSpec->Vector)); + RINOK(FillFileBlocks(node.Block, numBlocks, streamSpec->Vector)) streamSpec->InitAndSeek(); } @@ -2690,7 +2696,7 @@ if (size != node.FileSize) return S_FALSE; CMyComPtr inSeqStream; - RINOK(GetStream_Node(nodeIndex, &inSeqStream)); + RINOK(GetStream_Node(nodeIndex, &inSeqStream)) if (!inSeqStream) return S_FALSE; data.Alloc(size); @@ -2699,11 +2705,11 @@ } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _items.Size() + _auxItems.Size(); if (numItems == 0) @@ -2714,7 +2720,7 @@ for (i = 0; i < numItems; i++) { - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; if (index >= _items.Size()) continue; const CItem &item = _items[index]; @@ -2739,24 +2745,24 @@ { lps->InSize = totalPackSize; lps->OutSize = totalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) if (i == numItems) break; CMyComPtr outStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; - RINOK(extractCallback->GetStream(index, &outStream, askMode)); + RINOK(extractCallback->GetStream(index, &outStream, askMode)) if (index >= _items.Size()) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } @@ -2765,8 +2771,8 @@ if (node.IsDir()) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } @@ -2778,7 +2784,7 @@ if (!testMode && !outStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) int res = NExtract::NOperationResult::kDataError; { @@ -2792,7 +2798,7 @@ } else { - RINOK(hres); + RINOK(hres) { hres = copyCoder->Code(inSeqStream, outStream, NULL, NULL, progress); if (hres == S_OK) @@ -2806,12 +2812,12 @@ } else if (hres != S_FALSE) { - RINOK(hres); + RINOK(hres) } } } } - RINOK(extractCallback->SetOperationResult(res)); + RINOK(extractCallback->SetOperationResult(res)) } return S_OK; @@ -2819,12 +2825,12 @@ } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { *stream = NULL; if (index >= _items.Size()) return S_FALSE; - return GetStream_Node(_refs[_items[index].Node], stream); + return GetStream_Node((unsigned)_refs[_items[index].Node], stream); } @@ -2854,7 +2860,7 @@ static const Byte k_Signature[] = { 0x53, 0xEF }; REGISTER_ARC_I( - "Ext", "ext ext2 ext3 ext4 img", 0, 0xC7, + "Ext", "ext ext2 ext3 ext4 img", NULL, 0xC7, k_Signature, 0x438, 0, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/FatHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/FatHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/FatHandler.cpp 2022-03-28 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/FatHandler.cpp 2023-03-22 11:00:00.000000000 +0000 @@ -134,15 +134,15 @@ } { { - UInt32 val32 = Get16(p + 11); - int s = GetLog(val32); + const UInt32 val32 = Get16(p + 11); + const int s = GetLog(val32); if (s < 9 || s > 12) return false; SectorSizeLog = (Byte)s; } { - UInt32 val32 = p[13]; - int s = GetLog(val32); + const UInt32 val32 = p[13]; + const int s = GetLog(val32); if (s < 0) return false; SectorsPerClusterLog = (Byte)s; @@ -161,10 +161,10 @@ return false; // we also support images that contain 0 in offset field. - bool isOkOffset = (codeOffset == 0) + const bool isOkOffset = (codeOffset == 0) || (codeOffset == (p[0] == 0xEB ? 2 : 3)); - UInt16 numRootDirEntries = Get16(p + 17); + const UInt16 numRootDirEntries = Get16(p + 17); if (numRootDirEntries == 0) { if (codeOffset < 90 && !isOkOffset) @@ -178,7 +178,7 @@ if (codeOffset < 62 - 24 && !isOkOffset) return false; NumFatBits = 0; - UInt32 mask = (1 << (SectorSizeLog - 5)) - 1; + const UInt32 mask = (1 << (SectorSizeLog - 5)) - 1; if ((numRootDirEntries & mask) != 0) return false; NumRootDirSectors = (numRootDirEntries + mask) >> (SectorSizeLog - 5); @@ -187,8 +187,12 @@ NumSectors = Get16(p + 19); if (NumSectors == 0) NumSectors = Get32(p + 32); + /* + // mkfs.fat could create fat32 image with 16-bit number of sectors. + // v23: we allow 16-bit value for number of sectors in fat32. else if (IsFat32()) return false; + */ MediaType = p[21]; NumFatSectors = Get16(p + 22); @@ -241,19 +245,18 @@ DataSector = RootDirSector + NumRootDirSectors; if (NumSectors < DataSector) return false; - UInt32 numDataSectors = NumSectors - DataSector; - UInt32 numClusters = numDataSectors >> SectorsPerClusterLog; + const UInt32 numDataSectors = NumSectors - DataSector; + const UInt32 numClusters = numDataSectors >> SectorsPerClusterLog; BadCluster = 0x0FFFFFF7; - if (numClusters < 0xFFF5) + // v23: we support unusual (< 0xFFF5) numClusters values in fat32 systems + if (NumFatBits != 32) { - if (NumFatBits == 32) + if (numClusters >= 0xFFF5) return false; NumFatBits = (Byte)(numClusters < 0xFF5 ? 12 : 16); BadCluster &= ((1 << NumFatBits) - 1); } - else if (NumFatBits != 32) - return false; FatSize = numClusters + 2; if (FatSize > BadCluster || CalcFatSizeInSectors() > NumFatSectors) @@ -358,7 +361,7 @@ UInt64 PhySize; - CDatabase(): Fat(0) {} + CDatabase(): Fat(NULL) {} ~CDatabase() { ClearAndClose(); } void Clear(); @@ -366,7 +369,7 @@ HRESULT OpenProgressFat(bool changeTotal = true); HRESULT OpenProgress(); - UString GetItemPath(Int32 index) const; + UString GetItemPath(UInt32 index) const; HRESULT Open(); HRESULT ReadDir(Int32 parent, UInt32 cluster, unsigned level); @@ -380,7 +383,7 @@ HRESULT CDatabase::SeekToSector(UInt32 sector) { - return InStream->Seek((UInt64)sector << Header.SectorSizeLog, STREAM_SEEK_SET, NULL); + return InStream_SeekSet(InStream, (UInt64)sector << Header.SectorSizeLog); } void CDatabase::Clear() @@ -392,7 +395,7 @@ Items.Clear(); delete []Fat; - Fat = 0; + Fat = NULL; } void CDatabase::ClearAndClose() @@ -409,7 +412,7 @@ { UInt64 numTotalBytes = (Header.CalcFatSizeInSectors() << Header.SectorSizeLog) + ((UInt64)(Header.FatSize - NumFreeClusters) << Header.ClusterSizeLog); - RINOK(OpenCallback->SetTotal(NULL, &numTotalBytes)); + RINOK(OpenCallback->SetTotal(NULL, &numTotalBytes)) } return OpenCallback->SetCompleted(NULL, &NumCurUsedBytes); } @@ -422,14 +425,14 @@ return OpenCallback->SetCompleted(&numItems, &NumCurUsedBytes); } -UString CDatabase::GetItemPath(Int32 index) const +UString CDatabase::GetItemPath(UInt32 index) const { const CItem *item = &Items[index]; UString name = item->GetName(); for (;;) { - index = item->Parent; - if (index < 0) + index = (UInt32)item->Parent; + if (item->Parent < 0) return name; item = &Items[index]; name.InsertAtFront(WCHAR_PATH_SEPARATOR); @@ -464,7 +467,7 @@ if (!clusterMode) { blockSize = Header.SectorSize(); - RINOK(SeekToSector(Header.RootDirSector)); + RINOK(SeekToSector(Header.RootDirSector)) } ByteBuf.Alloc(blockSize); @@ -480,7 +483,7 @@ if ((NumDirClusters & 0xFF) == 0) { - RINOK(OpenProgress()); + RINOK(OpenProgress()) } if (clusterMode) @@ -490,7 +493,7 @@ if (!Header.IsValidCluster(cluster)) return S_FALSE; PRF(printf("\nCluster = %4X", cluster)); - RINOK(SeekToCluster(cluster)); + RINOK(SeekToCluster(cluster)) UInt32 newCluster = Fat[cluster]; if ((newCluster & kFatItemUsedByDirMask) != 0) return S_FALSE; @@ -502,7 +505,7 @@ else if (sectorIndex++ >= Header.NumRootDirSectors) break; - RINOK(ReadStream_FALSE(InStream, ByteBuf, blockSize)); + RINOK(ReadStream_FALSE(InStream, ByteBuf, blockSize)) } const Byte *p = ByteBuf + pos; @@ -621,7 +624,7 @@ if (item.IsDir()) { PRF(printf("\n%S", GetItemPath(i))); - RINOK(CDatabase::ReadDir(i, item.Cluster, level + 1)); + RINOK(CDatabase::ReadDir((int)i, item.Cluster, level + 1)) } } return S_OK; @@ -633,11 +636,11 @@ bool numFreeClustersDefined = false; { Byte buf[kHeaderSize]; - RINOK(ReadStream_FALSE(InStream, buf, kHeaderSize)); + RINOK(ReadStream_FALSE(InStream, buf, kHeaderSize)) if (!Header.Parse(buf)) return S_FALSE; UInt64 fileSize; - RINOK(InStream->Seek(0, STREAM_SEEK_END, &fileSize)); + RINOK(InStream_GetSize_SeekToEnd(InStream, fileSize)) /* we comment that check to support truncated images */ /* @@ -648,7 +651,7 @@ if (Header.IsFat32()) { SeekToSector(Header.FsInfoSector); - RINOK(ReadStream_FALSE(InStream, buf, kHeaderSize)); + RINOK(ReadStream_FALSE(InStream, buf, kHeaderSize)) if (buf[0x1FE] != 0x55 || buf[0x1FF] != 0xAA) return S_FALSE; if (Get32(buf) == 0x41615252 && Get32(buf + 484) == 0x61417272) @@ -666,8 +669,8 @@ CByteBuffer byteBuf; Fat = new UInt32[Header.FatSize]; - RINOK(OpenProgressFat()); - RINOK(SeekToSector(Header.GetFatSector())); + RINOK(OpenProgressFat()) + RINOK(SeekToSector(Header.GetFatSector())) if (Header.NumFatBits == 32) { const UInt32 kBufSize = (1 << 15); @@ -679,7 +682,7 @@ if (size > kBufSize32) size = kBufSize32; UInt32 readSize = Header.SizeToSectors(size * 4) << Header.SectorSizeLog; - RINOK(ReadStream_FALSE(InStream, byteBuf, readSize)); + RINOK(ReadStream_FALSE(InStream, byteBuf, readSize)) NumCurUsedBytes += readSize; const UInt32 *src = (const UInt32 *)(const void *)(const Byte *)byteBuf; @@ -701,7 +704,7 @@ i += size; if ((i & 0xFFFFF) == 0) { - RINOK(OpenProgressFat(!numFreeClustersDefined)); + RINOK(OpenProgressFat(!numFreeClustersDefined)) } } } @@ -711,7 +714,7 @@ NumCurUsedBytes += kBufSize; byteBuf.Alloc(kBufSize); Byte *p = byteBuf; - RINOK(ReadStream_FALSE(InStream, p, kBufSize)); + RINOK(ReadStream_FALSE(InStream, p, kBufSize)) UInt32 fatSize = Header.FatSize; UInt32 *fat = &Fat[0]; if (Header.NumFatBits == 16) @@ -730,7 +733,7 @@ } } - RINOK(OpenProgressFat()); + RINOK(OpenProgressFat()) if ((Fat[0] & 0xFF) != Header.MediaType) { @@ -741,28 +744,27 @@ return S_FALSE; } - RINOK(ReadDir(-1, Header.RootCluster, 0)); + RINOK(ReadDir(-1, Header.RootCluster, 0)) PhySize = Header.GetPhySize(); return S_OK; } -class CHandler: + + +Z7_class_CHandler_final: public IInArchive, public IInArchiveGetStream, public CMyUnknownImp, CDatabase { -public: - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); + Z7_IFACES_IMP_UNK_2(IInArchive, IInArchiveGetStream) }; -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN - *stream = 0; + *stream = NULL; const CItem &item = Items[index]; CClusterInStream *streamSpec = new CClusterInStream; CMyComPtr streamTemp = streamSpec; @@ -796,7 +798,7 @@ if (!Header.IsEocAndUnused(cluster)) return S_FALSE; } - RINOK(streamSpec->InitAndSeek()); + RINOK(streamSpec->InitAndSeek()) *stream = streamTemp.Detach(); return S_OK; COM_TRY_END @@ -873,7 +875,7 @@ #define STRING_TO_PROP(s, p) StringToProp(s, sizeof(s), prop) */ -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -911,7 +913,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -933,7 +935,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback)) { COM_TRY_BEGIN { @@ -957,17 +959,17 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { ClearAndClose(); return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = Items.Size(); if (numItems == 0) @@ -980,7 +982,7 @@ if (!item.IsDir()) totalSize += item.Size; } - RINOK(extractCallback->SetTotal(totalSize)); + RINOK(extractCallback->SetTotal(totalSize)) UInt64 totalPackSize; totalSize = totalPackSize = 0; @@ -995,23 +997,25 @@ CDummyOutStream *outStreamSpec = new CDummyOutStream; CMyComPtr outStream(outStreamSpec); - for (i = 0; i < numItems; i++) + for (i = 0;; i++) { lps->InSize = totalPackSize; lps->OutSize = totalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) + if (i == numItems) + break; CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - Int32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; const CItem &item = Items[index]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) if (item.IsDir()) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } @@ -1020,7 +1024,7 @@ if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) outStreamSpec->SetStream(realOutStream); realOutStream.Release(); @@ -1031,22 +1035,22 @@ HRESULT hres = GetStream(index, &inStream); if (hres != S_FALSE) { - RINOK(hres); + RINOK(hres) if (inStream) { - RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)) if (copyCoderSpec->TotalSize == item.Size) res = NExtract::NOperationResult::kOK; } } outStreamSpec->ReleaseStream(); - RINOK(extractCallback->SetOperationResult(res)); + RINOK(extractCallback->SetOperationResult(res)) } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = Items.Size(); return S_OK; @@ -1055,7 +1059,7 @@ static const Byte k_Signature[] = { 0x55, 0xAA }; REGISTER_ARC_I( - "FAT", "fat img", 0, 0xDA, + "FAT", "fat img", NULL, 0xDA, k_Signature, 0x1FE, 0, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/FlvHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/FlvHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/FlvHandler.cpp 2021-01-26 09:45:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/FlvHandler.cpp 2023-03-26 12:00:00.000000000 +0000 @@ -64,11 +64,10 @@ bool IsAudio() const { return Type == kType_Audio; } }; -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_CHandler_IInArchive_1( + IInArchiveGetStream +) CMyComPtr _stream; CObjectVector _items2; CByteBuffer _metadata; @@ -77,10 +76,6 @@ HRESULT Open2(IInStream *stream, IArchiveOpenCallback *callback); // AString GetComment(); -public: - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); }; static const Byte kProps[] = @@ -141,7 +136,7 @@ , "44 kHz" }; -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { NWindows::NCOM::CPropVariant prop; const CItem2 &item = _items2[index]; @@ -252,7 +247,7 @@ } */ -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { // COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -271,7 +266,7 @@ { const UInt32 kHeaderSize = 13; Byte header[kHeaderSize]; - RINOK(ReadStream_FALSE(stream, header, kHeaderSize)); + RINOK(ReadStream_FALSE(stream, header, kHeaderSize)) if (header[0] != 'F' || header[1] != 'L' || header[2] != 'V' || @@ -358,7 +353,7 @@ item2.Props = props; item2.NumChunks = 1; item2.SameSubTypes = true; - lasts[item.Type] = _items2.Add(item2); + lasts[item.Type] = (int)_items2.Add(item2); } else { @@ -420,7 +415,7 @@ return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *callback) +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *callback)) { COM_TRY_BEGIN Close(); @@ -441,7 +436,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _phySize = 0; _stream.Release(); @@ -450,17 +445,17 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _items2.Size(); return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _items2.Size(); if (numItems == 0) @@ -480,32 +475,32 @@ for (i = 0; i < numItems; i++) { lps->InSize = lps->OutSize = totalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr outStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; const CItem2 &item = _items2[index]; - RINOK(extractCallback->GetStream(index, &outStream, askMode)); + RINOK(extractCallback->GetStream(index, &outStream, askMode)) totalSize += item.Size; if (!testMode && !outStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) if (outStream) { - RINOK(WriteStream(outStream, item.BufSpec->Buf, item.BufSpec->Buf.Size())); + RINOK(WriteStream(outStream, item.BufSpec->Buf, item.BufSpec->Buf.Size())) } - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN - *stream = 0; + *stream = NULL; CBufInStream *streamSpec = new CBufInStream; CMyComPtr streamTemp = streamSpec; streamSpec->Init(_items2[index].BufSpec); @@ -517,7 +512,7 @@ static const Byte k_Signature[] = { 'F', 'L', 'V', 1, }; REGISTER_ARC_I( - "FLV", "flv", 0, 0xD6, + "FLV", "flv", NULL, 0xD6, k_Signature, 0, 0, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/GptHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/GptHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/GptHandler.cpp 2021-12-29 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/GptHandler.cpp 2023-03-27 17:00:00.000000000 +0000 @@ -30,10 +30,9 @@ namespace NGpt { -#define SIGNATURE { 'E', 'F', 'I', ' ', 'P', 'A', 'R', 'T', 0, 0, 1, 0 } - static const unsigned k_SignatureSize = 12; -static const Byte k_Signature[k_SignatureSize] = SIGNATURE; +static const Byte k_Signature[k_SignatureSize] = + { 'E', 'F', 'I', ' ', 'P', 'A', 'R', 'T', 0, 0, 1, 0 }; static const UInt32 kSectorSize = 512; @@ -93,29 +92,29 @@ static const CPartType kPartTypes[] = { - // { 0x0, 0, "Unused" }, + // { 0x0, NULL, "Unused" }, - { 0x21686148, 0, "BIOS Boot" }, + { 0x21686148, NULL, "BIOS Boot" }, - { 0xC12A7328, 0, "EFI System" }, - { 0x024DEE41, 0, "MBR" }, + { 0xC12A7328, NULL, "EFI System" }, + { 0x024DEE41, NULL, "MBR" }, - { 0xE3C9E316, 0, "Windows MSR" }, - { 0xEBD0A0A2, 0, "Windows BDP" }, - { 0x5808C8AA, 0, "Windows LDM Metadata" }, - { 0xAF9B60A0, 0, "Windows LDM Data" }, - { 0xDE94BBA4, 0, "Windows Recovery" }, - // { 0x37AFFC90, 0, "IBM GPFS" }, - // { 0xE75CAF8F, 0, "Windows Storage Spaces" }, - - { 0x0FC63DAF, 0, "Linux Data" }, - { 0x0657FD6D, 0, "Linux Swap" }, - - { 0x83BD6B9D, 0, "FreeBSD Boot" }, - { 0x516E7CB4, 0, "FreeBSD Data" }, - { 0x516E7CB5, 0, "FreeBSD Swap" }, + { 0xE3C9E316, NULL, "Windows MSR" }, + { 0xEBD0A0A2, NULL, "Windows BDP" }, + { 0x5808C8AA, NULL, "Windows LDM Metadata" }, + { 0xAF9B60A0, NULL, "Windows LDM Data" }, + { 0xDE94BBA4, NULL, "Windows Recovery" }, + // { 0x37AFFC90, NULL, "IBM GPFS" }, + // { 0xE75CAF8F, NULL, "Windows Storage Spaces" }, + + { 0x0FC63DAF, NULL, "Linux Data" }, + { 0x0657FD6D, NULL, "Linux Swap" }, + + { 0x83BD6B9D, NULL, "FreeBSD Boot" }, + { 0x516E7CB4, NULL, "FreeBSD Data" }, + { 0x516E7CB5, NULL, "FreeBSD Swap" }, { 0x516E7CB6, "ufs", "FreeBSD UFS" }, - { 0x516E7CB8, 0, "FreeBSD Vinum" }, + { 0x516E7CB8, NULL, "FreeBSD Vinum" }, { 0x516E7CB8, "zfs", "FreeBSD ZFS" }, { 0x48465300, "hfsx", "HFS+" }, @@ -124,10 +123,10 @@ static int FindPartType(const Byte *guid) { - UInt32 val = Get32(guid); - for (unsigned i = 0; i < ARRAY_SIZE(kPartTypes); i++) + const UInt32 val = Get32(guid); + for (unsigned i = 0; i < Z7_ARRAY_SIZE(kPartTypes); i++) if (kPartTypes[i].Id == val) - return i; + return (int)i; return -1; } @@ -139,8 +138,10 @@ } -class CHandler: public CHandlerCont +Z7_class_CHandler_final: public CHandlerCont { + Z7_IFACE_COM7_IMP(IInArchive_Cont) + CRecordVector _items; UInt64 _totalSize; Byte Guid[16]; @@ -149,23 +150,20 @@ HRESULT Open2(IInStream *stream); - virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const + virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const Z7_override { const CPartition &item = _items[index]; pos = item.GetPos(); size = item.GetSize(); return NExtract::NOperationResult::kOK; } - -public: - INTERFACE_IInArchive_Cont(;) }; HRESULT CHandler::Open2(IInStream *stream) { _buffer.Alloc(kSectorSize * 2); - RINOK(ReadStream_FALSE(stream, _buffer, kSectorSize * 2)); + RINOK(ReadStream_FALSE(stream, _buffer, kSectorSize * 2)) const Byte *buf = _buffer; if (buf[0x1FE] != 0x55 || buf[0x1FF] != 0xAA) @@ -180,24 +178,24 @@ if (headerSize > kSectorSize) return S_FALSE; UInt32 crc = Get32(buf + 0x10); - SetUi32(_buffer + kSectorSize + 0x10, 0); + SetUi32(_buffer + kSectorSize + 0x10, 0) if (CrcCalc(_buffer + kSectorSize, headerSize) != crc) return S_FALSE; } // UInt32 reserved = Get32(buf + 0x14); - UInt64 curLba = Get64(buf + 0x18); + const UInt64 curLba = Get64(buf + 0x18); if (curLba != 1) return S_FALSE; - UInt64 backupLba = Get64(buf + 0x20); + const UInt64 backupLba = Get64(buf + 0x20); // UInt64 firstUsableLba = Get64(buf + 0x28); // UInt64 lastUsableLba = Get64(buf + 0x30); memcpy(Guid, buf + 0x38, 16); - UInt64 tableLba = Get64(buf + 0x48); + const UInt64 tableLba = Get64(buf + 0x48); if (tableLba < 2) return S_FALSE; - UInt32 numEntries = Get32(buf + 0x50); - UInt32 entrySize = Get32(buf + 0x54); // = 128 usually - UInt32 entriesCrc = Get32(buf + 0x58); + const UInt32 numEntries = Get32(buf + 0x50); + const UInt32 entrySize = Get32(buf + 0x54); // = 128 usually + const UInt32 entriesCrc = Get32(buf + 0x58); if (entrySize < 128 || entrySize > (1 << 12) @@ -206,12 +204,12 @@ || tableLba >= ((UInt64)1 << (64 - 10))) return S_FALSE; - UInt32 tableSize = entrySize * numEntries; - UInt32 tableSizeAligned = (tableSize + kSectorSize - 1) & ~(kSectorSize - 1); + const UInt32 tableSize = entrySize * numEntries; + const UInt32 tableSizeAligned = (tableSize + kSectorSize - 1) & ~(kSectorSize - 1); _buffer.Alloc(tableSizeAligned); - UInt64 tableOffset = tableLba * kSectorSize; - RINOK(stream->Seek(tableOffset, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(stream, _buffer, tableSizeAligned)); + const UInt64 tableOffset = tableLba * kSectorSize; + RINOK(InStream_SeekSet(stream, tableOffset)) + RINOK(ReadStream_FALSE(stream, _buffer, tableSizeAligned)) if (CrcCalc(_buffer, tableSize) != entriesCrc) return S_FALSE; @@ -238,7 +236,7 @@ { UInt64 fileEnd; - RINOK(stream->Seek(0, STREAM_SEEK_END, &fileEnd)); + RINOK(InStream_GetSize_SeekToEnd(stream, fileEnd)) if (_totalSize < fileEnd) { @@ -246,7 +244,7 @@ const UInt64 kRemMax = 1 << 22; if (rem <= kRemMax) { - RINOK(stream->Seek(_totalSize, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, _totalSize)) bool areThereNonZeros = false; UInt64 numZeros = 0; if (ReadZeroTail(stream, areThereNonZeros, numZeros, kRemMax) == S_OK) @@ -269,7 +267,7 @@ { if (p[0x1FE] != 0x55 || p[0x1FF] != 0xAA) return false; - if (memcmp(p + 3, k_NtfsSignature, ARRAY_SIZE(k_NtfsSignature)) != 0) + if (memcmp(p + 3, k_NtfsSignature, Z7_ARRAY_SIZE(k_NtfsSignature)) != 0) return false; switch (p[0]) { @@ -281,13 +279,13 @@ } -STDMETHODIMP CHandler::Open(IInStream *stream, +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openArchiveCallback */) + IArchiveOpenCallback * /* openArchiveCallback */)) { COM_TRY_BEGIN Close(); - RINOK(Open2(stream)); + RINOK(Open2(stream)) _stream = stream; FOR_VECTOR (fileIndex, _items) @@ -305,7 +303,9 @@ if (t.Type && IsString1PrefixedByString2_NoCase_Ascii(t.Type, "Windows")) { CMyComPtr inStream; - if (GetStream(fileIndex, &inStream) == S_OK && inStream) + if ( + // ((IInArchiveGetStream *)this)-> + GetStream(fileIndex, &inStream) == S_OK && inStream) { Byte temp[k_Ntfs_Fat_HeaderSize]; if (ReadStream_FAIL(inStream, temp, k_Ntfs_Fat_HeaderSize) == S_OK) @@ -329,7 +329,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _totalSize = 0; memset(Guid, 0, sizeof(Guid)); @@ -356,7 +356,7 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -382,13 +382,13 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _items.Size(); return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -414,12 +414,12 @@ } if (!s2.IsEmpty()) { - s += '.'; + s.Add_Dot(); s += s2; } } { - s += '.'; + s.Add_Dot(); s += (item.Ext ? item.Ext : "img"); } prop = s; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/GzHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/GzHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/GzHandler.cpp 2022-05-09 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/GzHandler.cpp 2023-03-27 17:49:00.000000000 +0000 @@ -354,7 +354,7 @@ // UInt32 crc = CRC_INIT_VAL; Byte buf[10]; - RINOK(ReadBytes(stream, buf, 10)); + RINOK(ReadBytes(stream, buf, 10)) if (buf[0] != kSignature_0 || buf[1] != kSignature_1 || @@ -374,22 +374,22 @@ if (ExtraFieldIsPresent()) { UInt32 xlen; - RINOK(ReadUInt16(stream, xlen /* , crc */)); - RINOK(SkipBytes(stream, xlen)); + RINOK(ReadUInt16(stream, xlen /* , crc */)) + RINOK(SkipBytes(stream, xlen)) // Extra.SetCapacity(xlen); // RINOK(ReadStream_FALSE(stream, Extra, xlen)); // crc = CrcUpdate(crc, Extra, xlen); } if (NameIsPresent()) - RINOK(ReadString(stream, Name, kNameMaxLen /* , crc */)); + RINOK(ReadString(stream, Name, kNameMaxLen /* , crc */)) if (CommentIsPresent()) - RINOK(ReadString(stream, Comment, kCommentMaxLen /* , crc */)); + RINOK(ReadString(stream, Comment, kCommentMaxLen /* , crc */)) if (HeaderCrcIsPresent()) { UInt32 headerCRC; // UInt32 dummy = 0; - RINOK(ReadUInt16(stream, headerCRC /* , dummy */)); + RINOK(ReadUInt16(stream, headerCRC /* , dummy */)) /* if ((UInt16)CRC_GET_DIGEST(crc) != headerCRC) return S_FALSE; @@ -401,7 +401,7 @@ HRESULT CItem::ReadFooter1(NDecoder::CCOMCoder *stream) { Byte buf[8]; - RINOK(ReadBytes(stream, buf, 8)); + RINOK(ReadBytes(stream, buf, 8)) Crc = Get32(buf); Size32 = Get32(buf + 4); return stream->InputEofError() ? S_FALSE : S_OK; @@ -410,7 +410,7 @@ HRESULT CItem::ReadFooter2(ISequentialInStream *stream) { Byte buf[8]; - RINOK(ReadStream_FALSE(stream, buf, 8)); + RINOK(ReadStream_FALSE(stream, buf, 8)) Crc = Get32(buf); Size32 = Get32(buf + 4); return S_OK; @@ -424,15 +424,15 @@ buf[2] = kSignature_2; buf[3] = (Byte)(Flags & NFlags::kName); // buf[3] |= NFlags::kCrc; - SetUi32(buf + 4, Time); + SetUi32(buf + 4, Time) buf[8] = ExtraFlags; buf[9] = HostOS; - RINOK(WriteStream(stream, buf, 10)); + RINOK(WriteStream(stream, buf, 10)) // crc = CrcUpdate(CRC_INIT_VAL, buf, 10); if (NameIsPresent()) { // crc = CrcUpdate(crc, (const char *)Name, Name.Len() + 1); - RINOK(WriteStream(stream, (const char *)Name, Name.Len() + 1)); + RINOK(WriteStream(stream, (const char *)Name, Name.Len() + 1)) } // SetUi16(buf, (UInt16)CRC_GET_DIGEST(crc)); // RINOK(WriteStream(stream, buf, 2)); @@ -442,18 +442,16 @@ HRESULT CItem::WriteFooter(ISequentialOutStream *stream) { Byte buf[8]; - SetUi32(buf, Crc); - SetUi32(buf + 4, Size32); + SetUi32(buf, Crc) + SetUi32(buf + 4, Size32) return WriteStream(stream, buf, 8); } -class CHandler: - public IInArchive, - public IArchiveOpenSeq, - public IOutArchive, - public ISetProperties, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_3( + IArchiveOpenSeq, + IOutArchive, + ISetProperties +) CItem _item; bool _isArc; @@ -478,16 +476,6 @@ CHandlerTimeOptions _timeOptions; public: - MY_UNKNOWN_IMP4( - IInArchive, - IArchiveOpenSeq, - IOutArchive, - ISetProperties) - INTERFACE_IInArchive(;) - INTERFACE_IOutArchive(;) - STDMETHOD(OpenSeq)(ISequentialInStream *stream); - STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps); - CHandler(): _isArc(false), _decoderSpec(NULL) @@ -523,7 +511,7 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -557,13 +545,13 @@ } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = 1; return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -605,19 +593,17 @@ COM_TRY_END } -class CCompressProgressInfoImp: - public ICompressProgressInfo, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CCompressProgressInfoImp, + ICompressProgressInfo +) CMyComPtr Callback; public: UInt64 Offset; - MY_UNKNOWN_IMP1(ICompressProgressInfo) - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); void Init(IArchiveOpenCallback *callback) { Callback = callback; } }; -STDMETHODIMP CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */) +Z7_COM7F_IMF(CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */)) { if (Callback) { @@ -631,15 +617,15 @@ /* */ -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *)) { COM_TRY_BEGIN - RINOK(OpenSeq(stream)); + RINOK(OpenSeq(stream)) _isArc = false; UInt64 endPos; - RINOK(stream->Seek(-8, STREAM_SEEK_END, &endPos)); + RINOK(stream->Seek(-8, STREAM_SEEK_END, &endPos)) _packSize = endPos + 8; - RINOK(_item.ReadFooter2(stream)); + RINOK(_item.ReadFooter2(stream)) _stream = stream; _isArc = true; _needSeekToStart = true; @@ -647,7 +633,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { COM_TRY_BEGIN try @@ -656,7 +642,7 @@ CreateDecoder(); _decoderSpec->SetInStream(stream); _decoderSpec->InitInStream(true); - RINOK(_item.ReadHeader(_decoderSpec)); + RINOK(_item.ReadHeader(_decoderSpec)) if (_decoderSpec->InputEofError()) return S_FALSE; _headerSize = _decoderSpec->GetInputProcessedSize(); @@ -667,7 +653,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; _needSeekToStart = false; @@ -687,8 +673,8 @@ return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN if (numItems == 0) @@ -701,10 +687,10 @@ // UInt64 currentTotalPacked = 0; // RINOK(extractCallback->SetCompleted(¤tTotalPacked)); CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(0, &realOutStream, askMode)) if (!testMode && !realOutStream) return S_OK; @@ -728,7 +714,7 @@ { if (!_stream) return E_FAIL; - RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(_stream)) _decoderSpec->InitInStream(true); // printf("\nSeek"); } @@ -754,7 +740,7 @@ lps->InSize = packSize; lps->OutSize = unpackedSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CItem item; @@ -954,14 +940,15 @@ { CMyComPtr fileInStream; - RINOK(updateCallback->GetStream(0, &fileInStream)); + RINOK(updateCallback->GetStream(0, &fileInStream)) if (!fileInStream) return S_FALSE; { - CMyComPtr getProps; - fileInStream->QueryInterface(IID_IStreamGetProps, (void **)&getProps); + Z7_DECL_CMyComPtr_QI_FROM( + IStreamGetProps, + getProps, fileInStream) if (getProps) { FILETIME mTime; @@ -976,8 +963,8 @@ } UInt64 complexity = 0; - RINOK(updateCallback->SetTotal(unpackSize)); - RINOK(updateCallback->SetCompleted(&complexity)); + RINOK(updateCallback->SetTotal(unpackSize)) + RINOK(updateCallback->SetCompleted(&complexity)) CSequentialInStreamWithCRC *inStreamSpec = new CSequentialInStreamWithCRC; CMyComPtr crcStream(inStreamSpec); @@ -994,17 +981,17 @@ item.HostOS = kHostOS; - RINOK(item.WriteHeader(outStream)); + RINOK(item.WriteHeader(outStream)) NEncoder::CCOMCoder *deflateEncoderSpec = new NEncoder::CCOMCoder; CMyComPtr deflateEncoder = deflateEncoderSpec; - RINOK(props.SetCoderProps(deflateEncoderSpec, NULL)); - RINOK(deflateEncoder->Code(crcStream, outStream, NULL, NULL, progress)); + RINOK(props.SetCoderProps(deflateEncoderSpec, NULL)) + RINOK(deflateEncoder->Code(crcStream, outStream, NULL, NULL, progress)) item.Crc = inStreamSpec->GetCRC(); unpackSizeReal = inStreamSpec->GetSize(); item.Size32 = (UInt32)unpackSizeReal; - RINOK(item.WriteFooter(outStream)); + RINOK(item.WriteFooter(outStream)) } /* if (reportArcProp) @@ -1020,7 +1007,7 @@ } -STDMETHODIMP CHandler::GetFileTimeType(UInt32 *timeType) +Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *timeType)) { /* if (_item.Time != 0) @@ -1049,24 +1036,29 @@ return S_OK; } -STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, - IArchiveUpdateCallback *updateCallback) +Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, + IArchiveUpdateCallback *updateCallback)) { COM_TRY_BEGIN if (numItems != 1) return E_INVALIDARG; + { + Z7_DECL_CMyComPtr_QI_FROM( + IStreamSetRestriction, + setRestriction, outStream) + if (setRestriction) + RINOK(setRestriction->SetRestriction(0, 0)) + } + Int32 newData, newProps; UInt32 indexInArchive; if (!updateCallback) return E_FAIL; - RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProps, &indexInArchive)); + RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProps, &indexInArchive)) - /* - CMyComPtr reportArcProp; - updateCallback->QueryInterface(IID_IArchiveUpdateCallbackArcProp, (void **)&reportArcProp); - */ + // Z7_DECL_CMyComPtr_QI_FROM(IArchiveUpdateCallbackArcProp, reportArcProp, updateCallback) CItem newItem; @@ -1080,7 +1072,7 @@ if (_timeOptions.Write_MTime.Val) { NCOM::CPropVariant prop; - RINOK(updateCallback->GetProperty(0, kpidMTime, &prop)); + RINOK(updateCallback->GetProperty(0, kpidMTime, &prop)) if (prop.vt == VT_FILETIME) NTime::FileTime_To_UnixTime(prop.filetime, newItem.Time); else if (prop.vt == VT_EMPTY) @@ -1090,7 +1082,7 @@ } { NCOM::CPropVariant prop; - RINOK(updateCallback->GetProperty(0, kpidPath, &prop)); + RINOK(updateCallback->GetProperty(0, kpidPath, &prop)) if (prop.vt == VT_BSTR) { UString name = prop.bstrVal; @@ -1106,7 +1098,7 @@ } { NCOM::CPropVariant prop; - RINOK(updateCallback->GetProperty(0, kpidIsDir, &prop)); + RINOK(updateCallback->GetProperty(0, kpidIsDir, &prop)) if (prop.vt != VT_EMPTY) if (prop.vt != VT_BOOL || prop.boolVal != VARIANT_FALSE) return E_INVALIDARG; @@ -1118,7 +1110,7 @@ UInt64 size; { NCOM::CPropVariant prop; - RINOK(updateCallback->GetProperty(0, kpidSize, &prop)); + RINOK(updateCallback->GetProperty(0, kpidSize, &prop)) if (prop.vt != VT_UI8) return E_INVALIDARG; size = prop.uhVal.QuadPart; @@ -1136,8 +1128,9 @@ CMyComPtr progress = lps; lps->Init(updateCallback, true); - CMyComPtr opCallback; - updateCallback->QueryInterface(IID_IArchiveUpdateCallbackFile, (void **)&opCallback); + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveUpdateCallbackFile, + opCallback, updateCallback) if (opCallback) { RINOK(opCallback->ReportOperation( @@ -1153,7 +1146,7 @@ newItem.WriteHeader(outStream); offset += _headerSize; } - RINOK(_stream->Seek((Int64)offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_stream, offset)) /* if (reportArcProp) @@ -1168,7 +1161,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) +Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps)) { _timeOptions.Init(); _props.Init(); @@ -1182,7 +1175,7 @@ const PROPVARIANT &value = values[i]; { bool processed = false; - RINOK(_timeOptions.Parse(name, value, processed)); + RINOK(_timeOptions.Parse(name, value, processed)) if (processed) { if (_timeOptions.Write_CTime.Val || @@ -1197,7 +1190,7 @@ continue; } } - RINOK(_props.SetProperty(name, value)); + RINOK(_props.SetProperty(name, value)) } return S_OK; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/HandlerCont.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/HandlerCont.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/HandlerCont.cpp 2022-01-31 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/HandlerCont.cpp 2023-01-31 17:00:00.000000000 +0000 @@ -18,14 +18,14 @@ API_FUNC_IsArc IsArc_Ext(const Byte *p, size_t size); } -STDMETHODIMP CHandlerCont::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandlerCont::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) { - RINOK(GetNumberOfItems(&numItems)); + RINOK(GetNumberOfItems(&numItems)) } if (numItems == 0) return S_OK; @@ -56,14 +56,14 @@ { lps->InSize = totalSize; lps->OutSize = totalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr outStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - Int32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; - RINOK(extractCallback->GetStream(index, &outStream, askMode)); + RINOK(extractCallback->GetStream(index, &outStream, askMode)) UInt64 pos, size; int opRes = GetItem_ExtractInfo(index, pos, size); @@ -71,14 +71,14 @@ if (!testMode && !outStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) if (opRes == NExtract::NOperationResult::kOK) { - RINOK(_stream->Seek(pos, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_stream, pos)) streamSpec->Init(size); - RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)) opRes = NExtract::NOperationResult::kDataError; @@ -89,14 +89,14 @@ } outStream.Release(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } return S_OK; COM_TRY_END } -STDMETHODIMP CHandlerCont::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandlerCont::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN *stream = NULL; @@ -114,7 +114,7 @@ Clear_HandlerImg_Vars(); } -STDMETHODIMP CHandlerImg::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CHandlerImg::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { @@ -129,9 +129,9 @@ *newPosition = _virtPos; return HRESULT_WIN32_ERROR_NEGATIVE_SEEK; } - _virtPos = offset; + _virtPos = (UInt64)offset; if (newPosition) - *newPosition = offset; + *newPosition = (UInt64)offset; return S_OK; } @@ -171,9 +171,9 @@ Reset_PosInArc(); } -STDMETHODIMP CHandlerImg::Open(IInStream *stream, +Z7_COM7F_IMF(CHandlerImg::Open(IInStream *stream, const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * openCallback) + IArchiveOpenCallback * openCallback)) { COM_TRY_BEGIN { @@ -209,31 +209,26 @@ COM_TRY_END } -STDMETHODIMP CHandlerImg::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandlerImg::GetNumberOfItems(UInt32 *numItems)) { *numItems = 1; return S_OK; } -class CHandlerImgProgress: - public ICompressProgressInfo, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + CHandlerImgProgress + , ICompressProgressInfo +) public: CHandlerImg &Handler; CMyComPtr _ratioProgress; CHandlerImgProgress(CHandlerImg &handler) : Handler(handler) {} - - // MY_UNKNOWN_IMP1(ICompressProgressInfo) - MY_UNKNOWN_IMP - - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); }; -STDMETHODIMP CHandlerImgProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) +Z7_COM7F_IMF(CHandlerImgProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize)) { UInt64 inSize2; if (Handler.Get_PackSizeProcessed(inSize2)) @@ -242,8 +237,8 @@ } -STDMETHODIMP CHandlerImg::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandlerImg::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN if (numItems == 0) @@ -251,15 +246,15 @@ if (numItems != (UInt32)(Int32)-1 && (numItems != 1 || indices[0] != 0)) return E_INVALIDARG; - RINOK(extractCallback->SetTotal(_size)); + RINOK(extractCallback->SetTotal(_size)) CMyComPtr outStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - RINOK(extractCallback->GetStream(0, &outStream, askMode)); + RINOK(extractCallback->GetStream(0, &outStream, askMode)) if (!testMode && !outStream) return S_OK; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) int opRes = NExtract::NOperationResult::kDataError; @@ -332,7 +327,7 @@ for (;;) { UInt32 size = 0; - RINOK(stream->Read(buf, kBufSize, &size)); + RINOK(stream->Read(buf, kBufSize, &size)) if (size == 0) return S_OK; for (UInt32 i = 0; i < size; i++) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/HandlerCont.h 7zip-23.01+dfsg/CPP/7zip/Archive/HandlerCont.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/HandlerCont.h 2022-04-30 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/HandlerCont.h 2023-03-27 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // HandlerCont.h -#ifndef __HANDLER_CONT_H -#define __HANDLER_CONT_H +#ifndef ZIP7_INC_HANDLER_CONT_H +#define ZIP7_INC_HANDLER_CONT_H #include "../../Common/MyCom.h" @@ -9,62 +9,76 @@ namespace NArchive { -#define INTERFACE_IInArchive_Cont(x) \ - STDMETHOD(Open)(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(Close)() MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(GetNumberOfItems)(UInt32 *numItems) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) MY_NO_THROW_DECL_ONLY x; \ - /* STDMETHOD(Extract)(const UInt32* indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback) MY_NO_THROW_DECL_ONLY x; */ \ - STDMETHOD(GetArchiveProperty)(PROPID propID, PROPVARIANT *value) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(GetNumberOfProperties)(UInt32 *numProps) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(GetPropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(GetNumberOfArchiveProperties)(UInt32 *numProps) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(GetArchivePropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) MY_NO_THROW_DECL_ONLY x; \ +#define Z7_IFACEM_IInArchive_Cont(x) \ + x(Open(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback)) \ + x(Close()) \ + x(GetNumberOfItems(UInt32 *numItems)) \ + x(GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) \ + /* x(Extract(const UInt32 *indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback)) */ \ + x(GetArchiveProperty(PROPID propID, PROPVARIANT *value)) \ + x(GetNumberOfProperties(UInt32 *numProps)) \ + x(GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \ + x(GetNumberOfArchiveProperties(UInt32 *numProps)) \ + x(GetArchivePropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \ +// #define Z7_COM7F_PUREO(f) virtual Z7_COM7F_IMF(f) Z7_override =0; +// #define Z7_COM7F_PUREO2(t, f) virtual Z7_COM7F_IMF2(t, f) Z7_override =0; + class CHandlerCont: public IInArchive, public IInArchiveGetStream, public CMyUnknownImp { + Z7_COM_UNKNOWN_IMP_2( + IInArchive, + IInArchiveGetStream) + /* + Z7_IFACEM_IInArchive_Cont(Z7_COM7F_PUREO) + // Z7_IFACE_COM7_PURE(IInArchive_Cont) + */ + Z7_COM7F_IMP(Extract(const UInt32 *indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback)) protected: - CMyComPtr _stream; + Z7_IFACE_COM7_IMP(IInArchiveGetStream) + CMyComPtr _stream; virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const = 0; - -public: - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - INTERFACE_IInArchive_Cont(PURE) - - STDMETHOD(Extract)(const UInt32* indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback) MY_NO_THROW_DECL_ONLY; - - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); - // destructor must be virtual for this class virtual ~CHandlerCont() {} }; -#define INTERFACE_IInArchive_Img(x) \ - /* STDMETHOD(Open)(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback) MY_NO_THROW_DECL_ONLY x; */ \ - STDMETHOD(Close)() MY_NO_THROW_DECL_ONLY x; \ - /* STDMETHOD(GetNumberOfItems)(UInt32 *numItems) MY_NO_THROW_DECL_ONLY x; */ \ - STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) MY_NO_THROW_DECL_ONLY x; \ - /* STDMETHOD(Extract)(const UInt32* indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback) MY_NO_THROW_DECL_ONLY x; */ \ - STDMETHOD(GetArchiveProperty)(PROPID propID, PROPVARIANT *value) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(GetNumberOfProperties)(UInt32 *numProps) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(GetPropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(GetNumberOfArchiveProperties)(UInt32 *numProps) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(GetArchivePropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) MY_NO_THROW_DECL_ONLY x; \ +#define Z7_IFACEM_IInArchive_Img(x) \ + /* x(Open(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback)) */ \ + x(Close()) \ + /* x(GetNumberOfItems(UInt32 *numItems)) */ \ + x(GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) \ + /* x(Extract(const UInt32 *indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback)) */ \ + x(GetArchiveProperty(PROPID propID, PROPVARIANT *value)) \ + x(GetNumberOfProperties(UInt32 *numProps)) \ + x(GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \ + x(GetNumberOfArchiveProperties(UInt32 *numProps)) \ + x(GetArchivePropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \ class CHandlerImg: - public IInStream, public IInArchive, public IInArchiveGetStream, + public IInStream, public CMyUnknownImp { + Z7_COM_UNKNOWN_IMP_3( + IInArchive, + IInArchiveGetStream, + IInStream) + + Z7_COM7F_IMP(Open(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback)) + Z7_COM7F_IMP(GetNumberOfItems(UInt32 *numItems)) + Z7_COM7F_IMP(Extract(const UInt32 *indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback)) + Z7_IFACE_COM7_IMP(IInStream) + // Z7_IFACEM_IInArchive_Img(Z7_COM7F_PUREO) + protected: UInt64 _virtPos; UInt64 _posInArc; @@ -107,18 +121,6 @@ return false; } - MY_UNKNOWN_IMP3(IInArchive, IInArchiveGetStream, IInStream) - INTERFACE_IInArchive_Img(PURE) - - STDMETHOD(Open)(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback); - STDMETHOD(GetNumberOfItems)(UInt32 *numItems); - STDMETHOD(Extract)(const UInt32* indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback); - - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream) = 0; - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize) = 0; - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); - CHandlerImg(); // destructor must be virtual for this class virtual ~CHandlerImg() {} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/HfsHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/HfsHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/HfsHandler.cpp 2022-07-10 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/HfsHandler.cpp 2023-03-27 14:00:00.000000000 +0000 @@ -126,16 +126,16 @@ struct CIdIndexPair { UInt32 ID; - int Index; + unsigned Index; int Compare(const CIdIndexPair &a) const; }; -#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } +#define RINOZ(x) { const int _t_ = (x); if (_t_ != 0) return _t_; } int CIdIndexPair::Compare(const CIdIndexPair &a) const { - RINOZ(MyCompare(ID, a.ID)); + RINOZ(MyCompare(ID, a.ID)) return MyCompare(Index, a.Index); } @@ -144,10 +144,10 @@ unsigned left = 0, right = items.Size(); while (left != right) { - unsigned mid = (left + right) / 2; - UInt32 midVal = items[mid].ID; + const unsigned mid = (left + right) / 2; + const UInt32 midVal = items[mid].ID; if (id == midVal) - return items[mid].Index; + return (int)items[mid].Index; if (id < midVal) right = mid; else @@ -161,10 +161,10 @@ unsigned left = 0, right = items.Size(); while (left != right) { - unsigned mid = (left + right) / 2; - UInt32 midVal = items[mid].ID; + const unsigned mid = (left + right) / 2; + const UInt32 midVal = items[mid].ID; if (id == midVal) - return mid; + return (int)mid; if (id < midVal) right = mid; else @@ -244,6 +244,8 @@ // static const UInt32 kMethod_LZFSE_ATTR = 11; static const UInt32 kMethod_LZFSE_RSRC = 12; +// static const UInt32 kMethod_ZBM_RSRC = 14; + static const char * const g_Methods[] = { NULL @@ -259,6 +261,8 @@ , "COPY-rsrc" , "LZFSE-attr" , "LZFSE-rsrc" + , NULL + , "ZBM-rsrc" }; @@ -281,7 +285,9 @@ if ( Method == kMethod_ZLIB_RSRC || Method == kMethod_COPY_RSRC || Method == kMethod_LZVN_RSRC - || Method == kMethod_LZFSE_RSRC) + || Method == kMethod_LZFSE_RSRC + // || Method == kMethod_ZBM_RSRC // for debug + ) { IsResource = true; if (dataSize == 0) @@ -327,7 +333,7 @@ return; const UInt32 method = Method; const char *p = NULL; - if (method < ARRAY_SIZE(g_Methods)) + if (method < Z7_ARRAY_SIZE(g_Methods)) p = g_Methods[method]; AString s; if (p) @@ -520,7 +526,7 @@ { unsigned len = 0; const unsigned kNumLevelsMax = (1 << 10); - int cur = index; + unsigned cur = index; unsigned i; for (i = 0; i < kNumLevelsMax; i++) @@ -537,8 +543,8 @@ len += s->Len(); len++; - cur = ref.Parent; - if (cur < 0) + cur = (unsigned)ref.Parent; + if (ref.Parent < 0) break; } @@ -580,7 +586,7 @@ if (len == 0) break; p[--len] = delimChar; - cur = ref.Parent; + cur = (unsigned)ref.Parent; } } @@ -607,10 +613,10 @@ e.NumBlocks > fork.NumBlocks - curBlock || e.NumBlocks > Header.NumBlocks - e.Pos) return S_FALSE; - RINOK(inStream->Seek(SpecOffset + ((UInt64)e.Pos << Header.BlockSizeLog), STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(inStream, SpecOffset + ((UInt64)e.Pos << Header.BlockSizeLog))) RINOK(ReadStream_FALSE(inStream, (Byte *)buf + ((size_t)curBlock << Header.BlockSizeLog), - (size_t)e.NumBlocks << Header.BlockSizeLog)); + (size_t)e.NumBlocks << Header.BlockSizeLog)) curBlock += e.NumBlocks; } return S_OK; @@ -733,13 +739,13 @@ if (fork.NumBlocks == 0) return S_OK; CByteBuffer buf; - RINOK(ReadFile(fork, buf, inStream)); + RINOK(ReadFile(fork, buf, inStream)) const Byte *p = (const Byte *)buf; // CNodeDescriptor nodeDesc; // nodeDesc.Parse(p); CHeaderRec hr; - RINOK(hr.Parse2(buf)); + RINOK(hr.Parse2(buf)) UInt32 node = hr.FirstLeafNode; if (node == 0) @@ -872,13 +878,13 @@ return S_OK; CByteBuffer AttrBuf; - RINOK(ReadFile(fork, AttrBuf, inStream)); + RINOK(ReadFile(fork, AttrBuf, inStream)) const Byte *p = (const Byte *)AttrBuf; // CNodeDescriptor nodeDesc; // nodeDesc.Parse(p); CHeaderRec hr; - RINOK(hr.Parse2(AttrBuf)); + RINOK(hr.Parse2(AttrBuf)) // CaseSensetive = (Header.IsHfsX() && hr.KeyCompareType == 0xBC); @@ -948,7 +954,7 @@ if (progress && (Attrs.Size() & 0xFFF) == 0) { const UInt64 numFiles = 0; - RINOK(progress->SetCompleted(&numFiles, NULL)); + RINOK(progress->SetCompleted(&numFiles, NULL)) } if (Attrs.Size() >= ((UInt32)1 << 31)) @@ -1012,7 +1018,7 @@ if (item.CompressHeader.IsCorrect) { - item.decmpfs_AttrIndex = attrIndex; + item.decmpfs_AttrIndex = (int)attrIndex; skip = true; if (item.CompressHeader.Method < sizeof(MethodsMask) * 8) MethodsMask |= ((UInt32)1 << item.CompressHeader.Method); @@ -1025,13 +1031,13 @@ HRESULT CDatabase::LoadCatalog(const CFork &fork, const CObjectVector *overflowExtentsArray, IInStream *inStream, IArchiveOpenCallback *progress) { CByteBuffer buf; - RINOK(ReadFile(fork, buf, inStream)); + RINOK(ReadFile(fork, buf, inStream)) const Byte *p = (const Byte *)buf; // CNodeDescriptor nodeDesc; // nodeDesc.Parse(p); CHeaderRec hr; - RINOK(hr.Parse2(buf)); + RINOK(hr.Parse2(buf)) CRecordVector IdToIndexMap; @@ -1196,7 +1202,7 @@ if (progress && (Items.Size() & 0xFFF) == 0) { const UInt64 numItems = Items.Size(); - RINOK(progress->SetCompleted(&numItems, NULL)); + RINOK(progress->SetCompleted(&numItems, NULL)) } } node = desc.fLink; @@ -1265,7 +1271,7 @@ ThereAreAltStreams = true; ref.AttrIndex = kAttrIndex_Resource; - ref.Parent = Refs.Size() - 1; + ref.Parent = (int)(Refs.Size() - 1); Refs.Add(ref); #endif @@ -1311,7 +1317,7 @@ ThereAreAltStreams = true; CRef ref; - ref.AttrIndex = i; + ref.AttrIndex = (int)i; ref.Parent = refIndex; ref.ItemIndex = Refs[refIndex].ItemIndex; Refs.Add(ref); @@ -1352,7 +1358,7 @@ { Clear(); Byte buf[kHfsHeaderSize]; - RINOK(ReadStream_FALSE(inStream, buf, kHfsHeaderSize)); + RINOK(ReadStream_FALSE(inStream, buf, kHfsHeaderSize)) { for (unsigned i = 0; i < kHeaderPadSize; i++) if (buf[i] != 0) @@ -1388,7 +1394,7 @@ if (progress) { UInt64 numFiles = (UInt64)h.NumFiles + h.NumFolders + 1; - RINOK(progress->SetTotal(&numFiles, NULL)); + RINOK(progress->SetTotal(&numFiles, NULL)) } h.NumFreeBlocks = Get16(p + 0x22); */ @@ -1420,8 +1426,8 @@ UInt64 phy = SpecOffset + ((UInt64)blockCount << h.BlockSizeLog); if (PhySize2 < phy) PhySize2 = phy; - RINOK(inStream->Seek(SpecOffset, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(inStream, buf, kHfsHeaderSize)); + RINOK(InStream_SeekSet(inStream, SpecOffset)) + RINOK(ReadStream_FALSE(inStream, buf, kHfsHeaderSize)) } if (p[0] != 'H' || (p[1] != '+' && p[1] != 'X')) @@ -1446,12 +1452,12 @@ h.NumFiles > ((UInt32)1 << 30)) return S_FALSE; - RINOK(inStream->Seek(0, STREAM_SEEK_END, &ArcFileSize)); + RINOK(InStream_GetSize_SeekToEnd(inStream, ArcFileSize)) if (progress) { const UInt64 numFiles = (UInt64)h.NumFiles + h.NumFolders + 1; - RINOK(progress->SetTotal(&numFiles, NULL)); + RINOK(progress->SetTotal(&numFiles, NULL)) } UInt32 blockSize = Get32(p + 0x28); @@ -1504,10 +1510,10 @@ else { if (attrFork.Size != 0) - RINOK(LoadAttrs(attrFork, inStream, progress)); + RINOK(LoadAttrs(attrFork, inStream, progress)) } - RINOK(LoadCatalog(catalogFork, overflowExtents, inStream, progress)); + RINOK(LoadCatalog(catalogFork, overflowExtents, inStream, progress)) PhySize = Header.GetPhySize(); return S_OK; @@ -1515,22 +1521,20 @@ -class CHandler: +Z7_class_CHandler_final: public IInArchive, public IArchiveGetRawProps, public IInArchiveGetStream, public CMyUnknownImp, public CDatabase { - CMyComPtr _stream; + Z7_IFACES_IMP_UNK_3( + IInArchive, + IArchiveGetRawProps, + IInArchiveGetStream) + CMyComPtr _stream; HRESULT GetForkStream(const CFork &fork, ISequentialInStream **stream); - -public: - MY_UNKNOWN_IMP3(IInArchive, IArchiveGetRawProps, IInArchiveGetStream) - INTERFACE_IInArchive(;) - INTERFACE_IArchiveGetRawProps(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); }; static const Byte kProps[] = @@ -1576,7 +1580,7 @@ prop.SetAsTimeFrom_FT_Prec(ft, k_PropVar_TimePrec_Base); } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -1624,20 +1628,20 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) +Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps)) { *numProps = 0; return S_OK; } -STDMETHODIMP CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID) +Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID)) { *name = NULL; *propID = 0; return S_OK; } -STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType) +Z7_COM7F_IMF(CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType)) { const CRef &ref = Refs[index]; *parentType = ref.IsAltStream() ? @@ -1647,7 +1651,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) +Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType)) { *data = NULL; *dataSize = 0; @@ -1675,7 +1679,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -1761,19 +1765,19 @@ COM_TRY_END } -STDMETHODIMP CHandler::Open(IInStream *inStream, +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback *callback) + IArchiveOpenCallback *callback)) { COM_TRY_BEGIN Close(); - RINOK(Open2(inStream, callback)); + RINOK(Open2(inStream, callback)) _stream = inStream; return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _stream.Release(); Clear(); @@ -1802,7 +1806,7 @@ const size_t kBufSize = kCompressionBlockSize; _buf.Alloc(kBufSize + 0x10); // we need 1 additional bytes for uncompressed chunk header - RINOK(ReadStream_FALSE(inStream, _buf, kHeaderSize)); + RINOK(ReadStream_FALSE(inStream, _buf, kHeaderSize)) Byte *buf = _buf; const UInt32 dataPos = Get32(buf); const UInt32 mapPos = Get32(buf + 4); @@ -1837,7 +1841,7 @@ _tableBuf.AllocAtLeast(tableSize); - RINOK(ReadStream_FALSE(inStream, _tableBuf, tableSize)); + RINOK(ReadStream_FALSE(inStream, _tableBuf, tableSize)) const Byte *tableBuf = _tableBuf; UInt32 prev = 4 + tableSize; @@ -1878,7 +1882,7 @@ if (size > kCompressionBlockSize + 1) return S_FALSE; - RINOK(ReadStream_FALSE(inStream, buf, size)); + RINOK(ReadStream_FALSE(inStream, buf, size)) if ((buf[0] & 0xF) == 0xF) { @@ -1889,14 +1893,14 @@ if (outStream) { - RINOK(WriteStream(outStream, buf, blockSize)); + RINOK(WriteStream(outStream, buf + 1, blockSize)) } } else { const UInt64 blockSize64 = blockSize; bufInStreamSpec->Init(buf, size); - RINOK(_zlibDecoderSpec->Code(bufInStream, outStream, NULL, &blockSize64, NULL)); + RINOK(_zlibDecoder->Code(bufInStream, outStream, NULL, &blockSize64, NULL)) if (_zlibDecoderSpec->GetOutputProcessedSize() != blockSize) return S_FALSE; const UInt64 inSize = _zlibDecoderSpec->GetInputProcessedSize(); @@ -1928,7 +1932,7 @@ if ((i & 0xFF) == 0) { const UInt64 progressPos = progressStart + outPos; - RINOK(extractCallback->SetCompleted(&progressPos)); + RINOK(extractCallback->SetCompleted(&progressPos)) } } @@ -1940,7 +1944,7 @@ /* We check Resource Map Are there HFS files with another values in Resource Map ??? */ - RINOK(ReadStream_FALSE(inStream, buf, mapSize)); + RINOK(ReadStream_FALSE(inStream, buf, mapSize)) const UInt32 types = Get16(buf + 24); const UInt32 names = Get16(buf + 26); const UInt32 numTypes = Get16(buf + 28); @@ -1980,7 +1984,7 @@ if (tableSize > forkSize) return S_FALSE; _tableBuf.AllocAtLeast(tableSize); - RINOK(ReadStream_FALSE(inStream, _tableBuf, tableSize)); + RINOK(ReadStream_FALSE(inStream, _tableBuf, tableSize)) const Byte *tableBuf = _tableBuf; { @@ -2022,7 +2026,7 @@ if (size > kCompressionBlockSize + 1) return S_FALSE; - RINOK(ReadStream_FALSE(inStream, _buf, size)); + RINOK(ReadStream_FALSE(inStream, _buf, size)) const Byte *buf = _buf; if (buf[0] == k_LZVN_Uncompressed_Marker) @@ -2031,7 +2035,7 @@ return S_FALSE; if (outStream) { - RINOK(WriteStream(outStream, buf, blockSize)); + RINOK(WriteStream(outStream, buf + 1, blockSize)) } } else @@ -2039,7 +2043,7 @@ const UInt64 blockSize64 = blockSize; const UInt64 packSize64 = size; bufInStreamSpec->Init(buf, size); - RINOK(_lzfseDecoderSpec->Code(bufInStream, outStream, &packSize64, &blockSize64, NULL)); + RINOK(_lzfseDecoder->Code(bufInStream, outStream, &packSize64, &blockSize64, NULL)) // in/out sizes were checked in Code() } @@ -2047,7 +2051,7 @@ if ((i & 0xFF) == 0) { const UInt64 progressPos = progressStart + outPos; - RINOK(extractCallback->SetCompleted(&progressPos)); + RINOK(extractCallback->SetCompleted(&progressPos)) } } @@ -2055,6 +2059,186 @@ } +/* +static UInt32 GetUi24(const Byte *p) +{ + return p[0] + ((UInt32)p[1] << 8) + ((UInt32)p[2] << 24); +} + +HRESULT CDecoder::ExtractResourceFork_ZBM( + ISequentialInStream *inStream, ISequentialOutStream *outStream, + UInt64 forkSize, UInt64 unpackSize, + UInt64 progressStart, IArchiveExtractCallback *extractCallback) +{ + const UInt32 kNumBlocksMax = (UInt32)1 << 29; + if (unpackSize >= (UInt64)kNumBlocksMax * kCompressionBlockSize) + return S_FALSE; + const UInt32 numBlocks = (UInt32)((unpackSize + kCompressionBlockSize - 1) / kCompressionBlockSize); + const UInt32 numBlocks2 = numBlocks + 1; + const UInt32 tableSize = (numBlocks2 << 2); + if (tableSize > forkSize) + return S_FALSE; + _tableBuf.AllocAtLeast(tableSize); + RINOK(ReadStream_FALSE(inStream, _tableBuf, tableSize)); + const Byte *tableBuf = _tableBuf; + + { + UInt32 prev = GetUi32(tableBuf); + if (prev != tableSize) + return S_FALSE; + for (UInt32 i = 1; i < numBlocks2; i++) + { + const UInt32 offs = GetUi32(tableBuf + i * 4); + if (offs <= prev) + return S_FALSE; + prev = offs; + } + if (prev != forkSize) + return S_FALSE; + } + + const size_t kBufSize = kCompressionBlockSize; + _buf.Alloc(kBufSize + 0x10); // we need 1 additional bytes for uncompressed chunk header + + CBufInStream *bufInStreamSpec = new CBufInStream; + CMyComPtr bufInStream = bufInStreamSpec; + + UInt64 outPos = 0; + + for (UInt32 i = 0; i < numBlocks; i++) + { + const UInt64 rem = unpackSize - outPos; + if (rem == 0) + return S_FALSE; + UInt32 blockSize = kCompressionBlockSize; + if (rem < kCompressionBlockSize) + blockSize = (UInt32)rem; + + const UInt32 size = + GetUi32(tableBuf + i * 4 + 4) - + GetUi32(tableBuf + i * 4); + + // if (size > kCompressionBlockSize + 1) + if (size > blockSize + 1) + return S_FALSE; // we don't expect it, because encode will use uncompressed chunk + + RINOK(ReadStream_FALSE(inStream, _buf, size)); + const Byte *buf = _buf; + + // (size != 0) + // if (size == 0) return S_FALSE; + + if (buf[0] == 0xFF) // uncompressed marker + { + if (size != blockSize + 1) + return S_FALSE; + if (outStream) + { + RINOK(WriteStream(outStream, buf + 1, blockSize)); + } + } + else + { + if (size < 4) + return S_FALSE; + if (buf[0] != 'Z' || + buf[1] != 'B' || + buf[2] != 'M' || + buf[3] != 9) + return S_FALSE; + // for debug: + unsigned packPos = 4; + unsigned unpackPos = 0; + unsigned packRem = size - packPos; + for (;;) + { + if (packRem < 6) + return S_FALSE; + const UInt32 packSize = GetUi24(buf + packPos); + const UInt32 chunkUnpackSize = GetUi24(buf + packPos + 3); + if (packSize < 6) + return S_FALSE; + if (packSize > packRem) + return S_FALSE; + if (chunkUnpackSize > blockSize - unpackPos) + return S_FALSE; + packPos += packSize; + packRem -= packSize; + unpackPos += chunkUnpackSize; + if (packSize == 6) + { + if (chunkUnpackSize != 0) + return S_FALSE; + break; + } + if (packSize >= chunkUnpackSize + 6) + { + if (packSize > chunkUnpackSize + 6) + return S_FALSE; + // uncompressed chunk; + } + else + { + // compressed chunk + const Byte *t = buf + packPos - packSize + 6; + UInt32 r = packSize - 6; + if (r < 9) + return S_FALSE; + const UInt32 v0 = GetUi24(t); + const UInt32 v1 = GetUi24(t + 3); + const UInt32 v2 = GetUi24(t + 6); + if (v0 > v1 || v1 > v2 || v2 > packSize) + return S_FALSE; + // here we need the code that will decompress ZBM chunk + } + } + + if (unpackPos != blockSize) + return S_FALSE; + + UInt32 size1 = size; + if (size1 > kCompressionBlockSize) + { + size1 = kCompressionBlockSize; + // return S_FALSE; + } + if (outStream) + { + RINOK(WriteStream(outStream, buf, size1)) + + const UInt32 kTempSize = 1 << 16; + Byte temp[kTempSize]; + memset(temp, 0, kTempSize); + + for (UInt32 k = size1; k < kCompressionBlockSize; k++) + { + UInt32 cur = kCompressionBlockSize - k; + if (cur > kTempSize) + cur = kTempSize; + RINOK(WriteStream(outStream, temp, cur)) + k += cur; + } + } + + // const UInt64 blockSize64 = blockSize; + // const UInt64 packSize64 = size; + // bufInStreamSpec->Init(buf, size); + // RINOK(_zbmDecoderSpec->Code(bufInStream, outStream, &packSize64, &blockSize64, NULL)); + // in/out sizes were checked in Code() + } + + outPos += blockSize; + if ((i & 0xFF) == 0) + { + const UInt64 progressPos = progressStart + outPos; + RINOK(extractCallback->SetCompleted(&progressPos)); + } + } + + return S_OK; +} +*/ + HRESULT CDecoder::Extract( ISequentialInStream *inStreamFork, ISequentialOutStream *realOutStream, UInt64 forkSize, @@ -2070,7 +2254,7 @@ const size_t packSize = data->Size() - compressHeader.DataPos; if (realOutStream) { - RINOK(WriteStream(realOutStream, *data + compressHeader.DataPos, packSize)); + RINOK(WriteStream(realOutStream, *data + compressHeader.DataPos, packSize)) } opRes = NExtract::NOperationResult::kOK; return S_OK; @@ -2122,6 +2306,15 @@ forkSize, compressHeader.UnpackSize, progressStart, extractCallback); } + /* + else if (compressHeader.Method == NHfs::kMethod_ZBM_RSRC) + { + hres = ExtractResourceFork_ZBM( + inStreamFork, realOutStream, + forkSize, compressHeader.UnpackSize, + progressStart, extractCallback); + } + */ else { opRes = NExtract::NOperationResult::kUnsupportedMethod; @@ -2134,8 +2327,8 @@ } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN const bool allFilesMode = (numItems == (UInt32)(Int32)-1); @@ -2150,7 +2343,7 @@ const CRef &ref = Refs[allFilesMode ? i : indices[i]]; totalSize += Get_UnpackSize_of_Ref(ref); } - RINOK(extractCallback->SetTotal(totalSize)); + RINOK(extractCallback->SetTotal(totalSize)) UInt64 currentTotalSize = 0, currentItemSize = 0; @@ -2161,30 +2354,30 @@ for (i = 0;; i++, currentTotalSize += currentItemSize) { - RINOK(extractCallback->SetCompleted(¤tTotalSize)); + RINOK(extractCallback->SetCompleted(¤tTotalSize)) if (i == numItems) break; - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; const CRef &ref = Refs[index]; const CItem &item = Items[ref.ItemIndex]; currentItemSize = Get_UnpackSize_of_Ref(ref); CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) if (ref.IsItem() && item.IsDir()) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) UInt64 pos = 0; int opRes = NExtract::NOperationResult::kDataError; @@ -2203,7 +2396,7 @@ RINOK(WriteStream(realOutStream, // AttrBuf + attr.Pos, attr.Size attr.Data, attr.Data.Size() - )); + )) } } } @@ -2258,7 +2451,7 @@ if (fork->Size == pos) break; const CExtent &e = fork->Extents[extentIndex]; - RINOK(_stream->Seek(SpecOffset + ((UInt64)e.Pos << Header.BlockSizeLog), STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_stream, SpecOffset + ((UInt64)e.Pos << Header.BlockSizeLog))) UInt64 extentRem = (UInt64)e.NumBlocks << Header.BlockSizeLog; while (extentRem != 0) { @@ -2275,7 +2468,7 @@ cur = (size_t)rem; if (cur > extentRem) cur = (size_t)extentRem; - RINOK(ReadStream(_stream, buf, &cur)); + RINOK(ReadStream(_stream, buf, &cur)) if (cur == 0) { opRes = NExtract::NOperationResult::kDataError; @@ -2283,12 +2476,12 @@ } if (realOutStream) { - RINOK(WriteStream(realOutStream, buf, cur)); + RINOK(WriteStream(realOutStream, buf, cur)) } pos += cur; extentRem -= cur; const UInt64 processed = currentTotalSize + pos; - RINOK(extractCallback->SetCompleted(&processed)); + RINOK(extractCallback->SetCompleted(&processed)) } } if (extentIndex != fork->Extents.Size() || fork->Size != pos) @@ -2296,13 +2489,13 @@ } } realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = Refs.Size(); return S_OK; @@ -2310,7 +2503,7 @@ HRESULT CHandler::GetForkStream(const CFork &fork, ISequentialInStream **stream) { - *stream = 0; + *stream = NULL; if (!fork.IsOk(Header.BlockSizeLog)) return S_FALSE; @@ -2354,9 +2547,9 @@ return S_OK; } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { - *stream = 0; + *stream = NULL; const CRef &ref = Refs[index]; const CFork *fork = NULL; @@ -2388,7 +2581,7 @@ 4, 'H', 'X', 0, 5 }; REGISTER_ARC_I( - "HFS", "hfs hfsx", 0, 0xE3, + "HFS", "hfs hfsx", NULL, 0xE3, k_Signature, kHeaderPadSize, NArcInfoFlags::kMultiSignature, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/HfsHandler.h 7zip-23.01+dfsg/CPP/7zip/Archive/HfsHandler.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/HfsHandler.h 2022-07-10 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/HfsHandler.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // HfsHandler.h -#ifndef __HFS_HANDLER_H -#define __HFS_HANDLER_H +#ifndef ZIP7_INC_HFS_HANDLER_H +#define ZIP7_INC_HFS_HANDLER_H #include "../../Windows/PropVariant.h" @@ -66,6 +66,11 @@ ISequentialInStream *inStream, ISequentialOutStream *realOutStream, UInt64 forkSize, UInt64 unpackSize, UInt64 progressStart, IArchiveExtractCallback *extractCallback); + + HRESULT ExtractResourceFork_ZBM( + ISequentialInStream *inStream, ISequentialOutStream *realOutStream, + UInt64 forkSize, UInt64 unpackSize, + UInt64 progressStart, IArchiveExtractCallback *extractCallback); public: diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/IArchive.h 7zip-23.01+dfsg/CPP/7zip/Archive/IArchive.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/IArchive.h 2022-05-10 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/IArchive.h 2023-03-24 20:00:00.000000000 +0000 @@ -1,14 +1,21 @@ // IArchive.h -#ifndef __IARCHIVE_H -#define __IARCHIVE_H +#ifndef ZIP7_INC_IARCHIVE_H +#define ZIP7_INC_IARCHIVE_H #include "../IProgress.h" #include "../IStream.h" #include "../PropID.h" -#define ARCHIVE_INTERFACE_SUB(i, base, x) DECL_INTERFACE_SUB(i, base, 6, x) -#define ARCHIVE_INTERFACE(i, x) ARCHIVE_INTERFACE_SUB(i, IUnknown, x) +Z7_PURE_INTERFACES_BEGIN + + +#define Z7_IFACE_CONSTR_ARCHIVE_SUB(i, base, n) \ + Z7_DECL_IFACE_7ZIP_SUB(i, base, 6, n) \ + { Z7_IFACE_COM7_PURE(i) }; + +#define Z7_IFACE_CONSTR_ARCHIVE(i, n) \ + Z7_IFACE_CONSTR_ARCHIVE_SUB(i, IUnknown, n) /* How the function in 7-Zip returns object for output parameter via pointer @@ -81,11 +88,11 @@ const unsigned kTime_Prec_Default_num_bits = 5; } -#define TIME_PREC_TO_ARC_FLAGS_MASK(x) \ - ((UInt32)1 << (NArcInfoTimeFlags::kTime_Prec_Mask_bit_index + (x))) +#define TIME_PREC_TO_ARC_FLAGS_MASK(v) \ + ((UInt32)1 << (NArcInfoTimeFlags::kTime_Prec_Mask_bit_index + (v))) -#define TIME_PREC_TO_ARC_FLAGS_TIME_DEFAULT(x) \ - ((UInt32)(x) << NArcInfoTimeFlags::kTime_Prec_Default_bit_index) +#define TIME_PREC_TO_ARC_FLAGS_TIME_DEFAULT(v) \ + ((UInt32)(v) << NArcInfoTimeFlags::kTime_Prec_Default_bit_index) namespace NArchive { @@ -136,6 +143,7 @@ kIsNotArc, kHeadersError, kWrongPassword + // , kMemError }; } } @@ -166,14 +174,11 @@ } } -#define INTERFACE_IArchiveOpenCallback(x) \ - STDMETHOD(SetTotal)(const UInt64 *files, const UInt64 *bytes) x; \ - STDMETHOD(SetCompleted)(const UInt64 *files, const UInt64 *bytes) x; \ +#define Z7_IFACEM_IArchiveOpenCallback(x) \ + x(SetTotal(const UInt64 *files, const UInt64 *bytes)) \ + x(SetCompleted(const UInt64 *files, const UInt64 *bytes)) \ -ARCHIVE_INTERFACE(IArchiveOpenCallback, 0x10) -{ - INTERFACE_IArchiveOpenCallback(PURE); -}; +Z7_IFACE_CONSTR_ARCHIVE(IArchiveOpenCallback, 0x10) /* IArchiveExtractCallback:: @@ -224,57 +229,49 @@ Int32 opRes (NExtract::NOperationResult) */ -#define INTERFACE_IArchiveExtractCallback(x) \ - INTERFACE_IProgress(x) \ - STDMETHOD(GetStream)(UInt32 index, ISequentialOutStream **outStream, Int32 askExtractMode) x; \ - STDMETHOD(PrepareOperation)(Int32 askExtractMode) x; \ - STDMETHOD(SetOperationResult)(Int32 opRes) x; \ +// INTERFACE_IProgress(x) -ARCHIVE_INTERFACE_SUB(IArchiveExtractCallback, IProgress, 0x20) -{ - INTERFACE_IArchiveExtractCallback(PURE) -}; +#define Z7_IFACEM_IArchiveExtractCallback(x) \ + x(GetStream(UInt32 index, ISequentialOutStream **outStream, Int32 askExtractMode)) \ + x(PrepareOperation(Int32 askExtractMode)) \ + x(SetOperationResult(Int32 opRes)) \ + +Z7_IFACE_CONSTR_ARCHIVE_SUB(IArchiveExtractCallback, IProgress, 0x20) /* -IArchiveExtractCallbackMessage can be requested from IArchiveExtractCallback object +v23: +IArchiveExtractCallbackMessage2 can be requested from IArchiveExtractCallback object by Extract() or UpdateItems() functions to report about extracting errors ReportExtractResult() UInt32 indexType (NEventIndexType) UInt32 index Int32 opRes (NExtract::NOperationResult) */ - -#define INTERFACE_IArchiveExtractCallbackMessage(x) \ - STDMETHOD(ReportExtractResult)(UInt32 indexType, UInt32 index, Int32 opRes) x; \ - -ARCHIVE_INTERFACE_SUB(IArchiveExtractCallbackMessage, IProgress, 0x21) -{ - INTERFACE_IArchiveExtractCallbackMessage(PURE) -}; - - -#define INTERFACE_IArchiveOpenVolumeCallback(x) \ - STDMETHOD(GetProperty)(PROPID propID, PROPVARIANT *value) x; \ - STDMETHOD(GetStream)(const wchar_t *name, IInStream **inStream) x; \ - -ARCHIVE_INTERFACE(IArchiveOpenVolumeCallback, 0x30) -{ - INTERFACE_IArchiveOpenVolumeCallback(PURE); -}; - - -ARCHIVE_INTERFACE(IInArchiveGetStream, 0x40) -{ - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream) PURE; -}; - - -ARCHIVE_INTERFACE(IArchiveOpenSetSubArchiveName, 0x50) -{ - STDMETHOD(SetSubArchiveName)(const wchar_t *name) PURE; -}; +/* +before v23: +#define Z7_IFACEM_IArchiveExtractCallbackMessage(x) \ + x(ReportExtractResult(UInt32 indexType, UInt32 index, Int32 opRes)) +Z7_IFACE_CONSTR_ARCHIVE_SUB(IArchiveExtractCallbackMessage, IProgress, 0x21) +*/ +#define Z7_IFACEM_IArchiveExtractCallbackMessage2(x) \ + x(ReportExtractResult(UInt32 indexType, UInt32 index, Int32 opRes)) +Z7_IFACE_CONSTR_ARCHIVE(IArchiveExtractCallbackMessage2, 0x22) + +#define Z7_IFACEM_IArchiveOpenVolumeCallback(x) \ + x(GetProperty(PROPID propID, PROPVARIANT *value)) \ + x(GetStream(const wchar_t *name, IInStream **inStream)) +Z7_IFACE_CONSTR_ARCHIVE(IArchiveOpenVolumeCallback, 0x30) + + +#define Z7_IFACEM_IInArchiveGetStream(x) \ + x(GetStream(UInt32 index, ISequentialInStream **stream)) +Z7_IFACE_CONSTR_ARCHIVE(IInArchiveGetStream, 0x40) + +#define Z7_IFACEM_IArchiveOpenSetSubArchiveName(x) \ + x(SetSubArchiveName(const wchar_t *name)) +Z7_IFACE_CONSTR_ARCHIVE(IArchiveOpenSetSubArchiveName, 0x50) /* @@ -310,28 +307,25 @@ Some IInArchive handlers will work incorrectly in that case. */ -#ifdef _MSC_VER - #define MY_NO_THROW_DECL_ONLY throw() +#if defined(_MSC_VER) && !defined(__clang__) + #define MY_NO_THROW_DECL_ONLY Z7_COM7F_E #else #define MY_NO_THROW_DECL_ONLY #endif -#define INTERFACE_IInArchive(x) \ - STDMETHOD(Open)(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(Close)() MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(GetNumberOfItems)(UInt32 *numItems) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(Extract)(const UInt32* indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(GetArchiveProperty)(PROPID propID, PROPVARIANT *value) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(GetNumberOfProperties)(UInt32 *numProps) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(GetPropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(GetNumberOfArchiveProperties)(UInt32 *numProps) MY_NO_THROW_DECL_ONLY x; \ - STDMETHOD(GetArchivePropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) MY_NO_THROW_DECL_ONLY x; \ +#define Z7_IFACEM_IInArchive(x) \ + x(Open(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback)) \ + x(Close()) \ + x(GetNumberOfItems(UInt32 *numItems)) \ + x(GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) \ + x(Extract(const UInt32 *indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback)) \ + x(GetArchiveProperty(PROPID propID, PROPVARIANT *value)) \ + x(GetNumberOfProperties(UInt32 *numProps)) \ + x(GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \ + x(GetNumberOfArchiveProperties(UInt32 *numProps)) \ + x(GetArchivePropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \ -ARCHIVE_INTERFACE(IInArchive, 0x60) -{ - INTERFACE_IInArchive(PURE) -}; +Z7_IFACE_CONSTR_ARCHIVE(IInArchive, 0x60) namespace NParentType { @@ -340,7 +334,7 @@ kDir = 0, kAltStream }; -}; +} namespace NPropDataType { @@ -356,41 +350,36 @@ const UInt32 kUtf8z = kMask_Utf8 | kMask_ZeroEnd; const UInt32 kUtf16z = kMask_Utf16 | kMask_ZeroEnd; -}; +} // UTF string (pointer to wchar_t) with zero end and little-endian. #define PROP_DATA_TYPE_wchar_t_PTR_Z_LE ((NPropDataType::kMask_Utf | NPropDataType::kMask_ZeroEnd) + (sizeof(wchar_t) >> 1)) + /* GetRawProp: Result: S_OK - even if property is not set */ -#define INTERFACE_IArchiveGetRawProps(x) \ - STDMETHOD(GetParent)(UInt32 index, UInt32 *parent, UInt32 *parentType) x; \ - STDMETHOD(GetRawProp)(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) x; \ - STDMETHOD(GetNumRawProps)(UInt32 *numProps) x; \ - STDMETHOD(GetRawPropInfo)(UInt32 index, BSTR *name, PROPID *propID) x; - -ARCHIVE_INTERFACE(IArchiveGetRawProps, 0x70) -{ - INTERFACE_IArchiveGetRawProps(PURE) -}; - -#define INTERFACE_IArchiveGetRootProps(x) \ - STDMETHOD(GetRootProp)(PROPID propID, PROPVARIANT *value) x; \ - STDMETHOD(GetRootRawProp)(PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) x; \ +#define Z7_IFACEM_IArchiveGetRawProps(x) \ + x(GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType)) \ + x(GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType)) \ + x(GetNumRawProps(UInt32 *numProps)) \ + x(GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID)) + +Z7_IFACE_CONSTR_ARCHIVE(IArchiveGetRawProps, 0x70) + +#define Z7_IFACEM_IArchiveGetRootProps(x) \ + x(GetRootProp(PROPID propID, PROPVARIANT *value)) \ + x(GetRootRawProp(PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType)) \ -ARCHIVE_INTERFACE(IArchiveGetRootProps, 0x71) -{ - INTERFACE_IArchiveGetRootProps(PURE) -}; +Z7_IFACE_CONSTR_ARCHIVE(IArchiveGetRootProps, 0x71) -ARCHIVE_INTERFACE(IArchiveOpenSeq, 0x61) -{ - STDMETHOD(OpenSeq)(ISequentialInStream *stream) PURE; -}; +#define Z7_IFACEM_IArchiveOpenSeq(x) \ + x(OpenSeq(ISequentialInStream *stream)) \ + +Z7_IFACE_CONSTR_ARCHIVE(IArchiveOpenSeq, 0x61) /* OpenForSize @@ -416,12 +405,10 @@ the handler can return S_OK, but it doesn't check even Signature. So next Extract can be called for that sequential stream. */ - /* -ARCHIVE_INTERFACE(IArchiveOpen2, 0x62) -{ - STDMETHOD(ArcOpen2)(ISequentialInStream *stream, UInt32 flags, IArchiveOpenCallback *openCallback) PURE; -}; +#define Z7_IFACEM_IArchiveOpen2(x) \ + x(ArcOpen2(ISequentialInStream *stream, UInt32 flags, IArchiveOpenCallback *openCallback)) +Z7_IFACE_CONSTR_ARCHIVE(IArchiveOpen2, 0x62) */ // ---------- UPDATE ---------- @@ -454,27 +441,21 @@ Int32 opRes (NExtract::NOperationResult::kOK) */ -#define INTERFACE_IArchiveUpdateCallback(x) \ - INTERFACE_IProgress(x); \ - STDMETHOD(GetUpdateItemInfo)(UInt32 index, Int32 *newData, Int32 *newProps, UInt32 *indexInArchive) x; \ - STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) x; \ - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **inStream) x; \ - STDMETHOD(SetOperationResult)(Int32 operationResult) x; \ - -ARCHIVE_INTERFACE_SUB(IArchiveUpdateCallback, IProgress, 0x80) -{ - INTERFACE_IArchiveUpdateCallback(PURE); -}; - -#define INTERFACE_IArchiveUpdateCallback2(x) \ - INTERFACE_IArchiveUpdateCallback(x) \ - STDMETHOD(GetVolumeSize)(UInt32 index, UInt64 *size) x; \ - STDMETHOD(GetVolumeStream)(UInt32 index, ISequentialOutStream **volumeStream) x; \ +// INTERFACE_IProgress(x) +#define Z7_IFACEM_IArchiveUpdateCallback(x) \ + x(GetUpdateItemInfo(UInt32 index, Int32 *newData, Int32 *newProps, UInt32 *indexInArchive)) \ + x(GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) \ + x(GetStream(UInt32 index, ISequentialInStream **inStream)) \ + x(SetOperationResult(Int32 operationResult)) \ + +Z7_IFACE_CONSTR_ARCHIVE_SUB(IArchiveUpdateCallback, IProgress, 0x80) + +// INTERFACE_IArchiveUpdateCallback(x) +#define Z7_IFACEM_IArchiveUpdateCallback2(x) \ + x(GetVolumeSize(UInt32 index, UInt64 *size)) \ + x(GetVolumeStream(UInt32 index, ISequentialOutStream **volumeStream)) \ -ARCHIVE_INTERFACE_SUB(IArchiveUpdateCallback2, IArchiveUpdateCallback, 0x82) -{ - INTERFACE_IArchiveUpdateCallback2(PURE); -}; +Z7_IFACE_CONSTR_ARCHIVE_SUB(IArchiveUpdateCallback2, IArchiveUpdateCallback, 0x82) namespace NUpdateNotifyOp { @@ -493,7 +474,7 @@ // , kOpFinished // , kNumDefined }; -}; +} /* IArchiveUpdateCallbackFile::ReportOperation @@ -502,36 +483,26 @@ UInt32 notifyOp (NUpdateNotifyOp) */ -#define INTERFACE_IArchiveUpdateCallbackFile(x) \ - STDMETHOD(GetStream2)(UInt32 index, ISequentialInStream **inStream, UInt32 notifyOp) x; \ - STDMETHOD(ReportOperation)(UInt32 indexType, UInt32 index, UInt32 notifyOp) x; \ +#define Z7_IFACEM_IArchiveUpdateCallbackFile(x) \ + x(GetStream2(UInt32 index, ISequentialInStream **inStream, UInt32 notifyOp)) \ + x(ReportOperation(UInt32 indexType, UInt32 index, UInt32 notifyOp)) \ -ARCHIVE_INTERFACE(IArchiveUpdateCallbackFile, 0x83) -{ - INTERFACE_IArchiveUpdateCallbackFile(PURE); -}; +Z7_IFACE_CONSTR_ARCHIVE(IArchiveUpdateCallbackFile, 0x83) -#define INTERFACE_IArchiveGetDiskProperty(x) \ - STDMETHOD(GetDiskProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) x; \ +#define Z7_IFACEM_IArchiveGetDiskProperty(x) \ + x(GetDiskProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) \ -ARCHIVE_INTERFACE(IArchiveGetDiskProperty, 0x84) -{ - INTERFACE_IArchiveGetDiskProperty(PURE); -}; +Z7_IFACE_CONSTR_ARCHIVE(IArchiveGetDiskProperty, 0x84) /* -#define INTERFACE_IArchiveUpdateCallbackArcProp(x) \ - STDMETHOD(ReportProp)(UInt32 indexType, UInt32 index, PROPID propID, const PROPVARIANT *value) x; \ - STDMETHOD(ReportRawProp)(UInt32 indexType, UInt32 index, PROPID propID, const void *data, UInt32 dataSize, UInt32 propType) x; \ - STDMETHOD(ReportFinished)(UInt32 indexType, UInt32 index, Int32 opRes) x; \ - STDMETHOD(DoNeedArcProp)(PROPID propID, Int32 *answer) x; \ +#define Z7_IFACEM_IArchiveUpdateCallbackArcProp(x) \ + x(ReportProp(UInt32 indexType, UInt32 index, PROPID propID, const PROPVARIANT *value)) \ + x(ReportRawProp(UInt32 indexType, UInt32 index, PROPID propID, const void *data, UInt32 dataSize, UInt32 propType)) \ + x(ReportFinished(UInt32 indexType, UInt32 index, Int32 opRes)) \ + x(DoNeedArcProp(PROPID propID, Int32 *answer)) \ - -ARCHIVE_INTERFACE(IArchiveUpdateCallbackArcProp, 0x85) -{ - INTERFACE_IArchiveUpdateCallbackArcProp(PURE); -}; +Z7_IFACE_CONSTR_ARCHIVE(IArchiveUpdateCallbackArcProp, 0x85) */ /* @@ -556,14 +527,11 @@ */ -#define INTERFACE_IOutArchive(x) \ - STDMETHOD(UpdateItems)(ISequentialOutStream *outStream, UInt32 numItems, IArchiveUpdateCallback *updateCallback) x; \ - STDMETHOD(GetFileTimeType)(UInt32 *type) x; +#define Z7_IFACEM_IOutArchive(x) \ + x(UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, IArchiveUpdateCallback *updateCallback)) \ + x(GetFileTimeType(UInt32 *type)) -ARCHIVE_INTERFACE(IOutArchive, 0xA0) -{ - INTERFACE_IOutArchive(PURE) -}; +Z7_IFACE_CONSTR_ARCHIVE(IOutArchive, 0xA0) /* @@ -576,31 +544,26 @@ VT_BSTR */ -ARCHIVE_INTERFACE(ISetProperties, 0x03) -{ - STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) PURE; -}; +#define Z7_IFACEM_ISetProperties(x) \ + x(SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps)) -ARCHIVE_INTERFACE(IArchiveKeepModeForNextOpen, 0x04) -{ - STDMETHOD(KeepModeForNextOpen)() PURE; -}; +Z7_IFACE_CONSTR_ARCHIVE(ISetProperties, 0x03) + +#define Z7_IFACEM_IArchiveKeepModeForNextOpen(x) \ + x(KeepModeForNextOpen()) \ + +Z7_IFACE_CONSTR_ARCHIVE(IArchiveKeepModeForNextOpen, 0x04) /* Exe handler: the handler for executable format (PE, ELF, Mach-O). SFX archive: executable stub + some tail data. before 9.31: exe handler didn't parse SFX archives as executable format. for 9.31+: exe handler parses SFX archives as executable format, only if AllowTail(1) was called */ -ARCHIVE_INTERFACE(IArchiveAllowTail, 0x05) -{ - STDMETHOD(AllowTail)(Int32 allowTail) PURE; -}; +#define Z7_IFACEM_IArchiveAllowTail(x) \ + x(AllowTail(Int32 allowTail)) \ +Z7_IFACE_CONSTR_ARCHIVE(IArchiveAllowTail, 0x05) -#define IMP_IInArchive_GetProp(k) \ - (UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) \ - { if (index >= ARRAY_SIZE(k)) return E_INVALIDARG; \ - *propID = k[index]; *varType = k7z_PROPID_To_VARTYPE[(unsigned)*propID]; *name = 0; return S_OK; } \ struct CStatProp @@ -616,46 +579,69 @@ BSTR AllocBstrFromAscii(const char *s) throw(); }} -#define IMP_IInArchive_GetProp_WITH_NAME(k) \ - (UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) \ - { if (index >= ARRAY_SIZE(k)) return E_INVALIDARG; \ + +#define IMP_IInArchive_GetProp_Base(fn, f, k) \ + Z7_COM7F_IMF(CHandler::fn(UInt32 *numProps)) \ + { *numProps = Z7_ARRAY_SIZE(k); return S_OK; } \ + Z7_COM7F_IMF(CHandler::f(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \ + { if (index >= Z7_ARRAY_SIZE(k)) return E_INVALIDARG; \ + +#define IMP_IInArchive_GetProp_NO_NAME(fn, f, k) \ + IMP_IInArchive_GetProp_Base(fn, f, k) \ + *propID = k[index]; \ + *varType = k7z_PROPID_To_VARTYPE[(unsigned)*propID]; \ + *name = NULL; return S_OK; } \ + +#define IMP_IInArchive_GetProp_WITH_NAME(fn, f, k) \ + IMP_IInArchive_GetProp_Base(fn, f, k) \ const CStatProp &prop = k[index]; \ - *propID = (PROPID)prop.PropID; *varType = prop.vt; \ + *propID = (PROPID)prop.PropID; \ + *varType = prop.vt; \ *name = NWindows::NCOM::AllocBstrFromAscii(prop.Name); return S_OK; } \ + #define IMP_IInArchive_Props \ - STDMETHODIMP CHandler::GetNumberOfProperties(UInt32 *numProps) \ - { *numProps = ARRAY_SIZE(kProps); return S_OK; } \ - STDMETHODIMP CHandler::GetPropertyInfo IMP_IInArchive_GetProp(kProps) + IMP_IInArchive_GetProp_NO_NAME(GetNumberOfProperties, GetPropertyInfo, kProps) #define IMP_IInArchive_Props_WITH_NAME \ - STDMETHODIMP CHandler::GetNumberOfProperties(UInt32 *numProps) \ - { *numProps = ARRAY_SIZE(kProps); return S_OK; } \ - STDMETHODIMP CHandler::GetPropertyInfo IMP_IInArchive_GetProp_WITH_NAME(kProps) - + IMP_IInArchive_GetProp_WITH_NAME(GetNumberOfProperties, GetPropertyInfo, kProps) #define IMP_IInArchive_ArcProps \ - STDMETHODIMP CHandler::GetNumberOfArchiveProperties(UInt32 *numProps) \ - { *numProps = ARRAY_SIZE(kArcProps); return S_OK; } \ - STDMETHODIMP CHandler::GetArchivePropertyInfo IMP_IInArchive_GetProp(kArcProps) + IMP_IInArchive_GetProp_NO_NAME(GetNumberOfArchiveProperties, GetArchivePropertyInfo, kArcProps) #define IMP_IInArchive_ArcProps_WITH_NAME \ - STDMETHODIMP CHandler::GetNumberOfArchiveProperties(UInt32 *numProps) \ - { *numProps = ARRAY_SIZE(kArcProps); return S_OK; } \ - STDMETHODIMP CHandler::GetArchivePropertyInfo IMP_IInArchive_GetProp_WITH_NAME(kArcProps) + IMP_IInArchive_GetProp_WITH_NAME(GetNumberOfArchiveProperties, GetArchivePropertyInfo, kArcProps) #define IMP_IInArchive_ArcProps_NO_Table \ - STDMETHODIMP CHandler::GetNumberOfArchiveProperties(UInt32 *numProps) \ + Z7_COM7F_IMF(CHandler::GetNumberOfArchiveProperties(UInt32 *numProps)) \ { *numProps = 0; return S_OK; } \ - STDMETHODIMP CHandler::GetArchivePropertyInfo(UInt32, BSTR *, PROPID *, VARTYPE *) \ + Z7_COM7F_IMF(CHandler::GetArchivePropertyInfo(UInt32, BSTR *, PROPID *, VARTYPE *)) \ { return E_NOTIMPL; } \ #define IMP_IInArchive_ArcProps_NO \ IMP_IInArchive_ArcProps_NO_Table \ - STDMETHODIMP CHandler::GetArchiveProperty(PROPID, PROPVARIANT *value) \ + Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID, PROPVARIANT *value)) \ { value->vt = VT_EMPTY; return S_OK; } +#define Z7_class_CHandler_final \ + Z7_class_final(CHandler) + + +#define Z7_CLASS_IMP_CHandler_IInArchive_0 \ + Z7_CLASS_IMP_COM_1(CHandler, IInArchive) +#define Z7_CLASS_IMP_CHandler_IInArchive_1(i1) \ + Z7_CLASS_IMP_COM_2(CHandler, IInArchive, i1) +#define Z7_CLASS_IMP_CHandler_IInArchive_2(i1, i2) \ + Z7_CLASS_IMP_COM_3(CHandler, IInArchive, i1, i2) +#define Z7_CLASS_IMP_CHandler_IInArchive_3(i1, i2, i3) \ + Z7_CLASS_IMP_COM_4(CHandler, IInArchive, i1, i2, i3) +#define Z7_CLASS_IMP_CHandler_IInArchive_4(i1, i2, i3, i4) \ + Z7_CLASS_IMP_COM_5(CHandler, IInArchive, i1, i2, i3, i4) +#define Z7_CLASS_IMP_CHandler_IInArchive_5(i1, i2, i3, i4, i5) \ + Z7_CLASS_IMP_COM_6(CHandler, IInArchive, i1, i2, i3, i4, i5) + + #define k_IsArc_Res_NO 0 #define k_IsArc_Res_YES 1 @@ -714,4 +700,5 @@ NFileTimeType::kWindows)) */ +Z7_PURE_INTERFACES_END #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/IhexHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/IhexHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/IhexHandler.cpp 2021-01-26 09:46:16.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/IhexHandler.cpp 2023-03-27 09:00:00.000000000 +0000 @@ -27,10 +27,9 @@ UInt32 Offset; }; -class CHandler: - public IInArchive, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_CHandler_IInArchive_0 + bool _isArc; bool _needMoreInput; bool _dataError; @@ -38,9 +37,6 @@ UInt64 _phySize; CObjectVector _blocks; -public: - MY_UNKNOWN_IMP1(IInArchive) - INTERFACE_IInArchive(;) }; static const Byte kProps[] = @@ -53,13 +49,13 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps_NO_Table -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _blocks.Size(); return S_OK; } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { NWindows::NCOM::CPropVariant prop; switch (propID) @@ -68,7 +64,7 @@ case kpidErrorFlags: { UInt32 v = 0; - if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;; + if (!_isArc) v |= kpv_ErrorFlags_IsNotArc; if (_needMoreInput) v |= kpv_ErrorFlags_UnexpectedEnd; if (_dataError) v |= kpv_ErrorFlags_DataError; prop = v; @@ -78,7 +74,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -105,16 +101,16 @@ static inline int HexToByte(unsigned c) { - if (c >= '0' && c <= '9') return c - '0'; - if (c >= 'A' && c <= 'F') return c - 'A' + 10; - if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= '0' && c <= '9') return (int)(c - '0'); + if (c >= 'A' && c <= 'F') return (int)(c - 'A' + 10); + if (c >= 'a' && c <= 'f') return (int)(c - 'a' + 10); return -1; } static int Parse(const Byte *p) { - int c1 = HexToByte(p[0]); if (c1 < 0) return -1; - int c2 = HexToByte(p[1]); if (c2 < 0) return -1; + const int c1 = HexToByte(p[0]); if (c1 < 0) return -1; + const int c2 = HexToByte(p[1]); if (c2 < 0) return -1; return (c1 << 4) | c2; } @@ -207,7 +203,7 @@ { if (size == 0) return k_IsArc_Res_NEED_MORE; - char b = *p++; + const Byte b = *p++; size--; if (IS_LINE_DELIMITER(b)) continue; @@ -221,7 +217,7 @@ } } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *)) { COM_TRY_BEGIN { @@ -232,7 +228,7 @@ Byte temp[kStartSize]; { size_t size = kStartSize; - RINOK(ReadStream(stream, temp, &size)); + RINOK(ReadStream(stream, temp, &size)) UInt32 isArcRes = IsArc_Ihex(temp, size); if (isArcRes == k_IsArc_Res_NO) return S_FALSE; @@ -241,7 +237,7 @@ } _isArc = true; - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(stream)) CInBuffer s; if (!s.Create(1 << 15)) return E_OUTOFMEMORY; @@ -271,7 +267,7 @@ _needMoreInput = true; return S_FALSE; } - int num = Parse(temp); + const int num = Parse(temp); if (num < 0) { _dataError = true; @@ -287,17 +283,17 @@ return S_FALSE; } - unsigned sum = num; + unsigned sum = (unsigned)num; for (size_t i = 0; i < numPairs; i++) { - int a = Parse(temp + i * 2); + const int a = Parse(temp + i * 2); if (a < 0) { _dataError = true; return S_FALSE; } temp[i] = (Byte)a; - sum += a; + sum += (unsigned)a; } if ((sum & 0xFF) != 0) { @@ -413,7 +409,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _phySize = 0; @@ -426,11 +422,11 @@ } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _blocks.Size(); if (numItems == 0) @@ -453,18 +449,18 @@ { currentItemSize = 0; lps->InSize = lps->OutSize = currentTotalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; const CByteDynamicBuffer &data = _blocks[index].Data; currentItemSize = data.GetPos(); CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) if (!testMode && !realOutStream) continue; @@ -473,11 +469,11 @@ if (realOutStream) { - RINOK(WriteStream(realOutStream, (const Byte *)data, data.GetPos())); + RINOK(WriteStream(realOutStream, (const Byte *)data, data.GetPos())) } realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) } lps->InSize = lps->OutSize = currentTotalSize; @@ -489,7 +485,7 @@ // k_Signature: { ':', '1' } REGISTER_ARC_I_NO_SIG( - "IHex", "ihex", 0, 0xCD, + "IHex", "ihex", NULL, 0xCD, 0, NArcInfoFlags::kStartOpen, IsArc_Ihex) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Iso/IsoHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Iso/IsoHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Iso/IsoHandler.cpp 2022-05-03 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Iso/IsoHandler.cpp 2023-03-26 12:00:00.000000000 +0000 @@ -8,6 +8,7 @@ #include "../../Common/LimitedStreams.h" #include "../../Common/ProgressUtils.h" +#include "../../Common/StreamUtils.h" #include "../../Compress/CopyCoder.h" @@ -48,28 +49,28 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::Open(IInStream *stream, +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openArchiveCallback */) + IArchiveOpenCallback * /* openArchiveCallback */)) { COM_TRY_BEGIN Close(); { - RINOK(_archive.Open(stream)); + RINOK(_archive.Open(stream)) _stream = stream; } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _archive.Clear(); _stream.Release(); return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _archive.Refs.Size() + _archive.BootEntries.Size(); return S_OK; @@ -100,7 +101,7 @@ s += message; } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -161,7 +162,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -177,7 +178,7 @@ if (_archive.BootEntries.Size() != 1) { s.Add_UInt32(index + 1); - s += '-'; + s.Add_Minus(); } s += be.GetName(); prop = s; @@ -303,11 +304,11 @@ COM_TRY_END } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _archive.Refs.Size(); if (numItems == 0) @@ -346,15 +347,15 @@ for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize) { lps->InSize = lps->OutSize = currentTotalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) currentItemSize = 0; CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) UInt64 blockIndex; if (index < (UInt32)_archive.Refs.Size()) @@ -363,8 +364,8 @@ const CDir &item = ref.Dir->_subItems[ref.Index]; if (item.IsDir()) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } currentItemSize = ref.TotalSize; @@ -382,7 +383,7 @@ if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) bool isOK = true; if (index < (UInt32)_archive.Refs.Size()) @@ -395,9 +396,9 @@ if (item2.Size == 0) continue; lps->InSize = lps->OutSize = currentTotalSize + offset; - RINOK(_stream->Seek((UInt64)item2.ExtentLocation * kBlockSize, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_stream, (UInt64)item2.ExtentLocation * kBlockSize)) streamSpec->Init(item2.Size); - RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)) if (copyCoderSpec->TotalSize != item2.Size) { isOK = false; @@ -408,25 +409,25 @@ } else { - RINOK(_stream->Seek((UInt64)blockIndex * kBlockSize, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_stream, (UInt64)blockIndex * kBlockSize)) streamSpec->Init(currentItemSize); - RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)) if (copyCoderSpec->TotalSize != currentItemSize) isOK = false; } realOutStream.Release(); RINOK(extractCallback->SetOperationResult(isOK ? NExtract::NOperationResult::kOK: - NExtract::NOperationResult::kDataError)); + NExtract::NOperationResult::kDataError)) } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN - *stream = 0; + *stream = NULL; UInt64 blockIndex; UInt64 currentItemSize; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Iso/IsoHandler.h 7zip-23.01+dfsg/CPP/7zip/Archive/Iso/IsoHandler.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Iso/IsoHandler.h 2013-01-17 08:01:58.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Iso/IsoHandler.h 2023-03-26 13:00:00.000000000 +0000 @@ -1,29 +1,22 @@ // IsoHandler.h -#ifndef __ISO_HANDLER_H -#define __ISO_HANDLER_H +#ifndef ZIP7_INC_ISO_HANDLER_H +#define ZIP7_INC_ISO_HANDLER_H #include "../../../Common/MyCom.h" #include "../IArchive.h" #include "IsoIn.h" -#include "IsoItem.h" namespace NArchive { namespace NIso { -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_1( + IInArchiveGetStream +) CMyComPtr _stream; CInArchive _archive; -public: - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Iso/IsoHeader.h 7zip-23.01+dfsg/CPP/7zip/Archive/Iso/IsoHeader.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Iso/IsoHeader.h 2017-02-04 17:53:13.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Iso/IsoHeader.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Archive/IsoHeader.h -#ifndef __ARCHIVE_ISO_HEADER_H -#define __ARCHIVE_ISO_HEADER_H +#ifndef ZIP7_INC_ARCHIVE_ISO_HEADER_H +#define ZIP7_INC_ARCHIVE_ISO_HEADER_H #include "../../../Common/MyTypes.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Iso/IsoIn.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Iso/IsoIn.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Iso/IsoIn.cpp 2022-01-10 15:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Iso/IsoIn.cpp 2023-03-26 14:00:00.000000000 +0000 @@ -48,9 +48,9 @@ AString CBootInitialEntry::GetName() const { AString s (Bootable ? "Boot" : "NotBoot"); - s += '-'; + s.Add_Minus(); - if (BootMediaType < ARRAY_SIZE(kMediaTypes)) + if (BootMediaType < Z7_ARRAY_SIZE(kMediaTypes)) s += kMediaTypes[BootMediaType]; else s.Add_UInt32(BootMediaType); @@ -65,10 +65,10 @@ break; if (i == sizeof(VendorSpec)) { - s += '-'; + s.Add_Minus(); for (i = 1; i < sizeof(VendorSpec); i++) { - char c = VendorSpec[i]; + char c = (char)VendorSpec[i]; if (c == 0) break; if (c == '\\' || c == '/') @@ -134,7 +134,7 @@ { if (b[i] != b[3 - i]) IncorrectBigEndian = true; - val |= ((UInt16)(b[i]) << (8 * i)); + val |= ((UInt32)(b[i]) << (8 * i)); } return (UInt16)val; } @@ -316,7 +316,9 @@ void CInArchive::SeekToBlock(UInt32 blockIndex) { - HRESULT res = _stream->Seek((UInt64)blockIndex * VolDescs[MainVolDescIndex].LogicalBlockSize, STREAM_SEEK_SET, &_position); + const HRESULT res = _stream->Seek( + (Int64)((UInt64)blockIndex * VolDescs[MainVolDescIndex].LogicalBlockSize), + STREAM_SEEK_SET, &_position); if (res != S_OK) throw CSystemException(res); m_BufferPos = 0; @@ -506,10 +508,10 @@ HRESULT CInArchive::Open2() { _position = 0; - RINOK(_stream->Seek(0, STREAM_SEEK_END, &_fileSize)); + RINOK(InStream_GetSize_SeekToEnd(_stream, _fileSize)) if (_fileSize < kStartPos) return S_FALSE; - RINOK(_stream->Seek(kStartPos, STREAM_SEEK_SET, &_position)); + RINOK(_stream->Seek(kStartPos, STREAM_SEEK_SET, &_position)) PhySize = _position; m_BufferPos = 0; @@ -584,7 +586,7 @@ if (VolDescs.IsEmpty()) return S_FALSE; - for (MainVolDescIndex = VolDescs.Size() - 1; MainVolDescIndex > 0; MainVolDescIndex--) + for (MainVolDescIndex = (int)VolDescs.Size() - 1; MainVolDescIndex > 0; MainVolDescIndex--) if (VolDescs[MainVolDescIndex].IsJoliet()) break; /* FIXME: some volume can contain Rock Ridge, that is better than @@ -627,10 +629,10 @@ const UInt64 kRemMax = 1 << 21; if (rem <= kRemMax) { - RINOK(_stream->Seek(PhySize, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_stream, PhySize)) bool areThereNonZeros = false; UInt64 numZeros = 0; - RINOK(ReadZeroTail(_stream, areThereNonZeros, numZeros, kRemMax)); + RINOK(ReadZeroTail(_stream, areThereNonZeros, numZeros, kRemMax)) if (!areThereNonZeros) PhySize += numZeros; } @@ -670,4 +672,22 @@ IsSusp = false; } + +UInt64 CInArchive::GetBootItemSize(unsigned index) const +{ + const CBootInitialEntry &be = BootEntries[index]; + UInt64 size = be.GetSize(); + if (be.BootMediaType == NBootMediaType::k1d2Floppy) size = 1200 << 10; + else if (be.BootMediaType == NBootMediaType::k1d44Floppy) size = 1440 << 10; + else if (be.BootMediaType == NBootMediaType::k2d88Floppy) size = 2880 << 10; + const UInt64 startPos = (UInt64)be.LoadRBA * kBlockSize; + if (startPos < _fileSize) + { + const UInt64 rem = _fileSize - startPos; + if (rem < size) + size = rem; + } + return size; +} + }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Iso/IsoIn.h 7zip-23.01+dfsg/CPP/7zip/Archive/Iso/IsoIn.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Iso/IsoIn.h 2022-05-03 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Iso/IsoIn.h 2023-03-26 13:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Archive/IsoIn.h -#ifndef __ARCHIVE_ISO_IN_H -#define __ARCHIVE_ISO_IN_H +#ifndef ZIP7_INC_ARCHIVE_ISO_IN_H +#define ZIP7_INC_ARCHIVE_ISO_IN_H #include "../../../Common/MyCom.h" @@ -20,7 +20,7 @@ void Clear() { - Parent = 0; + Parent = NULL; _subItems.Clear(); } @@ -133,7 +133,7 @@ const bool res = NWindows::NTime::GetSecondsSince1601(Year, Month, Day, Hour, Minute, Second, v); if (res) { - v -= (Int64)((Int32)GmtOffset * 15 * 60); + v = (UInt64)((Int64)v - (Int64)((Int32)GmtOffset * 15 * 60)); v *= 10000000; if (Hundredths < 100) v += (UInt32)Hundredths * 100000; @@ -244,10 +244,6 @@ UInt32 m_BufferPos; - CDir _rootDir; - bool _bootIsDefined; - CBootRecordDescriptor _bootDesc; - void Skip(size_t size); void SkipZeros(size_t size); Byte ReadByte(); @@ -285,17 +281,21 @@ // UInt32 BlockSize; CObjectVector BootEntries; +private: + bool _bootIsDefined; +public: bool IsArc; bool UnexpectedEnd; bool HeadersError; bool IncorrectBigEndian; bool TooDeepDirs; bool SelfLinkedDirs; - CRecordVector UniqStartLocations; + bool IsSusp; + unsigned SuspSkipSize; - Byte m_Buffer[kBlockSize]; + CRecordVector UniqStartLocations; - void UpdatePhySize(UInt32 blockIndex, UInt64 size) + void UpdatePhySize(const UInt32 blockIndex, const UInt64 size) { const UInt64 alignedSize = (size + kBlockSize - 1) & ~((UInt64)kBlockSize - 1); const UInt64 end = (UInt64)blockIndex * kBlockSize + alignedSize; @@ -305,27 +305,12 @@ bool IsJoliet() const { return VolDescs[MainVolDescIndex].IsJoliet(); } - UInt64 GetBootItemSize(int index) const - { - const CBootInitialEntry &be = BootEntries[index]; - UInt64 size = be.GetSize(); - if (be.BootMediaType == NBootMediaType::k1d2Floppy) - size = (1200 << 10); - else if (be.BootMediaType == NBootMediaType::k1d44Floppy) - size = (1440 << 10); - else if (be.BootMediaType == NBootMediaType::k2d88Floppy) - size = (2880 << 10); - UInt64 startPos = (UInt64)be.LoadRBA * kBlockSize; - if (startPos < _fileSize) - { - if (_fileSize - startPos < size) - size = _fileSize - startPos; - } - return size; - } + UInt64 GetBootItemSize(unsigned index) const; - bool IsSusp; - unsigned SuspSkipSize; +private: + CDir _rootDir; + Byte m_Buffer[kBlockSize]; + CBootRecordDescriptor _bootDesc; }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Iso/IsoItem.h 7zip-23.01+dfsg/CPP/7zip/Archive/Iso/IsoItem.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Iso/IsoItem.h 2022-05-03 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Iso/IsoItem.h 2023-01-19 10:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Archive/IsoItem.h -#ifndef __ARCHIVE_ISO_ITEM_H -#define __ARCHIVE_ISO_ITEM_H +#ifndef ZIP7_INC_ARCHIVE_ISO_ITEM_H +#define ZIP7_INC_ARCHIVE_ISO_ITEM_H #include "../../../../C/CpuArch.h" @@ -31,7 +31,7 @@ const bool res = NWindows::NTime::GetSecondsSince1601(Year + 1900, Month, Day, Hour, Minute, Second, v); if (res) { - v -= (Int64)((Int32)GmtOffset * 15 * 60); + v = (UInt64)((Int64)v - (Int64)((Int32)GmtOffset * 15 * 60)); v *= 10000000; prop.SetAsTimeFrom_Ft64_Prec(v, k_PropVar_TimePrec_Base); } @@ -101,29 +101,29 @@ { lenRes = 0; if (SystemUse.Size() < skipSize) - return 0; + return NULL; const Byte *p = (const Byte *)SystemUse + skipSize; unsigned rem = (unsigned)(SystemUse.Size() - skipSize); while (rem >= 5) { unsigned len = p[2]; if (len < 3 || len > rem) - return 0; + return NULL; if (p[0] == id0 && p[1] == id1 && p[3] == 1) { if (len < 4) - return 0; // Check it + return NULL; // Check it lenRes = len - 4; return p + 4; } p += len; rem -= len; } - return 0; + return NULL; } - const Byte* GetNameCur(bool checkSusp, int skipSize, unsigned &nameLenRes) const + const Byte* GetNameCur(bool checkSusp, unsigned skipSize, unsigned &nameLenRes) const { const Byte *res = NULL; unsigned len = 0; @@ -148,7 +148,7 @@ } - bool GetSymLink(int skipSize, AString &link) const + bool GetSymLink(unsigned skipSize, AString &link) const { link.Empty(); const Byte *p = NULL; @@ -185,13 +185,13 @@ for (unsigned i = 0; i < cl; i++) { - char c = p[i]; + const Byte c = p[i]; if (c == 0) { break; // return false; } - link += c; + link += (char)c; } p += cl; @@ -220,7 +220,7 @@ } - bool GetPx(int skipSize, unsigned pxType, UInt32 &val) const + bool GetPx(unsigned skipSize, unsigned pxType, UInt32 &val) const { val = 0; const Byte *p = NULL; @@ -229,7 +229,7 @@ if (!p) return false; // px.Clear(); - if (len < ((unsigned)pxType + 1) * 8) + if (len < (pxType + 1) * 8) return false; return GetLe32Be32(p + pxType * 8, val); @@ -302,7 +302,7 @@ bool CheckSusp(unsigned &startPos) const { const Byte *p = (const Byte *)SystemUse; - unsigned len = (int)SystemUse.Size(); + const size_t len = SystemUse.Size(); const unsigned kMinLen = 7; if (len < kMinLen) return false; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Iso/IsoRegister.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Iso/IsoRegister.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Iso/IsoRegister.cpp 2015-02-11 09:22:40.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Iso/IsoRegister.cpp 2022-12-20 16:00:00.000000000 +0000 @@ -12,7 +12,7 @@ static const Byte k_Signature[] = { 'C', 'D', '0', '0', '1' }; REGISTER_ARC_I( - "Iso", "iso img", 0, 0xE7, + "Iso", "iso img", NULL, 0xE7, k_Signature, NArchive::NIso::kStartPos + 1, 0, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Iso/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Archive/Iso/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Iso/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Iso/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/LpHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/LpHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/LpHandler.cpp 2022-02-02 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/LpHandler.cpp 2023-03-06 16:00:00.000000000 +0000 @@ -59,9 +59,9 @@ #define LP_METADATA_GEOMETRY_SIZE 4096 #define LP_METADATA_HEADER_MAGIC 0x414C5030 -#define SIGNATURE { 0x67, 0x44, 0x6c, 0x61, 0x34, 0, 0, 0 } static const unsigned k_SignatureSize = 8; -static const Byte k_Signature[k_SignatureSize] = SIGNATURE; +static const Byte k_Signature[k_SignatureSize] = + { 0x67, 0x44, 0x6c, 0x61, 0x34, 0, 0, 0 }; // The length (36) is the same as the maximum length of a GPT partition name. static const unsigned kNameLen = 36; @@ -103,9 +103,9 @@ bool Parse(const Byte *p) { - G32 (40, metadata_max_size); - G32 (44, metadata_slot_count); - G32 (48, logical_block_size); + G32 (40, metadata_max_size) + G32 (44, metadata_slot_count) + G32 (48, logical_block_size) if (metadata_slot_count == 0 || metadata_slot_count >= ((UInt32)1 << 20)) return false; if (metadata_max_size == 0) @@ -135,9 +135,9 @@ void Parse(const Byte *p) { - G32 (0, offset); - G32 (4, num_entries); - G32 (8, entry_size); + G32 (0, offset) + G32 (4, num_entries) + G32 (8, entry_size) } bool CheckLimits(UInt32 limit) const @@ -208,10 +208,10 @@ void Parse(const Byte *p) { memcpy(name, p, kNameLen); - G32 (36, attributes); - G32 (40, first_extent_index); - G32 (44, num_extents); - G32 (48, group_index); + G32 (36, attributes) + G32 (40, first_extent_index) + G32 (44, num_extents) + G32 (48, group_index) } // calced properties: @@ -264,10 +264,10 @@ void Parse(const Byte *p) { - G64 (0, num_sectors); - G32 (8, target_type); - G64 (12, target_data); - G32 (20, target_source); + G64 (0, num_sectors) + G32 (8, target_type) + G64 (12, target_data) + G32 (20, target_source) } }; @@ -289,8 +289,8 @@ void Parse(const Byte *p) { memcpy(name, p, kNameLen); - G32 (36, flags); - G64 (40, maximum_size); + G32 (36, flags) + G64 (40, maximum_size) } }; @@ -358,11 +358,11 @@ void Parse(const Byte *p) { memcpy(partition_name, p + 24, kNameLen); - G64 (0, first_logical_sector); - G32 (8, alignment); - G32 (12, alignment_offset); - G64 (16, size); - G32 (60, flags); + G64 (0, first_logical_sector) + G32 (8, alignment) + G32 (12, alignment_offset) + G64 (16, size) + G32 (60, flags) } }; @@ -439,9 +439,9 @@ void Parse128(const Byte *p) { - G32 (0, magic); - G16 (4, major_version); - G16 (6, minor_version); + G32 (0, magic) + G16 (4, major_version) + G16 (6, minor_version) G32 (8, header_size) // Byte header_checksum[32]; G32 (44, tables_size) @@ -479,11 +479,9 @@ -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_1( + IInArchiveGetStream +) CRecordVector _items; CRecordVector Extents; @@ -505,11 +503,6 @@ AString DeviceArcName; HRESULT Open2(IInStream *stream); - -public: - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); }; @@ -533,10 +526,10 @@ HRESULT CHandler::Open2(IInStream *stream) { - RINOK(stream->Seek(LP_PARTITION_RESERVED_BYTES, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, LP_PARTITION_RESERVED_BYTES)) { Byte buf[k_Geometry_Size]; - RINOK(ReadStream_FALSE(stream, buf, k_Geometry_Size)); + RINOK(ReadStream_FALSE(stream, buf, k_Geometry_Size)) if (memcmp(buf, k_Signature, k_SignatureSize) != 0) return S_FALSE; if (!geom.Parse(buf)) @@ -546,11 +539,11 @@ } CByteBuffer buffer; - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(stream)) buffer.Alloc(LP_METADATA_GEOMETRY_SIZE * 2); { // buffer.Size() >= LP_PARTITION_RESERVED_BYTES - RINOK(ReadStream_FALSE(stream, buffer, LP_PARTITION_RESERVED_BYTES)); + RINOK(ReadStream_FALSE(stream, buffer, LP_PARTITION_RESERVED_BYTES)) if (!IsBufZero(buffer, LP_PARTITION_RESERVED_BYTES)) { _headerWarning = true; @@ -558,7 +551,7 @@ } } - RINOK(ReadStream_FALSE(stream, buffer, LP_METADATA_GEOMETRY_SIZE * 2)); + RINOK(ReadStream_FALSE(stream, buffer, LP_METADATA_GEOMETRY_SIZE * 2)) // we check that 2 copies of GEOMETRY are identical: if (memcmp(buffer, buffer + LP_METADATA_GEOMETRY_SIZE, LP_METADATA_GEOMETRY_SIZE) != 0 || !IsBufZero(buffer + k_Geometry_Size, LP_METADATA_GEOMETRY_SIZE - k_Geometry_Size)) @@ -567,7 +560,7 @@ // return S_FALSE; } - RINOK(ReadStream_FALSE(stream, buffer, k_LpMetadataHeader10_size)); + RINOK(ReadStream_FALSE(stream, buffer, k_LpMetadataHeader10_size)) LpMetadataHeader header; header.Parse128(buffer); if (header.magic != LP_METADATA_HEADER_MAGIC || @@ -580,7 +573,7 @@ if (header.header_size != k_LpMetadataHeader12_size) return S_FALSE; RINOK(ReadStream_FALSE(stream, buffer + k_LpMetadataHeader10_size, - header.header_size - k_LpMetadataHeader10_size)); + header.header_size - k_LpMetadataHeader10_size)) Flags = Get32(buffer + k_LpMetadataHeader10_size); } Major_version = header.major_version; @@ -594,7 +587,7 @@ return S_FALSE; buffer.AllocAtLeast(header.tables_size); - RINOK(ReadStream_FALSE(stream, buffer, header.tables_size)); + RINOK(ReadStream_FALSE(stream, buffer, header.tables_size)) const UInt64 totalMetaSize = geom.GetTotalMetadataSize(); // _headersSize = _totalSize; @@ -733,13 +726,13 @@ } -STDMETHODIMP CHandler::Open(IInStream *stream, +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openArchiveCallback */) + IArchiveOpenCallback * /* openArchiveCallback */)) { COM_TRY_BEGIN Close(); - RINOK(Open2(stream)); + RINOK(Open2(stream)) _stream = stream; int mainFileIndex = -1; @@ -750,7 +743,7 @@ CPartition &item = _items[fileIndex]; if (item.NumSectors != 0) { - mainFileIndex = fileIndex; + mainFileIndex = (int)fileIndex; numNonEmptyParts++; CMyComPtr parseStream; if (GetStream(fileIndex, &parseStream) == S_OK && parseStream) @@ -775,7 +768,7 @@ } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _totalSize = 0; // _usedSize = 0; @@ -818,7 +811,7 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -849,7 +842,7 @@ { AString s; s.Add_UInt32(Major_version); - s += '.'; + s.Add_Dot(); s.Add_UInt32(Minor_version); prop = s; break; @@ -874,7 +867,7 @@ if (Flags != 0) { s += "flags: "; - s += FlagsToString(g_Header_Flags, ARRAY_SIZE(g_Header_Flags), Flags); + s += FlagsToString(g_Header_Flags, Z7_ARRAY_SIZE(g_Header_Flags), Flags); s.Add_LF(); } @@ -916,14 +909,14 @@ } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _items.Size(); return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -940,7 +933,7 @@ s.Add_UInt32(index); if (item.num_extents != 0) { - s += '.'; + s.Add_Dot(); s += (item.Ext ? item.Ext : "img"); } prop = s; @@ -971,7 +964,7 @@ s += "group:"; s.Add_UInt32(item.group_index); s.Add_Space(); - s += FlagsToString(g_PartitionAttr, ARRAY_SIZE(g_PartitionAttr), item.attributes); + s += FlagsToString(g_PartitionAttr, Z7_ARRAY_SIZE(g_PartitionAttr), item.attributes); prop = s; break; } @@ -984,7 +977,7 @@ -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN *stream = NULL; @@ -1093,8 +1086,8 @@ } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN const bool allFilesMode = (numItems == (UInt32)(Int32)-1); @@ -1124,21 +1117,21 @@ { lps->InSize = totalSize; lps->OutSize = totalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr outStream; const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; const UInt32 index = allFilesMode ? i : indices[i]; - RINOK(extractCallback->GetStream(index, &outStream, askMode)); + RINOK(extractCallback->GetStream(index, &outStream, askMode)) const UInt64 size = _items[index].GetSize(); totalSize += size; if (!testMode && !outStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) CMyComPtr inStream; const HRESULT hres = GetStream(index, &inStream); @@ -1147,7 +1140,7 @@ { if (hres != S_OK) return hres; - RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)) opRes = NExtract::NOperationResult::kDataError; if (copyCoderSpec->TotalSize == size) opRes = NExtract::NOperationResult::kOK; @@ -1155,7 +1148,7 @@ opRes = NExtract::NOperationResult::kUnexpectedEnd; } outStream.Release(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } return S_OK; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/LzhHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/LzhHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/LzhHandler.cpp 2022-02-14 07:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/LzhHandler.cpp 2023-04-06 05:00:00.000000000 +0000 @@ -51,9 +51,8 @@ return crc; } -static class CLzhCrc16TableInit +static struct CLzhCrc16TableInit { -public: CLzhCrc16TableInit() { for (UInt32 i = 0; i < 256; i++) @@ -176,7 +175,7 @@ { FOR_VECTOR (i, Extensions) if (Extensions[i].Type == type) - return i; + return (int)i; return -1; } @@ -239,10 +238,10 @@ s.Empty(); for (size_t i = 0; i < size; i++) { - char c = p[i]; + const Byte c = p[i]; if (c == 0) break; - s += c; + s += (char)c; } return p + size; } @@ -271,7 +270,7 @@ Byte header[256]; processedSize = kBasicPartSize; - RINOK(ReadStream(stream, header, &processedSize)); + RINOK(ReadStream(stream, header, &processedSize)) if (processedSize != kBasicPartSize) return (startHeader[0] == 0) ? S_OK: S_FALSE; @@ -294,11 +293,11 @@ headerSize = startHeader[0]; if (headerSize < kBasicPartSize) return S_FALSE; - RINOK(ReadStream_FALSE(stream, header + kBasicPartSize, headerSize - kBasicPartSize)); + RINOK(ReadStream_FALSE(stream, header + kBasicPartSize, headerSize - kBasicPartSize)) if (startHeader[1] != CalcSum(header, headerSize)) return S_FALSE; - size_t nameLength = *p++; - if ((p - header) + nameLength + 2 > headerSize) + const size_t nameLength = *p++; + if ((size_t)(p - header) + nameLength + 2 > headerSize) return S_FALSE; p = ReadString(p, nameLength, item.Name); } @@ -309,7 +308,7 @@ { if (item.Level == 2) { - RINOK(ReadStream_FALSE(stream, header + kBasicPartSize, 2)); + RINOK(ReadStream_FALSE(stream, header + kBasicPartSize, 2)) } if ((size_t)(p - header) + 3 > headerSize) return S_FALSE; @@ -335,7 +334,7 @@ RINOK(ReadStream_FALSE(stream, (Byte *)ext.Data, nextSize)) item.Extensions.Add(ext); Byte hdr2[2]; - RINOK(ReadStream_FALSE(stream, hdr2, 2)); + RINOK(ReadStream_FALSE(stream, hdr2, 2)) ReadUInt16(hdr2, nextSize); } } @@ -380,15 +379,10 @@ }; -class COutStreamWithCRC: - public ISequentialOutStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); -private: +Z7_CLASS_IMP_NOQIB_1( + COutStreamWithCRC + , ISequentialOutStream +) UInt32 _crc; CMyComPtr _stream; public: @@ -401,7 +395,7 @@ UInt32 GetCRC() const { return _crc; } }; -STDMETHODIMP COutStreamWithCRC::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(COutStreamWithCRC::Write(const void *data, UInt32 size, UInt32 *processedSize)) { HRESULT res = S_OK; if (_stream) @@ -419,18 +413,14 @@ }; -class CHandler: - public IInArchive, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_0 + CObjectVector _items; CMyComPtr _stream; UInt64 _phySize; UInt32 _errorFlags; bool _isArc; public: - MY_UNKNOWN_IMP1(IInArchive) - INTERFACE_IInArchive(;) CHandler(); }; @@ -439,13 +429,13 @@ CHandler::CHandler() {} -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _items.Size(); return S_OK; } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; switch (propID) @@ -462,7 +452,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -509,8 +499,8 @@ COM_TRY_END } -STDMETHODIMP CHandler::Open(IInStream *stream, - const UInt64 * /* maxCheckStartPosition */, IArchiveOpenCallback *callback) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, + const UInt64 * /* maxCheckStartPosition */, IArchiveOpenCallback *callback)) { COM_TRY_BEGIN Close(); @@ -518,18 +508,17 @@ { _items.Clear(); - UInt64 endPos = 0; + UInt64 endPos; bool needSetTotal = true; - RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos)); - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_AtBegin_GetSize(stream, endPos)) for (;;) { CItemEx item; bool filled; - HRESULT res = GetNextItem(stream, filled, item); - RINOK(stream->Seek(0, STREAM_SEEK_CUR, &item.DataPosition)); + const HRESULT res = GetNextItem(stream, filled, item); + RINOK(InStream_GetPos(stream, item.DataPosition)) if (res == S_FALSE) { _errorFlags = kpv_ErrorFlags_HeadersError; @@ -546,7 +535,7 @@ _isArc = true; UInt64 newPostion; - RINOK(stream->Seek(item.PackSize, STREAM_SEEK_CUR, &newPostion)); + RINOK(stream->Seek(item.PackSize, STREAM_SEEK_CUR, &newPostion)) if (newPostion > endPos) { _phySize = endPos; @@ -558,14 +547,14 @@ { if (needSetTotal) { - RINOK(callback->SetTotal(NULL, &endPos)); + RINOK(callback->SetTotal(NULL, &endPos)) needSetTotal = false; } if (_items.Size() % 100 == 0) { UInt64 numFiles = _items.Size(); UInt64 numBytes = item.DataPosition; - RINOK(callback->SetCompleted(&numFiles, &numBytes)); + RINOK(callback->SetCompleted(&numFiles, &numBytes)) } } } @@ -582,7 +571,7 @@ return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; _phySize = 0; @@ -592,30 +581,28 @@ return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testModeSpec, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool testMode = (testModeSpec != 0); - UInt64 totalUnPacked = 0, totalPacked = 0; - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _items.Size(); if (numItems == 0) return S_OK; + UInt64 totalUnPacked = 0 /* , totalPacked = 0 */; UInt32 i; for (i = 0; i < numItems; i++) { const CItemEx &item = _items[allFilesMode ? i : indices[i]]; totalUnPacked += item.Size; - totalPacked += item.PackSize; + // totalPacked += item.PackSize; } - RINOK(extractCallback->SetTotal(totalUnPacked)); + RINOK(extractCallback->SetTotal(totalUnPacked)) - UInt64 currentTotalUnPacked = 0, currentTotalPacked = 0; UInt64 currentItemUnPacked, currentItemPacked; - NCompress::NLzh::NDecoder::CCoder *lzhDecoderSpec = 0; + NCompress::NLzh::NDecoder::CCoder *lzhDecoderSpec = NULL; CMyComPtr lzhDecoder; // CMyComPtr lzh1Decoder; // CMyComPtr arj2Decoder; @@ -631,30 +618,32 @@ CMyComPtr inStream(streamSpec); streamSpec->SetStream(_stream); - for (i = 0; i < numItems; i++, currentTotalUnPacked += currentItemUnPacked, - currentTotalPacked += currentItemPacked) + for (i = 0;; i++, + lps->OutSize += currentItemUnPacked, + lps->InSize += currentItemPacked) { currentItemUnPacked = 0; currentItemPacked = 0; - lps->InSize = currentTotalPacked; - lps->OutSize = currentTotalUnPacked; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) + + if (i >= numItems) + break; CMyComPtr realOutStream; - Int32 askMode; - askMode = testMode ? NExtract::NAskMode::kTest : + const Int32 askMode = testMode ? + NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - Int32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; const CItemEx &item = _items[index]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) if (item.IsDir()) { // if (!testMode) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) } continue; } @@ -662,7 +651,7 @@ if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) currentItemUnPacked = item.Size; currentItemPacked = item.PackSize; @@ -672,8 +661,7 @@ outStreamSpec->Init(realOutStream); realOutStream.Release(); - UInt64 pos; - _stream->Seek(item.DataPosition, STREAM_SEEK_SET, &pos); + RINOK(InStream_SeekSet(_stream, item.DataPosition)) streamSpec->Init(item.PackSize); @@ -720,13 +708,13 @@ opRes = NExtract::NOperationResult::kDataError; else { - RINOK(res); + RINOK(res) if (outStreamSpec->GetCRC() != item.CRC) opRes = NExtract::NOperationResult::kCRCError; } } outStream.Release(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } } return S_OK; @@ -736,7 +724,7 @@ static const Byte k_Signature[] = { '-', 'l', 'h' }; REGISTER_ARC_I( - "Lzh", "lzh lha", 0, 6, + "Lzh", "lzh lha", NULL, 6, k_Signature, 2, 0, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/LzmaHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/LzmaHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/LzmaHandler.cpp 2019-07-04 11:00:39.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/LzmaHandler.cpp 2023-03-27 09:00:00.000000000 +0000 @@ -76,7 +76,7 @@ && CheckDicSize(LzmaProps + 1); } -class CDecoder +class CDecoder Z7_final { CMyComPtr _bcjStream; CFilterCoder *_filterCoder; @@ -112,7 +112,7 @@ { _filterCoder = new CFilterCoder(false); CMyComPtr coder = _filterCoder; - _filterCoder->Filter = new NCompress::NBcj::CCoder(false); + _filterCoder->Filter = new NCompress::NBcj::CCoder2(z7_BranchConvSt_X86_Dec); _bcjStream = _filterCoder; } } @@ -131,15 +131,15 @@ if (header.FilterID > 1) return E_NOTIMPL; - RINOK(_lzmaDecoderSpec->SetDecoderProperties2(header.LzmaProps, 5)); + RINOK(_lzmaDecoderSpec->SetDecoderProperties2(header.LzmaProps, 5)) bool filteredMode = (header.FilterID == 1); if (filteredMode) { - RINOK(_filterCoder->SetOutStream(outStream)); + RINOK(_filterCoder->SetOutStream(outStream)) outStream = _bcjStream; - RINOK(_filterCoder->SetOutStreamSize(NULL)); + RINOK(_filterCoder->SetOutStreamSize(NULL)) } const UInt64 *Size = header.HasSize() ? &header.Size : NULL; @@ -157,7 +157,7 @@ res = res2; } - RINOK(res); + RINOK(res) if (header.HasSize()) if (_lzmaDecoderSpec->GetOutputProcessedSize() != header.Size) @@ -167,11 +167,9 @@ } -class CHandler: - public IInArchive, - public IArchiveOpenSeq, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_1( + IArchiveOpenSeq +) CHeader _header; bool _lzma86; CMyComPtr _stream; @@ -181,36 +179,28 @@ bool _needSeekToStart; bool _dataAfterEnd; bool _needMoreInput; + bool _unsupported; + bool _dataError; bool _packSize_Defined; bool _unpackSize_Defined; bool _numStreams_Defined; - bool _unsupported; - bool _dataError; - UInt64 _packSize; UInt64 _unpackSize; UInt64 _numStreams; void GetMethod(NCOM::CPropVariant &prop); + unsigned GetHeaderSize() const { return 5 + 8 + (_lzma86 ? 1 : 0); } public: - MY_UNKNOWN_IMP2(IInArchive, IArchiveOpenSeq) - - INTERFACE_IInArchive(;) - STDMETHOD(OpenSeq)(ISequentialInStream *stream); - CHandler(bool lzma86) { _lzma86 = lzma86; } - - unsigned GetHeaderSize() const { return 5 + 8 + (_lzma86 ? 1 : 0); } - }; IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; switch (propID) @@ -222,7 +212,7 @@ case kpidErrorFlags: { UInt32 v = 0; - if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;; + if (!_isArc) v |= kpv_ErrorFlags_IsNotArc; if (_needMoreInput) v |= kpv_ErrorFlags_UnexpectedEnd; if (_dataAfterEnd) v |= kpv_ErrorFlags_DataAfterEnd; if (_unsupported) v |= kpv_ErrorFlags_UnsupportedMethod; @@ -235,7 +225,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = 1; return S_OK; @@ -244,7 +234,7 @@ static char * DictSizeToString(UInt32 val, char *s) { - for (unsigned i = 0; i <= 31; i++) + for (unsigned i = 0; i < 32; i++) if (((UInt32)1 << i) == val) return ::ConvertUInt32ToString(i, s); char c = 'b'; @@ -290,7 +280,7 @@ } -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; switch (propID) @@ -348,7 +338,7 @@ -STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *) +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *)) { Close(); @@ -356,7 +346,7 @@ const UInt32 kBufSize = 1 << 7; Byte buf[kBufSize]; size_t processedSize = kBufSize; - RINOK(ReadStream(inStream, buf, &processedSize)); + RINOK(ReadStream(inStream, buf, &processedSize)) if (processedSize < headerSize + 2) return S_FALSE; if (!_header.Parse(buf, _lzma86)) @@ -365,9 +355,9 @@ if (start[0] != 0 /* || (start[1] & 0x80) != 0 */ ) // empty stream with EOS is not 0x80 return S_FALSE; - RINOK(inStream->Seek(0, STREAM_SEEK_END, &_packSize)); + RINOK(InStream_GetSize_SeekToEnd(inStream, _packSize)) - SizeT srcLen = processedSize - headerSize; + SizeT srcLen = (SizeT)processedSize - headerSize; if (srcLen > 10 && _header.Size == 0 @@ -401,7 +391,7 @@ return S_OK; } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { Close(); _isArc = true; @@ -409,41 +399,38 @@ return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; - _packSize_Defined = false; - _unpackSize_Defined = false; - _numStreams_Defined = false; - + _needSeekToStart = false; _dataAfterEnd = false; _needMoreInput = false; _unsupported = false; _dataError = false; - _packSize = 0; + _packSize_Defined = false; + _unpackSize_Defined = false; + _numStreams_Defined = false; - _needSeekToStart = false; + _packSize = 0; _stream.Release(); _seqStream.Release(); return S_OK; } -class CCompressProgressInfoImp: - public ICompressProgressInfo, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CCompressProgressInfoImp, + ICompressProgressInfo +) CMyComPtr Callback; public: UInt64 Offset; - - MY_UNKNOWN_IMP1(ICompressProgressInfo) - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); + void Init(IArchiveOpenCallback *callback) { Callback = callback; } }; -STDMETHODIMP CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */) +Z7_COM7F_IMF(CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */)) { if (Callback) { @@ -454,8 +441,8 @@ return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN @@ -469,10 +456,10 @@ CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(0, &realOutStream, askMode)) if (!testMode && !realOutStream) return S_OK; @@ -492,14 +479,14 @@ { if (!_stream) return E_FAIL; - RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(_stream)) } else _needSeekToStart = true; CDecoder decoder; HRESULT result = decoder.Create(_lzma86, _seqStream); - RINOK(result); + RINOK(result) bool firstItem = true; @@ -513,13 +500,13 @@ { lps->InSize = packSize; lps->OutSize = unpackSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) const UInt32 kBufSize = 1 + 5 + 8; Byte buf[kBufSize]; const UInt32 headerSize = GetHeaderSize(); UInt32 processed; - RINOK(decoder.ReadInput(buf, headerSize, &processed)); + RINOK(decoder.ReadInput(buf, headerSize, &processed)) if (processed != headerSize) { if (processed != 0) @@ -549,7 +536,7 @@ } if (result == S_FALSE) break; - RINOK(result); + RINOK(result) } if (firstItem) @@ -602,7 +589,7 @@ REGISTER_ARC_I_CLS_NO_SIG( CHandler(false), - "lzma", "lzma", 0, 0xA, + "lzma", "lzma", NULL, 0xA, 0, NArcInfoFlags::kStartOpen | NArcInfoFlags::kKeepName, @@ -614,7 +601,7 @@ REGISTER_ARC_I_CLS_NO_SIG( CHandler(true), - "lzma86", "lzma86", 0, 0xB, + "lzma86", "lzma86", NULL, 0xB, 0, NArcInfoFlags::kKeepName, IsArc_Lzma86) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/MachoHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/MachoHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/MachoHandler.cpp 2021-01-26 09:46:34.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/MachoHandler.cpp 2023-03-27 09:00:00.000000000 +0000 @@ -95,6 +95,13 @@ , "GB_ZEROFILL" , "INTERPOSING" , "16BYTE_LITERALS" + , "DTRACE_DOF" + , "LAZY_DYLIB_SYMBOL_POINTERS" + , "THREAD_LOCAL_REGULAR" + , "THREAD_LOCAL_ZEROFILL" + , "THREAD_LOCAL_VARIABLES" + , "THREAD_LOCAL_VARIABLE_POINTERS" + , "THREAD_LOCAL_INIT_FUNCTION_POINTERS" }; enum EFileType @@ -157,7 +164,7 @@ }; -static const CUInt32PCharPair g_Flags[] = +static const CUInt32PCharPair g_SectFlags[] = { { 31, "PURE_INSTRUCTIONS" }, { 30, "NO_TOC" }, @@ -171,25 +178,54 @@ { 8, "LOC_RELOC" } }; + +// VM_PROT_* +static const char * const g_SegmentProt[] = +{ + "READ" + , "WRITE" + , "EXECUTE" + /* + , "NO_CHANGE" + , "COPY" + , "TRUSTED" + , "IS_MASK" + */ +}; + +// SG_* + +static const char * const g_SegmentFlags[] = +{ + "SG_HIGHVM" + , "SG_FVMLIB" + , "SG_NORELOC" + , "SG_PROTECTED_VERSION_1" + , "SG_READ_ONLY" +}; + static const unsigned kNameSize = 16; struct CSegment { char Name[kNameSize]; + UInt32 MaxProt; + UInt32 InitProt; + UInt32 Flags; }; struct CSection { char Name[kNameSize]; - char SegName[kNameSize]; + // char SegName[kNameSize]; UInt64 Va; UInt64 Pa; UInt64 VSize; UInt64 PSize; + UInt32 Align; UInt32 Flags; - int SegmentIndex; - + unsigned SegmentIndex; bool IsDummy; CSection(): IsDummy(false) {} @@ -198,11 +234,9 @@ }; -class CHandler: - public IInArchive, - public IArchiveAllowTail, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_1( + IArchiveAllowTail +) CMyComPtr _inStream; CObjectVector _segments; CObjectVector _sections; @@ -218,9 +252,6 @@ HRESULT Open2(ISequentialInStream *stream); public: - MY_UNKNOWN_IMP2(IInArchive, IArchiveAllowTail) - INTERFACE_IInArchive(;) - STDMETHOD(AllowTail)(Int32 allowTail); CHandler(): _allowTail(false) {} }; @@ -240,13 +271,14 @@ kpidPackSize, kpidCharacts, kpidOffset, - kpidVa + kpidVa, + kpidClusterSize // Align }; IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN CPropVariant prop; @@ -256,35 +288,28 @@ case kpidCpu: { AString s; - char temp[16]; - UInt32 cpu = _cpuType & ~(UInt32)CPU_ARCH_ABI64; + const UInt32 cpu = _cpuType & ~(UInt32)CPU_ARCH_ABI64; UInt32 flag64 = _cpuType & (UInt32)CPU_ARCH_ABI64; { - const char *n = NULL; - for (unsigned i = 0; i < ARRAY_SIZE(g_CpuPairs); i++) + s.Add_UInt32(cpu); + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_CpuPairs); i++) { const CUInt32PCharPair &pair = g_CpuPairs[i]; if (pair.Value == cpu || pair.Value == _cpuType) { if (pair.Value == _cpuType) flag64 = 0; - n = pair.Name; + s = pair.Name; break; } } - if (!n) - { - ConvertUInt32ToString(cpu, temp); - n = temp; - } - s = n; if (flag64 != 0) - s += " 64-bit"; + s.Add_OptSpaced("64-bit"); else if ((_cpuSubType & CPU_SUBTYPE_LIB64) && _cpuType != CPU_TYPE_AMD64) - s += " 64-bit-lib"; + s.Add_OptSpaced("64-bit-lib"); } - UInt32 t = _cpuSubType & ~(UInt32)CPU_SUBTYPE_LIB64; + const UInt32 t = _cpuSubType & ~(UInt32)CPU_SUBTYPE_LIB64; if (t != 0 && (t != CPU_SUBTYPE_I386_ALL || cpu != CPU_TYPE_386)) { const char *n = NULL; @@ -292,16 +317,14 @@ { if (t == CPU_SUBTYPE_POWERPC_970) n = "970"; - else if (t < ARRAY_SIZE(k_PowerPc_SubTypes)) + else if (t < Z7_ARRAY_SIZE(k_PowerPc_SubTypes)) n = k_PowerPc_SubTypes[t]; } - if (!n) - { - ConvertUInt32ToString(t, temp); - n = temp; - } s.Add_Space(); - s += n; + if (n) + s += n; + else + s.Add_UInt32(t); } prop = s; break; @@ -309,8 +332,8 @@ case kpidCharacts: { // TYPE_TO_PROP(g_FileTypes, _type, prop); break; - AString res (TypeToString(g_FileTypes, ARRAY_SIZE(g_FileTypes), _type)); - AString s (FlagsToString(g_ArcFlags, ARRAY_SIZE(g_ArcFlags), _flags)); + AString res (TypeToString(g_FileTypes, Z7_ARRAY_SIZE(g_FileTypes), _type)); + const AString s (FlagsToString(g_ArcFlags, Z7_ARRAY_SIZE(g_ArcFlags), _flags)); if (!s.IsEmpty()) { res.Add_Space(); @@ -343,16 +366,16 @@ COM_TRY_END } -static AString GetName(const char *name) +static void AddName(AString &s, const char *name) { - char res[kNameSize + 1]; - memcpy(res, name, kNameSize); - res[kNameSize] = 0; - return (AString)res; + char temp[kNameSize + 1]; + memcpy(temp, name, kNameSize); + temp[kNameSize] = 0; + s += temp; } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN CPropVariant prop; @@ -361,29 +384,75 @@ { case kpidPath: { - AString s (GetName(_segments[item.SegmentIndex].Name)); + AString s; + AddName(s, _segments[item.SegmentIndex].Name); if (!item.IsDummy) - s += GetName(item.Name); + { + // CSection::SegName and CSegment::Name are same in real cases. + // AddName(s, item.SegName); + AddName(s, item.Name); + } prop = MultiByteToUnicodeString(s); break; } case kpidSize: /* prop = (UInt64)item.VSize; break; */ case kpidPackSize: prop = (UInt64)item.GetPackSize(); break; case kpidCharacts: - if (!item.IsDummy) + { + AString res; { - AString res (TypeToString(g_SectTypes, ARRAY_SIZE(g_SectTypes), item.Flags & SECT_TYPE_MASK)); - AString s (FlagsToString(g_Flags, ARRAY_SIZE(g_Flags), item.Flags & SECT_ATTR_MASK)); - if (!s.IsEmpty()) + if (!item.IsDummy) { - res.Add_Space(); - res += s; + { + const AString s (TypeToString(g_SectTypes, Z7_ARRAY_SIZE(g_SectTypes), item.Flags & SECT_TYPE_MASK)); + if (!s.IsEmpty()) + { + res.Add_OptSpaced("sect_type:"); + res.Add_OptSpaced(s); + } + } + { + const AString s (FlagsToString(g_SectFlags, Z7_ARRAY_SIZE(g_SectFlags), item.Flags & SECT_ATTR_MASK)); + if (!s.IsEmpty()) + { + res.Add_OptSpaced("sect_flags:"); + res.Add_OptSpaced(s); + } + } + } + const CSegment &seg = _segments[item.SegmentIndex]; + { + const AString s (FlagsToString(g_SegmentFlags, Z7_ARRAY_SIZE(g_SegmentFlags), seg.Flags)); + if (!s.IsEmpty()) + { + res.Add_OptSpaced("seg_flags:"); + res.Add_OptSpaced(s); + } + } + { + const AString s (FlagsToString(g_SegmentProt, Z7_ARRAY_SIZE(g_SegmentProt), seg.MaxProt)); + if (!s.IsEmpty()) + { + res.Add_OptSpaced("max_prot:"); + res.Add_OptSpaced(s); + } + } + { + const AString s (FlagsToString(g_SegmentProt, Z7_ARRAY_SIZE(g_SegmentProt), seg.InitProt)); + if (!s.IsEmpty()) + { + res.Add_OptSpaced("init_prot:"); + res.Add_OptSpaced(s); + } } - prop = res; } + if (!res.IsEmpty()) + prop = res; break; + } case kpidOffset: prop = item.Pa; break; case kpidVa: prop = item.Va; break; + case kpidClusterSize: prop = (UInt32)1 << item.Align; break; } prop.Detach(value); return S_OK; @@ -396,7 +465,7 @@ const UInt32 kStartHeaderSize = 7 * 4; Byte header[kStartHeaderSize]; - RINOK(ReadStream_FALSE(stream, header, kStartHeaderSize)); + RINOK(ReadStream_FALSE(stream, header, kStartHeaderSize)) bool be, mode64; switch (GetUi32(header)) { @@ -410,8 +479,8 @@ _mode64 = mode64; _be = be; - UInt32 numCommands = Get32(header + 0x10, be); - UInt32 commandsSize = Get32(header + 0x14, be); + const UInt32 numCommands = Get32(header + 0x10, be); + const UInt32 commandsSize = Get32(header + 0x14, be); if (numCommands == 0) return S_FALSE; @@ -443,7 +512,7 @@ _headersSize = startHeaderSize + commandsSize; _totalSize = _headersSize; CByteArr buffer(_headersSize); - RINOK(ReadStream_FALSE(stream, buffer + kStartHeaderSize, _headersSize - kStartHeaderSize)); + RINOK(ReadStream_FALSE(stream, buffer + kStartHeaderSize, _headersSize - kStartHeaderSize)) const Byte *buf = buffer + startHeaderSize; size_t size = _headersSize - startHeaderSize; for (UInt32 cmdIndex = 0; cmdIndex < numCommands; cmdIndex++) @@ -489,6 +558,9 @@ } CSegment seg; + seg.MaxProt = Get32(buf + offs - 16, be); + seg.InitProt = Get32(buf + offs - 12, be); + seg.Flags = Get32(buf + offs - 4, be); memcpy(seg.Name, buf + 8, kNameSize); _segments.Add(seg); @@ -505,11 +577,12 @@ sect.PSize = phSize; sect.VSize = vmSize; sect.Pa = phAddr; + sect.Align = 0; sect.Flags = 0; } else do { - UInt32 headSize = (cmd == CMD_SEGMENT_64) ? 0x50 : 0x44; + const UInt32 headSize = (cmd == CMD_SEGMENT_64) ? 0x50 : 0x44; const Byte *p = buf + offs; if (cmdSize - offs < headSize) break; @@ -528,13 +601,16 @@ f32Offset = 0x28; } sect.Pa = Get32(p + f32Offset, be); - sect.Flags = Get32(p + f32Offset + 10, be); - if (sect.Flags == SECT_ATTR_ZEROFILL) + sect.Align = Get32(p + f32Offset + 4, be); + // sect.reloff = Get32(p + f32Offset + 8, be); + // sect.nreloc = Get32(p + f32Offset + 12, be); + sect.Flags = Get32(p + f32Offset + 16, be); + if ((sect.Flags & SECT_TYPE_MASK) == SECT_ATTR_ZEROFILL) sect.PSize = 0; else sect.PSize = sect.VSize; memcpy(sect.Name, p, kNameSize); - memcpy(sect.SegName, p + kNameSize, kNameSize); + // memcpy(sect.SegName, p + kNameSize, kNameSize); sect.SegmentIndex = _segments.Size() - 1; offs += headSize; } @@ -553,17 +629,17 @@ return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *inStream, +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openArchiveCallback */) + IArchiveOpenCallback * /* openArchiveCallback */)) { COM_TRY_BEGIN Close(); - RINOK(Open2(inStream)); + RINOK(Open2(inStream)) if (!_allowTail) { UInt64 fileSize; - RINOK(inStream->Seek(0, STREAM_SEEK_END, &fileSize)); + RINOK(InStream_GetSize_SeekToEnd(inStream, fileSize)) if (fileSize > _totalSize) return S_FALSE; } @@ -572,7 +648,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _totalSize = 0; _inStream.Release(); @@ -581,17 +657,17 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _sections.Size(); return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _sections.Size(); if (numItems == 0) @@ -619,33 +695,33 @@ for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize) { lps->InSize = lps->OutSize = currentTotalSize; - RINOK(lps->SetCur()); - Int32 askMode = testMode ? + RINOK(lps->SetCur()) + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; const CSection &item = _sections[index]; currentItemSize = item.GetPackSize(); CMyComPtr outStream; - RINOK(extractCallback->GetStream(index, &outStream, askMode)); + RINOK(extractCallback->GetStream(index, &outStream, askMode)) if (!testMode && !outStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(_inStream->Seek(item.Pa, STREAM_SEEK_SET, NULL)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(InStream_SeekSet(_inStream, item.Pa)) streamSpec->Init(currentItemSize); - RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)) outStream.Release(); RINOK(extractCallback->SetOperationResult(copyCoderSpec->TotalSize == currentItemSize ? NExtract::NOperationResult::kOK: - NExtract::NOperationResult::kDataError)); + NExtract::NOperationResult::kDataError)) } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::AllowTail(Int32 allowTail) +Z7_COM7F_IMF(CHandler::AllowTail(Int32 allowTail)) { _allowTail = IntToBool(allowTail); return S_OK; @@ -658,7 +734,7 @@ 4, 0xFE, 0xED, 0xFA, 0xCF }; REGISTER_ARC_I( - "MachO", "macho", 0, 0xDF, + "MachO", "macho", NULL, 0xDF, k_Signature, 0, NArcInfoFlags::kMultiSignature | diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/MbrHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/MbrHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/MbrHandler.cpp 2021-01-26 09:47:12.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/MbrHandler.cpp 2023-03-06 17:00:00.000000000 +0000 @@ -54,7 +54,7 @@ // Chs in some MBRs contains only low bits of "Cyl number". So we disable check. /* -#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } +#define RINOZ(x) { int _t_ = (x); if (_t_ != 0) return _t_; } static int CompareChs(const CChs &c1, const CChs &c2) { RINOZ(MyCompare(c1.GetCyl(), c2.GetCyl())); @@ -67,9 +67,9 @@ { AString s; s.Add_UInt32(GetCyl()); - s += '-'; + s.Add_Minus(); s.Add_UInt32(Head); - s += '-'; + s.Add_Minus(); s.Add_UInt32(GetSector()); prop = s; } @@ -132,17 +132,25 @@ #define kFat "fat" +/* +if we use "format" command in Windows 10 for existing partition: + - if we format to ExFAT, it sets type=7 + - if we format to UDF, it doesn't change type from previous value. +*/ + +static const unsigned kType_Windows_NTFS = 7; + static const CPartType kPartTypes[] = { { 0x01, kFat, "FAT12" }, { 0x04, kFat, "FAT16 DOS 3.0+" }, - { 0x05, 0, "Extended" }, + { 0x05, NULL, "Extended" }, { 0x06, kFat, "FAT16 DOS 3.31+" }, { 0x07, "ntfs", "NTFS" }, { 0x0B, kFat, "FAT32" }, { 0x0C, kFat, "FAT32-LBA" }, { 0x0E, kFat, "FAT16-LBA" }, - { 0x0F, 0, "Extended-LBA" }, + { 0x0F, NULL, "Extended-LBA" }, { 0x11, kFat, "FAT12-Hidden" }, { 0x14, kFat, "FAT16-Hidden < 32 MB" }, { 0x16, kFat, "FAT16-Hidden >= 32 MB" }, @@ -150,23 +158,23 @@ { 0x1C, kFat, "FAT32-LBA-Hidden" }, { 0x1E, kFat, "FAT16-LBA-WIN95-Hidden" }, { 0x27, "ntfs", "NTFS-WinRE" }, - { 0x82, 0, "Solaris x86 / Linux swap" }, - { 0x83, 0, "Linux" }, + { 0x82, NULL, "Solaris x86 / Linux swap" }, + { 0x83, NULL, "Linux" }, { 0x8E, "lvm", "Linux LVM" }, - { 0xA5, 0, "BSD slice" }, - { 0xBE, 0, "Solaris 8 boot" }, - { 0xBF, 0, "New Solaris x86" }, - { 0xC2, 0, "Linux-Hidden" }, - { 0xC3, 0, "Linux swap-Hidden" }, - { 0xEE, 0, "GPT" }, - { 0xEE, 0, "EFI" } + { 0xA5, NULL, "BSD slice" }, + { 0xBE, NULL, "Solaris 8 boot" }, + { 0xBF, NULL, "New Solaris x86" }, + { 0xC2, NULL, "Linux-Hidden" }, + { 0xC3, NULL, "Linux swap-Hidden" }, + { 0xEE, NULL, "GPT" }, + { 0xEE, NULL, "EFI" } }; static int FindPartType(UInt32 type) { - for (unsigned i = 0; i < ARRAY_SIZE(kPartTypes); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(kPartTypes); i++) if (kPartTypes[i].Id == type) - return i; + return (int)i; return -1; } @@ -174,17 +182,27 @@ { bool IsReal; bool IsPrim; + bool WasParsed; + const char *FileSystem; UInt64 Size; CPartition Part; + + CItem(): + WasParsed(false), + FileSystem(NULL) + {} }; -class CHandler: public CHandlerCont + +Z7_class_CHandler_final: public CHandlerCont { + Z7_IFACE_COM7_IMP(IInArchive_Cont) + CObjectVector _items; UInt64 _totalSize; CByteBuffer _buffer; - virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const + virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const Z7_override Z7_final { const CItem &item = _items[index]; pos = item.Part.GetPos(); @@ -193,8 +211,6 @@ } HRESULT ReadTables(IInStream *stream, UInt32 baseLba, UInt32 lba, unsigned level); -public: - INTERFACE_IInArchive_Cont(;) }; HRESULT CHandler::ReadTables(IInStream *stream, UInt32 baseLba, UInt32 lba, unsigned level) @@ -212,8 +228,8 @@ UInt64 newPos = (UInt64)lba << 9; if (newPos + 512 > _totalSize) return S_FALSE; - RINOK(stream->Seek(newPos, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(stream, buf, kSectorSize)); + RINOK(InStream_SeekSet(stream, newPos)) + RINOK(ReadStream_FALSE(stream, buf, kSectorSize)) if (buf[0x1FE] != 0x55 || buf[0x1FF] != 0xAA) return S_FALSE; @@ -293,14 +309,87 @@ return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *stream, + +static bool Is_Ntfs(const Byte *p) +{ + if (p[0x1FE] != 0x55 || p[0x1FF] != 0xAA) + return false; + // int codeOffset = 0; + switch (p[0]) + { + case 0xE9: /* codeOffset = 3 + (Int16)Get16(p + 1); */ break; + case 0xEB: if (p[2] != 0x90) return false; /* codeOffset = 2 + (int)(signed char)p[1]; */ break; + default: return false; + } + return memcmp(p + 3, "NTFS ", 8) == 0; +} + +static bool Is_ExFat(const Byte *p) +{ + if (p[0x1FE] != 0x55 || p[0x1FF] != 0xAA) + return false; + if (p[0] != 0xEB || p[1] != 0x76 || p[2] != 0x90) + return false; + return memcmp(p + 3, "EXFAT ", 8) == 0; +} + +static bool AllAreZeros(const Byte *p, size_t size) +{ + for (size_t i = 0; i < size; i++) + if (p[i] != 0) + return false; + return true; +} + +static const UInt32 k_Udf_StartPos = 0x8000; +static const Byte k_Udf_Signature[] = { 0, 'B', 'E', 'A', '0', '1', 1, 0 }; + +static bool Is_Udf(const Byte *p) +{ + return memcmp(p + k_Udf_StartPos, k_Udf_Signature, sizeof(k_Udf_Signature)) == 0; +} + + +static const char *GetFileSystem( + ISequentialInStream *stream, UInt64 partitionSize) +{ + const size_t kHeaderSize = 1 << 9; + if (partitionSize >= kHeaderSize) + { + Byte buf[kHeaderSize]; + if (ReadStream_FAIL(stream, buf, kHeaderSize) == S_OK) + { + // NTFS is expected default filesystem for (Type == 7) + if (Is_Ntfs(buf)) + return "NTFS"; + if (Is_ExFat(buf)) + return "exFAT"; + const size_t kHeaderSize2 = k_Udf_StartPos + (1 << 9); + if (partitionSize >= kHeaderSize2) + { + if (AllAreZeros(buf, kHeaderSize)) + { + CByteBuffer buffer(kHeaderSize2); + // memcpy(buffer, buf, kHeaderSize); + if (ReadStream_FAIL(stream, buffer + kHeaderSize, kHeaderSize2 - kHeaderSize) == S_OK) + if (Is_Udf(buffer)) + return "UDF"; + } + } + } + } + return NULL; +} + + +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openArchiveCallback */) + IArchiveOpenCallback * /* openArchiveCallback */)) { COM_TRY_BEGIN Close(); - RINOK(stream->Seek(0, STREAM_SEEK_END, &_totalSize)); - RINOK(ReadTables(stream, 0, 0, 0)); + RINOK(InStream_GetSize_SeekToEnd(stream, _totalSize)) + RINOK(ReadTables(stream, 0, 0, 0)) if (_items.IsEmpty()) return S_FALSE; UInt32 lbaLimit = _items.Back().Part.GetLimit(); @@ -313,12 +402,25 @@ n.IsReal = false; _items.Add(n); } + + FOR_VECTOR (i, _items) + { + CItem &item = _items[i]; + if (item.Part.Type != kType_Windows_NTFS) + continue; + if (InStream_SeekSet(stream, item.Part.GetPos()) != S_OK) + continue; + item.FileSystem = GetFileSystem(stream, item.Size); + item.WasParsed = true; + } + _stream = stream; return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::Close() + +Z7_COM7F_IMF(CHandler::Close()) { _totalSize = 0; _items.Clear(); @@ -326,6 +428,7 @@ return S_OK; } + enum { kpidPrimary = kpidUserDefined, @@ -347,7 +450,7 @@ IMP_IInArchive_Props_WITH_NAME IMP_IInArchive_ArcProps_NO_Table -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; switch (propID) @@ -363,10 +466,10 @@ mainIndex = -1; break; } - mainIndex = i; + mainIndex = (int)i; } if (mainIndex >= 0) - prop = (UInt32)mainIndex; + prop = (UInt32)(Int32)mainIndex; break; } case kpidPhySize: prop = _totalSize; break; @@ -375,13 +478,13 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _items.Size(); return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -396,11 +499,21 @@ s.Add_UInt32(index); if (item.IsReal) { - s += '.'; + s.Add_Dot(); const char *ext = NULL; - int typeIndex = FindPartType(part.Type); - if (typeIndex >= 0) - ext = kPartTypes[(unsigned)typeIndex].Ext; + if (item.FileSystem) + { + ext = ""; + AString fs (item.FileSystem); + fs.MakeLower_Ascii(); + s += fs; + } + else if (!item.WasParsed) + { + const int typeIndex = FindPartType(part.Type); + if (typeIndex >= 0) + ext = kPartTypes[(unsigned)typeIndex].Ext; + } if (!ext) ext = "img"; s += ext; @@ -414,9 +527,18 @@ char s[32]; ConvertUInt32ToString(part.Type, s); const char *res = s; - int typeIndex = FindPartType(part.Type); - if (typeIndex >= 0 && kPartTypes[(unsigned)typeIndex].Name) - res = kPartTypes[(unsigned)typeIndex].Name; + if (item.FileSystem) + { + // strcat(s, "-"); + // strcpy(s, item.FileSystem); + res = item.FileSystem; + } + else if (!item.WasParsed) + { + const int typeIndex = FindPartType(part.Type); + if (typeIndex >= 0 && kPartTypes[(unsigned)typeIndex].Name) + res = kPartTypes[(unsigned)typeIndex].Name; + } prop = res; } break; @@ -437,7 +559,7 @@ // 2, { 0x55, 0x1FF }, REGISTER_ARC_I_NO_SIG( - "MBR", "mbr", 0, 0xDB, + "MBR", "mbr", NULL, 0xDB, 0, NArcInfoFlags::kPureStartOpen, NULL) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/MslzHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/MslzHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/MslzHandler.cpp 2017-02-02 19:41:45.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/MslzHandler.cpp 2023-03-26 18:00:00.000000000 +0000 @@ -21,11 +21,9 @@ static const UInt32 kUnpackSizeMax = 0xFFFFFFE0; -class CHandler: - public IInArchive, - public IArchiveOpenSeq, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_1( + IArchiveOpenSeq +) CMyComPtr _inStream; CMyComPtr _seqStream; @@ -43,10 +41,6 @@ UString _name; void ParseName(Byte replaceByte, IArchiveOpenCallback *callback); -public: - MY_UNKNOWN_IMP2(IInArchive, IArchiveOpenSeq) - INTERFACE_IInArchive(;) - STDMETHOD(OpenSeq)(ISequentialInStream *stream); }; static const Byte kProps[] = @@ -59,13 +53,13 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps_NO_Table -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = 1; return S_OK; } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -77,7 +71,7 @@ case kpidErrorFlags: { UInt32 v = 0; - if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;; + if (!_isArc) v |= kpv_ErrorFlags_IsNotArc; if (_needMoreInput) v |= kpv_ErrorFlags_UnexpectedEnd; if (_dataAfterEnd) v |= kpv_ErrorFlags_DataAfterEnd; prop = v; @@ -89,7 +83,7 @@ } -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -125,8 +119,7 @@ { if (!callback) return; - CMyComPtr volumeCallback; - callback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&volumeCallback); + Z7_DECL_CMyComPtr_QI_FROM(IArchiveOpenVolumeCallback, volumeCallback, callback) if (!volumeCallback) return; @@ -146,13 +139,13 @@ { if (s.Len() < 3 || s[s.Len() - 3] != '.') return; - for (unsigned i = 0; i < ARRAY_SIZE(g_Exts); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Exts); i++) { const char *ext = g_Exts[i]; if (s[s.Len() - 2] == (Byte)ext[0] && s[s.Len() - 1] == (Byte)ext[1]) { - replaceByte = ext[2]; + replaceByte = (Byte)ext[2]; break; } } @@ -162,21 +155,21 @@ _name += (char)replaceByte; } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback *callback) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 * /* maxCheckStartPosition */, + IArchiveOpenCallback *callback)) { COM_TRY_BEGIN { Close(); _needSeekToStart = true; Byte buffer[kHeaderSize]; - RINOK(ReadStream_FALSE(stream, buffer, kHeaderSize)); + RINOK(ReadStream_FALSE(stream, buffer, kHeaderSize)) if (memcmp(buffer, kSignature, kSignatureSize) != 0) return S_FALSE; _unpackSize = GetUi32(buffer + 10); if (_unpackSize > kUnpackSizeMax) return S_FALSE; - RINOK(stream->Seek(0, STREAM_SEEK_END, &_originalFileSize)); + RINOK(InStream_GetSize_SeekToEnd(stream, _originalFileSize)) _packSize = _originalFileSize; ParseName(buffer[kSignatureSize], callback); @@ -190,7 +183,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _originalFileSize = 0; _packSize = 0; @@ -276,11 +269,11 @@ } if (outStream) - RINOK(WriteStream(outStream, buf, dest & kMask)); + RINOK(WriteStream(outStream, buf, dest & kMask)) return S_OK; } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { COM_TRY_BEGIN Close(); @@ -290,8 +283,8 @@ COM_TRY_END } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN if (numItems == 0) @@ -302,10 +295,10 @@ // extractCallback->SetTotal(_unpackSize); CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(0, &realOutStream, askMode)) if (!testMode && !realOutStream) return S_OK; @@ -325,7 +318,7 @@ { if (!_inStream) return E_FAIL; - RINOK(_inStream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(_inStream)) } else _needSeekToStart = true; @@ -388,7 +381,7 @@ } REGISTER_ARC_I( - "MsLZ", "mslz", 0, 0xD5, + "MsLZ", "mslz", NULL, 0xD5, kSignature, 0, 0, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/MubHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/MubHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/MubHandler.cpp 2021-01-22 19:51:12.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/MubHandler.cpp 2023-03-15 10:00:00.000000000 +0000 @@ -3,6 +3,7 @@ #include "StdAfx.h" #include "../../../C/CpuArch.h" +#include "../../../C/SwapBytes.h" #include "../../Common/ComTry.h" #include "../../Common/IntToString.h" @@ -15,15 +16,13 @@ #include "HandlerCont.h" -static UInt32 Get32(const Byte *p, bool be) { if (be) return GetBe32(p); return GetUi32(p); } - using namespace NWindows; using namespace NCOM; namespace NArchive { namespace NMub { -#define MACH_CPU_ARCH_ABI64 (1 << 24) +#define MACH_CPU_ARCH_ABI64 ((UInt32)1 << 24) #define MACH_CPU_TYPE_386 7 #define MACH_CPU_TYPE_ARM 12 #define MACH_CPU_TYPE_SPARC 14 @@ -43,13 +42,15 @@ UInt32 SubType; UInt32 Offset; UInt32 Size; - // UInt32 Align; + UInt32 Align; }; -static const UInt32 kNumFilesMax = 10; +static const UInt32 kNumFilesMax = 6; -class CHandler: public CHandlerCont +Z7_class_CHandler_final: public CHandlerCont { + Z7_IFACE_COM7_IMP(IInArchive_Cont) + // UInt64 _startPos; UInt64 _phySize; UInt32 _numItems; @@ -58,16 +59,13 @@ HRESULT Open2(IInStream *stream); - virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const + virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const Z7_override { const CItem &item = _items[index]; pos = item.Offset; size = item.Size; return NExtract::NOperationResult::kOK; } - -public: - INTERFACE_IInArchive_Cont(;) }; static const Byte kArcProps[] = @@ -77,13 +75,16 @@ static const Byte kProps[] = { - kpidSize + kpidPath, + kpidSize, + kpidOffset, + kpidClusterSize // Align }; IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { PropVariant_Clear(value); switch (propID) @@ -94,7 +95,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { PropVariant_Clear(value); const CItem &item = _items[index]; @@ -103,7 +104,7 @@ case kpidExtension: { char temp[32]; - const char *ext = 0; + const char *ext = NULL; switch (item.Type) { case MACH_CPU_TYPE_386: ext = "x86"; break; @@ -117,13 +118,13 @@ temp[0] = 'c'; temp[1] = 'p'; temp[2] = 'u'; - ConvertUInt32ToString(item.Type & ~MACH_CPU_ARCH_ABI64, temp + 3); + char *p = ConvertUInt32ToString(item.Type & ~MACH_CPU_ARCH_ABI64, temp + 3); if (item.Type & MACH_CPU_ARCH_ABI64) - MyStringCopy(temp + MyStringLen(temp), "_64"); + MyStringCopy(p, "_64"); break; } if (ext) - strcpy(temp, ext); + MyStringCopy(temp, ext); if (item.SubType != 0) if ((item.Type != MACH_CPU_TYPE_386 && item.Type != MACH_CPU_TYPE_AMD64) @@ -140,32 +141,45 @@ case kpidPackSize: PropVarEm_Set_UInt64(value, item.Size); break; + case kpidOffset: + PropVarEm_Set_UInt64(value, item.Offset); + break; + case kpidClusterSize: + PropVarEm_Set_UInt32(value, (UInt32)1 << item.Align); + break; } return S_OK; } HRESULT CHandler::Open2(IInStream *stream) { - // RINOK(stream->Seek(0, STREAM_SEEK_CUR, &_startPos)); + // RINOK(InStream_GetPos(stream, _startPos)); - const UInt32 kHeaderSize = 8; - const UInt32 kRecordSize = 5 * 4; + const UInt32 kHeaderSize = 2; + const UInt32 kRecordSize = 5; const UInt32 kBufSize = kHeaderSize + kNumFilesMax * kRecordSize; - Byte buf[kBufSize]; - size_t processed = kBufSize; - RINOK(ReadStream(stream, buf, &processed)); + UInt32 buf[kBufSize]; + size_t processed = kBufSize * 4; + RINOK(ReadStream(stream, buf, &processed)) + processed >>= 2; if (processed < kHeaderSize) return S_FALSE; bool be; - switch (GetBe32(buf)) + switch (buf[0]) { - case 0xCAFEBABE: be = true; break; - case 0xB9FAF10E: be = false; break; + case Z7_CONV_BE_TO_NATIVE_CONST32(0xCAFEBABE): be = true; break; + case Z7_CONV_BE_TO_NATIVE_CONST32(0xB9FAF10E): be = false; break; default: return S_FALSE; } _bigEndian = be; - UInt32 num = Get32(buf + 4, be); + if ( + #if defined(MY_CPU_BE) + ! + #endif + be) + z7_SwapBytes4(&buf[1], processed - 1); + const UInt32 num = buf[1]; if (num > kNumFilesMax || processed < kHeaderSize + num * kRecordSize) return S_FALSE; if (num == 0) @@ -174,13 +188,14 @@ for (UInt32 i = 0; i < num; i++) { - const Byte *p = buf + kHeaderSize + i * kRecordSize; + const UInt32 *p = buf + kHeaderSize + i * kRecordSize; CItem &sb = _items[i]; - sb.Type = Get32(p, be); - sb.SubType = Get32(p + 4, be); - sb.Offset = Get32(p + 8, be); - sb.Size = Get32(p + 12, be); - UInt32 align = Get32(p + 16, be); + sb.Type = p[0]; + sb.SubType = p[1]; + sb.Offset = p[2]; + sb.Size = p[3]; + const UInt32 align = p[4]; + sb.Align = align; if (align > 31) return S_FALSE; if (sb.Offset < kHeaderSize + num * kRecordSize) @@ -189,7 +204,7 @@ (sb.SubType & ~MACH_CPU_SUBTYPE_LIB64) >= 0x100) return S_FALSE; - UInt64 endPos = (UInt64)sb.Offset + sb.Size; + const UInt64 endPos = (UInt64)sb.Offset + sb.Size; if (endPosMax < endPos) endPosMax = endPos; } @@ -198,9 +213,9 @@ return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *inStream, +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openArchiveCallback */) + IArchiveOpenCallback * /* openArchiveCallback */)) { COM_TRY_BEGIN Close(); @@ -215,7 +230,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _stream.Release(); _numItems = 0; @@ -223,7 +238,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _numItems; return S_OK; @@ -236,7 +251,7 @@ 4, 0xB9, 0xFA, 0xF1, 0x0E }; REGISTER_ARC_I( - "Mub", "mub", 0, 0xE2, + "Mub", "mub", NULL, 0xE2, k_Signature, 0, NArcInfoFlags::kMultiSignature, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Nsis/NsisDecode.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Nsis/NsisDecode.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Nsis/NsisDecode.cpp 2017-04-18 09:42:15.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Nsis/NsisDecode.cpp 2023-03-22 15:00:00.000000000 +0000 @@ -40,7 +40,7 @@ if (!_codecInStream) { - switch (Method) + switch ((int)Method) { // case NMethodType::kCopy: return E_NOTIMPL; case NMethodType::kDeflate: @@ -65,7 +65,7 @@ if (FilterFlag) { Byte flag; - RINOK(ReadStream_FALSE(inStream, &flag, 1)); + RINOK(ReadStream_FALSE(inStream, &flag, 1)) if (flag > 1) return E_NOTIMPL; useFilter = (flag != 0); @@ -79,9 +79,9 @@ { _filter = new CFilterCoder(false); _filterInStream = _filter; - _filter->Filter = new NCompress::NBcj::CCoder(false); + _filter->Filter = new NCompress::NBcj::CCoder2(z7_BranchConvSt_X86_Dec); } - RINOK(_filter->SetInStream(_codecInStream)); + RINOK(_filter->SetInStream(_codecInStream)) _decoderInStream = _filterInStream; } @@ -89,8 +89,8 @@ { const unsigned kPropsSize = LZMA_PROPS_SIZE; Byte props[kPropsSize]; - RINOK(ReadStream_FALSE(inStream, props, kPropsSize)); - RINOK(_lzmaDecoder->SetDecoderProperties2((const Byte *)props, kPropsSize)); + RINOK(ReadStream_FALSE(inStream, props, kPropsSize)) + RINOK(_lzmaDecoder->SetDecoderProperties2((const Byte *)props, kPropsSize)) } { @@ -98,7 +98,7 @@ _codecInStream.QueryInterface(IID_ICompressSetInStream, &setInStream); if (!setInStream) return E_NOTIMPL; - RINOK(setInStream->SetInStream(inStream)); + RINOK(setInStream->SetInStream(inStream)) } { @@ -106,12 +106,12 @@ _codecInStream.QueryInterface(IID_ICompressSetOutStreamSize, &setOutStreamSize); if (!setOutStreamSize) return E_NOTIMPL; - RINOK(setOutStreamSize->SetOutStreamSize(NULL)); + RINOK(setOutStreamSize->SetOutStreamSize(NULL)) } if (useFilter) { - RINOK(_filter->SetOutStreamSize(NULL)); + RINOK(_filter->SetOutStreamSize(NULL)) } return S_OK; @@ -130,14 +130,14 @@ while (StreamPos < pos) { size_t size = (size_t)MyMin(pos - StreamPos, (UInt64)Buffer.Size()); - RINOK(Read(Buffer, &size)); + RINOK(Read(Buffer, &size)) if (size == 0) return S_FALSE; StreamPos += size; offset += size; const UInt64 inSize = GetInputProcessedSize() - inSizeStart; - RINOK(progress->SetRatioInfo(&inSize, &offset)); + RINOK(progress->SetRatioInfo(&inSize, &offset)) } return S_OK; } @@ -156,7 +156,7 @@ { Byte temp[4]; size_t processedSize = 4; - RINOK(Read(temp, &processedSize)); + RINOK(Read(temp, &processedSize)) StreamPos += processedSize; if (processedSize != 4) return S_FALSE; @@ -171,7 +171,7 @@ Byte temp[4]; { size_t processedSize = 4; - RINOK(ReadStream(InputStream, temp, &processedSize)); + RINOK(ReadStream(InputStream, temp, &processedSize)) StreamPos += processedSize; if (processedSize != 4) return S_FALSE; @@ -192,7 +192,7 @@ { UInt32 curSize = (UInt32)MyMin((size_t)size, Buffer.Size()); UInt32 processedSize; - RINOK(InputStream->Read(Buffer, curSize, &processedSize)); + RINOK(InputStream->Read(Buffer, curSize, &processedSize)) if (processedSize == 0) return S_FALSE; if (outBuf) @@ -202,8 +202,8 @@ StreamPos += processedSize; unpackSizeRes += processedSize; if (realOutStream) - RINOK(WriteStream(realOutStream, Buffer, processedSize)); - RINOK(progress->SetRatioInfo(&offset, &offset)); + RINOK(WriteStream(realOutStream, Buffer, processedSize)) + RINOK(progress->SetRatioInfo(&offset, &offset)) } return S_OK; @@ -217,7 +217,7 @@ limitedStreamSpec->Init(size); { bool useFilter; - RINOK(Init(limitedStream, useFilter)); + RINOK(Init(limitedStream, useFilter)) } } @@ -244,7 +244,7 @@ size_t size = Buffer.Size(); if (size > rem) size = rem; - RINOK(Read(Buffer, &size)); + RINOK(Read(Buffer, &size)) if (size == 0) { if (unpackSizeDefined) @@ -277,7 +277,7 @@ unpackSizeRes += (UInt32)size; UInt64 outSize = offset; - RINOK(progress->SetRatioInfo(&inSize, &outSize)); + RINOK(progress->SetRatioInfo(&inSize, &outSize)) if (realOutStream) { res = WriteStream(realOutStream, Buffer, size); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Nsis/NsisDecode.h 7zip-23.01+dfsg/CPP/7zip/Archive/Nsis/NsisDecode.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Nsis/NsisDecode.h 2017-04-18 09:32:06.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Nsis/NsisDecode.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // NsisDecode.h -#ifndef __NSIS_DECODE_H -#define __NSIS_DECODE_H +#ifndef ZIP7_INC_NSIS_DECODE_H +#define ZIP7_INC_NSIS_DECODE_H #include "../../../Common/MyBuffer.h" @@ -82,7 +82,7 @@ HRESULT Read(void *data, size_t *processedSize) { - return ReadStream(_decoderInStream, data, processedSize);; + return ReadStream(_decoderInStream, data, processedSize); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Nsis/NsisHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Nsis/NsisHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Nsis/NsisHandler.cpp 2021-03-16 19:46:04.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Nsis/NsisHandler.cpp 2023-03-06 16:00:00.000000000 +0000 @@ -61,22 +61,19 @@ IMP_IInArchive_ArcProps -static AString UInt32ToString(UInt32 val) +static void AddDictProp(AString &s, UInt32 val) { - char s[16]; - ConvertUInt32ToString(val, s); - return (AString)s; -} - -static AString GetStringForSizeValue(UInt32 val) -{ - for (int i = 31; i >= 0; i--) + for (unsigned i = 0; i < 32; i++) if (((UInt32)1 << i) == val) - return UInt32ToString(i); + { + s.Add_UInt32(i); + return; + } char c = 'b'; if ((val & ((1 << 20) - 1)) == 0) { val >>= 20; c = 'm'; } else if ((val & ((1 << 10) - 1)) == 0) { val >>= 10; c = 'k'; } - return UInt32ToString(val) + c; + s.Add_UInt32(val); + s += c; } static AString GetMethod(bool useFilter, NMethodType::EEnum method, UInt32 dict) @@ -87,11 +84,11 @@ s += kBcjMethod; s.Add_Space(); } - s += ((unsigned)method < ARRAY_SIZE(kMethods)) ? kMethods[(unsigned)method] : kUnknownMethod; + s += ((unsigned)method < Z7_ARRAY_SIZE(kMethods)) ? kMethods[(unsigned)method] : kUnknownMethod; if (method == NMethodType::kLZMA) { s += ':'; - s += GetStringForSizeValue(dict); + AddDictProp(s, dict); } return s; } @@ -105,7 +102,7 @@ s += kBcjMethod; s.Add_Space(); } - s += (method < ARRAY_SIZE(kMethods)) ? kMethods[method] : kUnknownMethod; + s += (method < Z7_ARRAY_SIZE(kMethods)) ? kMethods[method] : kUnknownMethod; if (method == NMethodType::kLZMA) { s += ':'; @@ -115,7 +112,7 @@ } */ -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -162,7 +159,7 @@ if (!_archive.IsInstaller) { if (!s.IsEmpty()) - s += '.'; + s.Add_Dot(); s += "Uninstall"; } #endif @@ -190,7 +187,7 @@ } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback * /* openArchiveCallback */) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback * /* openArchiveCallback */)) { COM_TRY_BEGIN Close(); @@ -215,18 +212,18 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _archive.Clear(); _archive.Release(); return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _archive.Items.Size() #ifdef NSIS_SCRIPT - + 1 + _archive.LicenseFiles.Size(); + + 1 + _archive.LicenseFiles.Size() #endif ; return S_OK; @@ -240,7 +237,7 @@ size = item.Size; else if (_archive.IsSolid && item.EstimatedSize_Defined) size = item.EstimatedSize; - else + else if (!item.IsEmptyFile) return false; return true; } @@ -272,7 +269,7 @@ } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -360,21 +357,21 @@ } -static bool UninstallerPatch(const Byte *p, size_t size, CByteBuffer &dest) +static bool UninstallerPatch(const Byte *p, size_t size, Byte *dest, size_t destSize) { for (;;) { if (size < 4) return false; - UInt32 len = Get32(p); + const UInt32 len = Get32(p); if (len == 0) return size == 4; if (size < 8) return false; - UInt32 offs = Get32(p + 4); + const UInt32 offs = Get32(p + 4); p += 8; size -= 8; - if (size < len || offs > dest.Size() || len > dest.Size() - offs) + if (size < len || offs > destSize || len > destSize - offs) return false; memcpy(dest + offs, p, len); p += len; @@ -383,11 +380,11 @@ } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) GetNumberOfItems(&numItems); if (numItems == 0) @@ -399,7 +396,7 @@ UInt32 i; for (i = 0; i < numItems; i++) { - UInt32 index = (allFilesMode ? i : indices[i]); + const UInt32 index = (allFilesMode ? i : indices[i]); #ifdef NSIS_SCRIPT if (index >= _archive.Items.Size()) @@ -436,8 +433,8 @@ if (_archive.IsSolid) { - RINOK(_archive.SeekTo_DataStreamOffset()); - RINOK(_archive.InitDecoder()); + RINOK(_archive.SeekTo_DataStreamOffset()) + RINOK(_archive.InitDecoder()) _archive.Decoder.StreamPos = 0; } @@ -476,16 +473,16 @@ curPacked = 0; curUnpacked = 0; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) - // RINOK(extractCallback->SetCompleted(¤tTotalSize)); + // RINOK(extractCallback->SetCompleted(¤tTotalSize)) CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; const UInt32 index = allFilesMode ? i : indices[i]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) bool dataError = false; @@ -511,9 +508,9 @@ curUnpacked = size; if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) if (realOutStream) - RINOK(WriteStream(realOutStream, data, size)); + RINOK(WriteStream(realOutStream, data, size)) } else #endif @@ -526,15 +523,20 @@ if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) dataError = solidDataError; - bool needDecompress = !solidDataError; - if (needDecompress) + bool needDecompress = false; + + if (!item.IsEmptyFile) { - if (testMode && _archive.IsSolid && _archive.GetPosOfSolidItem(index) == prevPos) - needDecompress = false; + needDecompress = !solidDataError; + if (needDecompress) + { + if (testMode && _archive.IsSolid && _archive.GetPosOfSolidItem(index) == prevPos) + needDecompress = false; + } } if (needDecompress) @@ -544,7 +546,7 @@ if (!_archive.IsSolid) { - RINOK(_archive.SeekToNonSolidItem(index)); + RINOK(_archive.SeekToNonSolidItem(index)) } else { @@ -566,10 +568,11 @@ } else if (!testMode && i + 1 < numItems) { - UInt32 next = allFilesMode ? i + 1 : indices[i + 1]; + const UInt32 next = allFilesMode ? i + 1 : indices[i + 1]; if (next < _archive.Items.Size()) { - UInt64 nextPos = _archive.GetPosOfSolidItem(next); + // next cannot be IsEmptyFile + const UInt64 nextPos = _archive.GetPosOfSolidItem(next); if (nextPos == pos) { writeToTemp = true; @@ -581,12 +584,16 @@ prevPos = pos; } + /* nsis 3.08 can use (PatchSize == 0) for uninstaller without patched section */ + + const bool is_PatchedUninstaller = item.Is_PatchedUninstaller(); + if (!dataError) { // UInt32 unpackSize = 0; // bool unpackSize_Defined = false; bool writeToTemp1 = writeToTemp; - if (item.IsUninstaller) + if (is_PatchedUninstaller) { // unpackSize = item.PatchSize; // unpackSize_Defined = true; @@ -603,16 +610,16 @@ if (readFromTemp) { - if (realOutStream && !item.IsUninstaller) - RINOK(WriteStream(realOutStream, tempBuf, tempBuf.Size())); + if (realOutStream && !is_PatchedUninstaller) + RINOK(WriteStream(realOutStream, tempBuf, tempBuf.Size())) } else { UInt32 curUnpacked32 = 0; - HRESULT res = _archive.Decoder.Decode( + const HRESULT res = _archive.Decoder.Decode( writeToTemp1 ? &tempBuf : NULL, - item.IsUninstaller, item.PatchSize, - item.IsUninstaller ? NULL : (ISequentialOutStream *)realOutStream, + is_PatchedUninstaller, item.PatchSize, + is_PatchedUninstaller ? NULL : (ISequentialOutStream *)realOutStream, progress, curPacked, curUnpacked32); curUnpacked = curUnpacked32; @@ -629,21 +636,20 @@ } } - if (!dataError && item.IsUninstaller) + if (!dataError && is_PatchedUninstaller) { if (_archive.ExeStub.Size() != 0) { CByteBuffer destBuf = _archive.ExeStub; - dataError = !UninstallerPatch(tempBuf, tempBuf.Size(), destBuf); - + dataError = !UninstallerPatch(tempBuf, tempBuf.Size(), destBuf, destBuf.Size()); if (realOutStream) - RINOK(WriteStream(realOutStream, destBuf, destBuf.Size())); + RINOK(WriteStream(realOutStream, destBuf, destBuf.Size())) } if (readFromTemp) { if (realOutStream) - RINOK(WriteStream(realOutStream, tempBuf2, tempBuf2.Size())); + RINOK(WriteStream(realOutStream, tempBuf2, tempBuf2.Size())) } else { @@ -652,10 +658,10 @@ if (!_archive.IsSolid) { - RINOK(_archive.SeekTo(_archive.GetPosOfNonSolidItem(index) + 4 + curPacked )); + RINOK(_archive.SeekTo(_archive.GetPosOfNonSolidItem(index) + 4 + curPacked )) } - HRESULT res = _archive.Decoder.Decode( + const HRESULT res = _archive.Decoder.Decode( writeToTemp ? &tempBuf2 : NULL, false, 0, realOutStream, @@ -679,7 +685,7 @@ realOutStream.Release(); RINOK(extractCallback->SetOperationResult(dataError ? NExtract::NOperationResult::kDataError : - NExtract::NOperationResult::kOK)); + NExtract::NOperationResult::kOK)) } return S_OK; COM_TRY_END diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Nsis/NsisHandler.h 7zip-23.01+dfsg/CPP/7zip/Archive/Nsis/NsisHandler.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Nsis/NsisHandler.h 2013-02-10 05:29:50.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Nsis/NsisHandler.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // NSisHandler.h -#ifndef __NSIS_HANDLER_H -#define __NSIS_HANDLER_H +#ifndef ZIP7_INC_NSIS_HANDLER_H +#define ZIP7_INC_NSIS_HANDLER_H #include "../../../Common/MyCom.h" @@ -14,10 +14,8 @@ namespace NArchive { namespace NNsis { -class CHandler: - public IInArchive, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_0 + CInArchive _archive; AString _methodString; @@ -25,10 +23,6 @@ bool GetCompressedSize(unsigned index, UInt32 &size) const; // AString GetMethod(NMethodType::EEnum method, bool useItemFilter, UInt32 dictionary) const; -public: - MY_UNKNOWN_IMP1(IInArchive) - - INTERFACE_IInArchive(;) }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Nsis/NsisIn.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Nsis/NsisIn.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Nsis/NsisIn.cpp 2021-11-12 16:52:52.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Nsis/NsisIn.cpp 2023-04-06 11:00:00.000000000 +0000 @@ -6,7 +6,6 @@ #include "../../../Common/StringToInt.h" #include "../../Common/LimitedStreams.h" -#include "../../Common/StreamUtils.h" #include "NsisIn.h" @@ -32,7 +31,7 @@ static const char * const kErrorStr = "$_ERROR_STR_"; -#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } +#define RINOZ(x) { int _tt_ = (x); if (_tt_ != 0) return _tt_; } /* There are several versions of NSIS: @@ -466,8 +465,8 @@ } strUsed[param] = 1; - UInt32 start = _stringsPos + (IsUnicode ? param * 2 : param); - UInt32 offset = start + (IsUnicode ? 2 : 1); + const UInt32 start = _stringsPos + (IsUnicode ? param * 2 : param); + const UInt32 offset = start + (IsUnicode ? 2 : 1); { FOR_VECTOR (i, LicenseFiles) { @@ -484,16 +483,16 @@ { fileName += "\\license-"; // LangId_To_String(fileName, langID); - UIntToString(fileName, langID); + UIntToString(fileName, (UInt32)langID); } else if (++_numRootLicenses > 1) { - fileName += '-'; + fileName.Add_Minus(); UIntToString(fileName, _numRootLicenses); } const Byte *sz = (_data + start); - unsigned marker = IsUnicode ? Get16(sz) : *sz; - bool isRTF = (marker == 2); + const unsigned marker = IsUnicode ? Get16(sz) : *sz; + const bool isRTF = (marker == 2); fileName += isRTF ? ".rtf" : ".txt"; // if (*sz == 1) it's text; Script += fileName; @@ -505,7 +504,7 @@ else { sz += 2; - UInt32 len = GetUi16Str_Len(sz); + const UInt32 len = GetUi16Str_Len(sz); lic.Size = len * 2; if (isRTF) { @@ -526,6 +525,26 @@ #endif +#ifdef NSIS_SCRIPT +#define Z7_NSIS_WIN_GENERIC_READ ((UInt32)1 << 31) +#endif +#define Z7_NSIS_WIN_GENERIC_WRITE ((UInt32)1 << 30) +#ifdef NSIS_SCRIPT +#define Z7_NSIS_WIN_GENERIC_EXECUTE ((UInt32)1 << 29) +#define Z7_NSIS_WIN_GENERIC_ALL ((UInt32)1 << 28) +#endif + +#ifdef NSIS_SCRIPT +#define Z7_NSIS_WIN_CREATE_NEW 1 +#endif +#define Z7_NSIS_WIN_CREATE_ALWAYS 2 +#ifdef NSIS_SCRIPT +#define Z7_NSIS_WIN_OPEN_EXISTING 3 +#define Z7_NSIS_WIN_OPEN_ALWAYS 4 +#define Z7_NSIS_WIN_TRUNCATE_EXISTING 5 +#endif + + // #define kVar_CMDLINE 20 #define kVar_INSTDIR 21 #define kVar_OUTDIR 22 @@ -562,9 +581,9 @@ , "_OUTDIR" // NSIS 2.04+ }; -static const unsigned kNumInternalVars = 20 + ARRAY_SIZE(kVarStrings); +static const unsigned kNumInternalVars = 20 + Z7_ARRAY_SIZE(kVarStrings); -#define GET_NUM_INTERNAL_VARS (IsNsis200 ? kNumInternalVars - 3 : IsNsis225 ? kNumInternalVars - 2 : kNumInternalVars); +#define GET_NUM_INTERNAL_VARS (IsNsis200 ? kNumInternalVars - 3 : IsNsis225 ? kNumInternalVars - 2 : kNumInternalVars) void CInArchive::GetVar2(AString &res, UInt32 index) { @@ -643,7 +662,7 @@ #define IS_NS_SPEC_CHAR(c) ((c) >= NS_CODE_SKIP) #define IS_PARK_SPEC_CHAR(c) ((c) >= PARK_CODE_SKIP && (c) <= PARK_CODE_LANG) -#define DECODE_NUMBER_FROM_2_CHARS(c0, c1) (((c0) & 0x7F) | (((unsigned)((c1) & 0x7F)) << 7)) +#define DECODE_NUMBER_FROM_2_CHARS(c0, c1) (((unsigned)(c0) & 0x7F) | (((unsigned)((c1) & 0x7F)) << 7)) #define CONVERT_NUMBER_NS_3_UNICODE(n) n = ((n & 0x7F) | (((n >> 8) & 0x7F) << 7)) #define CONVERT_NUMBER_PARK(n) n &= 0x7FFF @@ -738,7 +757,7 @@ } s += '$'; - if (index1 < ARRAY_SIZE(kShellStrings)) + if (index1 < Z7_ARRAY_SIZE(kShellStrings)) { const char *sz = kShellStrings[index1]; if (sz) @@ -747,7 +766,7 @@ return; } } - if (index2 < ARRAY_SIZE(kShellStrings)) + if (index2 < Z7_ARRAY_SIZE(kShellStrings)) { const char *sz = kShellStrings[index2]; if (sz) @@ -1151,7 +1170,7 @@ Raw_AString.Empty(); Raw_UString.Empty(); if ((Int32)pos < 0) - Add_LangStr(Raw_AString, -((Int32)pos + 1)); + Add_LangStr(Raw_AString, (UInt32)-((Int32)pos + 1)); else if (pos >= NumStringChars) { Raw_AString += kErrorStr; @@ -1361,7 +1380,7 @@ { if ((Int32)pos < 0) { - Add_LangStr(s, -((Int32)pos + 1)); + Add_LangStr(s, (UInt32)-((Int32)pos + 1)); return; } @@ -1537,7 +1556,7 @@ static const UInt32 CMD_REF_OnFunc = (1 << 5); static const UInt32 CMD_REF_Section = (1 << 6); static const UInt32 CMD_REF_InitPluginDir = (1 << 7); -// static const UInt32 CMD_REF_Creator = (1 << 5); // _Pre is used instead +// static const UInt32 CMD_REF_Creator = (1 << 5); // CMD_REF_Pre is used instead static const unsigned CMD_REF_OnFunc_NumShifts = 28; // it uses for onFunc too static const unsigned CMD_REF_Page_NumShifts = 16; // it uses for onFunc too static const UInt32 CMD_REF_Page_Mask = 0x0FFF0000; @@ -1617,7 +1636,7 @@ { Space(); if ((Int32)param < 0) - Add_Var(-((Int32)param + 1)); + Add_Var((UInt32)-((Int32)param + 1)); else Add_LabelName(param - 1); } @@ -1647,8 +1666,8 @@ static const char * const k_REBOOTOK = " /REBOOTOK"; -#define MY__MB_ABORTRETRYIGNORE 2 -#define MY__MB_RETRYCANCEL 5 +#define Z7_NSIS_WIN_MB_ABORTRETRYIGNORE 2 +#define Z7_NSIS_WIN_MB_RETRYCANCEL 5 static const char * const k_MB_Buttons[] = { @@ -1661,7 +1680,7 @@ , "CANCELTRYCONTINUE" }; -#define MY__MB_ICONSTOP (1 << 4) +#define Z7_NSIS_WIN_MB_ICONSTOP (1 << 4) static const char * const k_MB_Icons[] = { @@ -1684,8 +1703,8 @@ // , "SERVICE_NOTIFICATION" // unsupported. That bit is used for NSIS purposes }; -#define MY__IDCANCEL 2 -#define MY__IDIGNORE 5 +#define Z7_NSIS_WIN_IDCANCEL 2 +#define Z7_NSIS_WIN_IDIGNORE 5 static const char * const k_Button_IDs[] = { @@ -1706,7 +1725,7 @@ void CInArchive::Add_ButtonID(UInt32 buttonID) { Space(); - if (buttonID < ARRAY_SIZE(k_Button_IDs)) + if (buttonID < Z7_ARRAY_SIZE(k_Button_IDs)) Script += k_Button_IDs[buttonID]; else { @@ -1774,19 +1793,8 @@ } // Win32 constants -#define MY__TRANSPARENT 1 -// #define MY__OPAQUE 2 - -#define MY__GENERIC_READ ((UInt32)1 << 31) -#define MY__GENERIC_WRITE ((UInt32)1 << 30) -#define MY__GENERIC_EXECUTE ((UInt32)1 << 29) -#define MY__GENERIC_ALL ((UInt32)1 << 28) - -#define MY__CREATE_NEW 1 -#define MY__CREATE_ALWAYS 2 -#define MY__OPEN_EXISTING 3 -#define MY__OPEN_ALWAYS 4 -#define MY__TRUNCATE_EXISTING 5 +#define Z7_NSIS_WIN_TRANSPARENT 1 +// #define Z7_NSIS_WIN_OPAQUE 2 // text/bg colors #define kColorsFlags_TEXT 1 @@ -1821,12 +1829,12 @@ Add_Color2(v); } -#define MY__SW_HIDE 0 -#define MY__SW_SHOWNORMAL 1 +#define Z7_NSIS_WIN_SW_HIDE 0 +#define Z7_NSIS_WIN_SW_SHOWNORMAL 1 -#define MY__SW_SHOWMINIMIZED 2 -#define MY__SW_SHOWMINNOACTIVE 7 -#define MY__SW_SHOWNA 8 +#define Z7_NSIS_WIN_SW_SHOWMINIMIZED 2 +#define Z7_NSIS_WIN_SW_SHOWMINNOACTIVE 7 +#define Z7_NSIS_WIN_SW_SHOWNA 8 static const char * const kShowWindow_Commands[] = { @@ -1846,7 +1854,7 @@ static void Add_ShowWindow_Cmd_2(AString &s, UInt32 cmd) { - if (cmd < ARRAY_SIZE(kShowWindow_Commands)) + if (cmd < Z7_ARRAY_SIZE(kShowWindow_Commands)) { s += "SW_"; s += kShowWindow_Commands[cmd]; @@ -1857,7 +1865,7 @@ void CInArchive::Add_ShowWindow_Cmd(UInt32 cmd) { - if (cmd < ARRAY_SIZE(kShowWindow_Commands)) + if (cmd < Z7_ARRAY_SIZE(kShowWindow_Commands)) { Script += "SW_"; Script += kShowWindow_Commands[cmd]; @@ -1877,7 +1885,7 @@ } } -#define ADD_TYPE_FROM_LIST(table, type) Add_TypeFromList(table, ARRAY_SIZE(table), type) +#define ADD_TYPE_FROM_LIST(table, type) Add_TypeFromList(table, Z7_ARRAY_SIZE(table), type) enum { @@ -1894,7 +1902,7 @@ k_ExecFlags_rtl, k_ExecFlags_ErrorLevel, k_ExecFlags_RegView, - k_ExecFlags_DetailsPrint = 13, + k_ExecFlags_DetailsPrint = 13 }; // Names for NSIS exec_flags_t structure vars @@ -2097,7 +2105,7 @@ StartCmdIndex = Get32(p + 12); NumCommands = Get32(p + 16); SizeKB = Get32(p + 20); -}; +} // used for section->flags #define SF_SELECTED (1 << 0) @@ -2182,7 +2190,7 @@ { TabString("SectionIn"); UInt32 instTypes = sect.InstallTypes; - for (int i = 0; i < 32; i++, instTypes >>= 1) + for (unsigned i = 0; i < 32; i++, instTypes >>= 1) if ((instTypes & 1) != 0) { AddParam_UInt(i + 1); @@ -2270,7 +2278,7 @@ { UInt32 v = param & 0xF; Script += " MB_"; - if (v < ARRAY_SIZE(k_MB_Buttons)) + if (v < Z7_ARRAY_SIZE(k_MB_Buttons)) Script += k_MB_Buttons[v]; else { @@ -2283,7 +2291,7 @@ if (icon != 0) { Script += "|MB_"; - if (icon < ARRAY_SIZE(k_MB_Icons) && k_MB_Icons[icon] != 0) + if (icon < Z7_ARRAY_SIZE(k_MB_Icons) && k_MB_Icons[icon]) Script += k_MB_Icons[icon]; else { @@ -2308,7 +2316,7 @@ else if (modal == 2) Script += "|MB_TASKMODAL"; else if (modal == 3) Script += "|0x3000"; UInt32 flags = (param >> 14); - for (unsigned i = 0; i < ARRAY_SIZE(k_MB_Flags); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_MB_Flags); i++) if ((flags & (1 << i)) != 0) { Script += "|MB_"; @@ -2381,7 +2389,7 @@ if (BadCmd >= 0) { AddString(s, "BadCmd="); - UIntToString(s, BadCmd); + UIntToString(s, (UInt32)BadCmd); } return s; } @@ -2455,7 +2463,7 @@ for (UInt32 kkk = 0; kkk < bh.Num; kkk++, p += kCmdSize) { - UInt32 id = GetCmd(Get32(p)); + const UInt32 id = GetCmd(Get32(p)); if (id >= kNumCmds) continue; if (BadCmd >= 0 && id >= (unsigned)BadCmd) @@ -2465,7 +2473,7 @@ { if (id == EW_RESERVEDOPCODE) { - BadCmd = id; + BadCmd = (int)id; continue; } } @@ -2474,23 +2482,23 @@ // if (id == EW_GETLABELADDR || id == EW_GETFUNCTIONADDR) if (id == EW_RESERVEDOPCODE || id == EW_GETOSINFO) { - BadCmd = id; + BadCmd = (int)id; continue; } } for (i = 6; i != 0; i--) { - UInt32 param = Get32(p + i * 4); + const UInt32 param = Get32(p + i * 4); if (param != 0) break; } if (id == EW_FINDPROC && i == 0) { - BadCmd = id; + BadCmd = (int)id; continue; } if (k_Commands[id].NumParams < i) - BadCmd = id; + BadCmd = (int)id; } } @@ -2770,13 +2778,13 @@ else if (c != NS_CODE_VAR) return -1; - unsigned c0 = p[1]; + const unsigned c0 = p[1]; if (c0 == 0) return -1; - unsigned c1 = p[2]; + const unsigned c1 = p[2]; if (c1 == 0) return -1; - return DECODE_NUMBER_FROM_2_CHARS(c0, c1); + return (Int32)DECODE_NUMBER_FROM_2_CHARS(c0, c1); } Int32 CInArchive::GetVarIndex(UInt32 strPos, UInt32 &resOffset) const @@ -2870,18 +2878,18 @@ void CInArchive::SetItemName(CItem &item, UInt32 strPos) { ReadString2_Raw(strPos); - bool isAbs = IsAbsolutePathVar(strPos); + const bool isAbs = IsAbsolutePathVar(strPos); if (IsUnicode) { item.NameU = Raw_UString; if (!isAbs && !IsAbsolutePath(Raw_UString)) - item.Prefix = UPrefixes.Size() - 1; + item.Prefix = (int)UPrefixes.Size() - 1; } else { item.NameA = Raw_AString; if (!isAbs && !IsAbsolutePath(Raw_AString)) - item.Prefix = APrefixes.Size() - 1; + item.Prefix = (int)APrefixes.Size() - 1; } } @@ -2949,9 +2957,9 @@ for (int i = 0; i < 5; i++) params[i] = Get32(p + 44 + 4 * i); - SET_FUNC_REF(preFunc, CMD_REF_Pre); - SET_FUNC_REF(showFunc, CMD_REF_Show); - SET_FUNC_REF(leaveFunc, CMD_REF_Leave); + SET_FUNC_REF(preFunc, CMD_REF_Pre) + SET_FUNC_REF(showFunc, CMD_REF_Show) + SET_FUNC_REF(leaveFunc, CMD_REF_Leave) if (wndProcID == PWP_COMPLETED) CommentOpen(); @@ -2969,7 +2977,7 @@ else s += IsInstaller ? "Page " : "UninstPage "; - if (wndProcID < ARRAY_SIZE(kPageTypes)) + if (wndProcID < Z7_ARRAY_SIZE(kPageTypes)) s += kPageTypes[wndProcID]; else Add_UInt(wndProcID); @@ -3189,11 +3197,11 @@ } */ if (IsFunc(flg) - && bh.Num - kkk >= ARRAY_SIZE(k_InitPluginDir_Commands) - && CompareCommands(p, k_InitPluginDir_Commands, ARRAY_SIZE(k_InitPluginDir_Commands))) + && bh.Num - kkk >= Z7_ARRAY_SIZE(k_InitPluginDir_Commands) + && CompareCommands(p, k_InitPluginDir_Commands, Z7_ARRAY_SIZE(k_InitPluginDir_Commands))) { - InitPluginsDir_Start = kkk; - InitPluginsDir_End = (int)(kkk + ARRAY_SIZE(k_InitPluginDir_Commands)); + InitPluginsDir_Start = (int)kkk; + InitPluginsDir_End = (int)(kkk + Z7_ARRAY_SIZE(k_InitPluginDir_Commands)); labels[kkk] |= CMD_REF_InitPluginDir; break; } @@ -3356,7 +3364,7 @@ unsigned numSkipParams = 0; - if (commandId < ARRAY_SIZE(k_Commands) && commandId < numSupportedCommands) + if (commandId < Z7_ARRAY_SIZE(k_Commands) && commandId < numSupportedCommands) { numSkipParams = k_Commands[commandId].NumParams; const char *sz = k_CommandNames[commandId]; @@ -3505,9 +3513,9 @@ UInt32 b1 = nsisMB >> 21; // NSIS 2.06+ UInt32 b2 = nsisMB >> 20; // NSIS old Int32 asf = (Int32)nsisMB; - if (mb == (MY__MB_ABORTRETRYIGNORE | MY__MB_ICONSTOP) && (b1 == MY__IDIGNORE || b2 == MY__IDIGNORE)) + if (mb == (Z7_NSIS_WIN_MB_ABORTRETRYIGNORE | Z7_NSIS_WIN_MB_ICONSTOP) && (b1 == Z7_NSIS_WIN_IDIGNORE || b2 == Z7_NSIS_WIN_IDIGNORE)) asf = -1; - else if (mb == (MY__MB_RETRYCANCEL | MY__MB_ICONSTOP) && (b1 == MY__IDCANCEL || b2 == MY__IDCANCEL)) + else if (mb == (Z7_NSIS_WIN_MB_RETRYCANCEL | Z7_NSIS_WIN_MB_ICONSTOP) && (b1 == Z7_NSIS_WIN_IDCANCEL || b2 == Z7_NSIS_WIN_IDCANCEL)) asf = -2; else { @@ -3591,7 +3599,7 @@ #ifdef NSIS_SCRIPT AddParam(params[0]); Space(); - FlagsToString2(s, g_WinAttrib, ARRAY_SIZE(g_WinAttrib), params[1]); + FlagsToString2(s, g_WinAttrib, Z7_ARRAY_SIZE(g_WinAttrib), params[1]); #endif break; } @@ -3603,7 +3611,7 @@ NSIS installer uses alternative path, if main path from params[0] is not absolute path */ - bool pathOk = (params[0] > 0) && IsGoodString(params[0]); + const bool pathOk = (params[0] > 0) && IsGoodString(params[0]); if (!pathOk) { @@ -3613,9 +3621,11 @@ break; } + #ifdef NSIS_SCRIPT + bool altPathOk = true; - UInt32 altParam = params[3]; + const UInt32 altParam = params[3]; if (altParam != 0) { altPathOk = false; @@ -3624,9 +3634,6 @@ altPathOk = AreTwoParamStringsEqual(altParam + additional, params[0]); } - - #ifdef NSIS_SCRIPT - AddParam(params[0]); /* @@ -3640,8 +3647,6 @@ AddParam(params[3]); } - #endif - if (!altPathOk) { #ifdef NSIS_SCRIPT @@ -3649,9 +3654,11 @@ #endif } + #endif + if (BadCmd >= 0 && BadCmd <= EW_WRITEUNINSTALLER) { - /* We don't cases with incorrect installer commands. + /* We don't support cases with incorrect installer commands. Such bad installer item can break unpacking for other items. */ #ifdef NSIS_SCRIPT AddError("SKIP possible BadCmd"); @@ -3659,13 +3666,23 @@ break; } - CItem &item = Items.AddNew();; + CItem &item = Items.AddNew(); SetItemName(item, params[0]); item.Pos = params[1]; item.PatchSize = params[2]; item.IsUninstaller = true; + const UInt32 param3 = params[3]; + if (param3 != 0 && item.Prefix != -1) + { + /* (item.Prefix != -1) case means that param[0] path was not absolute. + So we use params[3] in that case, as original nsis */ + SetItemName(item, param3); + } + /* UNINSTALLER file doesn't use directory prefixes. + So we remove prefix: */ + item.Prefix = -1; /* // we can add second time to test the code @@ -3834,12 +3851,12 @@ s += "Call "; if ((Int32)params[0] < 0) - Add_Var(-((Int32)params[0] + 1)); + Add_Var((UInt32)-((Int32)params[0] + 1)); else if (params[0] == 0) s += '0'; else { - UInt32 val = params[0] - 1; + const UInt32 val = params[0] - 1; if (params[1] == 1) // it's Call :Label { s += ':'; @@ -3860,8 +3877,8 @@ case EW_CHDETAILSVIEW: { - if (params[0] == MY__SW_SHOWNA && params[1] == MY__SW_HIDE) s += " show"; - else if (params[1] == MY__SW_SHOWNA && params[0] == MY__SW_HIDE) s += " hide"; + if (params[0] == Z7_NSIS_WIN_SW_SHOWNA && params[1] == Z7_NSIS_WIN_SW_HIDE) s += " show"; + else if (params[1] == Z7_NSIS_WIN_SW_SHOWNA && params[0] == Z7_NSIS_WIN_SW_HIDE) s += " hide"; else for (int i = 0; i < 2; i++) { @@ -3935,7 +3952,7 @@ Add_ExecFlags(params[2]); Add_GotoVars2(¶ms[0]); /* - static const unsigned kIfErrors = 2; + const unsigned kIfErrors = 2; if (params[2] != kIfErrors && params[3] != 0xFFFFFFFF || params[2] == kIfErrors && params[3] != 0) { @@ -4244,7 +4261,7 @@ AString bk; bool bkc = false; - if (colors.bkmode == MY__TRANSPARENT) + if (colors.bkmode == Z7_NSIS_WIN_TRANSPARENT) bk += " transparent"; else if (colors.flags & kColorsFlags_BKB) { @@ -4305,7 +4322,7 @@ bool valDefined = false; if (StringToUInt32(sw, val)) { - if (val < ARRAY_SIZE(kShowWindow_Commands)) + if (val < Z7_ARRAY_SIZE(kShowWindow_Commands)) { sw.Empty(); sw += "${"; @@ -4338,10 +4355,10 @@ case EW_SHELLEXEC: { AddParams(params, 2); - if (params[2] != 0 || params[3] != MY__SW_SHOWNORMAL) + if (params[2] != 0 || params[3] != Z7_NSIS_WIN_SW_SHOWNORMAL) { AddParam(params[2]); - if (params[3] != MY__SW_SHOWNORMAL) + if (params[3] != Z7_NSIS_WIN_SW_SHOWNORMAL) { Space(); Add_ShowWindow_Cmd(params[3]); @@ -4442,8 +4459,8 @@ UInt32 sw = (spec >> sw_shift) & sw_mask; Space(); // NSIS encoder replaces these names: - if (sw == MY__SW_SHOWMINNOACTIVE) - sw = MY__SW_SHOWMINIMIZED; + if (sw == Z7_NSIS_WIN_SW_SHOWMINNOACTIVE) + sw = Z7_NSIS_WIN_SW_SHOWMINIMIZED; if (sw == 0) AddQuotes(); else @@ -4467,7 +4484,7 @@ if (modKey & 4) s += "ALT|"; if (modKey & 8) s += "EXT|"; - static const unsigned kMy_VK_F1 = 0x70; + const unsigned kMy_VK_F1 = 0x70; if (key >= kMy_VK_F1 && key <= kMy_VK_F1 + 23) { s += 'F'; @@ -4559,7 +4576,7 @@ case EW_WRITEREG: { - const char *s2 = 0; + const char *s2 = NULL; switch (params[4]) { case 1: s2 = "Str"; break; @@ -4642,20 +4659,42 @@ break; } + #endif + case EW_FOPEN: { + /* + the pattern for empty files is following: + FileOpen $0 "file_name" w + FileClose $0 + */ + + const UInt32 acc = params[1]; // dwDesiredAccess + const UInt32 creat = params[2]; // dwCreationDisposition + if (creat == Z7_NSIS_WIN_CREATE_ALWAYS && acc == Z7_NSIS_WIN_GENERIC_WRITE) + { + if (kkk + 1 < bh.Num) + if (Get32(p + kCmdSize) == EW_FCLOSE) + if (Get32(p + kCmdSize + 4) == params[0]) + { + CItem &item = Items.AddNew(); + item.IsEmptyFile = true; + SetItemName(item, params[3]); + } + } + + #ifdef NSIS_SCRIPT + AddParam_Var(params[0]); AddParam(params[3]); - UInt32 acc = params[1]; // dwDesiredAccess - UInt32 creat = params[2]; // dwCreationDisposition if (acc == 0 && creat == 0) break; char cc = 0; - if (acc == MY__GENERIC_READ && creat == OPEN_EXISTING) + if (creat == Z7_NSIS_WIN_OPEN_EXISTING && acc == Z7_NSIS_WIN_GENERIC_READ) cc = 'r'; - else if (creat == CREATE_ALWAYS && acc == MY__GENERIC_WRITE) + else if (creat == Z7_NSIS_WIN_CREATE_ALWAYS && acc == Z7_NSIS_WIN_GENERIC_WRITE) cc = 'w'; - else if (creat == OPEN_ALWAYS && (acc == (MY__GENERIC_WRITE | MY__GENERIC_READ))) + else if (creat == Z7_NSIS_WIN_OPEN_ALWAYS && (acc == (Z7_NSIS_WIN_GENERIC_WRITE | Z7_NSIS_WIN_GENERIC_READ))) cc = 'a'; // cc = 0; if (cc != 0) @@ -4665,28 +4704,32 @@ break; } - if (acc & MY__GENERIC_READ) s += " GENERIC_READ"; - if (acc & MY__GENERIC_WRITE) s += " GENERIC_WRITE"; - if (acc & MY__GENERIC_EXECUTE) s += " GENERIC_EXECUTE"; - if (acc & MY__GENERIC_ALL) s += " GENERIC_ALL"; + if (acc & Z7_NSIS_WIN_GENERIC_READ) s += " GENERIC_READ"; + if (acc & Z7_NSIS_WIN_GENERIC_WRITE) s += " GENERIC_WRITE"; + if (acc & Z7_NSIS_WIN_GENERIC_EXECUTE) s += " GENERIC_EXECUTE"; + if (acc & Z7_NSIS_WIN_GENERIC_ALL) s += " GENERIC_ALL"; const char *s2 = NULL; switch (creat) { - case MY__CREATE_NEW: s2 = "CREATE_NEW"; break; - case MY__CREATE_ALWAYS: s2 = "CREATE_ALWAYS"; break; - case MY__OPEN_EXISTING: s2 = "OPEN_EXISTING"; break; - case MY__OPEN_ALWAYS: s2 = "OPEN_ALWAYS"; break; - case MY__TRUNCATE_EXISTING: s2 = "TRUNCATE_EXISTING"; break; + case Z7_NSIS_WIN_CREATE_NEW: s2 = "CREATE_NEW"; break; + case Z7_NSIS_WIN_CREATE_ALWAYS: s2 = "CREATE_ALWAYS"; break; + case Z7_NSIS_WIN_OPEN_EXISTING: s2 = "OPEN_EXISTING"; break; + case Z7_NSIS_WIN_OPEN_ALWAYS: s2 = "OPEN_ALWAYS"; break; + case Z7_NSIS_WIN_TRUNCATE_EXISTING: s2 = "TRUNCATE_EXISTING"; break; } Space(); if (s2) s += s2; else Add_UInt(creat); + #endif + break; } + #ifdef NSIS_SCRIPT + case EW_FPUTS: case EW_FPUTWS: { @@ -4780,7 +4823,7 @@ else { s += "Set"; - UInt32 t = -(Int32)params[2] - 1; + const UInt32 t = (UInt32)(-(Int32)params[2] - 1); Add_SectOp(t); AddParam(params[0]); AddParam(params[t == 0 ? 4 : 1]); @@ -4793,7 +4836,7 @@ case EW_INSTTYPESET: { - int numQwParams = 0; + unsigned numQwParams = 0; const char *s2; if (params[3] == 0) { @@ -4952,7 +4995,18 @@ { const CItem &i1 = **(const CItem *const *)p1; const CItem &i2 = **(const CItem *const *)p2; - RINOZ(MyCompare(i1.Pos, i2.Pos)); + RINOZ(MyCompare(i1.Pos, i2.Pos)) + + /* In another code we check CItem::Pos after each solid item. + So here we place empty files before all non empty files */ + if (i1.IsEmptyFile) + { + if (!i2.IsEmptyFile) + return -1; + } + else if (i2.IsEmptyFile) + return 1; + const CInArchive *inArchive = (const CInArchive *)param; if (inArchive->IsUnicode) { @@ -4962,9 +5016,9 @@ if (i2.Prefix < 0) return 1; RINOZ( inArchive->UPrefixes[i1.Prefix].Compare( - inArchive->UPrefixes[i2.Prefix])); + inArchive->UPrefixes[i2.Prefix])) } - RINOZ(i1.NameU.Compare(i2.NameU)); + RINOZ(i1.NameU.Compare(i2.NameU)) } else { @@ -4974,9 +5028,9 @@ if (i2.Prefix < 0) return 1; RINOZ(strcmp( inArchive->APrefixes[i1.Prefix], - inArchive->APrefixes[i2.Prefix])); + inArchive->APrefixes[i2.Prefix])) } - RINOZ(strcmp(i1.NameA, i2.NameA)); + RINOZ(strcmp(i1.NameA, i2.NameA)) } return 0; } @@ -4990,6 +5044,8 @@ for (i = 0; i + 1 < Items.Size(); i++) { const CItem &i1 = Items[i]; + if (i1.IsEmptyFile) + continue; const CItem &i2 = Items[i + 1]; if (i1.Pos != i2.Pos) continue; @@ -5019,10 +5075,14 @@ for (i = 0; i < Items.Size(); i++) { CItem &item = Items[i]; - UInt32 curPos = item.Pos + 4; + if (item.IsEmptyFile) + continue; + const UInt32 curPos = item.Pos + 4; for (unsigned nextIndex = i + 1; nextIndex < Items.Size(); nextIndex++) { - UInt32 nextPos = Items[nextIndex].Pos; + const CItem &nextItem = Items[nextIndex]; + // if (nextItem.IsEmptyFile) continue; + const UInt32 nextPos = nextItem.Pos; if (curPos <= nextPos) { item.EstimatedSize_Defined = true; @@ -5037,11 +5097,13 @@ for (i = 0; i < Items.Size(); i++) { CItem &item = Items[i]; - RINOK(SeekToNonSolidItem(i)); + if (item.IsEmptyFile) + continue; + RINOK(SeekToNonSolidItem(i)) const UInt32 kSigSize = 4 + 1 + 1 + 4; // size,[flag],prop,dict BYTE sig[kSigSize]; size_t processedSize = kSigSize; - RINOK(ReadStream(_stream, sig, &processedSize)); + RINOK(ReadStream(_stream, sig, &processedSize)) if (processedSize < 4) return S_FALSE; UInt32 size = Get32(sig); @@ -5218,7 +5280,7 @@ if (Method != NMethodType::kCopy) { const char *m = NULL; - switch (Method) + switch ((int)Method) { case NMethodType::kDeflate: m = "zlib"; break; case NMethodType::kBZip2: m = "bzip2"; break; @@ -5451,7 +5513,7 @@ if (val != 0) { Script += "LicenseLangString "; - Add_LangStr_Simple(licenseLangIndex); + Add_LangStr_Simple((UInt32)licenseLangIndex); AddParam_UInt(langID); AddLicense(val, langID); noParseStringIndexes.AddToUniqueSorted(val); @@ -5470,7 +5532,7 @@ const UInt16 langID = Get16(p); if (i == 0 || langID == 1033) _mainLang = p + 10; - for (unsigned k = 0; k < ARRAY_SIZE(names) && k < numStrings; k++) + for (unsigned k = 0; k < Z7_ARRAY_SIZE(names) && k < numStrings; k++) { UInt32 v = Get32(p + 10 + k * 4); if (v != 0 && (langID == 1033 || names[k] == 0)) @@ -5567,7 +5629,7 @@ } onFuncOffset = paramsOffset + 40; - numOnFunc = ARRAY_SIZE(kOnFunc); + numOnFunc = Z7_ARRAY_SIZE(kOnFunc); if (bhPages.Offset == 276) numOnFunc--; p2 += 40 + numOnFunc * 4; @@ -5629,7 +5691,7 @@ #endif - RINOK(ReadEntries(bhEntries)); + RINOK(ReadEntries(bhEntries)) #ifdef NSIS_SCRIPT @@ -5747,14 +5809,14 @@ if (IsSolid) { - RINOK(SeekTo_DataStreamOffset()); + RINOK(SeekTo_DataStreamOffset()) } else { _headerIsCompressed = ((compressedHeaderSize & kMask_IsCompressed) != 0); compressedHeaderSize &= ~kMask_IsCompressed; _nonSolidStartOffset = compressedHeaderSize; - RINOK(SeekTo(DataStreamOffset + 4)); + RINOK(SeekTo(DataStreamOffset + 4)) } if (FirstHeader.HeaderSize == 0) @@ -5775,12 +5837,12 @@ if (_headerIsCompressed) { - RINOK(Decoder.Init(_stream, UseFilter)); + RINOK(Decoder.Init(_stream, UseFilter)) if (IsSolid) { size_t processedSize = 4; Byte buf[4]; - RINOK(Decoder.Read(buf, &processedSize)); + RINOK(Decoder.Read(buf, &processedSize)) if (processedSize != 4) return S_FALSE; if (Get32((const Byte *)buf) != FirstHeader.HeaderSize) @@ -5788,7 +5850,7 @@ } { size_t processedSize = FirstHeader.HeaderSize; - RINOK(Decoder.Read(_data, &processedSize)); + RINOK(Decoder.Read(_data, &processedSize)) if (processedSize != FirstHeader.HeaderSize) return S_FALSE; } @@ -5800,7 +5862,7 @@ AfterHeaderSize = (1 << 12); _afterHeader.Alloc(AfterHeaderSize); size_t processedSize = AfterHeaderSize; - RINOK(Decoder.Read(_afterHeader, &processedSize)); + RINOK(Decoder.Read(_afterHeader, &processedSize)) AfterHeaderSize = (UInt32)processedSize; } #endif @@ -5808,7 +5870,7 @@ else { size_t processedSize = FirstHeader.HeaderSize; - RINOK(ReadStream(_stream, (Byte *)_data, &processedSize)); + RINOK(ReadStream(_stream, (Byte *)_data, &processedSize)) if (processedSize < FirstHeader.HeaderSize) return S_FALSE; } @@ -5892,7 +5954,7 @@ { Clear(); - RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &StartOffset)); + RINOK(InStream_GetPos(inStream, StartOffset)) const UInt32 kStartHeaderSize = 4 * 7; const unsigned kStep = 512; // nsis start is aligned for 512 @@ -5904,7 +5966,7 @@ for (;;) { bufSize = kStep; - RINOK(ReadStream(inStream, buf, &bufSize)); + RINOK(ReadStream(inStream, buf, &bufSize)) if (bufSize < kStartHeaderSize) return S_FALSE; if (memcmp(buf + 4, kSignature, kSignatureSize) == 0) @@ -5936,8 +5998,8 @@ if (pos - posCur > (1 << 20)) break; bufSize = kStep; - RINOK(inStream->Seek(posCur, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream(inStream, buf, &bufSize)); + RINOK(InStream_SeekSet(inStream, posCur)) + RINOK(ReadStream(inStream, buf, &bufSize)) if (bufSize < kStep) break; if (IsArc_Pe(buf, bufSize)) @@ -5949,8 +6011,8 @@ // restore buf to nsis header bufSize = kStep; - RINOK(inStream->Seek(pos, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream(inStream, buf, &bufSize)); + RINOK(InStream_SeekSet(inStream, pos)) + RINOK(ReadStream(inStream, buf, &bufSize)) if (bufSize < kStartHeaderSize) return S_FALSE; } @@ -5990,15 +6052,15 @@ } */ - RINOK(inStream->Seek(0, STREAM_SEEK_END, &_fileSize)); + RINOK(InStream_GetSize_SeekToEnd(inStream, _fileSize)) IsArc = true; if (peSize != 0) { ExeStub.Alloc(peSize); - RINOK(inStream->Seek(pePos, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(inStream, ExeStub, peSize)); + RINOK(InStream_SeekSet(inStream, pePos)) + RINOK(ReadStream_FALSE(inStream, ExeStub, peSize)) } HRESULT res = S_FALSE; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Nsis/NsisIn.h 7zip-23.01+dfsg/CPP/7zip/Archive/Nsis/NsisIn.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Nsis/NsisIn.h 2021-11-18 08:25:35.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Nsis/NsisIn.h 2023-03-26 14:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // NsisIn.h -#ifndef __ARCHIVE_NSIS_IN_H -#define __ARCHIVE_NSIS_IN_H +#ifndef ZIP7_INC_ARCHIVE_NSIS_IN_H +#define ZIP7_INC_ARCHIVE_NSIS_IN_H #include "../../../../C/CpuArch.h" @@ -11,6 +11,8 @@ #include "../../../Common/StringConvert.h" #include "../../../Common/UTFConvert.h" +#include "../../Common/StreamUtils.h" + #include "NsisDecode.h" /* If NSIS_SCRIPT is defined, it will decompile NSIS script to [NSIS].nsi file. @@ -68,6 +70,7 @@ struct CItem { + bool IsEmptyFile; bool IsCompressed; bool Size_Defined; bool CompressedSize_Defined; @@ -77,7 +80,7 @@ // bool UseFilter; UInt32 Attrib; - UInt32 Pos; + UInt32 Pos; // = 0, if (IsEmptyFile == true) UInt32 Size; UInt32 CompressedSize; UInt32 EstimatedSize; @@ -89,7 +92,10 @@ AString NameA; UString NameU; + bool Is_PatchedUninstaller() const { return PatchSize != 0; } + CItem(): + IsEmptyFile(false), IsCompressed(true), Size_Defined(false), CompressedSize_Defined(false), @@ -354,7 +360,7 @@ HRESULT SeekTo(UInt64 pos) { - return _stream->Seek(pos, STREAM_SEEK_SET, NULL); + return InStream_SeekSet(_stream, pos); } HRESULT SeekTo_DataStreamOffset() @@ -433,7 +439,7 @@ if (s[0] == L'\\') s.DeleteFrontal(1); } - if (item.IsUninstaller && ExeStub.Size() == 0) + if (item.Is_PatchedUninstaller() && ExeStub.Size() == 0) s += ".nsis"; return s; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Nsis/NsisRegister.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Nsis/NsisRegister.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Nsis/NsisRegister.cpp 2015-02-11 09:22:51.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Nsis/NsisRegister.cpp 2022-12-20 16:00:00.000000000 +0000 @@ -10,7 +10,7 @@ namespace NNsis { REGISTER_ARC_I( - "Nsis", "nsis", 0, 0x9, + "Nsis", "nsis", NULL, 0x9, kSignature, 4, NArcInfoFlags::kFindSignature | diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Nsis/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Archive/Nsis/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Nsis/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Nsis/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/NtfsHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/NtfsHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/NtfsHandler.cpp 2022-05-01 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/NtfsHandler.cpp 2023-04-06 11:00:00.000000000 +0000 @@ -47,9 +47,9 @@ #define Get32(p) GetUi32(p) #define Get64(p) GetUi64(p) -#define G16(p, dest) dest = Get16(p); -#define G32(p, dest) dest = Get32(p); -#define G64(p, dest) dest = Get64(p); +#define G16(p, dest) dest = Get16(p) +#define G32(p, dest) dest = Get32(p) +#define G64(p, dest) dest = Get64(p) using namespace NWindows; @@ -114,11 +114,11 @@ int t = GetLog(Get16(p + 11)); if (t < 9 || t > 12) return false; - SectorSizeLog = t; + SectorSizeLog = (unsigned)t; t = GetLog(p[13]); if (t < 0) return false; - sectorsPerClusterLog = t; + sectorsPerClusterLog = (unsigned)t; ClusterSizeLog = SectorSizeLog + sectorsPerClusterLog; if (ClusterSizeLog > 30) return false; @@ -173,6 +173,8 @@ UInt64 GetIndex() const { return Val & (((UInt64)1 << 48) - 1); } UInt16 GetNumber() const { return (UInt16)(Val >> 48); } bool IsBaseItself() const { return Val == 0; } + + CMftRef(): Val(0) {} }; #define ATNAME(n) ATTR_TYPE_ ## n @@ -233,6 +235,11 @@ bool IsWin32() const { return (NameType == kFileNameType_Win32); } bool Parse(const Byte *p, unsigned size); + + CFileNameAttr(): + Attrib(0), + NameType(0) + {} }; static void GetString(const Byte *p, unsigned len, UString2 &res) @@ -292,8 +299,18 @@ // UInt64 QuotaCharged; bool Parse(const Byte *p, unsigned size); + + CSiAttr(): + CTime(0), + MTime(0), + ThisRecMTime(0), + ATime(0), + Attrib(0), + SecurityId(0) + {} }; + bool CSiAttr::Parse(const Byte *p, unsigned size) { if (size < 0x24) @@ -382,13 +399,13 @@ } }; -#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } +#define RINOZ(x) { int _tt_ = (x); if (_tt_ != 0) return _tt_; } static int CompareAttr(void *const *elem1, void *const *elem2, void *) { const CAttr &a1 = *(*((const CAttr *const *)elem1)); const CAttr &a2 = *(*((const CAttr *const *)elem2)); - RINOZ(MyCompare(a1.Type, a2.Type)); + RINOZ(MyCompare(a1.Type, a2.Type)) if (a1.Name.IsEmpty()) { if (!a2.Name.IsEmpty()) @@ -398,7 +415,7 @@ return 1; else { - RINOZ(a1.Name.Compare(a2.Name.GetRawPtr())); + RINOZ(a1.Name.Compare(a2.Name.GetRawPtr())) } return MyCompare(a1.LowVcn, a2.LowVcn); } @@ -575,7 +592,7 @@ } p += num; size -= num; - lcn += v; + lcn = (UInt64)((Int64)lcn + v); if (lcn > numClustersMax) return false; e.Phy = lcn; @@ -597,18 +614,20 @@ static const unsigned kNumCacheChunksLog = 1; static const size_t kNumCacheChunks = (size_t)1 << kNumCacheChunksLog; -class CInStream: - public IInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CInStream + , IInStream +) + Z7_IFACE_COM7_IMP(ISequentialInStream) + UInt64 _virtPos; UInt64 _physPos; UInt64 _curRem; bool _sparseMode; - - +public: + bool InUse; +private: unsigned _chunkSizeLog; - UInt64 _tags[kNumCacheChunks]; CByteBuffer _inBuf; CByteBuffer _outBuf; public: @@ -617,12 +636,13 @@ unsigned BlockSizeLog; unsigned CompressionUnit; CRecordVector Extents; - bool InUse; CMyComPtr Stream; +private: + UInt64 _tags[kNumCacheChunks]; - HRESULT SeekToPhys() { return Stream->Seek(_physPos, STREAM_SEEK_SET, NULL); } - + HRESULT SeekToPhys() { return InStream_SeekSet(Stream, _physPos); } UInt32 GetCuSize() const { return (UInt32)1 << (BlockSizeLog + CompressionUnit); } +public: HRESULT InitAndSeek(unsigned compressionUnit) { CompressionUnit = compressionUnit; @@ -645,11 +665,6 @@ _physPos = e.Phy << BlockSizeLog; return SeekToPhys(); } - - MY_UNKNOWN_IMP1(IInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); }; static size_t Lznt1Dec(Byte *dest, size_t outBufLim, size_t destLen, const Byte *src, size_t srcLen) @@ -737,7 +752,7 @@ return destSize; } -STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -827,7 +842,7 @@ if (newPos != _physPos) { _physPos = newPos; - RINOK(SeekToPhys()); + RINOK(SeekToPhys()) } UInt64 next = Extents[i + 1].Virt; if (next > virtBlock2End) @@ -870,30 +885,30 @@ break; if (e.Virt >= virtBlock2End) return S_FALSE; - UInt64 newPos = (e.Phy + (curVirt - e.Virt)) << BlockSizeLog; + const UInt64 newPos = (e.Phy + (curVirt - e.Virt)) << BlockSizeLog; if (newPos != _physPos) { _physPos = newPos; - RINOK(SeekToPhys()); + RINOK(SeekToPhys()) } UInt64 numChunks = Extents[i + 1].Virt - curVirt; if (curVirt + numChunks > virtBlock2End) numChunks = virtBlock2End - curVirt; - size_t compressed = (size_t)numChunks << BlockSizeLog; - RINOK(ReadStream_FALSE(Stream, _inBuf + offs, compressed)); + const size_t compressed = (size_t)numChunks << BlockSizeLog; + RINOK(ReadStream_FALSE(Stream, _inBuf + offs, compressed)) curVirt += numChunks; _physPos += compressed; offs += compressed; } - size_t destLenMax = GetCuSize(); + const size_t destLenMax = GetCuSize(); size_t destLen = destLenMax; const UInt64 rem = Size - (virtBlock2 << BlockSizeLog); if (destLen > rem) destLen = (size_t)rem; Byte *dest = _outBuf + (cacheIndex << _chunkSizeLog); - size_t destSizeRes = Lznt1Dec(dest, destLenMax, destLen, _inBuf, offs); + const size_t destSizeRes = Lznt1Dec(dest, destLenMax, destLen, _inBuf, offs); _tags[cacheIndex] = cacheTag; // some files in Vista have destSize > destLen @@ -922,7 +937,7 @@ return res; } -STDMETHODIMP CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { @@ -936,10 +951,10 @@ if (_virtPos != (UInt64)offset) { _curRem = 0; - _virtPos = offset; + _virtPos = (UInt64)offset; } if (newPosition) - *newPosition = offset; + *newPosition = (UInt64)offset; return S_OK; } @@ -1002,6 +1017,15 @@ static const UInt32 kMagic_FILE = 0x454C4946; static const UInt32 kMagic_BAAD = 0x44414142; +// 22.02: we support some rare case magic values: +static const UInt32 kMagic_INDX = 0x58444e49; +static const UInt32 kMagic_HOLE = 0x454c4f48; +static const UInt32 kMagic_RSTR = 0x52545352; +static const UInt32 kMagic_RCRD = 0x44524352; +static const UInt32 kMagic_CHKD = 0x444b4843; +static const UInt32 kMagic_FFFFFFFF = 0xFFFFFFFF; + + struct CMftRec { UInt32 Magic; @@ -1033,7 +1057,7 @@ { const CFileNameAttr &next = FileNames[i]; if (next.IsWin32() && cur.ParentDirRef.Val == next.ParentDirRef.Val) - return i; + return (int)i; } return -1; } @@ -1046,7 +1070,7 @@ { const CFileNameAttr &next = FileNames[i]; if (next.IsDos() && cur.ParentDirRef.Val == next.ParentDirRef.Val) - return i; + return (int)i; } return -1; } @@ -1078,9 +1102,25 @@ bool Parse(Byte *p, unsigned sectorSizeLog, UInt32 numSectors, UInt32 recNumber, CObjectVector *attrs); - bool IsEmpty() const { return (Magic <= 2); } - bool IsFILE() const { return (Magic == kMagic_FILE); } - bool IsBAAD() const { return (Magic == kMagic_BAAD); } + bool Is_Magic_Empty() const + { + // what exact Magic values are possible for empty and unused records? + const UInt32 k_Magic_Unused_MAX = 5; // 22.02 + return (Magic <= k_Magic_Unused_MAX); + } + bool Is_Magic_FILE() const { return (Magic == kMagic_FILE); } + // bool Is_Magic_BAAD() const { return (Magic == kMagic_BAAD); } + bool Is_Magic_CanIgnore() const + { + return Is_Magic_Empty() + || Magic == kMagic_BAAD + || Magic == kMagic_INDX + || Magic == kMagic_HOLE + || Magic == kMagic_RSTR + || Magic == kMagic_RCRD + || Magic == kMagic_CHKD + || Magic == kMagic_FFFFFFFF; + } bool InUse() const { return (Flags & 1) != 0; } bool IsDir() const { return (Flags & 2) != 0; } @@ -1092,7 +1132,11 @@ UInt64 GetSize(unsigned dataIndex) const { return DataAttrs[DataRefs[dataIndex].Start].GetSize(); } - CMftRec(): MyNumNameLinks(0), MyItemIndex(-1) {} + CMftRec(): + SeqNumber(0), + Flags(0), + MyNumNameLinks(0), + MyItemIndex(-1) {} }; void CMftRec::ParseDataNames() @@ -1115,7 +1159,7 @@ HRESULT CMftRec::GetStream(IInStream *mainStream, int dataIndex, unsigned clusterSizeLog, UInt64 numPhysClusters, IInStream **destStream) const { - *destStream = 0; + *destStream = NULL; CBufferInStream *streamSpec = new CBufferInStream; CMyComPtr streamTemp = streamSpec; @@ -1137,13 +1181,13 @@ return S_FALSE; CInStream *ss = new CInStream; CMyComPtr streamTemp2 = ss; - RINOK(DataParseExtents(clusterSizeLog, DataAttrs, ref.Start, ref.Start + ref.Num, numPhysClusters, ss->Extents)); + RINOK(DataParseExtents(clusterSizeLog, DataAttrs, ref.Start, ref.Start + ref.Num, numPhysClusters, ss->Extents)) ss->Size = attr0.Size; ss->InitializedSize = attr0.InitializedSize; ss->Stream = mainStream; ss->BlockSizeLog = clusterSizeLog; ss->InUse = InUse(); - RINOK(ss->InitAndSeek(attr0.CompressionUnit)); + RINOK(ss->InitAndSeek(attr0.CompressionUnit)) *destStream = streamTemp2.Detach(); return S_OK; } @@ -1189,9 +1233,8 @@ CObjectVector *attrs) { G32(p, Magic); - if (!IsFILE()) - return IsEmpty() || IsBAAD(); - + if (!Is_Magic_FILE()) + return Is_Magic_CanIgnore(); { UInt32 usaOffset; @@ -1228,7 +1271,7 @@ void *pp = p + (i << sectorSizeLog) - 2; if (Get16(pp) != usn) return false; - SetUi16(pp, Get16(p + usaOffset + i * 2)); + SetUi16(pp, Get16(p + usaOffset + i * 2)) } } @@ -1455,7 +1498,7 @@ HRESULT CDatabase::SeekToCluster(UInt64 cluster) { - return InStream->Seek(cluster << Header.ClusterSizeLog, STREAM_SEEK_SET, NULL); + return InStream_SeekSet(InStream, cluster << Header.ClusterSizeLog); } void CDatabase::Clear() @@ -1702,14 +1745,14 @@ */ { - static const UInt32 kHeaderSize = 512; + const UInt32 kHeaderSize = 512; Byte buf[kHeaderSize]; - RINOK(ReadStream_FALSE(InStream, buf, kHeaderSize)); + RINOK(ReadStream_FALSE(InStream, buf, kHeaderSize)) if (!Header.Parse(buf)) return S_FALSE; UInt64 fileSize; - RINOK(InStream->Seek(0, STREAM_SEEK_END, &fileSize)); + RINOK(InStream_GetSize_SeekToEnd(InStream, fileSize)) PhySize = Header.GetPhySize_Clusters(); if (fileSize < PhySize) return S_FALSE; @@ -1717,7 +1760,7 @@ UInt64 phySizeMax = Header.GetPhySize_Max(); if (fileSize >= phySizeMax) { - RINOK(InStream->Seek(Header.NumSectors << Header.SectorSizeLog, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(InStream, Header.NumSectors << Header.SectorSizeLog)) Byte buf2[kHeaderSize]; if (ReadStream_FALSE(InStream, buf2, kHeaderSize) == S_OK) { @@ -1737,14 +1780,14 @@ { UInt32 blockSize = 1 << 12; ByteBuf.Alloc(blockSize); - RINOK(ReadStream_FALSE(InStream, ByteBuf, blockSize)); + RINOK(ReadStream_FALSE(InStream, ByteBuf, blockSize)) { - UInt32 allocSize = Get32(ByteBuf + 0x1C); - int t = GetLog(allocSize); + const UInt32 allocSize = Get32(ByteBuf + 0x1C); + const int t = GetLog(allocSize); if (t < (int)Header.SectorSizeLog) return S_FALSE; - RecSizeLog = t; + RecSizeLog = (unsigned)t; if (RecSizeLog > 15) return S_FALSE; } @@ -1752,12 +1795,12 @@ numSectorsInRec = 1 << (RecSizeLog - Header.SectorSizeLog); if (!mftRec.Parse(ByteBuf, Header.SectorSizeLog, numSectorsInRec, 0, NULL)) return S_FALSE; - if (!mftRec.IsFILE()) + if (!mftRec.Is_Magic_FILE()) return S_FALSE; mftRec.ParseDataNames(); if (mftRec.DataRefs.IsEmpty()) return S_FALSE; - RINOK(mftRec.GetStream(InStream, 0, Header.ClusterSizeLog, Header.NumClusters, &mftStream)); + RINOK(mftRec.GetStream(InStream, 0, Header.ClusterSizeLog, Header.NumClusters, &mftStream)) if (!mftStream) return S_FALSE; } @@ -1779,7 +1822,7 @@ return S_FALSE; if (OpenCallback) { - RINOK(OpenCallback->SetTotal(&numFiles, &mftSize)); + RINOK(OpenCallback->SetTotal(&numFiles, &mftSize)) } ByteBuf.Alloc(kBufSize); @@ -1791,9 +1834,9 @@ if (OpenCallback) { const UInt64 numFiles = Recs.Size(); - if ((numFiles & 0x3FF) == 0) + if ((numFiles & 0x3FFF) == 0) { - RINOK(OpenCallback->SetCompleted(&numFiles, &pos64)); + RINOK(OpenCallback->SetCompleted(&numFiles, &pos64)) } } size_t readSize = kBufSize; @@ -1804,7 +1847,7 @@ } if (readSize < recSize) break; - RINOK(ReadStream_FALSE(mftStream, ByteBuf, readSize)); + RINOK(ReadStream_FALSE(mftStream, ByteBuf, readSize)) pos64 += readSize; for (size_t i = 0; readSize >= recSize; i += recSize, readSize -= recSize) @@ -1880,12 +1923,18 @@ for (i = 0; i < Recs.Size(); i++) { CMftRec &rec = Recs[i]; + if (!rec.Is_Magic_FILE()) + continue; + if (!rec.BaseMftRef.IsBaseItself()) { - UInt64 refIndex = rec.BaseMftRef.GetIndex(); - if (refIndex > (UInt32)Recs.Size()) + const UInt64 refIndex = rec.BaseMftRef.GetIndex(); + if (refIndex >= Recs.Size()) return S_FALSE; CMftRec &refRec = Recs[(unsigned)refIndex]; + if (!refRec.Is_Magic_FILE()) + continue; + bool moveAttrs = (refRec.SeqNumber == rec.BaseMftRef.GetNumber() && refRec.BaseMftRef.IsBaseItself()); if (rec.InUse() && refRec.InUse()) { @@ -1900,12 +1949,17 @@ } for (i = 0; i < Recs.Size(); i++) - Recs[i].ParseDataNames(); + { + CMftRec &rec = Recs[i]; + if (!rec.Is_Magic_FILE()) + continue; + rec.ParseDataNames(); + } for (i = 0; i < Recs.Size(); i++) { CMftRec &rec = Recs[i]; - if (!rec.IsFILE() || !rec.BaseMftRef.IsBaseItself()) + if (!rec.Is_Magic_FILE() || !rec.BaseMftRef.IsBaseItself()) continue; if (i < kNumSysRecs && !_showSystemFiles) continue; @@ -1927,7 +1981,7 @@ FOR_VECTOR (di, rec.DataRefs) if (rec.DataAttrs[rec.DataRefs[di].Start].Name.IsEmpty()) { - indexOfUnnamedStream = di; + indexOfUnnamedStream = (int)di; break; } } @@ -1985,14 +2039,14 @@ indexOfUnnamedStream); if (rec.MyItemIndex < 0) - rec.MyItemIndex = Items.Size(); - item.ParentHost = Items.Add(item); + rec.MyItemIndex = (int)Items.Size(); + item.ParentHost = (int)Items.Add(item); /* we can use that code to reduce the number of alt streams: it will not show how alt streams for hard links. */ // if (!isMainName) continue; isMainName = false; - unsigned numAltStreams = 0; + // unsigned numAltStreams = 0; FOR_VECTOR (di, rec.DataRefs) { @@ -2010,9 +2064,9 @@ continue; } - numAltStreams++; + // numAltStreams++; ThereAreAltStreams = true; - item.DataIndex = di; + item.DataIndex = (int)di; Items.Add(item); } } @@ -2027,10 +2081,10 @@ if (attr.Name == L"$SDS") { CMyComPtr sdsStream; - RINOK(rec.GetStream(InStream, di, Header.ClusterSizeLog, Header.NumClusters, &sdsStream)); + RINOK(rec.GetStream(InStream, (int)di, Header.ClusterSizeLog, Header.NumClusters, &sdsStream)) if (sdsStream) { - UInt64 size64 = attr.GetSize(); + const UInt64 size64 = attr.GetSize(); if (size64 < (UInt32)1 << 29) { size_t size = (size_t)size64; @@ -2060,7 +2114,7 @@ const CMftRec &rec = Recs[item.RecIndex]; const CFileNameAttr &fn = rec.FileNames[item.NameIndex]; const CMftRef &parentDirRef = fn.ParentDirRef; - UInt64 refIndex = parentDirRef.GetIndex(); + const UInt64 refIndex = parentDirRef.GetIndex(); if (refIndex == kRecIndex_RootDir) item.ParentFolder = -1; else @@ -2087,57 +2141,52 @@ unsigned virtIndex = Items.Size(); if (_showSystemFiles) { - _systemFolderIndex = virtIndex++; + _systemFolderIndex = (int)(virtIndex++); VirtFolderNames.Add(kVirtualFolder_System); } if (thereAreUnknownFolders_Normal) { - _lostFolderIndex_Normal = virtIndex++; + _lostFolderIndex_Normal = (int)(virtIndex++); VirtFolderNames.Add(kVirtualFolder_Lost_Normal); } if (thereAreUnknownFolders_Deleted) { - _lostFolderIndex_Deleted = virtIndex++; + _lostFolderIndex_Deleted = (int)(virtIndex++); VirtFolderNames.Add(kVirtualFolder_Lost_Deleted); } return S_OK; } -class CHandler: +Z7_class_CHandler_final: public IInArchive, public IArchiveGetRawProps, public IInArchiveGetStream, public ISetProperties, public CMyUnknownImp, - CDatabase + public CDatabase { -public: - MY_UNKNOWN_IMP4( + Z7_IFACES_IMP_UNK_4( IInArchive, IArchiveGetRawProps, IInArchiveGetStream, ISetProperties) - INTERFACE_IInArchive(;) - INTERFACE_IArchiveGetRawProps(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); - STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps); }; -STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) +Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps)) { *numProps = 2; return S_OK; } -STDMETHODIMP CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID) +Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID)) { *name = NULL; *propID = index == 0 ? kpidNtReparse : kpidNtSecure; return S_OK; } -STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType) +Z7_COM7F_IMF(CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType)) { *parentType = NParentType::kDir; int par = -1; @@ -2167,7 +2216,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) +Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType)) { *data = NULL; *dataSize = 0; @@ -2236,10 +2285,10 @@ return S_OK; } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN - *stream = 0; + *stream = NULL; if (index >= Items.Size()) return S_OK; IInStream *stream2; @@ -2357,7 +2406,7 @@ prop = ft; } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -2415,7 +2464,7 @@ { s.Add_Space(); s.Add_UInt32(vi.MajorVer); - s += '.'; + s.Add_Dot(); s.Add_UInt32(vi.MinorVer); } break; @@ -2461,7 +2510,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -2529,7 +2578,7 @@ { // const CMftRec &rec = Recs[item.RecIndex]; // prop = ((UInt64)rec.SeqNumber << 48) | item.RecIndex; - prop = item.RecIndex; + prop = (UInt32)item.RecIndex; break; } case kpidStreamId: @@ -2622,7 +2671,7 @@ if (!rec.IsDir() && rec.DataAttrs[rec.DataRefs[0].Start].Name.IsEmpty()) num--; if (num > 0) - prop = num; + prop = (UInt32)num; } } break; @@ -2637,7 +2686,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback)) { COM_TRY_BEGIN { @@ -2661,17 +2710,17 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { ClearAndClose(); return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = Items.Size(); if (numItems == 0) @@ -2680,15 +2729,15 @@ UInt64 totalSize = 0; for (i = 0; i < numItems; i++) { - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; if (index >= (UInt32)Items.Size()) continue; const CItem &item = Items[allFilesMode ? i : indices[i]]; const CMftRec &rec = Recs[item.RecIndex]; if (item.DataIndex >= 0) - totalSize += rec.GetSize(item.DataIndex); + totalSize += rec.GetSize((unsigned)item.DataIndex); } - RINOK(extractCallback->SetTotal(totalSize)); + RINOK(extractCallback->SetTotal(totalSize)) UInt64 totalPackSize; totalSize = totalPackSize = 0; @@ -2710,18 +2759,18 @@ { lps->InSize = totalPackSize; lps->OutSize = totalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - UInt32 index = allFilesMode ? i : indices[i]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + const UInt32 index = allFilesMode ? i : indices[i]; + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) if (index >= (UInt32)Items.Size() || Items[index].IsDir()) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } @@ -2729,7 +2778,7 @@ if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) outStreamSpec->SetStream(realOutStream); realOutStream.Release(); @@ -2745,13 +2794,13 @@ res = NExtract::NOperationResult::kUnsupportedMethod; else { - RINOK(hres); + RINOK(hres) if (inStream) { hres = copyCoder->Code(inStream, outStream, NULL, NULL, progress); if (hres != S_OK && hres != S_FALSE) { - RINOK(hres); + RINOK(hres) } if (/* copyCoderSpec->TotalSize == item.GetSize() && */ hres == S_OK) res = NExtract::NOperationResult::kOK; @@ -2765,19 +2814,19 @@ totalSize += data.GetSize(); } outStreamSpec->ReleaseStream(); - RINOK(extractCallback->SetOperationResult(res)); + RINOK(extractCallback->SetOperationResult(res)) } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = Items.Size() + VirtFolderNames.Size(); return S_OK; } -STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) +Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps)) { InitProps(); @@ -2788,11 +2837,11 @@ if (StringsAreEqualNoCase_Ascii(name, "ld")) { - RINOK(PROPVARIANT_to_bool(prop, _showDeletedFiles)); + RINOK(PROPVARIANT_to_bool(prop, _showDeletedFiles)) } else if (StringsAreEqualNoCase_Ascii(name, "ls")) { - RINOK(PROPVARIANT_to_bool(prop, _showSystemFiles)); + RINOK(PROPVARIANT_to_bool(prop, _showSystemFiles)) } else return E_INVALIDARG; @@ -2803,7 +2852,7 @@ static const Byte k_Signature[] = { 'N', 'T', 'F', 'S', ' ', ' ', ' ', ' ', 0 }; REGISTER_ARC_I( - "NTFS", "ntfs img", 0, 0xD9, + "NTFS", "ntfs img", NULL, 0xD9, k_Signature, 3, 0, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/PeHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/PeHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/PeHandler.cpp 2022-02-14 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/PeHandler.cpp 2023-03-26 12:00:00.000000000 +0000 @@ -28,9 +28,10 @@ #define G16(offs, v) v = Get16(p + (offs)) #define G32(offs, v) v = Get32(p + (offs)) +#define G32_signed(offs, v) v = (Int32)Get32(p + (offs)) #define G64(offs, v) v = Get64(p + (offs)) -#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } +#define RINOZ(x) { int _tt_ = (x); if (_tt_ != 0) return _tt_; } using namespace NWindows; @@ -55,7 +56,7 @@ if (rem == 0) break; size_t processed = rem; - RINOK(ReadStream(stream, buf, &processed)); + RINOK(ReadStream(stream, buf, &processed)) for (unsigned j = 0; j < 4; j++) { @@ -258,9 +259,9 @@ int GetNumFileAlignBits() const { - for (unsigned i = 0; i <= 31; i++) + for (unsigned i = 0; i < 32; i++) if (((UInt32)1 << i) == FileAlign) - return i; + return (int)i; return -1; } @@ -339,6 +340,7 @@ pos += 4; if (pos + 8 * NumDirItems > size) return false; + memset((void *)DirItems, 0, sizeof(DirItems)); for (UInt32 i = 0; i < NumDirItems && i < kNumDirItemsMax; i++) DirItems[i].Parse(p + pos + i * 8); return true; @@ -377,7 +379,7 @@ int Compare(const CSection &s) const { - RINOZ(MyCompare(Pa, s.Pa)); + RINOZ(MyCompare(Pa, s.Pa)) UInt32 size1 = GetSizeExtract(); UInt32 size2 = s.GetSizeExtract(); return MyCompare(size1, size2); @@ -613,7 +615,7 @@ size_t FinalSize() const { return Buf.GetPos(); } - void AddChar(Byte c); + void AddChar(char c); void AddWChar(UInt16 c); void AddWChar_Smart(UInt16 c); void NewLine(); @@ -638,17 +640,17 @@ } }; -void CTextFile::AddChar(Byte c) +void CTextFile::AddChar(char c) { Byte *p = Buf.GetCurPtrAndGrow(2); - p[0] = c; + p[0] = (Byte)c; p[1] = 0; } void CTextFile::AddWChar(UInt16 c) { Byte *p = Buf.GetCurPtrAndGrow(2); - SetUi16(p, c); + SetUi16(p, c) } void CTextFile::AddWChar_Smart(UInt16 c) @@ -743,12 +745,11 @@ UString Value; }; -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public IArchiveAllowTail, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_CHandler_IInArchive_2( + IInArchiveGetStream, + IArchiveAllowTail +) CMyComPtr _stream; CObjectVector _sections; CHeader _header; @@ -770,6 +771,7 @@ CUsedBitmap _usedRes; // bool _parseResources; bool _checksumError; + bool _sectionsError; bool IsOpt() const { return _header.OptHeaderSize != 0; } @@ -800,11 +802,6 @@ _coffMode(coffMode), _allowTail(coffMode) {} - - MY_UNKNOWN_IMP3(IInArchive, IInArchiveGetStream, IArchiveAllowTail) - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); - STDMETHOD(AllowTail)(Int32 allowTail); }; @@ -888,7 +885,7 @@ PropVariant_SetFrom_UnixTime(prop, unixTime); } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -911,6 +908,15 @@ // case kpidError: case kpidWarning: if (_checksumError) prop = "Checksum error"; break; + case kpidWarningFlags: + { + UInt32 v = 0; + if (_sectionsError) v |= kpv_ErrorFlags_HeadersError; + if (v != 0) + prop = v; + break; + } + case kpidCpu: PAIR_TO_PROP(g_MachinePairs, _header.Machine, prop); break; case kpidMTime: case kpidCTime: TimeToProp(_header.Time, prop); break; @@ -1029,7 +1035,7 @@ } } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -1081,7 +1087,7 @@ AddLangPrefix(s, item.Lang); { const char *p = NULL; - if (item.Type < ARRAY_SIZE(g_ResTypes)) + if (item.Type < Z7_ARRAY_SIZE(g_ResTypes)) p = g_ResTypes[item.Type]; if (p) s += p; @@ -1109,7 +1115,14 @@ const CSection &item = _sections[mixItem.SectionIndex]; switch (propID) { - case kpidPath: prop = MultiByteToUnicodeString(item.Name); break; + case kpidPath: + { + AString s = item.Name; + s.Replace('/', '_'); + s.Replace('\\', '_'); + prop = MultiByteToUnicodeString(s); + break; + } case kpidSize: prop = (UInt64)item.PSize; break; case kpidPackSize: prop = (UInt64)item.PSize; break; case kpidVirtualSize: prop = (UInt64)item.VSize; break; @@ -1122,8 +1135,8 @@ if (item.IsRealSect) { UInt32 flags = item.Flags; - const UInt32 MY__IMAGE_SCN_ALIGN_MASK = 0x00F00000; - AString s = FlagsToString(g_SectFlags, ARRAY_SIZE(g_SectFlags), item.Flags & ~MY__IMAGE_SCN_ALIGN_MASK); + const UInt32 MY_IMAGE_SCN_ALIGN_MASK = 0x00F00000; + AString s = FlagsToString(g_SectFlags, Z7_ARRAY_SIZE(g_SectFlags), item.Flags & ~MY_IMAGE_SCN_ALIGN_MASK); const UInt32 align = ((flags >> 20) & 0xF); if (align != 0) { @@ -1185,8 +1198,8 @@ CByteBuffer buffer(debugLink.Size); Byte *buf = buffer; - RINOK(stream->Seek(pa, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(stream, buf, debugLink.Size)); + RINOK(InStream_SeekSet(stream, pa)) + RINOK(ReadStream_FALSE(stream, buf, debugLink.Size)) for (i = 0; i < numItems; i++) { @@ -1271,7 +1284,7 @@ if (size < kBitmapInfoHeader_Size || Get32(p) != kBitmapInfoHeader_Size) return false; G32( 4, XSize); - G32( 8, YSize); + G32_signed( 8, YSize); G16(12, Planes); G16(14, BitCount); G32(16, Compression); @@ -1291,21 +1304,24 @@ return 0; if (h.YSize < 0) h.YSize = -h.YSize; - if (h.XSize > (1 << 26) || h.YSize > (1 << 26) || h.Planes != 1 || h.BitCount > 32) + if (h.XSize > (1 << 26) + || h.YSize > (1 << 26) + || h.YSize < 0 + || h.Planes != 1 || h.BitCount > 32) return 0; if (h.SizeImage == 0) { if (h.Compression != 0) // BI_RGB return 0; - h.SizeImage = GetImageSize(h.XSize, h.YSize, h.BitCount); + h.SizeImage = GetImageSize(h.XSize, (UInt32)h.YSize, h.BitCount); } UInt32 totalSize = kBmpHeaderSize + size; UInt32 offBits = totalSize - h.SizeImage; // BITMAPFILEHEADER - SetUi16(dest, 0x4D42); - SetUi32(dest + 2, totalSize); - SetUi32(dest + 6, 0); - SetUi32(dest + 10, offBits); + SetUi16(dest, 0x4D42) + SetUi32(dest + 2, totalSize) + SetUi32(dest + 6, 0) + SetUi32(dest + 10, offBits) return kBmpHeaderSize; } @@ -1316,11 +1332,14 @@ return 0; if (h.YSize < 0) h.YSize = -h.YSize; - if (h.XSize > (1 << 26) || h.YSize > (1 << 26) || h.Planes != 1 || - h.Compression != 0) // BI_RGB + if (h.XSize > (1 << 26) + || h.YSize > (1 << 26) + || h.YSize < 0 + || h.Planes != 1 + || h.Compression != 0) // BI_RGB return 0; - UInt32 numBitCount = h.BitCount; + const UInt32 numBitCount = h.BitCount; if (numBitCount != 1 && numBitCount != 4 && numBitCount != 8 && @@ -1341,29 +1360,29 @@ // UInt32 imageSize = h.SizeImage; // if (imageSize == 0) // { - UInt32 image1Size = GetImageSize(h.XSize, h.YSize, h.BitCount); - UInt32 image2Size = GetImageSize(h.XSize, h.YSize, 1); + const UInt32 image1Size = GetImageSize(h.XSize, (UInt32)h.YSize, h.BitCount); + const UInt32 image2Size = GetImageSize(h.XSize, (UInt32)h.YSize, 1); imageSize = image1Size + image2Size; // } UInt32 numColors = 0; if (numBitCount < 16) numColors = 1 << numBitCount; - SetUi16(dest, 0); // Reserved - SetUi16(dest + 2, 1); // RES_ICON - SetUi16(dest + 4, 1); // ResCount + SetUi16(dest, 0) // Reserved + SetUi16(dest + 2, 1) // RES_ICON + SetUi16(dest + 4, 1) // ResCount dest[6] = (Byte)h.XSize; // Width dest[7] = (Byte)h.YSize; // Height dest[8] = (Byte)numColors; // ColorCount dest[9] = 0; // Reserved - SetUi32(dest + 10, 0); // Reserved1 / Reserved2 + SetUi32(dest + 10, 0) // Reserved1 / Reserved2 UInt32 numQuadsBytes = numColors * 4; UInt32 BytesInRes = kBitmapInfoHeader_Size + numQuadsBytes + imageSize; - SetUi32(dest + 14, BytesInRes); - SetUi32(dest + 18, kIconHeaderSize); + SetUi32(dest + 14, BytesInRes) + SetUi32(dest + 18, kIconHeaderSize) /* Description = DWORDToString(xSize) + @@ -1500,9 +1519,9 @@ static void PrintVersion(UString &s, UInt32 ms, UInt32 ls) { - PrintUInt32(s, HIWORD(ms)); s += '.'; - PrintUInt32(s, LOWORD(ms)); s += '.'; - PrintUInt32(s, HIWORD(ls)); s += '.'; + PrintUInt32(s, HIWORD(ms)); s.Add_Dot(); + PrintUInt32(s, LOWORD(ms)); s.Add_Dot(); + PrintUInt32(s, HIWORD(ls)); s.Add_Dot(); PrintUInt32(s, LOWORD(ls)); } @@ -1590,7 +1609,7 @@ { FOR_VECTOR (i, v) if (v[i].Key.IsEqualTo(key)) - return i; + return (int)i; return -1; } @@ -1642,7 +1661,7 @@ f.AddString("FILEFLAGS "); { bool wasPrinted = false; - for (unsigned i = 0; i < ARRAY_SIZE(k_VS_FileFlags); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_VS_FileFlags); i++) { if ((Flags & ((UInt32)1 << i)) != 0) { @@ -1653,7 +1672,7 @@ wasPrinted = true; } } - UInt32 v = Flags & ~(((UInt32)1 << ARRAY_SIZE(k_VS_FileFlags)) - 1); + UInt32 v = Flags & ~(((UInt32)1 << Z7_ARRAY_SIZE(k_VS_FileFlags)) - 1); if (v != 0 || !wasPrinted) { if (wasPrinted) @@ -1666,7 +1685,7 @@ // OS = 0x111230; f.AddString("FILEOS "); unsigned i; - for (i = 0; i < ARRAY_SIZE(k_VS_FileOS); i++) + for (i = 0; i < Z7_ARRAY_SIZE(k_VS_FileOS); i++) { const CUInt32PCharPair &pair = k_VS_FileOS[i]; if (OS == pair.Value) @@ -1677,10 +1696,10 @@ break; } } - if (i == ARRAY_SIZE(k_VS_FileOS)) + if (i == Z7_ARRAY_SIZE(k_VS_FileOS)) { UInt32 high = OS >> 16; - if (high < ARRAY_SIZE(k_VS_FileOS_High)) + if (high < Z7_ARRAY_SIZE(k_VS_FileOS_High)) f.AddString(k_VS_FileOS_High[high]); else PrintHex(f, high << 16); @@ -1688,7 +1707,7 @@ if (low != 0) { f.AddString(" | "); - if (low < ARRAY_SIZE(k_VS_FileOS_Low)) + if (low < Z7_ARRAY_SIZE(k_VS_FileOS_Low)) f.AddString(k_VS_FileOS_Low[low]); else PrintHex(f, low); @@ -1697,7 +1716,7 @@ f.NewLine(); f.AddString("FILETYPE "); - if (Type < ARRAY_SIZE(k_VS_FileType)) + if (Type < Z7_ARRAY_SIZE(k_VS_FileType)) f.AddString(k_VS_FileType[Type]); else PrintHex(f, Type); @@ -1707,7 +1726,7 @@ bool needPrintSubType = true; if (Type == kMY_VFT_DRV) { - if (Subtype != 0 && Subtype < ARRAY_SIZE(k_VS_FileSubType_DRV)) + if (Subtype != 0 && Subtype < Z7_ARRAY_SIZE(k_VS_FileSubType_DRV)) { f.AddString("VFT2_DRV_"); f.AddString(k_VS_FileSubType_DRV[Subtype]); @@ -1716,7 +1735,7 @@ } else if (Type == kMY_VFT_FONT) { - if (Subtype != 0 && Subtype < ARRAY_SIZE(k_VS_FileSubType_FONT)) + if (Subtype != 0 && Subtype < Z7_ARRAY_SIZE(k_VS_FileSubType_FONT)) { f.AddString(k_VS_FileSubType_FONT[Subtype]); needPrintSubType = false; @@ -1744,7 +1763,7 @@ unsigned pos = 0; for (;;) { - Byte c = *s++; + const Byte c = (Byte)*s++; if (Get16(p + pos) != c) return false; pos += 2; @@ -1771,7 +1790,7 @@ if (pos + 1 >= size) return -1; if (Get16(p + pos) == 0) - return pos; + return (int)pos; pos += 2; } } @@ -1793,10 +1812,10 @@ default: return false; } StrSize = 0; - int t = Get_Utf16Str_Len_InBytes(p + k_ResoureBlockHeader_Size, TotalLen - k_ResoureBlockHeader_Size); + const int t = Get_Utf16Str_Len_InBytes(p + k_ResoureBlockHeader_Size, TotalLen - k_ResoureBlockHeader_Size); if (t < 0) return false; - StrSize = t; + StrSize = (unsigned)t; return true; } @@ -1962,12 +1981,12 @@ { f.AddChar(','); f.AddSpaces((34 - (int)vb3.StrSize) / 2); - int sLen = Get_Utf16Str_Len_InBytes(p + pos, endPos3 - pos); + const int sLen = Get_Utf16Str_Len_InBytes(p + pos, endPos3 - pos); if (sLen < 0) return false; AddParamString(f, p + pos, (unsigned)sLen); CopyToUString(p + pos, value); - pos += sLen + 2; + pos += (unsigned)sLen + 2; } AddToUniqueUStringVector(keys, key, value); } @@ -2016,10 +2035,10 @@ { const UInt64 fileSize64 = fileSize; if (callback) - RINOK(callback->SetTotal(NULL, &fileSize64)); + RINOK(callback->SetTotal(NULL, &fileSize64)) } - RINOK(stream->Seek(sect.Pa, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, sect.Pa)) _buf.Alloc(fileSize); @@ -2033,7 +2052,7 @@ RINOK(callback->SetCompleted(NULL, &offset64)) } size_t rem = MyMin(fileSize - pos, (size_t)(1 << 22)); - RINOK(ReadStream(stream, _buf + pos, &rem)); + RINOK(ReadStream(stream, _buf + pos, &rem)) if (rem == 0) { if (pos < fileSizeMin) @@ -2049,7 +2068,7 @@ _usedRes.Alloc(fileSize); CRecordVector specItems; - RINOK(ReadTable(0, specItems)); + RINOK(ReadTable(0, specItems)) _oneLang = true; bool stringsOk = true; @@ -2062,7 +2081,7 @@ return S_FALSE; CRecordVector specItems2; - RINOK(ReadTable(item1.Offset & kMask, specItems2)); + RINOK(ReadTable(item1.Offset & kMask, specItems2)) FOR_VECTOR (j, specItems2) { @@ -2071,7 +2090,7 @@ return S_FALSE; CRecordVector specItems3; - RINOK(ReadTable(item2.Offset & kMask, specItems3)); + RINOK(ReadTable(item2.Offset & kMask, specItems3)) CResItem item; item.Type = item1.ID; @@ -2126,8 +2145,8 @@ if (ParseVersion((const Byte *)_buf + offset, item.Size, f, _versionKeys)) { CMixItem mixItem; - mixItem.VersionIndex = _versionFiles.Size(); - mixItem.SectionIndex = sectionIndex; // check it !!!! + mixItem.VersionIndex = (int)_versionFiles.Size(); + mixItem.SectionIndex = (int)sectionIndex; // check it !!!! CByteBuffer_WithLang &vf = _versionFiles.AddNew(); vf.Lang = item.Lang; vf.CopyFrom(f.Buf, f.Buf.GetPos()); @@ -2157,8 +2176,8 @@ if (_strings[i].FinalSize() == 0) continue; CMixItem mixItem; - mixItem.StringIndex = i; - mixItem.SectionIndex = sectionIndex; + mixItem.StringIndex = (int)i; + mixItem.SectionIndex = (int)sectionIndex; _mixItems.Add(mixItem); } } @@ -2219,7 +2238,7 @@ if (NumSections == 0 && OptHeaderSize == 0) return false; - for (unsigned i = 0; i < ARRAY_SIZE(g_MachinePairs); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_MachinePairs); i++) if (Machine == g_MachinePairs[i].Value) return true; if (Machine == 0) @@ -2263,7 +2282,7 @@ if (_coffMode) { Byte h[kCoffHeaderSize]; - RINOK(ReadStream_FALSE(stream, h, kCoffHeaderSize)); + RINOK(ReadStream_FALSE(stream, h, kCoffHeaderSize)) if (!_header.ParseCoff(h)) return S_FALSE; } @@ -2272,7 +2291,7 @@ UInt32 _peOffset; { Byte h[kStartSize]; - RINOK(ReadStream_FALSE(stream, h, kStartSize)); + RINOK(ReadStream_FALSE(stream, h, kStartSize)) if (h[0] != 'M' || h[1] != 'Z') return S_FALSE; /* most of PE files contain 0x0090 at offset 2. @@ -2285,8 +2304,8 @@ } { Byte h[kPeHeaderSize]; - RINOK(stream->Seek(_peOffset, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(stream, h, kPeHeaderSize)); + RINOK(InStream_SeekSet(stream, _peOffset)) + RINOK(ReadStream_FALSE(stream, h, kPeHeaderSize)) if (!_header.ParsePe(h)) return S_FALSE; } @@ -2297,8 +2316,9 @@ _totalSize = optStart + bufSize; CByteBuffer buffer(bufSize); - RINOK(ReadStream_FALSE(stream, buffer, bufSize)); + RINOK(ReadStream_FALSE(stream, buffer, bufSize)) + // memset((void *)&_optHeader, 0, sizeof(_optHeader)); if (_header.OptHeaderSize != 0) if (!_optHeader.Parse(buffer, _header.OptHeaderSize)) return S_FALSE; @@ -2312,26 +2332,40 @@ sect.IsRealSect = true; /* PE pre-file in .hxs file has errors: - PSize of resource is larger tnan real size. - So it overlaps next ".its" section. - We correct it. */ - - if (i > 0) - { - CSection &prev = _sections[i - 1]; - if (prev.Pa < sect.Pa && - prev.Pa + prev.PSize > sect.Pa && - sect.PSize > 0) - { - // printf("\n !!!! Section correction: %s\n ", prev.Name); - // fflush(stdout); - prev.PSize = sect.Pa - prev.Pa; + PSize of resource is larger than real size. + So it overlaps next ".its" section. + 7-zip before 22.02: we corrected it. + + 22.02: another bad case is possible in incorrect pe (exe) file: + PSize in .rsrc section is correct, + but next .reloc section has incorrect (Pa) that overlaps with .rsrc. + */ + + if (i != 0) + { + const CSection &prev = _sections[i - 1]; + if (prev.Pa < sect.Pa + && prev.Pa + prev.PSize > sect.Pa + && sect.PSize != 0 + && prev.PSize != 0) + { + _sectionsError = true; + // PRF(printf("\n !!!! Section correction: %s\n ", prev.Name)); + + /* we corrected that case in 7-zip before 22.02: */ + // prev.PSize = sect.Pa - prev.Pa; + + /* 22.02: here we can try to change bad section position to expected postion. + but original Windows code probably will not do same things. */ + // if (prev.PSize <= sect.Va - prev.Va) sect.Pa = prev.Pa + prev.PSize; } } /* last ".its" section in hxs file has incorrect sect.PSize. - So we reduce it to real sect.VSize */ + 7-zip before 22.02: we reduced section to real sect.VSize */ + /* if (sect.VSize == 24 && sect.PSize == 512 && i == (unsigned)_header.NumSections - 1) sect.PSize = sect.VSize; + */ } for (i = 0; i < _sections.Size(); i++) @@ -2340,7 +2374,7 @@ bool thereISDebug = false; if (IsOpt()) { - RINOK(LoadDebugSections(stream, thereISDebug)); + RINOK(LoadDebugSections(stream, thereISDebug)) const CDirLink &certLink = _optHeader.DirItems[kDirLink_Certificate]; if (certLink.Size != 0) @@ -2364,11 +2398,11 @@ if (alignPos != 0) { UInt32 size = kAlign - alignPos; - RINOK(stream->Seek(_totalSize, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, _totalSize)) buffer.Alloc(kAlign); Byte *buf = buffer; size_t processed = size; - RINOK(ReadStream(stream, buf, &processed)); + RINOK(ReadStream(stream, buf, &processed)) /* if (processed != 0) @@ -2395,9 +2429,9 @@ if (_header.NumSymbols >= (1 << 24)) return S_FALSE; UInt32 size = _header.NumSymbols * 18; - RINOK(stream->Seek((UInt64)_header.PointerToSymbolTable + size, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, (UInt64)_header.PointerToSymbolTable + size)) Byte buf[4]; - RINOK(ReadStream_FALSE(stream, buf, 4)); + RINOK(ReadStream_FALSE(stream, buf, 4)) UInt32 size2 = Get32(buf); if (size2 >= (1 << 28)) return S_FALSE; @@ -2442,9 +2476,9 @@ if (IsOpt()) if (_optHeader.CheckSum != 0) { - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(stream)) UInt32 checkSum = 0; - RINOK(CalcCheckSum(stream, _totalSize, optStart + k_CheckSum_Field_Offset, checkSum)); + RINOK(CalcCheckSum(stream, _totalSize, optStart + k_CheckSum_Field_Offset, checkSum)) _checksumError = (checkSum != _optHeader.CheckSum); } @@ -2452,13 +2486,13 @@ if (!_allowTail) { UInt64 fileSize; - RINOK(stream->Seek(0, STREAM_SEEK_END, &fileSize)); + RINOK(InStream_GetSize_SeekToEnd(stream, fileSize)) if (fileSize > _totalSize) return S_FALSE; } bool _parseResources = true; - // _parseResources = false; + // _parseResources = false; // for debug UInt64 mainSize = 0, mainSize2 = 0; @@ -2482,15 +2516,15 @@ if (item.Enabled) { CMixItem mixItem; - mixItem.SectionIndex = i; - mixItem.ResourceIndex = j; + mixItem.SectionIndex = (int)i; + mixItem.ResourceIndex = (int)j; if (item.IsRcDataOrUnknown()) { if (item.Size >= mainSize) { mainSize2 = mainSize; mainSize = item.Size; - _mainSubfile = _mixItems.Size(); + _mainSubfile = (Int32)(int)_mixItems.Size(); } else if (item.Size >= mainSize2) mainSize2 = item.Size; @@ -2538,14 +2572,14 @@ { mainSize2 = mainSize; mainSize = sect.PSize; - _mainSubfile = _mixItems.Size(); + _mainSubfile = (Int32)(int)_mixItems.Size(); } else if (sect.PSize >= mainSize2) mainSize2 = sect.PSize; } CMixItem mixItem; - mixItem.SectionIndex = i; + mixItem.SectionIndex = (int)i; _mixItems.Add(mixItem); } @@ -2557,7 +2591,7 @@ const CMixItem &mixItem = _mixItems[i]; if (mixItem.StringIndex < 0 && mixItem.ResourceIndex < 0 && _sections[mixItem.SectionIndex].Name == "_winzip_") { - _mainSubfile = i; + _mainSubfile = (Int32)(int)i; break; } } @@ -2594,11 +2628,11 @@ return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *callback) +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *callback)) { COM_TRY_BEGIN Close(); - RINOK(Open2(inStream, callback)); + RINOK(Open2(inStream, callback)) _stream = inStream; return S_OK; COM_TRY_END @@ -2617,10 +2651,11 @@ _versionKeys.Clear(); } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _totalSize = 0; _checksumError = false; + _sectionsError = false; _mainSubfile = -1; _stream.Release(); @@ -2630,17 +2665,17 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _mixItems.Size(); return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _mixItems.Size(); if (numItems == 0) @@ -2680,14 +2715,14 @@ for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize) { lps->InSize = lps->OutSize = currentTotalSize; - RINOK(lps->SetCur()); - Int32 askMode = testMode ? + RINOK(lps->SetCur()) + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; CMyComPtr outStream; - RINOK(extractCallback->GetStream(index, &outStream, askMode)); + RINOK(extractCallback->GetStream(index, &outStream, askMode)) const CMixItem &mixItem = _mixItems[index]; const CSection § = _sections[mixItem.SectionIndex]; @@ -2699,9 +2734,9 @@ if (!testMode && !outStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) if (outStream) - RINOK(WriteStream(outStream, item.Buf, item.FinalSize())); + RINOK(WriteStream(outStream, item.Buf, item.FinalSize())) } else if (mixItem.VersionIndex >= 0) { @@ -2710,9 +2745,9 @@ if (!testMode && !outStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) if (outStream) - RINOK(WriteStream(outStream, item, item.Size())); + RINOK(WriteStream(outStream, item, item.Size())) } else if (mixItem.ResourceIndex >= 0) { @@ -2721,15 +2756,15 @@ if (!testMode && !outStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) size_t offset = item.Offset - sect.Va; if (!CheckItem(sect, item, offset)) isOk = false; else if (outStream) { if (item.HeaderSize != 0) - RINOK(WriteStream(outStream, item.Header, item.HeaderSize)); - RINOK(WriteStream(outStream, _buf + offset, item.Size)); + RINOK(WriteStream(outStream, item.Header, item.HeaderSize)) + RINOK(WriteStream(outStream, _buf + offset, item.Size)) } } else @@ -2738,26 +2773,26 @@ if (!testMode && !outStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(_stream->Seek(sect.Pa, STREAM_SEEK_SET, NULL)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(InStream_SeekSet(_stream, sect.Pa)) streamSpec->Init(currentItemSize); - RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)) isOk = (copyCoderSpec->TotalSize == currentItemSize); } outStream.Release(); RINOK(extractCallback->SetOperationResult(isOk ? NExtract::NOperationResult::kOK : - NExtract::NOperationResult::kDataError)); + NExtract::NOperationResult::kDataError)) } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN - *stream = 0; + *stream = NULL; const CMixItem &mixItem = _mixItems[index]; const CSection § = _sections[mixItem.SectionIndex]; @@ -2804,7 +2839,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::AllowTail(Int32 allowTail) +Z7_COM7F_IMF(CHandler::AllowTail(Int32 allowTail)) { _allowTail = IntToBool(allowTail); return S_OK; @@ -2813,7 +2848,7 @@ static const Byte k_Signature[] = { 'M', 'Z' }; REGISTER_ARC_I( - "PE", "exe dll sys", 0, 0xDD, + "PE", "exe dll sys", NULL, 0xDD, k_Signature, 0, NArcInfoFlags::kPreArc, @@ -2846,7 +2881,7 @@ REGISTER_ARC_I_CLS_NO_SIG( NPe::CHandler(true), - "COFF", "obj", 0, 0xC6, + "COFF", "obj", NULL, 0xC6, // k_Signature, 0, // NArcInfoFlags::kMultiSignature | @@ -2881,8 +2916,8 @@ return false; } -#define MY_FIND_VALUE(pairs, val) FindValue(pairs, ARRAY_SIZE(pairs), val) -#define MY_FIND_VALUE_2(strings, val) (val < ARRAY_SIZE(strings) && strings[val]) +#define MY_FIND_VALUE(pairs, val) FindValue(pairs, Z7_ARRAY_SIZE(pairs), val) +#define MY_FIND_VALUE_2(strings, val) (val < Z7_ARRAY_SIZE(strings) && strings[val]) static const UInt32 kNumSection_MAX = 32; @@ -2988,12 +3023,11 @@ } }; -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public IArchiveAllowTail, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_CHandler_IInArchive_2( + IInArchiveGetStream, + IArchiveAllowTail +) CRecordVector _items; CMyComPtr _stream; UInt32 _totalSize; @@ -3002,10 +3036,6 @@ HRESULT Open2(IInStream *stream); public: - MY_UNKNOWN_IMP3(IInArchive, IInArchiveGetStream, IArchiveAllowTail) - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); - STDMETHOD(AllowTail)(Int32 allowTail); CHandler(): _allowTail(false) {} }; @@ -3036,7 +3066,7 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps_WITH_NAME -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -3056,7 +3086,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -3087,7 +3117,7 @@ HRESULT CHandler::Open2(IInStream *stream) { Byte h[kHeaderSize]; - RINOK(ReadStream_FALSE(stream, h, kHeaderSize)); + RINOK(ReadStream_FALSE(stream, h, kHeaderSize)) if (h[0] != 'V' || h[1] != 'Z') return S_FALSE; if (!_h.Parse(h)) @@ -3095,7 +3125,7 @@ UInt32 headerSize = NPe::kSectionSize * (UInt32)_h.NumSections; CByteArr buf(headerSize); - RINOK(ReadStream_FALSE(stream, buf, headerSize)); + RINOK(ReadStream_FALSE(stream, buf, headerSize)) headerSize += kHeaderSize; _totalSize = headerSize; @@ -3117,7 +3147,7 @@ if (!_allowTail) { UInt64 fileSize; - RINOK(stream->Seek(0, STREAM_SEEK_END, &fileSize)); + RINOK(InStream_GetSize_SeekToEnd(stream, fileSize)) if (fileSize > _totalSize) return S_FALSE; } @@ -3125,9 +3155,9 @@ return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *inStream, +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openArchiveCallback */) + IArchiveOpenCallback * /* openArchiveCallback */)) { COM_TRY_BEGIN Close(); @@ -3142,7 +3172,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _totalSize = 0; _stream.Release(); @@ -3150,17 +3180,17 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _items.Size(); return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _items.Size(); if (numItems == 0) @@ -3187,35 +3217,35 @@ for (i = 0; i < numItems; i++) { lps->InSize = lps->OutSize = currentTotalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; const CSection &item = _items[index]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) currentTotalSize += item.PSize; if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) int res = NExtract::NOperationResult::kDataError; - RINOK(_stream->Seek(item.Pa, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_stream, item.Pa)) streamSpec->Init(item.PSize); - RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)) if (copyCoderSpec->TotalSize == item.PSize) res = NExtract::NOperationResult::kOK; realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(res)); + RINOK(extractCallback->SetOperationResult(res)) } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN const CSection &item = _items[index]; @@ -3223,7 +3253,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::AllowTail(Int32 allowTail) +Z7_COM7F_IMF(CHandler::AllowTail(Int32 allowTail)) { _allowTail = IntToBool(allowTail); return S_OK; @@ -3232,7 +3262,7 @@ static const Byte k_Signature[] = { 'V', 'Z' }; REGISTER_ARC_I( - "TE", "te", 0, 0xCF, + "TE", "te", NULL, 0xCF, k_Signature, 0, NArcInfoFlags::kPreArc, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/PpmdHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/PpmdHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/PpmdHandler.cpp 2022-03-28 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/PpmdHandler.cpp 2023-01-31 17:00:00.000000000 +0000 @@ -33,13 +33,13 @@ { Byte *Buf; - CBuf(): Buf(0) {} + CBuf(): Buf(NULL) {} ~CBuf() { ::MidFree(Buf); } bool Alloc() { if (!Buf) Buf = (Byte *)::MidAlloc(kBufSize); - return (Buf != 0); + return (Buf != NULL); } }; @@ -59,13 +59,17 @@ unsigned Restor; HRESULT ReadHeader(ISequentialInStream *s, UInt32 &headerSize); - bool IsSupported() const { return Ver == 7 || (Ver == 8 && Restor < PPMD8_RESTORE_METHOD_UNSUPPPORTED); } + bool IsSupported() const + { + return (Ver == 7 && Order >= PPMD7_MIN_ORDER) + || (Ver == 8 && Order >= PPMD8_MIN_ORDER && Restor < PPMD8_RESTORE_METHOD_UNSUPPPORTED); + } }; HRESULT CItem::ReadHeader(ISequentialInStream *s, UInt32 &headerSize) { Byte h[kHeaderSize]; - RINOK(ReadStream_FALSE(s, h, kHeaderSize)); + RINOK(ReadStream_FALSE(s, h, kHeaderSize)) if (GetUi32(h) != kSignature) return S_FALSE; Attrib = GetUi32(h + 4); @@ -92,11 +96,10 @@ return res; } -class CHandler: - public IInArchive, - public IArchiveOpenSeq, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_CHandler_IInArchive_1( + IArchiveOpenSeq +) CItem _item; UInt32 _headerSize; bool _packSize_Defined; @@ -104,11 +107,6 @@ CMyComPtr _stream; void GetVersion(NCOM::CPropVariant &prop); - -public: - MY_UNKNOWN_IMP2(IInArchive, IArchiveOpenSeq) - INTERFACE_IInArchive(;) - STDMETHOD(OpenSeq)(ISequentialInStream *stream); }; static const Byte kProps[] = @@ -144,7 +142,7 @@ prop = s; } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; switch (propID) @@ -157,13 +155,13 @@ } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = 1; return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -187,12 +185,12 @@ COM_TRY_END } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *)) { return OpenSeq(stream); } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { COM_TRY_BEGIN HRESULT res; @@ -210,7 +208,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _packSize = 0; _packSize_Defined = false; @@ -252,7 +250,7 @@ if (Ver == 7) Ppmd7_Init(&_ppmd7, order); else - Ppmd8_Init(&_ppmd8, order, restor);; + Ppmd8_Init(&_ppmd8, order, restor); } bool InitRc(CByteInBufWrap *inStream) @@ -278,8 +276,8 @@ }; -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { if (numItems == 0) return S_OK; @@ -288,12 +286,12 @@ // extractCallback->SetTotal(_packSize); UInt64 currentTotalPacked = 0; - RINOK(extractCallback->SetCompleted(¤tTotalPacked)); + RINOK(extractCallback->SetCompleted(¤tTotalPacked)) CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(0, &realOutStream, askMode)) if (!testMode && !realOutStream) return S_OK; @@ -331,7 +329,7 @@ { lps->InSize = _packSize = inBuf.GetProcessed(); lps->OutSize = outSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) size_t i; int sym = 0; @@ -363,7 +361,7 @@ _packSize_Defined = true; if (realOutStream) { - RINOK(WriteStream(realOutStream, outBuf.Buf, i)); + RINOK(WriteStream(realOutStream, outBuf.Buf, i)) } if (inBuf.Extra) @@ -380,7 +378,7 @@ } } - RINOK(inBuf.Res); + RINOK(inBuf.Res) } realOutStream.Release(); @@ -391,7 +389,7 @@ static const Byte k_Signature[] = { 0x8F, 0xAF, 0xAC, 0x84 }; REGISTER_ARC_I( - "Ppmd", "pmd", 0, 0xD, + "Ppmd", "pmd", NULL, 0xD, k_Signature, 0, 0, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/QcowHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/QcowHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/QcowHandler.cpp 2021-12-14 07:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/QcowHandler.cpp 2023-03-27 13:00:00.000000000 +0000 @@ -28,9 +28,7 @@ namespace NArchive { namespace NQcow { -#define SIGNATURE { 'Q', 'F', 'I', 0xFB, 0, 0, 0 } - -static const Byte k_Signature[] = SIGNATURE; +static const Byte k_Signature[] = { 'Q', 'F', 'I', 0xFB, 0, 0, 0 }; /* VA to PA maps: @@ -39,8 +37,12 @@ low bits : _clusterBits */ -class CHandler: public CHandlerImg +Z7_class_CHandler_final: public CHandlerImg { + Z7_IFACE_COM7_IMP(IInArchive_Img) + Z7_IFACE_COM7_IMP(IInArchiveGetStream) + Z7_IFACE_COM7_IMP(ISequentialInStream) + unsigned _clusterBits; unsigned _numMidBits; UInt64 _compressedFlag; @@ -75,7 +77,7 @@ HRESULT Seek2(UInt64 offset) { _posInArc = offset; - return Stream->Seek(offset, STREAM_SEEK_SET, NULL); + return InStream_SeekSet(Stream, offset); } HRESULT InitAndSeek() @@ -84,19 +86,13 @@ return Seek2(0); } - HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openCallback); - -public: - INTERFACE_IInArchive_Img(;) - - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); + HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openCallback) Z7_override; }; static const UInt32 kEmptyDirItem = (UInt32)0 - 1; -STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -190,14 +186,14 @@ if (sectorOffset != _posInArc) { // printf("\nDeflate-Seek %12I64x %12I64x\n", sectorOffset, sectorOffset - _posInArc); - RINOK(Seek2(sectorOffset)); + RINOK(Seek2(sectorOffset)) } if (_cacheCompressed.Size() < dataSize) return E_FAIL; const size_t dataSize3 = dataSize - _comprSize; size_t dataSize2 = dataSize3; // printf("\n\n=======\nReadStream = %6d _comprPos = %6d \n", (UInt32)dataSize2, (UInt32)_comprPos); - RINOK(ReadStream(Stream, _cacheCompressed + _comprSize, &dataSize2)); + RINOK(ReadStream(Stream, _cacheCompressed + _comprSize, &dataSize2)) _posInArc += dataSize2; if (dataSize2 != dataSize3) return E_FAIL; @@ -215,7 +211,7 @@ // Do we need to use smaller block than clusterSize for last cluster? const UInt64 blockSize64 = clusterSize; - HRESULT res = _deflateDecoderSpec->Code(_bufInStream, _bufOutStream, NULL, &blockSize64, NULL); + HRESULT res = _deflateDecoder->Code(_bufInStream, _bufOutStream, NULL, &blockSize64, NULL); /* if (_bufOutStreamSpec->GetPos() != clusterSize) @@ -227,7 +223,7 @@ || _bufOutStreamSpec->GetPos() != clusterSize) res = S_FALSE; - RINOK(res); + RINOK(res) _cacheCluster = cluster; continue; @@ -245,7 +241,7 @@ if (v != _posInArc) { // printf("\n%12I64x\n", v - _posInArc); - RINOK(Seek2(v)); + RINOK(Seek2(v)) } HRESULT res = Stream->Read(data, size, &size); _posInArc += size; @@ -285,7 +281,7 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -322,7 +318,7 @@ case kpidErrorFlags: { UInt32 v = 0; - if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;; + if (!_isArc) v |= kpv_ErrorFlags_IsNotArc; if (_unsupported) v |= kpv_ErrorFlags_UnsupportedMethod; // if (_headerError) v |= kpv_ErrorFlags_HeadersError; if (!Stream && v == 0 && _isArc) @@ -339,7 +335,7 @@ } -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -361,7 +357,7 @@ { const unsigned kHeaderSize = 18 * 4; Byte buf[kHeaderSize]; - RINOK(ReadStream_FALSE(stream, buf, kHeaderSize)); + RINOK(ReadStream_FALSE(stream, buf, kHeaderSize)) if (memcmp(buf, k_Signature, 4) != 0) return S_FALSE; @@ -423,7 +419,7 @@ /* CByteBuffer refs; refs.Alloc(numBytes); - RINOK(stream->Seek(refOffset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, refOffset)) RINOK(ReadStream_FALSE(stream, refs, numBytes)); */ const UInt64 end = refOffset + numBytes; @@ -456,8 +452,8 @@ if ((t1SizeBytes >> 3) != l1Size) return S_FALSE; table.Alloc(t1SizeBytes); - RINOK(stream->Seek(l1Offset, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(stream, table, t1SizeBytes)); + RINOK(InStream_SeekSet(stream, l1Offset)) + RINOK(ReadStream_FALSE(stream, table, t1SizeBytes)) { UInt64 end = l1Offset + t1SizeBytes; @@ -498,7 +494,7 @@ if (openCallback) { const UInt64 totalBytes = (UInt64)numTables << (_numMidBits + 3); - RINOK(openCallback->SetTotal(NULL, &totalBytes)); + RINOK(openCallback->SetTotal(NULL, &totalBytes)) } for (i = 0; i < l1Size; i++) @@ -522,11 +518,11 @@ if (openCallback && (tableOffset & 0xFFFFF) == 0) { const UInt64 numBytes = tableOffset; - RINOK(openCallback->SetCompleted(NULL, &numBytes)); + RINOK(openCallback->SetCompleted(NULL, &numBytes)) } - RINOK(stream->Seek(v, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(stream, buf2, midSize)); + RINOK(InStream_SeekSet(stream, v)) + RINOK(ReadStream_FALSE(stream, buf2, midSize)) const UInt64 end = v + midSize; if (_phySize < end) @@ -596,7 +592,7 @@ } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _table.Free(); _dir.Free(); @@ -617,7 +613,7 @@ } -STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream)) { COM_TRY_BEGIN *stream = NULL; @@ -655,7 +651,7 @@ } CMyComPtr streamTemp = this; - RINOK(InitAndSeek()); + RINOK(InitAndSeek()) *stream = streamTemp.Detach(); return S_OK; COM_TRY_END diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Rar/Rar5Handler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Rar/Rar5Handler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Rar/Rar5Handler.cpp 2022-05-04 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Rar/Rar5Handler.cpp 2023-03-26 12:00:00.000000000 +0000 @@ -45,9 +45,8 @@ static const unsigned kMarkerSize = 8; -#define SIGNATURE { 0x52 , 0x61, 0x72, 0x21, 0x1a, 0x07, 0x01, 0 } - -static const Byte kMarker[kMarkerSize] = SIGNATURE; +static const Byte kMarker[kMarkerSize] = + { 0x52, 0x61, 0x72, 0x21, 0x1a, 0x07, 0x01, 0 }; static const size_t kCommentSize_Max = (size_t)1 << 16; @@ -252,7 +251,7 @@ rem++; s.Add_Space_if_NotEmpty(); - PrintType(s, g_ExtraTypes, ARRAY_SIZE(g_ExtraTypes), id); + PrintType(s, g_ExtraTypes, Z7_ARRAY_SIZE(g_ExtraTypes), id); if (id == NExtraID::kTime) { @@ -262,10 +261,10 @@ if (num != 0) { s += ':'; - for (unsigned i = 0; i < ARRAY_SIZE(g_ExtraTimeFlags); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_ExtraTimeFlags); i++) if ((flags & ((UInt64)1 << i)) != 0) s += g_ExtraTimeFlags[i]; - flags &= ~(((UInt64)1 << ARRAY_SIZE(g_ExtraTimeFlags)) - 1); + flags &= ~(((UInt64)1 << Z7_ARRAY_SIZE(g_ExtraTimeFlags)) - 1); if (flags != 0) { s += '_'; @@ -279,7 +278,7 @@ if (linkInfo.Parse(Extra + offset, (unsigned)rem)) { s += ':'; - PrintType(s, g_LinkTypes, ARRAY_SIZE(g_LinkTypes), linkInfo.Type); + PrintType(s, g_LinkTypes, Z7_ARRAY_SIZE(g_LinkTypes), linkInfo.Type); UInt64 flags = linkInfo.Flags; if (flags != 0) { @@ -349,12 +348,12 @@ bool CItem::FindExtra_Link(CLinkInfo &link) const { unsigned size; - int offset = FindExtra(NExtraID::kLink, size); + const int offset = FindExtra(NExtraID::kLink, size); if (offset < 0) return false; if (!link.Parse(Extra + (unsigned)offset, size)) return false; - link.NameOffset += offset; + link.NameOffset += (unsigned)offset; return true; } @@ -481,10 +480,10 @@ } -class COutStreamWithHash: - public ISequentialOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + COutStreamWithHash + , ISequentialOutStream +) ISequentialOutStream *_stream; UInt64 _pos; UInt64 _size; @@ -495,8 +494,6 @@ COutStreamWithHash(): _destBuf(NULL) {} - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); void SetStream(ISequentialOutStream *stream) { _stream = stream; } void Init(const CItem &item, Byte *destBuf) { @@ -516,7 +513,7 @@ }; -STDMETHODIMP COutStreamWithHash::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(COutStreamWithHash::Write(const void *data, UInt32 size, UInt32 *processedSize)) { HRESULT result = S_OK; if (_size_Defined) @@ -550,7 +547,7 @@ NCrypto::NRar5::CDecoder *m_CryptoDecoderSpec; CMyComPtr m_CryptoDecoder; - CLASS_NO_COPY(CInArchive) + Z7_CLASS_NO_COPY(CInArchive) HRESULT ReadStream_Check(void *data, size_t size); @@ -591,7 +588,7 @@ static HRESULT MySetPassword(ICryptoGetTextPassword *getTextPassword, NCrypto::NRar5::CDecoder *cryptoDecoderSpec) { CMyComBSTR_Wipe password; - RINOK(getTextPassword->CryptoGetTextPassword(&password)); + RINOK(getTextPassword->CryptoGetTextPassword(&password)) AString_Wipe utf8; const unsigned kPasswordLen_MAX = 127; UString_Wipe unicode; @@ -615,7 +612,7 @@ HRESULT CInArchive::ReadStream_Check(void *data, size_t size) { size_t size2 = size; - RINOK(ReadStream(_stream, data, &size2)); + RINOK(ReadStream(_stream, data, &size2)) if (size2 == size) return S_OK; UnexpectedEnd = true; @@ -637,23 +634,23 @@ if (m_CryptoMode) { - RINOK(ReadStream_Check(buf, kBufSize)); + RINOK(ReadStream_Check(buf, kBufSize)) memcpy(m_CryptoDecoderSpec->_iv, buf, AES_BLOCK_SIZE); - RINOK(m_CryptoDecoderSpec->Init()); + RINOK(m_CryptoDecoderSpec->Init()) _buf.AllocAtLeast(1 << 12); if (!(Byte *)_buf) return E_OUTOFMEMORY; memcpy(_buf, buf + AES_BLOCK_SIZE, AES_BLOCK_SIZE); - if (m_CryptoDecoderSpec->Filter(_buf, AES_BLOCK_SIZE) != AES_BLOCK_SIZE) + if (m_CryptoDecoder->Filter(_buf, AES_BLOCK_SIZE) != AES_BLOCK_SIZE) return E_FAIL; memcpy(buf, _buf, AES_BLOCK_SIZE); filled = AES_BLOCK_SIZE; } else { - RINOK(ReadStream_Check(buf, kStartSize)); + RINOK(ReadStream_Check(buf, kStartSize)) filled = kStartSize; } @@ -680,10 +677,10 @@ size_t rem = allocSize - filled; AddToSeekValue(allocSize + (m_CryptoMode ? AES_BLOCK_SIZE : 0)); - RINOK(ReadStream_Check(_buf + filled, rem)); + RINOK(ReadStream_Check(_buf + filled, rem)) if (m_CryptoMode) { - if (m_CryptoDecoderSpec->Filter(_buf + filled, (UInt32)rem) != rem) + if (m_CryptoDecoder->Filter(_buf + filled, (UInt32)rem) != rem) return E_FAIL; } @@ -804,19 +801,19 @@ UInt64 arcStartPos = StreamStartPosition; { Byte marker[kMarkerSize]; - RINOK(ReadStream_FALSE(stream, marker, kMarkerSize)); + RINOK(ReadStream_FALSE(stream, marker, kMarkerSize)) if (memcmp(marker, kMarker, kMarkerSize) == 0) Position += kMarkerSize; else { if (searchHeaderSizeLimit && *searchHeaderSizeLimit == 0) return S_FALSE; - RINOK(stream->Seek(StreamStartPosition, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, StreamStartPosition)) RINOK(FindSignatureInStream(stream, kMarker, kMarkerSize, - searchHeaderSizeLimit, arcStartPos)); + searchHeaderSizeLimit, arcStartPos)) arcStartPos += StreamStartPosition; Position = arcStartPos + kMarkerSize; - RINOK(stream->Seek(Position, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, Position)) } } @@ -824,7 +821,7 @@ _stream = stream; CHeader h; - RINOK(ReadBlockHeader(h)); + RINOK(ReadBlockHeader(h)) info.IsEncrypted = false; if (h.Type == NHeaderType::kArcEncrypt) @@ -843,9 +840,9 @@ } RINOK(m_CryptoDecoderSpec->SetDecoderProps( - _buf + _bufPos, (unsigned)(_bufSize - _bufPos), false, false)); + _buf + _bufPos, (unsigned)(_bufSize - _bufPos), false, false)) - RINOK(MySetPassword(getTextPassword, m_CryptoDecoderSpec)); + RINOK(MySetPassword(getTextPassword, m_CryptoDecoderSpec)) if (!m_CryptoDecoderSpec->CalcKey_and_CheckPassword()) { @@ -853,7 +850,7 @@ return S_FALSE; } - RINOK(ReadBlockHeader(h)); + RINOK(ReadBlockHeader(h)) } if (h.Type != NHeaderType::kArc) @@ -1052,16 +1049,16 @@ if (!lzCoder) { const UInt32 methodID = 0x40305; - RINOK(CreateCoder_Id(EXTERNAL_CODECS_LOC_VARS methodID, false, lzCoder)); + RINOK(CreateCoder_Id(EXTERNAL_CODECS_LOC_VARS methodID, false, lzCoder)) if (!lzCoder) return E_NOTIMPL; } CMyComPtr csdp; - RINOK(lzCoder.QueryInterface(IID_ICompressSetDecoderProperties2, &csdp)); + RINOK(lzCoder.QueryInterface(IID_ICompressSetDecoderProperties2, &csdp)) Byte props[2] = { (Byte)(item.GetDictSize()), (Byte)(isSolid ? 1 : 0) }; - RINOK(csdp->SetDecoderProperties2(props, 2)); + RINOK(csdp->SetDecoderProperties2(props, 2)) } unsigned cryptoSize = 0; @@ -1081,7 +1078,7 @@ cryptoDecoder = cryptoDecoderSpec; } - RINOK(cryptoDecoderSpec->SetDecoderProps(item.Extra + (unsigned)cryptoOffset, cryptoSize, true, item.IsService())); + RINOK(cryptoDecoderSpec->SetDecoderProps(item.Extra + (unsigned)cryptoOffset, cryptoSize, true, item.IsService())) if (!getTextPassword) { @@ -1089,7 +1086,7 @@ return E_NOTIMPL; } - RINOK(MySetPassword(getTextPassword, cryptoDecoderSpec)); + RINOK(MySetPassword(getTextPassword, cryptoDecoderSpec)) if (!cryptoDecoderSpec->CalcKey_and_CheckPassword()) wrongPassword = True; @@ -1273,7 +1270,7 @@ _buf.ChangeSize_KeepData(newSize, _offset); Byte *data = (Byte *)_buf + _offset; - RINOK(ReadStream_FALSE(inStream, data, packSize)); + RINOK(ReadStream_FALSE(inStream, data, packSize)) _offset += packSize; @@ -1293,7 +1290,7 @@ if (_offset == 0) { RINOK(unpacker.DecodeToBuf(EXTERNAL_CODECS_LOC_VARS - item, item.PackSize, inStream, destBuf)); + item, item.PackSize, inStream, destBuf)) } else { @@ -1301,7 +1298,7 @@ CMyComPtr bufInStream = bufInStreamSpec; bufInStreamSpec->Init(_buf, _offset); RINOK(unpacker.DecodeToBuf(EXTERNAL_CODECS_LOC_VARS - item, _offset, bufInStream, destBuf)); + item, _offset, bufInStream, destBuf)) } } } @@ -1367,12 +1364,12 @@ size += item.PackSize; if (item.NextItem < 0) return size; - index = item.NextItem; + index = (unsigned)item.NextItem; } } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN @@ -1501,7 +1498,7 @@ } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _refs.Size(); return S_OK; @@ -1515,20 +1512,20 @@ }; -STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) +Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps)) { - *numProps = ARRAY_SIZE(kRawProps); + *numProps = Z7_ARRAY_SIZE(kRawProps); return S_OK; } -STDMETHODIMP CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID) +Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID)) { *propID = kRawProps[index]; - *name = 0; + *name = NULL; return S_OK; } -STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType) +Z7_COM7F_IMF(CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType)) { *parentType = NParentType::kDir; *parent = (UInt32)(Int32)-1; @@ -1549,7 +1546,7 @@ } -STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) +Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType)) { *data = NULL; *dataSize = 0; @@ -1660,7 +1657,7 @@ } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN @@ -1680,7 +1677,7 @@ AString s; if (ref.Parent >= 0) { - CItem &mainItem = _items[_refs[ref.Parent].Item]; + const CItem &mainItem = _items[_refs[ref.Parent].Item]; s = mainItem.Name; } @@ -1856,7 +1853,7 @@ if (flags != 0) { - AString s2 = FlagsToString(k_FileFlags, ARRAY_SIZE(k_FileFlags), flags); + AString s2 = FlagsToString(k_FileFlags, Z7_ARRAY_SIZE(k_FileFlags), flags); if (!s2.IsEmpty()) { s.Add_OptSpaced(s2); @@ -1872,7 +1869,7 @@ case kpidHostOS: - if (item.HostOS < ARRAY_SIZE(kHostOS)) + if (item.HostOS < Z7_ARRAY_SIZE(kHostOS)) prop = kHostOS[(size_t)item.HostOS]; else prop = (UInt64)item.HostOS; @@ -1933,24 +1930,24 @@ { if (left > 0) { - unsigned refIndex = sorted[left - 1]; + const unsigned refIndex = sorted[left - 1]; if (CompareItemsPaths(handler, index, refIndex, &s) == 0) - return refIndex; + return (int)refIndex; } if (right < sorted.Size()) { - unsigned refIndex = sorted[right]; + const unsigned refIndex = sorted[right]; if (CompareItemsPaths(handler, index, refIndex, &s) == 0) - return refIndex; + return (int)refIndex; } return -1; } - unsigned mid = (left + right) / 2; - unsigned refIndex = sorted[mid]; - int compare = CompareItemsPaths2(handler, index, refIndex, &s); + const unsigned mid = (left + right) / 2; + const unsigned refIndex = sorted[mid]; + const int compare = CompareItemsPaths2(handler, index, refIndex, &s); if (compare == 0) - return refIndex; + return (int)refIndex; if (compare < 0) right = mid; else @@ -2062,7 +2059,7 @@ UString baseName; { NCOM::CPropVariant prop; - RINOK(openVolumeCallback->GetProperty(kpidName, &prop)); + RINOK(openVolumeCallback->GetProperty(kpidName, &prop)) if (prop.vt != VT_BSTR) break; baseName = prop.bstrVal; @@ -2087,14 +2084,12 @@ } UInt64 endPos = 0; - RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &arch.StreamStartPosition)); - RINOK(inStream->Seek(0, STREAM_SEEK_END, &endPos)); - RINOK(inStream->Seek(arch.StreamStartPosition, STREAM_SEEK_SET, NULL)); + RINOK(InStream_GetPos_GetSize(inStream, arch.StreamStartPosition, endPos)) if (openCallback) { totalBytes += endPos; - RINOK(openCallback->SetTotal(NULL, &totalBytes)); + RINOK(openCallback->SetTotal(NULL, &totalBytes)) } CInArcInfo arcInfoOpen; @@ -2136,7 +2131,7 @@ break; } - RINOK(inStream->Seek(arch.Position, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(inStream, arch.Position)) { CInArchive::CHeader h; @@ -2168,11 +2163,11 @@ { // for multivolume archives RAR can add ZERO bytes at the end for alignment. // We must skip these bytes to prevent phySize warning. - RINOK(inStream->Seek(arcInfo.EndPos, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(inStream, arcInfo.EndPos)) bool areThereNonZeros; UInt64 numZeros; const UInt64 maxSize = 1 << 12; - RINOK(ReadZeroTail(inStream, areThereNonZeros, numZeros, maxSize)); + RINOK(ReadZeroTail(inStream, areThereNonZeros, numZeros, maxSize)) if (!areThereNonZeros && numZeros != 0 && numZeros <= maxSize) arcInfo.EndPos += numZeros; } @@ -2226,7 +2221,7 @@ && item.GetMethod() == 0 && !item.IsSplit()) { - RINOK(unpacker.DecodeToBuf(EXTERNAL_CODECS_VARS item, item.PackSize, inStream, _comment)); + RINOK(unpacker.DecodeToBuf(EXTERNAL_CODECS_VARS item, item.PackSize, inStream, _comment)) needAdd = false; } } @@ -2273,7 +2268,7 @@ { if (_acls.IsEmpty() || acl != _acls.Back()) _acls.Add(acl); - mainItem.ACL = _acls.Size() - 1; + mainItem.ACL = (int)_acls.Size() - 1; } } } @@ -2292,7 +2287,7 @@ if (item.IsNextForItem(prevItem)) { ref2.Last = _items.Size(); - prevItem.NextItem = ref2.Last; + prevItem.NextItem = (int)ref2.Last; needAdd = false; } } @@ -2302,9 +2297,9 @@ if (needAdd) { if (item.IsSplitAfter()) - prevSplitFile = _refs.Size(); + prevSplitFile = (int)_refs.Size(); if (!item.IsService()) - prevMainFile = _refs.Size(); + prevMainFile = (int)_refs.Size(); _refs.Add(ref); } } @@ -2325,7 +2320,7 @@ { UInt64 numFiles = _items.Size(); UInt64 numBytes = curBytes + item.DataPos; - RINOK(openCallback->SetCompleted(&numFiles, &numBytes)); + RINOK(openCallback->SetCompleted(&numFiles, &numBytes)) } if (!isOk_packSize) @@ -2353,9 +2348,9 @@ } -STDMETHODIMP CHandler::Open(IInStream *stream, +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *maxCheckStartPosition, - IArchiveOpenCallback *openCallback) + IArchiveOpenCallback *openCallback)) { COM_TRY_BEGIN Close(); @@ -2363,7 +2358,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { COM_TRY_BEGIN _missingVolName.Empty(); @@ -2380,10 +2375,10 @@ } -class CVolsInStream: - public ISequentialInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + CVolsInStream + , ISequentialInStream +) UInt64 _rem; ISequentialInStream *_stream; const CObjectVector *_arcs; @@ -2394,22 +2389,19 @@ private: CHash _hash; public: - MY_UNKNOWN_IMP void Init(const CObjectVector *arcs, const CObjectVector *items, unsigned itemIndex) { _arcs = arcs; _items = items; - _itemIndex = itemIndex; + _itemIndex = (int)itemIndex; _stream = NULL; CrcIsOK = true; } - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); }; -STDMETHODIMP CVolsInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CVolsInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -2423,7 +2415,7 @@ break; const CItem &item = (*_items)[_itemIndex]; IInStream *s = (*_arcs)[item.VolIndex].Stream; - RINOK(s->Seek(item.GetDataPosition(), STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(s, item.GetDataPosition())) _stream = s; if (CrcIsOK && item.IsSplitAfter()) _hash.Init(item); @@ -2472,10 +2464,10 @@ { if (left == right) return -1; - unsigned mid = (left + right) / 2; - unsigned linkIndex = linkFiles[mid].Index; + const unsigned mid = (left + right) / 2; + const unsigned linkIndex = linkFiles[mid].Index; if (index == linkIndex) - return mid; + return (int)mid; if (index < linkIndex) right = mid; else @@ -2512,14 +2504,14 @@ cur = kStepSize; cur32 = (UInt32)cur; } - RINOK(outStream->Write(data + pos, cur32, &cur32)); + RINOK(outStream->Write(data + pos, cur32, &cur32)) if (cur32 == 0) return E_FAIL; pos += cur32; if (progress) { UInt64 pos64 = pos; - RINOK(progress->SetRatioInfo(&pos64, &pos64)); + RINOK(progress->SetRatioInfo(&pos64, &pos64)) } } @@ -2527,12 +2519,11 @@ } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _refs.Size(); if (numItems == 0) @@ -2706,7 +2697,7 @@ const CItem &linkItem = _items[_refs[(unsigned)linkIndex].Item]; if (!linkItem.IsSolid() || linkItem.Size > k_CopyLinkFile_MaxSize) continue; - int bufIndex = FindLinkBuf(linkFiles, linkIndex); + const int bufIndex = FindLinkBuf(linkFiles, (unsigned)linkIndex); if (bufIndex < 0) return E_FAIL; linkFiles[bufIndex].NumLinks++; @@ -2715,7 +2706,7 @@ if (total != 0 || !isThereUndefinedSize) { - RINOK(extractCallback->SetTotal(total)); + RINOK(extractCallback->SetTotal(total)) } } @@ -2745,7 +2736,7 @@ totalPacked += curPackSize; lps->InSize = totalPacked; lps->OutSize = totalUnpacked; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr realOutStream; @@ -2781,7 +2772,7 @@ curPackSize = GetPackSize(index); - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) bool isSolid = false; if (!item->IsService()) @@ -2793,8 +2784,8 @@ if (item->IsDir()) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } @@ -2815,12 +2806,12 @@ curUnpackSize = lastItem2.Size; else curUnpackSize = 0; - curPackSize = GetPackSize(index2); + curPackSize = GetPackSize((unsigned)index2); } else { if ((unsigned)index2 < index) - bufIndex = FindLinkBuf(linkFiles, index2); + bufIndex = FindLinkBuf(linkFiles, (unsigned)index2); } } @@ -2839,8 +2830,8 @@ opRes = DecoderRes_to_OpRes(linkFile.Res, linkFile.crcOK); } - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(opRes)) continue; } } @@ -2874,7 +2865,7 @@ if (needCallback) { - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) } if (bufIndex >= 0) @@ -2889,7 +2880,7 @@ if (needCallback) if (realOutStream) { - RINOK(CopyData_with_Progress(linkFile.Data, linkFile.Data.Size(), realOutStream, progress)); + RINOK(CopyData_with_Progress(linkFile.Data, linkFile.Data.Size(), realOutStream, progress)) } if (--linkFile.NumLinks == 0) @@ -2898,7 +2889,7 @@ if (needCallback) { - RINOK(extractCallback->SetOperationResult(DecoderRes_to_OpRes(linkFile.Res, linkFile.crcOK))); + RINOK(extractCallback->SetOperationResult(DecoderRes_to_OpRes(linkFile.Res, linkFile.crcOK))) } continue; } @@ -2912,7 +2903,7 @@ NExtract::NOperationResult::kUnsupportedMethod: NExtract::NOperationResult::kOK; realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) continue; } @@ -2930,7 +2921,7 @@ if (wrongPassword) { realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kWrongPassword)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kWrongPassword)) continue; } @@ -2955,7 +2946,7 @@ return result; } - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } { @@ -2973,7 +2964,7 @@ IMPL_ISetCompressCodecsInfo REGISTER_ARC_I( - "Rar5", "rar r00", 0, 0xCC, + "Rar5", "rar r00", NULL, 0xCC, kMarker, 0, NArcInfoFlags::kFindSignature, @@ -2982,31 +2973,27 @@ }} -class CBlake2spHasher: - public IHasher, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CBlake2spHasher + , IHasher +) CBlake2sp _blake; - Byte mtDummy[1 << 7]; - public: + Byte _mtDummy[1 << 7]; // it's public to eliminate clang warning: unused private field CBlake2spHasher() { Init(); } - - MY_UNKNOWN_IMP - INTERFACE_IHasher(;) }; -STDMETHODIMP_(void) CBlake2spHasher::Init() throw() +Z7_COM7F_IMF2(void, CBlake2spHasher::Init()) { Blake2sp_Init(&_blake); } -STDMETHODIMP_(void) CBlake2spHasher::Update(const void *data, UInt32 size) throw() +Z7_COM7F_IMF2(void, CBlake2spHasher::Update(const void *data, UInt32 size)) { Blake2sp_Update(&_blake, (const Byte *)data, size); } -STDMETHODIMP_(void) CBlake2spHasher::Final(Byte *digest) throw() +Z7_COM7F_IMF2(void, CBlake2spHasher::Final(Byte *digest)) { Blake2sp_Final(&_blake, digest); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Rar/Rar5Handler.h 7zip-23.01+dfsg/CPP/7zip/Archive/Rar/Rar5Handler.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Rar/Rar5Handler.h 2018-04-01 08:10:26.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Rar/Rar5Handler.h 2023-02-01 10:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Rar5Handler.h -#ifndef __RAR5_HANDLER_H -#define __RAR5_HANDLER_H +#ifndef ZIP7_INC_RAR5_HANDLER_H +#define ZIP7_INC_RAR5_HANDLER_H #include "../../../../C/Blake2.h" @@ -374,12 +374,22 @@ }; -class CHandler: +class CHandler Z7_final: public IInArchive, public IArchiveGetRawProps, - PUBLIC_ISetCompressCodecsInfo + Z7_PUBLIC_ISetCompressCodecsInfo_IFEC public CMyUnknownImp { + Z7_COM_QI_BEGIN2(IInArchive) + Z7_COM_QI_ENTRY(IArchiveGetRawProps) + Z7_COM_QI_ENTRY_ISetCompressCodecsInfo_IFEC + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(IInArchive) + Z7_IFACE_COM7_IMP(IArchiveGetRawProps) + DECL_ISetCompressCodecsInfo + public: CRecordVector _refs; CObjectVector _items; @@ -402,18 +412,6 @@ HRESULT Open2(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback); - -public: - MY_QUERYINTERFACE_BEGIN2(IInArchive) - MY_QUERYINTERFACE_ENTRY(IArchiveGetRawProps) - QUERY_ENTRY_ISetCompressCodecsInfo - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IInArchive(;) - INTERFACE_IArchiveGetRawProps(;) - - DECL_ISetCompressCodecsInfo }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Rar/RarHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Rar/RarHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Rar/RarHandler.cpp 2022-05-04 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Rar/RarHandler.cpp 2023-03-06 16:00:00.000000000 +0000 @@ -44,9 +44,8 @@ namespace NArchive { namespace NRar { -#define SIGNATURE { 0x52 , 0x61, 0x72, 0x21, 0x1a, 0x07, 0x00 } - -static const Byte kMarker[NHeader::kMarkerSize] = SIGNATURE; +static const Byte kMarker[NHeader::kMarkerSize] = + { 0x52, 0x61, 0x72, 0x21, 0x1a, 0x07, 0x00 }; const unsigned kPasswordLen_MAX = 127; @@ -184,35 +183,33 @@ { HeaderErrorWarning = false; m_CryptoMode = false; - RINOK(stream->Seek(0, STREAM_SEEK_CUR, &m_StreamStartPosition)); - RINOK(stream->Seek(0, STREAM_SEEK_END, &ArcInfo.FileSize)); - RINOK(stream->Seek(m_StreamStartPosition, STREAM_SEEK_SET, NULL)); + RINOK(InStream_GetPos_GetSize(stream, m_StreamStartPosition, ArcInfo.FileSize)) m_Position = m_StreamStartPosition; UInt64 arcStartPos = m_StreamStartPosition; { Byte marker[NHeader::kMarkerSize]; - RINOK(ReadStream_FALSE(stream, marker, NHeader::kMarkerSize)); + RINOK(ReadStream_FALSE(stream, marker, NHeader::kMarkerSize)) if (memcmp(marker, kMarker, NHeader::kMarkerSize) == 0) m_Position += NHeader::kMarkerSize; else { if (searchHeaderSizeLimit && *searchHeaderSizeLimit == 0) return S_FALSE; - RINOK(stream->Seek(m_StreamStartPosition, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, m_StreamStartPosition)) RINOK(FindSignatureInStream(stream, kMarker, NHeader::kMarkerSize, - searchHeaderSizeLimit, arcStartPos)); + searchHeaderSizeLimit, arcStartPos)) m_Position = arcStartPos + NHeader::kMarkerSize; - RINOK(stream->Seek(m_Position, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, m_Position)) } } Byte buf[NHeader::NArchive::kArchiveHeaderSize + 1]; - RINOK(ReadStream_FALSE(stream, buf, NHeader::NArchive::kArchiveHeaderSize)); + RINOK(ReadStream_FALSE(stream, buf, NHeader::NArchive::kArchiveHeaderSize)) AddToSeekValue(NHeader::NArchive::kArchiveHeaderSize); - UInt32 blockSize = Get16(buf + 5); + const UInt32 blockSize = Get16(buf + 5); ArcInfo.EncryptVersion = 0; ArcInfo.Flags = Get16(buf + 3); @@ -238,7 +235,7 @@ size_t commentSize = blockSize - headerSize; _comment.Alloc(commentSize); - RINOK(ReadStream_FALSE(stream, _comment, commentSize)); + RINOK(ReadStream_FALSE(stream, _comment, commentSize)) AddToSeekValue(commentSize); m_Stream = stream; ArcInfo.StartPos = arcStartPos; @@ -368,7 +365,7 @@ return -1; for (unsigned i = 0; i < numDigits; i++) rarTime.SubTime[3 - numDigits + i] = p[i]; - return numDigits; + return (int)numDigits; } #define READ_TIME(_mask_, _ttt_) \ @@ -480,10 +477,10 @@ Byte cMask = (Byte)(b & 0xF); if ((mMask & 8) != 0) { - READ_TIME(mMask, item.MTime); + READ_TIME(mMask, item.MTime) } - READ_TIME_2(cMask, item.CTimeDefined, item.CTime); - READ_TIME_2(aMask, item.ATimeDefined, item.ATime); + READ_TIME_2(cMask, item.CTimeDefined, item.CTime) + READ_TIME_2(aMask, item.ATimeDefined, item.ATime) } unsigned fileHeaderWithNameSize = 7 + (unsigned)(p - pStart); @@ -508,13 +505,13 @@ error = k_ErrorType_OK; for (;;) { - m_Stream->Seek(m_Position, STREAM_SEEK_SET, NULL); + RINOK(InStream_SeekSet(m_Stream, m_Position)) ArcInfo.EndPos = m_Position; if (!m_CryptoMode && (ArcInfo.Flags & NHeader::NArchive::kBlockHeadersAreEncrypted) != 0) { m_CryptoMode = false; - if (getTextPassword == 0) + if (!getTextPassword) { error = k_ErrorType_DecryptionError; return S_OK; // return S_FALSE; @@ -565,9 +562,9 @@ if (!m_DecryptedDataAligned.IsAllocated()) return E_OUTOFMEMORY; } - RINOK(m_RarAES->Init()); + RINOK(m_RarAES->Init()) size_t decryptedDataSizeT = kDecryptedBufferSize; - RINOK(ReadStream(m_Stream, m_DecryptedDataAligned, &decryptedDataSizeT)); + RINOK(ReadStream(m_Stream, m_DecryptedDataAligned, &decryptedDataSizeT)) m_DecryptedDataSize = (UInt32)decryptedDataSizeT; m_DecryptedDataSize = m_RarAES->Filter(m_DecryptedDataAligned, m_DecryptedDataSize); @@ -577,7 +574,7 @@ m_FileHeaderData.AllocAtLeast(7); size_t processed = 7; - RINOK(ReadBytesSpec((Byte *)m_FileHeaderData, &processed)); + RINOK(ReadBytesSpec((Byte *)m_FileHeaderData, &processed)) if (processed != 7) { if (processed != 0) @@ -715,7 +712,7 @@ FinishCryptoBlock(); m_CryptoMode = false; // Move Position to compressed Data; - m_Stream->Seek(m_Position, STREAM_SEEK_SET, NULL); + RINOK(InStream_SeekSet(m_Stream, m_Position)) AddToSeekValue(item.PackSize); // m_Position points to next header; // if (okItem) return S_OK; @@ -828,7 +825,7 @@ return item.IsSolid(); } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -838,7 +835,7 @@ case kpidSolid: prop = _arcInfo.IsSolid(); break; case kpidCharacts: { - AString s (FlagsToString(k_Flags, ARRAY_SIZE(k_Flags), _arcInfo.Flags)); + AString s (FlagsToString(k_Flags, Z7_ARRAY_SIZE(k_Flags), _arcInfo.Flags)); // FLAGS_TO_PROP(k_Flags, _arcInfo.Flags, prop); if (_arcInfo.Is_DataCRC_Defined()) { @@ -935,7 +932,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _refItems.Size(); return S_OK; @@ -969,7 +966,7 @@ */ } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -1087,7 +1084,7 @@ UString baseName; { NCOM::CPropVariant prop; - RINOK(openVolumeCallback->GetProperty(kpidName, &prop)); + RINOK(openVolumeCallback->GetProperty(kpidName, &prop)) if (prop.vt != VT_BSTR) break; baseName = prop.bstrVal; @@ -1119,16 +1116,15 @@ else inStream = stream; - UInt64 endPos = 0; - RINOK(inStream->Seek(0, STREAM_SEEK_END, &endPos)); - RINOK(inStream->Seek(0, STREAM_SEEK_SET, NULL)); + UInt64 endPos; + RINOK(InStream_AtBegin_GetSize(inStream, endPos)) if (openCallback) { totalBytes += endPos; - RINOK(openCallback->SetTotal(NULL, &totalBytes)); + RINOK(openCallback->SetTotal(NULL, &totalBytes)) } - RINOK(archive.Open(inStream, maxCheckStartPosition)); + RINOK(archive.Open(inStream, maxCheckStartPosition)) _isArc = true; CItem item; @@ -1157,7 +1153,7 @@ // AddErrorMessage(errorMessageLoc); } - RINOK(result); + RINOK(result) if (!filled) { @@ -1169,11 +1165,11 @@ /* if there is recovery record for multivolume archive, RAR adds 18 bytes (ZERO bytes) at the end for alignment. We must skip these bytes to prevent phySize warning. */ - RINOK(inStream->Seek(archive.ArcInfo.EndPos, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(inStream, archive.ArcInfo.EndPos)) bool areThereNonZeros; UInt64 numZeros; const UInt64 maxSize = 1 << 12; - RINOK(ReadZeroTail(inStream, areThereNonZeros, numZeros, maxSize)); + RINOK(ReadZeroTail(inStream, areThereNonZeros, numZeros, maxSize)) if (!areThereNonZeros && numZeros != 0 && numZeros <= maxSize) archive.ArcInfo.EndPos += numZeros; } @@ -1210,7 +1206,7 @@ { UInt64 numFiles = _items.Size(); UInt64 numBytes = curBytes + item.Position; - RINOK(openCallback->SetCompleted(&numFiles, &numBytes)); + RINOK(openCallback->SetCompleted(&numFiles, &numBytes)) } } @@ -1260,9 +1256,9 @@ return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *stream, +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *maxCheckStartPosition, - IArchiveOpenCallback *openCallback) + IArchiveOpenCallback *openCallback)) { COM_TRY_BEGIN Close(); @@ -1281,7 +1277,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { COM_TRY_BEGIN // _errorMessage.Empty(); @@ -1303,10 +1299,10 @@ }; -class CVolsInStream: - public ISequentialInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + CVolsInStream + , ISequentialInStream +) UInt64 _rem; ISequentialInStream *_stream; const CObjectVector *_arcs; @@ -1317,10 +1313,6 @@ bool _calcCrc; public: - MY_UNKNOWN_IMP - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - void Init(const CObjectVector *arcs, const CObjectVector *items, const CRefItem &refItem) @@ -1337,7 +1329,7 @@ }; -STDMETHODIMP CVolsInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CVolsInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -1357,7 +1349,7 @@ // return S_FALSE; } IInStream *s = (*_arcs)[volIndex].Stream; - RINOK(s->Seek(item.GetDataPosition(), STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(s, item.GetDataPosition())) _stream = s; _calcCrc = (CrcIsOK && item.IsSplitAfter()); _crc = CRC_INIT_VAL; @@ -1397,16 +1389,16 @@ return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN CMyComPtr getTextPassword; - UInt64 censoredTotalUnPacked = 0, + UInt64 // censoredTotalUnPacked = 0, // censoredTotalPacked = 0, importantTotalUnPacked = 0; // importantTotalPacked = 0; - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _refItems.Size(); if (numItems == 0) @@ -1426,7 +1418,9 @@ const CItem &item = _items[refItem.ItemIndex + refItem.NumItems - 1]; if (item.Is_Size_Defined()) - censoredTotalUnPacked += item.Size; + { + // censoredTotalUnPacked += item.Size; + } else isThereUndefinedSize = true; @@ -1458,7 +1452,7 @@ if (importantTotalUnPacked != 0 || !isThereUndefinedSize) { - RINOK(extractCallback->SetTotal(importantTotalUnPacked)); + RINOK(extractCallback->SetTotal(importantTotalUnPacked)) } UInt64 currentImportantTotalUnPacked = 0; @@ -1494,7 +1488,7 @@ { lps->InSize = currentImportantTotalPacked; lps->OutSize = currentImportantTotalUnPacked; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) if (i >= importantIndexes.Size()) break; @@ -1528,14 +1522,14 @@ if (item.IgnoreItem()) continue; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) if (!IsSolid(index)) solidStart = true; if (item.IsDir()) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } @@ -1554,7 +1548,7 @@ if (!realOutStream && !testMode) askMode = NExtract::NAskMode::kSkip; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) COutStreamWithCRC *outStreamSpec = new COutStreamWithCRC; CMyComPtr outStream(outStreamSpec); @@ -1594,7 +1588,7 @@ RINOK(rar3CryptoDecoder.QueryInterface(IID_ICompressSetDecoderProperties2, &cryptoProperties)); */ - RINOK(rar3CryptoDecoderSpec->SetDecoderProperties2(item.Salt, item.HasSalt() ? sizeof(item.Salt) : 0)); + RINOK(rar3CryptoDecoderSpec->SetDecoderProperties2(item.Salt, item.HasSalt() ? sizeof(item.Salt) : 0)) filterStreamSpec->Filter = rar3CryptoDecoder; } else if (item.UnPackVersion >= 20) @@ -1609,7 +1603,7 @@ else { outStream.Release(); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)) continue; } @@ -1621,14 +1615,14 @@ if (!getTextPassword) { outStream.Release(); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)) continue; } // if (getTextPassword) { CMyComBSTR_Wipe password; - RINOK(getTextPassword->CryptoGetTextPassword(&password)); + RINOK(getTextPassword->CryptoGetTextPassword(&password)) if (item.UnPackVersion >= 29) { @@ -1710,13 +1704,13 @@ methodID += 2; else methodID += 3; - RINOK(CreateCoder_Id(EXTERNAL_CODECS_VARS methodID, false, mi.Coder)); + RINOK(CreateCoder_Id(EXTERNAL_CODECS_VARS methodID, false, mi.Coder)) } - if (mi.Coder == 0) + if (!mi.Coder) { outStream.Release(); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)) continue; } @@ -1726,7 +1720,7 @@ CMyComPtr compressSetDecoderProperties; RINOK(decoder.QueryInterface(IID_ICompressSetDecoderProperties2, - &compressSetDecoderProperties)); + &compressSetDecoderProperties)) Byte isSolid = (Byte)((IsSolid(index) || item.IsSplitBefore()) ? 1: 0); if (solidStart) @@ -1736,14 +1730,14 @@ } - RINOK(compressSetDecoderProperties->SetDecoderProperties2(&isSolid, 1)); + RINOK(compressSetDecoderProperties->SetDecoderProperties2(&isSolid, 1)) commonCoder = decoder; break; } default: outStream.Release(); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)) continue; } @@ -1769,7 +1763,7 @@ else return result; } - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } return S_OK; @@ -1779,7 +1773,7 @@ IMPL_ISetCompressCodecsInfo REGISTER_ARC_I( - "Rar", "rar r00", 0, 3, + "Rar", "rar r00", NULL, 3, kMarker, 0, NArcInfoFlags::kFindSignature, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Rar/RarHandler.h 7zip-23.01+dfsg/CPP/7zip/Archive/Rar/RarHandler.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Rar/RarHandler.h 2020-09-28 09:29:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Rar/RarHandler.h 2023-02-01 10:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // RarHandler.h -#ifndef __RAR_HANDLER_H -#define __RAR_HANDLER_H +#ifndef ZIP7_INC_RAR_HANDLER_H +#define ZIP7_INC_RAR_HANDLER_H #include "../IArchive.h" @@ -67,11 +67,19 @@ unsigned NumItems; }; -class CHandler: +class CHandler Z7_final: public IInArchive, - PUBLIC_ISetCompressCodecsInfo + Z7_PUBLIC_ISetCompressCodecsInfo_IFEC public CMyUnknownImp { + Z7_COM_QI_BEGIN2(IInArchive) + Z7_COM_QI_ENTRY_ISetCompressCodecsInfo_IFEC + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(IInArchive) + DECL_ISetCompressCodecsInfo + CRecordVector _refItems; CObjectVector _items; CObjectVector _arcs; @@ -99,16 +107,6 @@ HRESULT Open2(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback); - -public: - MY_QUERYINTERFACE_BEGIN2(IInArchive) - QUERY_ENTRY_ISetCompressCodecsInfo - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IInArchive(;) - - DECL_ISetCompressCodecsInfo }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Rar/RarHeader.h 7zip-23.01+dfsg/CPP/7zip/Archive/Rar/RarHeader.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Rar/RarHeader.h 2016-05-20 11:31:39.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Rar/RarHeader.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Archive/RarHeader.h -#ifndef __ARCHIVE_RAR_HEADER_H -#define __ARCHIVE_RAR_HEADER_H +#ifndef ZIP7_INC_ARCHIVE_RAR_HEADER_H +#define ZIP7_INC_ARCHIVE_RAR_HEADER_H #include "../../../Common/MyTypes.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Rar/RarItem.h 7zip-23.01+dfsg/CPP/7zip/Archive/Rar/RarItem.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Rar/RarItem.h 2016-02-23 10:00:39.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Rar/RarItem.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // RarItem.h -#ifndef __ARCHIVE_RAR_ITEM_H -#define __ARCHIVE_RAR_ITEM_H +#ifndef ZIP7_INC_ARCHIVE_RAR_ITEM_H +#define ZIP7_INC_ARCHIVE_RAR_ITEM_H #include "../../../Common/StringConvert.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Rar/RarVol.h 7zip-23.01+dfsg/CPP/7zip/Archive/Rar/RarVol.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Rar/RarVol.h 2022-02-15 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Rar/RarVol.h 2023-01-17 12:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // RarVol.h -#ifndef __ARCHIVE_RAR_VOL_H -#define __ARCHIVE_RAR_VOL_H +#ifndef ZIP7_INC_ARCHIVE_RAR_VOL_H +#define ZIP7_INC_ARCHIVE_RAR_VOL_H #include "../../../Common/StringConvert.h" @@ -22,7 +22,7 @@ UString _changed; UString _after; public: - CVolumeName(): _needChangeForNext(true) {}; + CVolumeName(): _needChangeForNext(true) {} bool InitName(const UString &name, bool newStyle = true) { @@ -52,7 +52,7 @@ ext.IsEqualTo_Ascii_NoCase("r01")) { _changed = ext; - _before.SetFrom(name.Ptr(), dotPos + 1); + _before.SetFrom(name.Ptr(), (unsigned)dotPos + 1); return true; } } @@ -83,7 +83,7 @@ _after.Empty(); _before = base; - _before += '.'; + _before.Add_Dot(); _changed = "r00"; _needChangeForNext = false; return true; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Rar/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Archive/Rar/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Rar/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Rar/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/RpmHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/RpmHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/RpmHandler.cpp 2022-02-14 07:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/RpmHandler.cpp 2023-03-27 13:00:00.000000000 +0000 @@ -19,7 +19,7 @@ #include "HandlerCont.h" -// #define _SHOW_RPM_METADATA +// #define Z7_RPM_SHOW_METADATA using namespace NWindows; @@ -169,7 +169,7 @@ }; -#ifdef _SHOW_RPM_METADATA +#ifdef Z7_RPM_SHOW_METADATA struct CMetaFile { UInt32 Tag; @@ -178,8 +178,10 @@ }; #endif -class CHandler: public CHandlerCont +Z7_class_CHandler_final: public CHandlerCont { + Z7_IFACE_COM7_IMP(IInArchive_Cont) + UInt64 _headersSize; // is equal to start offset of payload data UInt64 _payloadSize; UInt64 _size; @@ -207,7 +209,7 @@ CLead _lead; - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA AString _metadata; CRecordVector _metaFiles; #endif @@ -234,15 +236,12 @@ HRESULT ReadHeader(ISequentialInStream *stream, bool isMainHeader); HRESULT Open2(ISequentialInStream *stream); - virtual int GetItem_ExtractInfo(UInt32 /* index */, UInt64 &pos, UInt64 &size) const + virtual int GetItem_ExtractInfo(UInt32 /* index */, UInt64 &pos, UInt64 &size) const Z7_override { pos = _headersSize; size = _size; return NExtract::NOperationResult::kOK; } - -public: - INTERFACE_IInArchive_Cont(;) }; static const Byte kArcProps[] = @@ -251,7 +250,7 @@ kpidCpu, kpidHostOS, kpidCTime - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA , kpidComment #endif }; @@ -274,7 +273,7 @@ { if (_lead.Type == kRpmType_Bin) { - if (_lead.Cpu < ARRAY_SIZE(k_CPUs)) + if (_lead.Cpu < Z7_ARRAY_SIZE(k_CPUs)) s += k_CPUs[_lead.Cpu]; else s.Add_UInt32(_lead.Cpu); @@ -290,19 +289,19 @@ s = _name; if (!_version.IsEmpty()) { - s += '-'; + s.Add_Minus(); s += _version; } if (!_release.IsEmpty()) { - s += '-'; + s.Add_Minus(); s += _release; } } else s.SetFrom_CalcLen(_lead.Name, kNameSize); - s += '.'; + s.Add_Dot(); if (_lead.Type == kRpmType_Src) s += "src"; else @@ -316,7 +315,7 @@ res += _format; else res += "cpio"; - res += '.'; + res.Add_Dot(); const char *s; @@ -344,7 +343,7 @@ res += s; } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -383,7 +382,7 @@ break; } - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA // case kpidComment: SetStringProp(_metadata, prop); break; #endif @@ -399,7 +398,7 @@ } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { NWindows::NCOM::CPropVariant prop; if (index == 0) @@ -418,7 +417,7 @@ case kpidPath: { AString s (GetBaseName()); - s += '.'; + s.Add_Dot(); AddSubFileExtension(s); SetStringProp(s, prop); break; @@ -432,7 +431,7 @@ } */ } - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA else { index--; @@ -467,7 +466,7 @@ return S_OK; } -#ifdef _SHOW_RPM_METADATA +#ifdef Z7_RPM_SHOW_METADATA static inline char GetHex(unsigned value) { return (char)((value < 10) ? ('0' + value) : ('A' + (value - 10))); @@ -480,7 +479,7 @@ UInt32 dataLen; { char buf[k_HeaderSig_Size]; - RINOK(ReadStream_FALSE(stream, buf, k_HeaderSig_Size)); + RINOK(ReadStream_FALSE(stream, buf, k_HeaderSig_Size)) if (Get32(buf) != 0x8EADE801) // buf[3] = 0x01 - is version return S_FALSE; // reserved = Get32(buf + 4); @@ -494,7 +493,7 @@ if (headerSize < dataLen) return S_FALSE; CByteBuffer buffer(headerSize); - RINOK(ReadStream_FALSE(stream, buffer, headerSize)); + RINOK(ReadStream_FALSE(stream, buffer, headerSize)) for (UInt32 i = 0; i < numEntries; i++) { @@ -520,7 +519,7 @@ } else { - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA { _metadata.Add_UInt32(entry.Tag); _metadata += ": "; @@ -547,7 +546,7 @@ case RPMTAG_PAYLOADCOMPRESSOR: _compressor = s; break; } - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA _metadata += s; #endif } @@ -563,7 +562,7 @@ _time_Defined = true; } - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA for (UInt32 t = 0; t < entry.Count; t++) { if (t != 0) @@ -573,7 +572,7 @@ #endif } - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA else if ( entry.Type == k_EntryType_STRING_ARRAY || @@ -628,7 +627,7 @@ #endif } - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA CMetaFile meta; meta.Offset = entry.Offset; meta.Tag = entry.Tag; @@ -656,7 +655,7 @@ { { Byte buf[kLeadSize]; - RINOK(ReadStream_FALSE(stream, buf, kLeadSize)); + RINOK(ReadStream_FALSE(stream, buf, kLeadSize)) if (Get32(buf) != 0xEDABEEDB) return S_FALSE; _lead.Parse(buf); @@ -668,22 +667,22 @@ if (_lead.SignatureType == RPMSIG_NONE) { - ; + } else if (_lead.SignatureType == RPMSIG_PGP262_1024) { Byte temp[256]; - RINOK(ReadStream_FALSE(stream, temp, sizeof(temp))); + RINOK(ReadStream_FALSE(stream, temp, sizeof(temp))) } else if (_lead.SignatureType == RPMSIG_HEADERSIG) { - RINOK(ReadHeader(stream, false)); + RINOK(ReadHeader(stream, false)) unsigned pos = (unsigned)_headersSize & 7; if (pos != 0) { Byte temp[8]; unsigned num = 8 - pos; - RINOK(ReadStream_FALSE(stream, temp, num)); + RINOK(ReadStream_FALSE(stream, temp, num)) _headersSize += num; } } @@ -694,20 +693,20 @@ } -STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *) +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *)) { COM_TRY_BEGIN { Close(); - RINOK(Open2(inStream)); + RINOK(Open2(inStream)) // start of payload is allowed to be unaligned - RINOK(ReadStream_FALSE(inStream, _payloadSig, sizeof(_payloadSig))); + RINOK(ReadStream_FALSE(inStream, _payloadSig, sizeof(_payloadSig))) if (!_payloadSize_Defined) { UInt64 endPos; - RINOK(inStream->Seek(0, STREAM_SEEK_END, &endPos)); + RINOK(InStream_GetSize_SeekToEnd(inStream, endPos)) _size = endPos - _headersSize; } _stream = inStream; @@ -716,7 +715,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _headersSize = 0; _payloadSize = 0; @@ -738,7 +737,7 @@ _format.Empty(); _compressor.Empty(); - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA _metadata.Empty(); _metaFiles.Size(); #endif @@ -747,10 +746,10 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = 1 - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA + _metaFiles.Size() #endif ; @@ -761,7 +760,7 @@ static const Byte k_Signature[] = { 0xED, 0xAB, 0xEE, 0xDB}; REGISTER_ARC_I( - "Rpm", "rpm", 0, 0xEB, + "Rpm", "rpm", NULL, 0xEB, k_Signature, 0, 0, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/SparseHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/SparseHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/SparseHandler.cpp 2022-02-01 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/SparseHandler.cpp 2023-03-27 13:00:00.000000000 +0000 @@ -42,11 +42,11 @@ { // G16 (4, major_version); // G16 (6, minor_version); - G16 (8, file_hdr_sz); - G16 (10, chunk_hdr_sz); - G32 (12, BlockSize); - G32 (16, NumBlocks); - G32 (20, NumChunks); + G16 (8, file_hdr_sz) + G16 (10, chunk_hdr_sz) + G32 (12, BlockSize) + G32 (16, NumBlocks) + G32 (20, NumChunks) // G32 (24, image_checksum); } }; @@ -58,9 +58,9 @@ #define CHUNK_TYPE_DONT_CARE 0xCAC3 #define CHUNK_TYPE_CRC32 0xCAC4 -#define MY__CHUNK_TYPE_FILL 0 -#define MY__CHUNK_TYPE_DONT_CARE 1 -#define MY__CHUNK_TYPE_RAW__START 2 +#define MY_CHUNK_TYPE_FILL 0 +#define MY_CHUNK_TYPE_DONT_CARE 1 +#define MY_CHUNK_TYPE_RAW_START 2 static const char * const g_Methods[] = { @@ -82,8 +82,13 @@ static const Byte k_Signature[] = { 0x3a, 0xff, 0x26, 0xed, 1, 0 }; -class CHandler: public CHandlerImg +Z7_class_CHandler_final: public CHandlerImg { + Z7_IFACE_COM7_IMP(IInArchive_Img) + + Z7_IFACE_COM7_IMP(IInArchiveGetStream) + Z7_IFACE_COM7_IMP(ISequentialInStream) + CRecordVector Chunks; UInt64 _virtSize_fromChunks; unsigned _blockSizeLog; @@ -101,7 +106,7 @@ HRESULT Seek2(UInt64 offset) { _posInArc = offset; - return Stream->Seek(offset, STREAM_SEEK_SET, NULL); + return InStream_SeekSet(Stream, offset); } void InitSeekPositions() @@ -115,25 +120,19 @@ } // virtual functions - bool Init_PackSizeProcessed() + bool Init_PackSizeProcessed() Z7_override { _packSizeProcessed = 0; return true; } - bool Get_PackSizeProcessed(UInt64 &size) + bool Get_PackSizeProcessed(UInt64 &size) Z7_override { size = _packSizeProcessed; return true; } - HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openCallback); + HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openCallback) Z7_override; HRESULT ReadPhy(UInt64 offset, void *data, UInt32 size, UInt32 &processed); - -public: - INTERFACE_IInArchive_Img(;) - - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); }; @@ -154,7 +153,7 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -193,7 +192,7 @@ } -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -228,7 +227,7 @@ CHeader h; { Byte buf[kHeaderSize]; - RINOK(ReadStream_FALSE(stream, buf, kHeaderSize)); + RINOK(ReadStream_FALSE(stream, buf, kHeaderSize)) if (memcmp(buf, k_Signature, 6) != 0) return S_FALSE; h.Parse(buf); @@ -262,13 +261,13 @@ const UInt32 mask = ((UInt32)1 << 16) - 1; if ((i & mask) == mask && openCallback) { - RINOK(openCallback->SetCompleted(NULL, &offset)); + RINOK(openCallback->SetCompleted(NULL, &offset)) } } Byte buf[kChunkHeaderSize]; { size_t processed = kChunkHeaderSize; - RINOK(ReadStream(stream, buf, &processed)); + RINOK(ReadStream(stream, buf, &processed)) if (kChunkHeaderSize != processed) { offset += kChunkHeaderSize; @@ -301,7 +300,7 @@ return S_FALSE; { size_t processed = kFillSize; - RINOK(ReadStream(stream, c.Fill, &processed)); + RINOK(ReadStream(stream, c.Fill, &processed)) if (kFillSize != processed) break; } @@ -316,15 +315,15 @@ { if (size != 0) return S_FALSE; - c.PhyOffset = MY__CHUNK_TYPE_DONT_CARE; + c.PhyOffset = MY_CHUNK_TYPE_DONT_CARE; } else if (type == CHUNK_TYPE_FILL) { if (size != kFillSize) return S_FALSE; - c.PhyOffset = MY__CHUNK_TYPE_FILL; + c.PhyOffset = MY_CHUNK_TYPE_FILL; size_t processed = kFillSize; - RINOK(ReadStream(stream, c.Fill, &processed)); + RINOK(ReadStream(stream, c.Fill, &processed)) if (kFillSize != processed) break; } @@ -343,7 +342,7 @@ virtBlock += numBlocks; Chunks.AddInReserved(c); if (type == CHUNK_TYPE_RAW) - RINOK(stream->Seek(offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, offset)) } } @@ -367,7 +366,7 @@ } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { Chunks.Clear(); _isArc = false; @@ -388,7 +387,7 @@ } -STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream)) { COM_TRY_BEGIN *stream = NULL; @@ -436,7 +435,7 @@ } -STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -486,7 +485,7 @@ const UInt64 phyOffset = c.PhyOffset; - if (phyOffset >= MY__CHUNK_TYPE_RAW__START) + if (phyOffset >= MY_CHUNK_TYPE_RAW_START) { UInt32 processed = 0; const HRESULT res = ReadPhy(phyOffset + offset, data, size, processed); @@ -496,9 +495,9 @@ return res; } - unsigned b = 0; + Byte b = 0; - if (phyOffset == MY__CHUNK_TYPE_FILL) + if (phyOffset == MY_CHUNK_TYPE_FILL) { const Byte b0 = c.Fill [0]; const Byte b1 = c.Fill [1]; @@ -528,7 +527,7 @@ } b = b0; } - else if (phyOffset != MY__CHUNK_TYPE_DONT_CARE) + else if (phyOffset != MY_CHUNK_TYPE_DONT_CARE) return S_FALSE; memset(data, b, size); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/SplitHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/SplitHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/SplitHandler.cpp 2022-05-15 07:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/SplitHandler.cpp 2023-03-27 13:00:00.000000000 +0000 @@ -9,6 +9,7 @@ #include "../Common/ProgressUtils.h" #include "../Common/RegisterArc.h" +#include "../Common/StreamUtils.h" #include "../Compress/CopyCoder.h" @@ -31,27 +32,22 @@ kpidTotalPhySize }; -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_CHandler_IInArchive_1( + IInArchiveGetStream +) CObjectVector > _streams; CRecordVector _sizes; UString _subName; UInt64 _totalSize; HRESULT Open2(IInStream *stream, IArchiveOpenCallback *callback); -public: - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); }; IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; switch (propID) @@ -121,27 +117,29 @@ } }; + HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) { Close(); if (!callback) return S_FALSE; - CMyComPtr volumeCallback; - callback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&volumeCallback); + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveOpenVolumeCallback, + volumeCallback, callback) if (!volumeCallback) return S_FALSE; UString name; { NCOM::CPropVariant prop; - RINOK(volumeCallback->GetProperty(kpidName, &prop)); + RINOK(volumeCallback->GetProperty(kpidName, &prop)) if (prop.vt != VT_BSTR) return S_FALSE; name = prop.bstrVal; } - int dotPos = name.ReverseFind_Dot(); + const int dotPos = name.ReverseFind_Dot(); const UString prefix = name.Left((unsigned)(dotPos + 1)); const UString ext = name.Ptr((unsigned)(dotPos + 1)); UString ext2 = ext; @@ -192,14 +190,13 @@ { /* NCOM::CPropVariant prop; - RINOK(volumeCallback->GetProperty(kpidSize, &prop)); + RINOK(volumeCallback->GetProperty(kpidSize, &prop)) if (prop.vt != VT_UI8) return E_INVALIDARG; size = prop.uhVal.QuadPart; */ - RINOK(stream->Seek(0, STREAM_SEEK_END, &size)); - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); } + RINOK(InStream_AtBegin_GetSize(stream, size)) _totalSize += size; _sizes.Add(size); @@ -207,7 +204,7 @@ { const UInt64 numFiles = _streams.Size(); - RINOK(callback->SetCompleted(&numFiles, NULL)); + RINOK(callback->SetCompleted(&numFiles, NULL)) } for (;;) @@ -216,30 +213,20 @@ if (!seqName.GetNextName(fullName)) break; CMyComPtr nextStream; - HRESULT result = volumeCallback->GetStream(fullName, &nextStream); + const HRESULT result = volumeCallback->GetStream(fullName, &nextStream); if (result == S_FALSE) break; if (result != S_OK) return result; if (!nextStream) break; - { - /* - NCOM::CPropVariant prop; - RINOK(volumeCallback->GetProperty(kpidSize, &prop)); - if (prop.vt != VT_UI8) - return E_INVALIDARG; - size = prop.uhVal.QuadPart; - */ - RINOK(nextStream->Seek(0, STREAM_SEEK_END, &size)); - RINOK(nextStream->Seek(0, STREAM_SEEK_SET, NULL)); - } + RINOK(InStream_AtBegin_GetSize(nextStream, size)) _totalSize += size; _sizes.Add(size); _streams.Add(nextStream); { const UInt64 numFiles = _streams.Size(); - RINOK(callback->SetCompleted(&numFiles, NULL)); + RINOK(callback->SetCompleted(&numFiles, NULL)) } } @@ -251,17 +238,17 @@ return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback)) { COM_TRY_BEGIN - HRESULT res = Open2(stream, callback); + const HRESULT res = Open2(stream, callback); if (res != S_OK) Close(); return res; COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _totalSize = 0; _subName.Empty(); @@ -270,13 +257,13 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _streams.IsEmpty() ? 0 : 1; return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; switch (propID) @@ -291,8 +278,8 @@ return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN if (numItems == 0) @@ -301,15 +288,15 @@ return E_INVALIDARG; UInt64 currentTotalSize = 0; - RINOK(extractCallback->SetTotal(_totalSize)); + RINOK(extractCallback->SetTotal(_totalSize)) CMyComPtr outStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - RINOK(extractCallback->GetStream(0, &outStream, askMode)); + RINOK(extractCallback->GetStream(0, &outStream, askMode)) if (!testMode && !outStream) return S_OK; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder; CMyComPtr copyCoder = copyCoderSpec; @@ -318,13 +305,15 @@ CMyComPtr progress = lps; lps->Init(extractCallback, false); - FOR_VECTOR (i, _streams) + for (unsigned i = 0;; i++) { lps->InSize = lps->OutSize = currentTotalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) + if (i == _streams.Size()) + break; IInStream *inStream = _streams[i]; - RINOK(inStream->Seek(0, STREAM_SEEK_SET, NULL)); - RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); + RINOK(InStream_SeekToBegin(inStream)) + RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)) currentTotalSize += copyCoderSpec->TotalSize; } outStream.Release(); @@ -332,12 +321,12 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN if (index != 0) return E_INVALIDARG; - *stream = 0; + *stream = NULL; CMultiStream *streamSpec = new CMultiStream; CMyComPtr streamTemp = streamSpec; FOR_VECTOR (i, _streams) @@ -354,7 +343,7 @@ } REGISTER_ARC_I_NO_SIG( - "Split", "001", 0, 0xEA, + "Split", "001", NULL, 0xEA, 0, 0, NULL) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/SquashfsHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/SquashfsHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/SquashfsHandler.cpp 2022-05-02 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/SquashfsHandler.cpp 2023-03-26 12:00:00.000000000 +0000 @@ -49,13 +49,13 @@ #define Get32(p) Get32b(p, be) #define Get64(p) Get64b(p, be) -#define LE_16(offs, dest) dest = GetUi16(p + (offs)); -#define LE_32(offs, dest) dest = GetUi32(p + (offs)); -#define LE_64(offs, dest) dest = GetUi64(p + (offs)); - -#define GET_16(offs, dest) dest = Get16(p + (offs)); -#define GET_32(offs, dest) dest = Get32(p + (offs)); -#define GET_64(offs, dest) dest = Get64(p + (offs)); +#define LE_16(offs, dest) dest = GetUi16(p + (offs)) +#define LE_32(offs, dest) dest = GetUi32(p + (offs)) +#define LE_64(offs, dest) dest = GetUi64(p + (offs)) + +#define GET_16(offs, dest) dest = Get16(p + (offs)) +#define GET_32(offs, dest) dest = Get32(p + (offs)) +#define GET_64(offs, dest) dest = Get64(p + (offs)) static const UInt32 kSignature32_LE = 0x73717368; static const UInt32 kSignature32_BE = 0x68737173; @@ -831,11 +831,10 @@ UInt32 Size; }; -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_CHandler_IInArchive_1( + IInArchiveGetStream +) CRecordVector _items; CRecordVector _nodes; CRecordVector _nodesPos; @@ -893,7 +892,7 @@ HRESULT Seek2(UInt64 offset) { - return _stream->Seek(offset, STREAM_SEEK_SET, NULL); + return InStream_SeekSet(_stream, offset); } HRESULT Decompress(ISequentialOutStream *outStream, Byte *outBuf, bool *outBufWasWritten, UInt32 *outBufWasWrittenSize, @@ -906,8 +905,8 @@ HRESULT ScanInodes(UInt64 ptr); HRESULT ReadUids(UInt64 start, UInt32 num, CByteBuffer &ids); HRESULT Open2(IInStream *inStream); - AString GetPath(int index) const; - bool GetPackSize(int index, UInt64 &res, bool fillOffsets); + AString GetPath(unsigned index) const; + bool GetPackSize(unsigned index, UInt64 &res, bool fillOffsets); public: CHandler(); @@ -916,13 +915,10 @@ XzUnpacker_Free(&_xz); } - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); - HRESULT ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize); }; + CHandler::CHandler() { XzUnpacker_Construct(&_xz, &g_Alloc); @@ -1044,7 +1040,7 @@ } srcRem--; - back = (b >> 2) + (*src++ << 2); + back = (b >> 2) + ((UInt32)*src++ << 2); len = 2; if (mode == 4) { @@ -1086,8 +1082,8 @@ back += ((bOld & 8) << 11); if (back == 0) { - *destLen = dest - destStart; - *srcLen = src - srcStart; + *destLen = (size_t)(dest - destStart); + *srcLen = (size_t)(src - srcStart); return S_OK; } back += (1 << 14) - 1; @@ -1137,16 +1133,16 @@ if (_h.SeveralMethods) { Byte b; - RINOK(ReadStream_FALSE(_stream, &b, 1)); - RINOK(_stream->Seek(-1, STREAM_SEEK_CUR, NULL)); + RINOK(ReadStream_FALSE(_stream, &b, 1)) + RINOK(_stream->Seek(-1, STREAM_SEEK_CUR, NULL)) method = (b == 0x5D ? kMethod_LZMA : kMethod_ZLIB); } if (method == kMethod_ZLIB && _needCheckLzma) { Byte b; - RINOK(ReadStream_FALSE(_stream, &b, 1)); - RINOK(_stream->Seek(-1, STREAM_SEEK_CUR, NULL)); + RINOK(ReadStream_FALSE(_stream, &b, 1)) + RINOK(_stream->Seek(-1, STREAM_SEEK_CUR, NULL)) if (b == 0) { _noPropsLZMA = true; @@ -1162,7 +1158,7 @@ _zlibDecoderSpec = new NCompress::NZlib::CDecoder(); _zlibDecoder = _zlibDecoderSpec; } - RINOK(_zlibDecoder->Code(_limitedInStream, outStream, NULL, NULL, NULL)); + RINOK(_zlibDecoder->Code(_limitedInStream, outStream, NULL, NULL, NULL)) if (inSize != _zlibDecoderSpec->GetInputProcessedSize()) return S_FALSE; } @@ -1204,7 +1200,7 @@ { if (_inputBuffer.Size() < inSize) _inputBuffer.Alloc(inSize); - RINOK(ReadStream_FALSE(_stream, _inputBuffer, inSize)); + RINOK(ReadStream_FALSE(_stream, _inputBuffer, inSize)) Byte *dest = outBuf; if (!outBuf) @@ -1218,7 +1214,7 @@ if (method == kMethod_LZO) { - RINOK(LzoDecode(dest, &destLen, _inputBuffer, &srcLen)); + RINOK(LzoDecode(dest, &destLen, _inputBuffer, &srcLen)) } else if (method == kMethod_LZMA) { @@ -1228,7 +1224,7 @@ if (_noPropsLZMA) { props[0] = 0x5D; - SetUi32(&props[1], _h.BlockSize); + SetUi32(&props[1], _h.BlockSize) } else { @@ -1289,7 +1285,7 @@ const unsigned offset = _h.NeedCheckData() ? 3 : 2; if (offset > packSize) return S_FALSE; - RINOK(ReadStream_FALSE(_stream, temp, offset)); + RINOK(ReadStream_FALSE(_stream, temp, offset)) // if (NeedCheckData && Major < 4) checkByte must be = 0xFF const bool be = _h.be; UInt32 size = Get16(temp); @@ -1303,7 +1299,7 @@ if (isCompressed) { _limitedInStreamSpec->Init(size); - RINOK(Decompress(_dynOutStream, NULL, NULL, NULL, size, kMetadataBlockSize)); + RINOK(Decompress(_dynOutStream, NULL, NULL, NULL, size, kMetadataBlockSize)) } else { @@ -1311,7 +1307,7 @@ Byte *buf = _dynOutStreamSpec->GetBufPtrForWriting(size); if (!buf) return E_OUTOFMEMORY; - RINOK(ReadStream_FALSE(_stream, buf, size)); + RINOK(ReadStream_FALSE(_stream, buf, size)) _dynOutStreamSpec->UpdateSize(size); } return S_OK; @@ -1330,7 +1326,7 @@ if (end < start || end - start >= ((UInt64)1 << 32)) return S_FALSE; const UInt32 size = (UInt32)(end - start); - RINOK(Seek2(start)); + RINOK(Seek2(start)) _dynOutStreamSpec->Init(); UInt32 packPos = 0; while (packPos != size) @@ -1340,7 +1336,7 @@ if (packPos > size) return S_FALSE; UInt32 packSize = size - packPos; - RINOK(ReadMetadataBlock(packSize)); + RINOK(ReadMetadataBlock(packSize)) { const size_t tSize = _dynOutStreamSpec->GetSize(); if (tSize != (UInt32)tSize) @@ -1466,7 +1462,7 @@ UInt64 numFiles = _items.Size(); if ((numFiles & 0xFFFF) == 0) { - RINOK(_openCallback->SetCompleted(&numFiles, NULL)); + RINOK(_openCallback->SetCompleted(&numFiles, NULL)) } } @@ -1521,13 +1517,13 @@ } } - int startItemIndex = _items.Size() - tempItems.Size(); + const unsigned startItemIndex = _items.Size() - tempItems.Size(); FOR_VECTOR (i, tempItems) { const CTempItem &tempItem = tempItems[i]; - int index = startItemIndex + i; + const unsigned index = startItemIndex + i; CItem &item = _items[index]; - RINOK(OpenDir(index, tempItem.StartBlock, tempItem.Offset, level + 1, item.Node)); + RINOK(OpenDir((int)index, tempItem.StartBlock, tempItem.Offset, level + 1, item.Node)) } return S_OK; @@ -1539,7 +1535,7 @@ ids.Alloc(size); if (num == 0) return S_OK; - RINOK(Seek2(start)); + RINOK(Seek2(start)) return ReadStream_FALSE(_stream, ids, size); } @@ -1547,7 +1543,7 @@ { { Byte buf[kHeaderSize3]; - RINOK(ReadStream_FALSE(inStream, buf, kHeaderSize3)); + RINOK(ReadStream_FALSE(inStream, buf, kHeaderSize3)) if (!_h.Parse(buf)) return S_FALSE; if (!_h.IsSupported()) @@ -1580,15 +1576,15 @@ const UInt32 numBlocks = (_h.NumFrags + (1 << fragPtrsInBlockLog) - 1) >> fragPtrsInBlockLog; const size_t numBlocksBytes = (size_t)numBlocks << (2 + bigFrag); CByteBuffer data(numBlocksBytes); - RINOK(Seek2(_h.FragTable)); - RINOK(ReadStream_FALSE(inStream, data, numBlocksBytes)); + RINOK(Seek2(_h.FragTable)) + RINOK(ReadStream_FALSE(inStream, data, numBlocksBytes)) const bool be = _h.be; for (UInt32 i = 0; i < numBlocks; i++) { const UInt64 offset = bigFrag ? Get64(data + i * 8) : Get32(data + i * 4); - RINOK(Seek2(offset)); - RINOK(ReadMetadataBlock2()); + RINOK(Seek2(offset)) + RINOK(ReadMetadataBlock2()) const UInt32 unpackSize = (UInt32)_dynOutStreamSpec->GetSize(); if (unpackSize != kMetadataBlockSize) if (i != numBlocks - 1 || unpackSize != ((_h.NumFrags << (3 + bigFrag)) & (kMetadataBlockSize - 1))) @@ -1617,8 +1613,8 @@ return S_FALSE; } - RINOK(ReadData(_inodesData, _h.InodeTable, _h.DirTable)); - RINOK(ReadData(_dirs, _h.DirTable, _h.FragTable)); + RINOK(ReadData(_inodesData, _h.InodeTable, _h.DirTable)) + RINOK(ReadData(_dirs, _h.DirTable, _h.FragTable)) UInt64 absOffset = _h.RootInode >> 16; if (absOffset >= ((UInt64)1 << 32)) @@ -1663,12 +1659,12 @@ return S_FALSE; } int rootNodeIndex; - RINOK(OpenDir(-1, (UInt32)absOffset, (UInt32)_h.RootInode & 0xFFFF, 0, rootNodeIndex)); + RINOK(OpenDir(-1, (UInt32)absOffset, (UInt32)_h.RootInode & 0xFFFF, 0, rootNodeIndex)) if (_h.Major < 4) { - RINOK(ReadUids(_h.UidTable, _h.NumUids, _uids)); - RINOK(ReadUids(_h.GidTable, _h.NumGids, _gids)); + RINOK(ReadUids(_h.UidTable, _h.NumUids, _uids)) + RINOK(ReadUids(_h.GidTable, _h.NumGids, _gids)) } else { @@ -1677,29 +1673,29 @@ const UInt32 numBlocks = (size + kMetadataBlockSize - 1) / kMetadataBlockSize; const UInt32 numBlocksBytes = numBlocks << 3; - CByteBuffer data; - data.Alloc(numBlocksBytes); - RINOK(Seek2(_h.UidTable)); - RINOK(ReadStream_FALSE(inStream, data, numBlocksBytes)); + CByteBuffer data(numBlocksBytes); + RINOK(Seek2(_h.UidTable)) + RINOK(ReadStream_FALSE(inStream, data, numBlocksBytes)) for (UInt32 i = 0; i < numBlocks; i++) { const UInt64 offset = GetUi64(data + i * 8); - RINOK(Seek2(offset)); + RINOK(Seek2(offset)) // RINOK(ReadMetadataBlock(NULL, _uids + kMetadataBlockSize * i, packSize, unpackSize)); - RINOK(ReadMetadataBlock2()); + RINOK(ReadMetadataBlock2()) const size_t unpackSize = _dynOutStreamSpec->GetSize(); - if (unpackSize != kMetadataBlockSize) - if (i != numBlocks - 1 || unpackSize != (size & (kMetadataBlockSize - 1))) - return S_FALSE; - memcpy(_uids + kMetadataBlockSize * i, _dynOutStreamSpec->GetBuffer(), unpackSize); + const UInt32 remSize = (i == numBlocks - 1) ? + (size & (kMetadataBlockSize - 1)) : kMetadataBlockSize; + if (unpackSize != remSize) + return S_FALSE; + memcpy(_uids + kMetadataBlockSize * i, _dynOutStreamSpec->GetBuffer(), remSize); } } { const UInt32 alignSize = 1 << 12; Byte buf[alignSize]; - RINOK(Seek2(_h.Size)); + RINOK(Seek2(_h.Size)) UInt32 rem = (UInt32)(0 - _h.Size) & (alignSize - 1); _sizeCalculated = _h.Size; if (rem != 0) @@ -1716,23 +1712,24 @@ return S_OK; } -AString CHandler::GetPath(int index) const +AString CHandler::GetPath(unsigned index) const { unsigned len = 0; - int indexMem = index; + const unsigned indexMem = index; const bool be = _h.be; - do + for (;;) { const CItem &item = _items[index]; - index = item.Parent; const Byte *p = _dirs.Data + item.Ptr; - unsigned size = (_h.IsOldVersion() ? (unsigned)p[2] : (unsigned)Get16(p + 6)) + 1; + const unsigned size = (_h.IsOldVersion() ? (unsigned)p[2] : (unsigned)Get16(p + 6)) + 1; p += _h.GetFileNameOffset(); unsigned i; for (i = 0; i < size && p[i]; i++); len += i + 1; + index = (unsigned)item.Parent; + if (item.Parent < 0) + break; } - while (index >= 0); len--; AString path; @@ -1741,22 +1738,22 @@ for (;;) { const CItem &item = _items[index]; - index = item.Parent; const Byte *p = _dirs.Data + item.Ptr; - unsigned size = (_h.IsOldVersion() ? (unsigned)p[2] : (unsigned)Get16(p + 6)) + 1; + const unsigned size = (_h.IsOldVersion() ? (unsigned)p[2] : (unsigned)Get16(p + 6)) + 1; p += _h.GetFileNameOffset(); unsigned i; for (i = 0; i < size && p[i]; i++); dest -= i; memcpy(dest, p, i); - if (index < 0) + index = (unsigned)item.Parent; + if (item.Parent < 0) break; *(--dest) = CHAR_PATH_SEPARATOR; } return path; } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback)) { COM_TRY_BEGIN { @@ -1784,7 +1781,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _openCodePage = CP_UTF8; _sizeCalculated = 0; @@ -1800,8 +1797,8 @@ _inodesData.Clear(); _dirs.Clear(); - // _uids.Free(); - // _gids.Free();; + _uids.Free(); + _gids.Free(); _cachedBlock.Free(); ClearCache(); @@ -1809,7 +1806,7 @@ return S_OK; } -bool CHandler::GetPackSize(int index, UInt64 &totalPack, bool fillOffsets) +bool CHandler::GetPackSize(unsigned index, UInt64 &totalPack, bool fillOffsets) { totalPack = 0; const CItem &item = _items[index]; @@ -1818,7 +1815,7 @@ const Byte *p = _inodesData.Data + ptr; const bool be = _h.be; - UInt32 type = node.Type; + const UInt32 type = node.Type; UInt32 offset; if (node.IsLink() || node.FileSize == 0) { @@ -1826,7 +1823,7 @@ return true; } - UInt32 numBlocks = (UInt32)node.GetNumBlocks(_h); + const UInt32 numBlocks = (UInt32)node.GetNumBlocks(_h); if (fillOffsets) { @@ -1896,13 +1893,13 @@ } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _items.Size(); return S_OK; } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -1919,7 +1916,7 @@ else { s = NULL; - if (_h.Method < ARRAY_SIZE(k_Methods)) + if (_h.Method < Z7_ARRAY_SIZE(k_Methods)) s = k_Methods[_h.Method]; if (!s) { @@ -1937,7 +1934,7 @@ res += "-LZMA"; res.Add_Space(); res.Add_UInt32(_h.Major); - res += '.'; + res.Add_Dot(); res.Add_UInt32(_h.Minor); prop = res; break; @@ -1979,7 +1976,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -2043,40 +2040,29 @@ } case kpidPosixAttrib: { - if (node.Type != 0 && node.Type < ARRAY_SIZE(k_TypeToMode)) + if (node.Type != 0 && node.Type < Z7_ARRAY_SIZE(k_TypeToMode)) prop = (UInt32)(node.Mode & 0xFFF) | k_TypeToMode[node.Type]; break; } case kpidUserId: - { - const UInt32 offset = (UInt32)node.Uid * 4; - if (offset < _uids.Size()) - prop = (UInt32)Get32(_uids + offset); - break; - } case kpidGroupId: { - if (_h.Major < 4) + UInt32 id = node.Uid; + const CByteBuffer *ids = &_uids; + if (propID == kpidGroupId) { - if (node.Gid == _h.GetSpecGuidIndex()) - { - const UInt32 offset = (UInt32)node.Uid * 4; - if (offset < _uids.Size()) - prop = (UInt32)Get32(_uids + offset); - } - else + id = node.Gid; + if (_h.Major < 4) { - const UInt32 offset = (UInt32)node.Gid * 4; - if (offset < _gids.Size()) - prop = (UInt32)Get32(_gids + offset); + if (id == _h.GetSpecGuidIndex()) + id = node.Uid; + else + ids = &_gids; } } - else - { - const UInt32 offset = (UInt32)node.Gid * 4; - if (offset < _uids.Size()) - prop = (UInt32)Get32(_uids + offset); - } + const UInt32 offset = (UInt32)id * 4; + if (offset < ids->Size()) + prop = (UInt32)Get32(*ids + offset); break; } /* @@ -2093,7 +2079,7 @@ class CSquashfsInStream: public CCachedInStream { - HRESULT ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize); + HRESULT ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize) Z7_override; public: CHandler *Handler; }; @@ -2139,7 +2125,7 @@ packBlockSize != _cachedPackBlockSize) { ClearCache(); - RINOK(Seek2(blockOffset)); + RINOK(Seek2(blockOffset)) _limitedInStreamSpec->Init(packBlockSize); if (compressed) @@ -2148,7 +2134,7 @@ bool outBufWasWritten; UInt32 outBufWasWrittenSize; HRESULT res = Decompress(_outStream, _cachedBlock, &outBufWasWritten, &outBufWasWrittenSize, packBlockSize, _h.BlockSize); - RINOK(res); + RINOK(res) if (outBufWasWritten) _cachedUnpackBlockSize = outBufWasWrittenSize; else @@ -2158,7 +2144,7 @@ { if (packBlockSize > _h.BlockSize) return S_FALSE; - RINOK(ReadStream_FALSE(_limitedInStream, _cachedBlock, packBlockSize)); + RINOK(ReadStream_FALSE(_limitedInStream, _cachedBlock, packBlockSize)) _cachedUnpackBlockSize = packBlockSize; } _cachedBlockStartPos = blockOffset; @@ -2171,11 +2157,11 @@ return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _items.Size(); if (numItems == 0) @@ -2204,21 +2190,21 @@ { lps->InSize = totalPackSize; lps->OutSize = totalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr outStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; const CItem &item = _items[index]; const CNode &node = _nodes[item.Node]; - RINOK(extractCallback->GetStream(index, &outStream, askMode)); + RINOK(extractCallback->GetStream(index, &outStream, askMode)) // const Byte *p = _data + item.Offset; if (node.IsDir()) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } UInt64 unpackSize = node.GetSize(); @@ -2229,7 +2215,7 @@ if (!testMode && !outStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) int res = NExtract::NOperationResult::kDataError; { @@ -2243,7 +2229,7 @@ } else { - RINOK(hres); + RINOK(hres) { hres = copyCoder->Code(inSeqStream, outStream, NULL, NULL, progress); if (hres == S_OK) @@ -2257,13 +2243,13 @@ } else if (hres != S_FALSE) { - RINOK(hres); + RINOK(hres) } } } } - RINOK(extractCallback->SetOperationResult(res)); + RINOK(extractCallback->SetOperationResult(res)) } return S_OK; @@ -2271,7 +2257,7 @@ } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN @@ -2331,7 +2317,7 @@ 4, 'q', 's', 'h', 's' }; REGISTER_ARC_I( - "SquashFS", "squashfs", 0, 0xD2, + "SquashFS", "squashfs", NULL, 0xD2, k_Signature, 0, NArcInfoFlags::kMultiSignature, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Archive/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/StdAfx.h 2013-11-13 06:36:46.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/SwfHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/SwfHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/SwfHandler.cpp 2021-12-16 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/SwfHandler.cpp 2023-03-27 12:51:00.000000000 +0000 @@ -25,9 +25,9 @@ #include "Common/DummyOutStream.h" -// #define SWF_UPDATE +// #define Z7_SWF_UPDATE -#ifdef SWF_UPDATE +#ifdef Z7_SWF_UPDATE #include "../Compress/LzmaEncoder.h" #include "../Compress/ZlibEncoder.h" @@ -142,7 +142,7 @@ Buf[0] = SWF_COMPRESSED_LZMA; if (Buf[3] < SWF_MIN_COMPRESSED_LZMA_VER) Buf[3] = SWF_MIN_COMPRESSED_LZMA_VER; - SetUi32(Buf + 8, packSize); + SetUi32(Buf + 8, packSize) HeaderSize = kHeaderLzmaSize; } @@ -157,37 +157,37 @@ } }; -class CHandler: + +Z7_class_CHandler_final: public IInArchive, public IArchiveOpenSeq, - #ifdef SWF_UPDATE + #ifdef Z7_SWF_UPDATE public IOutArchive, public ISetProperties, #endif public CMyUnknownImp { + #ifdef Z7_SWF_UPDATE + Z7_IFACES_IMP_UNK_4(IInArchive, IArchiveOpenSeq, IOutArchive, ISetProperties) + #else + Z7_IFACES_IMP_UNK_2(IInArchive, IArchiveOpenSeq) + #endif + CItem _item; UInt64 _packSize; bool _packSizeDefined; CMyComPtr _seqStream; CMyComPtr _stream; - #ifdef SWF_UPDATE + #ifdef Z7_SWF_UPDATE CSingleMethodProps _props; bool _lzmaMode; #endif public: - #ifdef SWF_UPDATE - MY_UNKNOWN_IMP4(IInArchive, IArchiveOpenSeq, IOutArchive, ISetProperties) + #ifdef Z7_SWF_UPDATE CHandler(): _lzmaMode(false) {} - INTERFACE_IOutArchive(;) - STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps); - #else - MY_UNKNOWN_IMP2(IInArchive, IArchiveOpenSeq) #endif - INTERFACE_IInArchive(;) - STDMETHOD(OpenSeq)(ISequentialInStream *stream); }; static const Byte kProps[] = @@ -200,7 +200,7 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps_NO_Table -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; switch (propID) @@ -212,7 +212,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = 1; return S_OK; @@ -222,7 +222,7 @@ { char c = 0; unsigned i; - for (i = 0; i <= 31; i++) + for (i = 0; i < 32; i++) if (((UInt32)1 << i) == val) { val = i; @@ -240,7 +240,7 @@ s[pos] = 0; } -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)) { NWindows::NCOM::CPropVariant prop; switch (propID) @@ -265,22 +265,22 @@ return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *)) { - RINOK(OpenSeq(stream)); + RINOK(OpenSeq(stream)) _stream = stream; return S_OK; } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { Close(); - RINOK(_item.ReadHeader(stream)); + RINOK(_item.ReadHeader(stream)) if (!_item.IsSwf()) return S_FALSE; if (_item.IsLzma()) { - RINOK(ReadStream_FALSE(stream, _item.Buf + kHeaderBaseSize, kHeaderLzmaSize - kHeaderBaseSize)); + RINOK(ReadStream_FALSE(stream, _item.Buf + kHeaderBaseSize, kHeaderLzmaSize - kHeaderBaseSize)) _item.HeaderSize = kHeaderLzmaSize; _packSize = _item.GetLzmaPackSize(); _packSizeDefined = true; @@ -293,7 +293,7 @@ return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _packSize = 0; _packSizeDefined = false; @@ -302,31 +302,29 @@ return S_OK; } -class CCompressProgressInfoImp: - public ICompressProgressInfo, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CCompressProgressInfoImp, + ICompressProgressInfo +) CMyComPtr Callback; public: UInt64 Offset; - MY_UNKNOWN_IMP1(ICompressProgressInfo) - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); void Init(IArchiveOpenCallback *callback) { Callback = callback; } }; -STDMETHODIMP CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */) +Z7_COM7F_IMF(CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */)) { if (Callback) { - UInt64 files = 0; - UInt64 value = Offset + *inSize; + const UInt64 files = 0; + const UInt64 value = Offset + *inSize; return Callback->SetCompleted(&files, &value); } return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN if (numItems == 0) @@ -334,12 +332,12 @@ if (numItems != (UInt32)(Int32)-1 && (numItems != 1 || indices[0] != 0)) return E_INVALIDARG; - extractCallback->SetTotal(_item.GetSize()); + RINOK(extractCallback->SetTotal(_item.GetSize())) CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(0, &realOutStream, askMode)) if (!testMode && !realOutStream) return S_OK; @@ -357,12 +355,12 @@ lps->InSize = _item.HeaderSize; lps->OutSize = outStreamSpec->GetSize(); - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CItem item = _item; item.MakeUncompressed(); if (_stream) - RINOK(_stream->Seek(_item.HeaderSize, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_stream, _item.HeaderSize)) NCompress::NZlib::CDecoder *_decoderZlibSpec = NULL; NCompress::NLzma::CDecoder *_decoderLzmaSpec = NULL; CMyComPtr _decoder; @@ -400,11 +398,11 @@ if (dicSize > (UInt32)unpackSize) { dicSize = (UInt32)unpackSize; - SetUi32(props + 1, dicSize); + SetUi32(props + 1, dicSize) } - RINOK(_decoderLzmaSpec->SetDecoderProperties2(props, 5)); + RINOK(_decoderLzmaSpec->SetDecoderProperties2(props, 5)) } - RINOK(item.WriteHeader(outStream)); + RINOK(item.WriteHeader(outStream)) HRESULT result = _decoder->Code(inStream2, outStream, NULL, &unpackSize, progress); Int32 opRes = NExtract::NOperationResult::kDataError; if (result == S_OK) @@ -433,18 +431,18 @@ } -#ifdef SWF_UPDATE +#ifdef Z7_SWF_UPDATE static HRESULT UpdateArchive(ISequentialOutStream *outStream, UInt64 size, bool lzmaMode, const CSingleMethodProps &props, IArchiveUpdateCallback *updateCallback) { UInt64 complexity = 0; - RINOK(updateCallback->SetTotal(size)); - RINOK(updateCallback->SetCompleted(&complexity)); + RINOK(updateCallback->SetTotal(size)) + RINOK(updateCallback->SetCompleted(&complexity)) CMyComPtr fileInStream; - RINOK(updateCallback->GetStream(0, &fileInStream)); + RINOK(updateCallback->GetStream(0, &fileInStream)) /* CDummyOutStream *outStreamSpec = new CDummyOutStream; @@ -455,10 +453,10 @@ */ CItem item; - HRESULT res = item.ReadHeader(fileInStream); + const HRESULT res = item.ReadHeader(fileInStream); if (res == S_FALSE) return E_INVALIDARG; - RINOK(res); + RINOK(res) if (!item.IsSwf() || !item.IsUncompressed() || size != item.GetSize()) return E_INVALIDARG; @@ -473,39 +471,39 @@ return E_NOTIMPL; encoderLzmaSpec = new NCompress::NLzma::CEncoder; encoder = encoderLzmaSpec; - RINOK(props.SetCoderProps(encoderLzmaSpec, &size)); + RINOK(props.SetCoderProps(encoderLzmaSpec, &size)) item.MakeLzma((UInt32)0xFFFFFFFF); CBufPtrSeqOutStream *propStreamSpec = new CBufPtrSeqOutStream; CMyComPtr propStream = propStreamSpec; propStreamSpec->Init(item.Buf + 12, 5); - RINOK(encoderLzmaSpec->WriteCoderProperties(propStream)); + RINOK(encoderLzmaSpec->WriteCoderProperties(propStream)) } else { encoderZlibSpec = new NCompress::NZlib::CEncoder; encoder = encoderZlibSpec; encoderZlibSpec->Create(); - RINOK(props.SetCoderProps(encoderZlibSpec->DeflateEncoderSpec, NULL)); + RINOK(props.SetCoderProps(encoderZlibSpec->DeflateEncoderSpec, NULL)) item.MakeZlib(); } - RINOK(item.WriteHeader(outStream)); + RINOK(item.WriteHeader(outStream)) CLocalProgress *lps = new CLocalProgress; CMyComPtr progress = lps; lps->Init(updateCallback, true); - RINOK(encoder->Code(fileInStream, outStream, NULL, NULL, progress)); + RINOK(encoder->Code(fileInStream, outStream, NULL, NULL, progress)) UInt64 inputProcessed; if (lzmaMode) { UInt64 curPos = 0; - RINOK(outSeekStream->Seek(0, STREAM_SEEK_CUR, &curPos)); - UInt64 packSize = curPos - kHeaderLzmaSize; + RINOK(outSeekStream->Seek(0, STREAM_SEEK_CUR, &curPos)) + const UInt64 packSize = curPos - kHeaderLzmaSize; if (packSize > (UInt32)0xFFFFFFFF) return E_INVALIDARG; item.MakeLzma((UInt32)packSize); - RINOK(outSeekStream->Seek(0, STREAM_SEEK_SET, NULL)); - item.WriteHeader(outStream); + RINOK(outSeekStream->Seek(0, STREAM_SEEK_SET, NULL)) + RINOK(item.WriteHeader(outStream)) inputProcessed = encoderLzmaSpec->GetInputProcessedSize(); } else @@ -517,14 +515,14 @@ return updateCallback->SetOperationResult(NUpdate::NOperationResult::kOK); } -STDMETHODIMP CHandler::GetFileTimeType(UInt32 *timeType) +Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *timeType)) { *timeType = NFileTimeType::kUnix; return S_OK; } -STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, - IArchiveUpdateCallback *updateCallback) +Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, + IArchiveUpdateCallback *updateCallback)) { if (numItems != 1) return E_INVALIDARG; @@ -533,13 +531,13 @@ UInt32 indexInArchive; if (!updateCallback) return E_FAIL; - RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProps, &indexInArchive)); + RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProps, &indexInArchive)) if (IntToBool(newProps)) { { NCOM::CPropVariant prop; - RINOK(updateCallback->GetProperty(0, kpidIsDir, &prop)); + RINOK(updateCallback->GetProperty(0, kpidIsDir, &prop)) if (prop.vt == VT_BOOL) { if (prop.boolVal != VARIANT_FALSE) @@ -555,7 +553,7 @@ UInt64 size; { NCOM::CPropVariant prop; - RINOK(updateCallback->GetProperty(0, kpidSize, &prop)); + RINOK(updateCallback->GetProperty(0, kpidSize, &prop)) if (prop.vt != VT_UI8) return E_INVALIDARG; size = prop.uhVal.QuadPart; @@ -571,17 +569,17 @@ if (_stream) { - RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(_stream)) } else _item.WriteHeader(outStream); return NCompress::CopyStream(_seqStream, outStream, NULL); } -STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) +Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps)) { _lzmaMode = false; - RINOK(_props.SetProperties(names, values, numProps)); + RINOK(_props.SetProperties(names, values, numProps)) const AString &m = _props.MethodName; if (m.IsEqualTo_Ascii_NoCase("lzma")) { @@ -621,22 +619,16 @@ CByteBuffer Buf; }; -class CHandler: - public IInArchive, - public IArchiveOpenSeq, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_CHandler_IInArchive_1( + IArchiveOpenSeq +) CObjectVector _tags; NSwfc::CItem _item; UInt64 _phySize; HRESULT OpenSeq3(ISequentialInStream *stream, IArchiveOpenCallback *callback); HRESULT OpenSeq2(ISequentialInStream *stream, IArchiveOpenCallback *callback); -public: - MY_UNKNOWN_IMP2(IInArchive, IArchiveOpenSeq) - INTERFACE_IInArchive(;) - - STDMETHOD(OpenSeq)(ISequentialInStream *stream); }; static const Byte kProps[] = @@ -649,7 +641,7 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps_NO_Table -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; switch (propID) @@ -662,7 +654,7 @@ } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _tags.Size(); return S_OK; @@ -764,7 +756,7 @@ , "DefineFont4" }; -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { NWindows::NCOM::CPropVariant prop; const CTag &tag = _tags[index]; @@ -791,7 +783,7 @@ return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback)) { return OpenSeq2(stream, callback); } @@ -867,7 +859,7 @@ RINOK(_item.ReadHeader(stream)) if (!_item.IsSwf() || !_item.IsUncompressed()) return S_FALSE; - UInt32 uncompressedSize = _item.GetSize(); + const UInt32 uncompressedSize = _item.GetSize(); if (uncompressedSize > kFileSizeMax) return S_FALSE; @@ -880,7 +872,7 @@ { CBitReader br; br.stream = &s; - unsigned numBits = br.ReadBits(5); + const unsigned numBits = br.ReadBits(5); /* UInt32 xMin = */ br.ReadBits(numBits); /* UInt32 xMax = */ br.ReadBits(numBits); /* UInt32 yMin = */ br.ReadBits(numBits); @@ -893,14 +885,14 @@ UInt64 offsetPrev = 0; for (;;) { - UInt32 pair = Read16(s); - UInt32 type = pair >> 6; + const UInt32 pair = Read16(s); + const UInt32 type = pair >> 6; UInt32 length = pair & 0x3F; if (length == 0x3F) length = Read32(s); if (type == 0) break; - UInt64 offset = s.GetProcessedSize() + NSwfc::kHeaderBaseSize + length; + const UInt64 offset = s.GetProcessedSize() + NSwfc::kHeaderBaseSize + length; if (offset > uncompressedSize || _tags.Size() >= kNumTagsMax) return S_FALSE; CTag &tag = _tags.AddNew(); @@ -910,8 +902,8 @@ return S_FALSE; if (callback && offset >= offsetPrev + (1 << 20)) { - UInt64 numItems = _tags.Size(); - RINOK(callback->SetCompleted(&numItems, &offset)); + const UInt64 numItems = _tags.Size(); + RINOK(callback->SetCompleted(&numItems, &offset)) offsetPrev = offset; } } @@ -932,22 +924,22 @@ return res; } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { return OpenSeq2(stream, NULL); } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _phySize = 0; return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _tags.Size(); if (numItems == 0) @@ -956,7 +948,7 @@ UInt32 i; for (i = 0; i < numItems; i++) totalSize += _tags[allFilesMode ? i : indices[i]].Buf.Size(); - extractCallback->SetTotal(totalSize); + RINOK(extractCallback->SetTotal(totalSize)) CLocalProgress *lps = new CLocalProgress; CMyComPtr progress = lps; @@ -967,24 +959,24 @@ for (i = 0; i < numItems; i++) { lps->InSize = lps->OutSize = totalSize; - RINOK(lps->SetCur()); - Int32 askMode = testMode ? + RINOK(lps->SetCur()) + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; const CByteBuffer &buf = _tags[index].Buf; totalSize += buf.Size(); CMyComPtr outStream; - RINOK(extractCallback->GetStream(index, &outStream, askMode)); + RINOK(extractCallback->GetStream(index, &outStream, askMode)) if (!testMode && !outStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) if (outStream) - RINOK(WriteStream(outStream, buf, buf.Size())); + RINOK(WriteStream(outStream, buf, buf.Size())) outStream.Release(); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) } return S_OK; COM_TRY_END @@ -993,7 +985,7 @@ static const Byte k_Signature[] = { 'F', 'W', 'S' }; REGISTER_ARC_I( - "SWF", "swf", 0, 0xD7, + "SWF", "swf", NULL, 0xD7, k_Signature, 0, NArcInfoFlags::kKeepName, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarHandler.cpp 2022-05-18 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarHandler.cpp 2023-03-27 09:00:00.000000000 +0000 @@ -67,7 +67,7 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; switch (propID) @@ -83,9 +83,9 @@ { case k_ErrorType_UnexpectedEnd: flags = kpv_ErrorFlags_UnexpectedEnd; break; case k_ErrorType_Corrupted: flags = kpv_ErrorFlags_HeadersError; break; - // case k_ErrorType_OK: break; + case k_ErrorType_OK: break; // case k_ErrorType_Warning: break; - default: break; + // default: break; } if (flags != 0) prop = flags; @@ -206,10 +206,9 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) { - UInt64 endPos = 0; + UInt64 endPos; { - RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos)); - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_AtBegin_GetSize(stream, endPos)) } _arc._phySize_Defined = true; @@ -224,7 +223,7 @@ for (;;) { _arc.NumFiles = _items.Size(); - RINOK(_arc.ReadItem(item)); + RINOK(_arc.ReadItem(item)) if (!_arc.filled) break; @@ -245,7 +244,7 @@ _items.Add(item); - RINOK(stream->Seek((Int64)item.Get_PackSize_Aligned(), STREAM_SEEK_CUR, &_arc._phySize)); + RINOK(stream->Seek((Int64)item.Get_PackSize_Aligned(), STREAM_SEEK_CUR, &_arc._phySize)) if (_arc._phySize > endPos) { _arc._error = k_ErrorType_UnexpectedEnd; @@ -290,10 +289,11 @@ _isArc = false; return S_FALSE; } - CMyComPtr openVolumeCallback; if (!callback) return S_FALSE; - callback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&openVolumeCallback); + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveOpenVolumeCallback, + openVolumeCallback, callback) if (!openVolumeCallback) return S_FALSE; NCOM::CPropVariant prop; @@ -310,20 +310,20 @@ return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *openArchiveCallback) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *openArchiveCallback)) { COM_TRY_BEGIN // for (int i = 0; i < 10; i++) // for debug { Close(); - RINOK(Open2(stream, openArchiveCallback)); + RINOK(Open2(stream, openArchiveCallback)) _stream = stream; } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { Close(); _seqStream = stream; @@ -331,7 +331,7 @@ return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; @@ -346,7 +346,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = (_stream ? _items.Size() : (UInt32)(Int32)-1); return S_OK; @@ -367,7 +367,7 @@ if (_latestIsRead) { const UInt64 packSize = _latestItem.Get_PackSize_Aligned(); - RINOK(copyCoderSpec->Code(_seqStream, NULL, &packSize, &packSize, NULL)); + RINOK(copyCoder->Code(_seqStream, NULL, &packSize, &packSize, NULL)) _arc._phySize += copyCoderSpec->TotalSize; if (copyCoderSpec->TotalSize != packSize) { @@ -381,7 +381,7 @@ { _arc.SeqStream = _seqStream; _arc.InStream = NULL; - RINOK(_arc.ReadItem(_latestItem)); + RINOK(_arc.ReadItem(_latestItem)) if (!_arc.filled) { _arc._phySize_Defined = true; @@ -407,6 +407,7 @@ } +// CPaxTime is defined (NumDigits >= 0) static void PaxTimeToProp(const CPaxTime &pt, NWindows::NCOM::CPropVariant &prop) { UInt64 v; @@ -418,7 +419,7 @@ ft.dwLowDateTime = (DWORD)v; ft.dwHighDateTime = (DWORD)(v >> 32); prop.SetAsTimeFrom_FT_Prec_Ns100(ft, - k_PropVar_TimePrec_Base + pt.NumDigits, pt.Ns % 100); + k_PropVar_TimePrec_Base + (unsigned)pt.NumDigits, pt.Ns % 100); } @@ -469,7 +470,7 @@ } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -483,7 +484,7 @@ return E_INVALIDARG; else { - RINOK(SkipTo(index)); + RINOK(SkipTo(index)) item = &_latestItem; } } @@ -665,8 +666,8 @@ } -HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN ISequentialInStream *stream = _seqStream; @@ -703,7 +704,7 @@ { lps->InSize = totalPackSize; lps->OutSize = totalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr realOutStream; Int32 askMode = testMode ? NExtract::NAskMode::kTest : @@ -715,20 +716,20 @@ HRESULT res = SkipTo(index); if (res == E_INVALIDARG) break; - RINOK(res); + RINOK(res) item = &_latestItem; } else item = &_items[index]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) const UInt64 unpackSize = item->Get_UnpackSize(); totalSize += unpackSize; totalPackSize += item->Get_PackSize_Aligned(); if (item->IsDir()) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } bool skipMode = false; @@ -741,8 +742,8 @@ if (item->IsHardLink() || item->IsSymLink()) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) } */ continue; @@ -750,7 +751,7 @@ skipMode = true; askMode = NExtract::NAskMode::kSkip; } - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) outStreamSpec->SetStream(realOutStream); realOutStream.Release(); @@ -770,16 +771,16 @@ { if (item->Is_SymLink()) { - RINOK(WriteStream(outStreamSpec, (const char *)item->LinkName, item->LinkName.Len())); + RINOK(WriteStream(outStreamSpec, (const char *)item->LinkName, item->LinkName.Len())) } else { if (!seqMode) { - RINOK(_stream->Seek((Int64)item->Get_DataPos(), STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_stream, item->Get_DataPos())) } streamSpec->Init(item->Get_PackSize_Aligned()); - RINOK(copyCoder->Code(inStream2, outStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStream2, outStream, NULL, NULL, progress)) } if (outStreamSpec->GetRem() != 0) opRes = NExtract::NOperationResult::kDataError; @@ -790,16 +791,16 @@ _curIndex++; } outStreamSpec->ReleaseStream(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } return S_OK; COM_TRY_END } -class CSparseStream: - public IInStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_IInStream( + CSparseStream +) UInt64 _phyPos; UInt64 _virtPos; bool _needStartSeek; @@ -810,10 +811,6 @@ unsigned ItemIndex; CRecordVector PhyOffsets; - MY_UNKNOWN_IMP2(ISequentialInStream, IInStream) - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); - void Init() { _virtPos = 0; @@ -823,7 +820,7 @@ }; -STDMETHODIMP CSparseStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CSparseStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -867,7 +864,7 @@ UInt64 phyPos = PhyOffsets[left] + relat; if (_needStartSeek || _phyPos != phyPos) { - RINOK(Handler->_stream->Seek((Int64)(item.Get_DataPos() + phyPos), STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(Handler->_stream, (item.Get_DataPos() + phyPos))) _needStartSeek = false; _phyPos = phyPos; } @@ -894,7 +891,7 @@ return res; } -STDMETHODIMP CSparseStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CSparseStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { @@ -911,7 +908,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN @@ -961,7 +958,7 @@ } -STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) +Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps)) { Init(); @@ -978,12 +975,12 @@ { // some clients write 'x' property. So we support it UInt32 level = 0; - RINOK(ParsePropToUInt32(name.Ptr(1), prop, level)); + RINOK(ParsePropToUInt32(name.Ptr(1), prop, level)) } else if (name.IsEqualTo("cp")) { UInt32 cp = CP_OEMCP; - RINOK(ParsePropToUInt32(L"", prop, cp)); + RINOK(ParsePropToUInt32(L"", prop, cp)) _forceCodePage = true; _curCodePage = _specifiedCodePage = cp; } @@ -1036,7 +1033,7 @@ } */ bool processed = false; - RINOK(_handlerTimeOptions.Parse(name, prop, processed)); + RINOK(_handlerTimeOptions.Parse(name, prop, processed)) if (processed) continue; return E_INVALIDARG; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarHandler.h 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarHandler.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarHandler.h 2022-03-22 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarHandler.h 2023-03-27 09:00:00.000000000 +0000 @@ -1,12 +1,10 @@ // TarHandler.h -#ifndef __TAR_HANDLER_H -#define __TAR_HANDLER_H +#ifndef ZIP7_INC_TAR_HANDLER_H +#define ZIP7_INC_TAR_HANDLER_H #include "../../../Common/MyCom.h" -#include "../../../Windows/PropVariant.h" - #include "../../Compress/CopyCoder.h" #include "../Common/HandlerOut.h" @@ -16,14 +14,12 @@ namespace NArchive { namespace NTar { -class CHandler: - public IInArchive, - public IArchiveOpenSeq, - public IInArchiveGetStream, - public ISetProperties, - public IOutArchive, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_4( + IArchiveOpenSeq + , IInArchiveGetStream + , ISetProperties + , IOutArchive +) public: CObjectVector _items; CMyComPtr _stream; @@ -53,20 +49,6 @@ HRESULT SkipTo(UInt32 index); void TarStringToUnicode(const AString &s, NWindows::NCOM::CPropVariant &prop, bool toOs = false) const; public: - MY_UNKNOWN_IMP5( - IInArchive, - IArchiveOpenSeq, - IInArchiveGetStream, - ISetProperties, - IOutArchive - ) - - INTERFACE_IInArchive(;) - INTERFACE_IOutArchive(;) - STDMETHOD(OpenSeq)(ISequentialInStream *stream); - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); - STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps); - void Init(); CHandler(); }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarHandlerOut.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarHandlerOut.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarHandlerOut.cpp 2022-03-27 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarHandlerOut.cpp 2023-03-15 20:00:00.000000000 +0000 @@ -20,7 +20,7 @@ namespace NArchive { namespace NTar { -STDMETHODIMP CHandler::GetFileTimeType(UInt32 *type) +Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *type)) { UInt32 t = NFileTimeType::kUnix; const UInt32 prec = _handlerTimeOptions.Prec; @@ -55,7 +55,7 @@ UINT codePage, unsigned utfFlags, bool convertSlash) { NCOM::CPropVariant prop; - RINOK(callback->GetProperty(index, propId, &prop)); + RINOK(callback->GetProperty(index, propId, &prop)) if (prop.vt == VT_BSTR) { @@ -94,7 +94,7 @@ { pt.Clear(); NCOM::CPropVariant prop; - RINOK(callback->GetProperty(i, pid, &prop)); + RINOK(callback->GetProperty(i, pid, &prop)) return Prop_To_PaxTime(prop, pt); } @@ -125,7 +125,7 @@ { defined = false; NWindows::NCOM::CPropVariant prop; - RINOK(callback->GetProperty(i, pid, &prop)); + RINOK(callback->GetProperty(i, pid, &prop)) if (prop.vt == VT_EMPTY) return S_OK; if (prop.vt == VT_UI4) @@ -147,7 +147,7 @@ bool isSet = false; { NWindows::NCOM::CPropVariant prop; - RINOK(callback->GetProperty(i, pidId, &prop)); + RINOK(callback->GetProperty(i, pidId, &prop)) if (prop.vt == VT_UI4) { isSet = true; @@ -160,7 +160,7 @@ } { NWindows::NCOM::CPropVariant prop; - RINOK(callback->GetProperty(i, pidName, &prop)); + RINOK(callback->GetProperty(i, pidName, &prop)) if (prop.vt == VT_BSTR) { const UString s = prop.bstrVal; @@ -181,8 +181,8 @@ -STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, - IArchiveUpdateCallback *callback) +Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, + IArchiveUpdateCallback *callback)) { COM_TRY_BEGIN @@ -196,8 +196,8 @@ /* // for debug only: unsigned utfFlags = 0; - utfFlags |= UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE; - utfFlags |= UTF_FLAG__TO_UTF8__SURROGATE_ERROR; + utfFlags |= Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE; + utfFlags |= Z7_UTF_FLAG_TO_UTF8_SURROGATE_ERROR; */ for (UInt32 i = 0; i < numItems; i++) @@ -210,7 +210,7 @@ if (!callback) return E_FAIL; - RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArc)); + RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArc)) ui.NewProps = IntToBool(newProps); ui.NewData = IntToBool(newData); @@ -221,7 +221,7 @@ { { NCOM::CPropVariant prop; - RINOK(callback->GetProperty(i, kpidIsDir, &prop)); + RINOK(callback->GetProperty(i, kpidIsDir, &prop)) if (prop.vt == VT_EMPTY) ui.IsDir = false; else if (prop.vt != VT_BOOL) @@ -232,7 +232,7 @@ { NCOM::CPropVariant prop; - RINOK(callback->GetProperty(i, kpidPosixAttrib, &prop)); + RINOK(callback->GetProperty(i, kpidPosixAttrib, &prop)) if (prop.vt == VT_EMPTY) ui.Mode = MY_LIN_S_IRWXO @@ -255,25 +255,25 @@ if (_handlerTimeOptions.Write_CTime.Val) RINOK(GetTime(i, kpidCTime, callback, ui.PaxTimes.CTime)) - RINOK(GetPropString(callback, i, kpidPath, ui.Name, codePage, utfFlags, true)); + RINOK(GetPropString(callback, i, kpidPath, ui.Name, codePage, utfFlags, true)) if (ui.IsDir && !ui.Name.IsEmpty() && ui.Name.Back() != '/') ui.Name += '/'; // ui.Name += '/'; // for debug if (_posixMode) { - RINOK(GetDevice(callback, i, kpidDeviceMajor, ui.DeviceMajor, ui.DeviceMajor_Defined)); - RINOK(GetDevice(callback, i, kpidDeviceMinor, ui.DeviceMinor, ui.DeviceMinor_Defined)); + RINOK(GetDevice(callback, i, kpidDeviceMajor, ui.DeviceMajor, ui.DeviceMajor_Defined)) + RINOK(GetDevice(callback, i, kpidDeviceMinor, ui.DeviceMinor, ui.DeviceMinor_Defined)) } - RINOK(GetUser(callback, i, kpidUser, kpidUserId, ui.User, ui.UID, codePage, utfFlags)); - RINOK(GetUser(callback, i, kpidGroup, kpidGroupId, ui.Group, ui.GID, codePage, utfFlags)); + RINOK(GetUser(callback, i, kpidUser, kpidUserId, ui.User, ui.UID, codePage, utfFlags)) + RINOK(GetUser(callback, i, kpidGroup, kpidGroupId, ui.Group, ui.GID, codePage, utfFlags)) } if (IntToBool(newData)) { NCOM::CPropVariant prop; - RINOK(callback->GetProperty(i, kpidSize, &prop)); + RINOK(callback->GetProperty(i, kpidSize, &prop)) if (prop.vt != VT_UI8) return E_INVALIDARG; ui.Size = prop.uhVal.QuadPart; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarHeader.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarHeader.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarHeader.cpp 2022-03-21 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarHeader.cpp 2022-12-20 16:00:00.000000000 +0000 @@ -20,7 +20,7 @@ // 7-Zip used kUsTar_00 before 21.07: const char k_Posix_ustar_00[8] = { 'u', 's', 't', 'a', 'r', 0, '0', '0' } ; // GNU TAR uses such header: - const char k_GNU_ustar__[8] = { 'u', 's', 't', 'a', 'r', ' ', ' ', 0 } ; + const char k_GNU_ustar[8] = { 'u', 's', 't', 'a', 'r', ' ', ' ', 0 } ; } /* diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarHeader.h 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarHeader.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarHeader.h 2022-03-21 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarHeader.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Archive/TarHeader.h -#ifndef __ARCHIVE_TAR_HEADER_H -#define __ARCHIVE_TAR_HEADER_H +#ifndef ZIP7_INC_ARCHIVE_TAR_HEADER_H +#define ZIP7_INC_ARCHIVE_TAR_HEADER_H #include "../../../Common/MyTypes.h" @@ -81,7 +81,7 @@ // extern const char * const kGNUTar; // = "GNUtar "; // 7 chars and a null // extern const char * const kEmpty; // = "\0\0\0\0\0\0\0\0" extern const char k_Posix_ustar_00[8]; - extern const char k_GNU_ustar__[8]; + extern const char k_GNU_ustar[8]; } } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarIn.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarIn.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarIn.cpp 2022-03-02 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarIn.cpp 2023-03-07 07:00:00.000000000 +0000 @@ -14,8 +14,8 @@ #define NUM_UNROLL_BYTES (8 * 4) -MY_NO_INLINE static bool IsBufNonZero(const void *data, size_t size); -MY_NO_INLINE static bool IsBufNonZero(const void *data, size_t size) +Z7_NO_INLINE static bool IsBufNonZero(const void *data, size_t size); +Z7_NO_INLINE static bool IsBufNonZero(const void *data, size_t size) { const Byte *p = (const Byte *)data; @@ -159,7 +159,7 @@ UInt32 mode; // we allow empty Mode value for LongName prefix items - CHECK(OctalToNumber32(p, mode, true)); p += 8; + CHECK(OctalToNumber32(p, mode, true)) p += 8; // if (!OctalToNumber32(p, item.UID)) item.UID = 0; p += 8; @@ -170,9 +170,9 @@ Int64 time; UInt32 checkSum; bool isBin; - CHECK(ParseSize(p, packSize, isBin)); p += 12; - CHECK(ParseInt64_MTime(p, time, isBin)); p += 12; - CHECK(OctalToNumber32(p, checkSum)); + CHECK(ParseSize(p, packSize, isBin)) p += 12; + CHECK(ParseInt64_MTime(p, time, isBin)) p += 12; + CHECK(OctalToNumber32(p, checkSum)) return k_IsArc_Res_YES; } @@ -188,7 +188,7 @@ for (;;) { size_t processedSize = NFileHeader::kRecordSize; - RINOK(ReadStream(SeqStream, buf, &processedSize)); + RINOK(ReadStream(SeqStream, buf, &processedSize)) if (processedSize == 0) { if (!thereAreEmptyRecords) @@ -220,7 +220,7 @@ thereAreEmptyRecords = true; if (OpenCallback) { - RINOK(Progress(item, 0)); + RINOK(Progress(item, 0)) } } if (thereAreEmptyRecords) @@ -243,19 +243,19 @@ */ // we allow empty Mode value for LongName prefix items - RIF(OctalToNumber32(p, item.Mode, true)); p += 8; + RIF(OctalToNumber32(p, item.Mode, true)) p += 8; if (!OctalToNumber32(p, item.UID)) { item.UID = 0; } p += 8; if (!OctalToNumber32(p, item.GID)) { item.GID = 0; } p += 8; - RIF(ParseSize(p, item.PackSize, item.PackSize_IsBin)); + RIF(ParseSize(p, item.PackSize, item.PackSize_IsBin)) item.Size = item.PackSize; item.Size_IsBin = item.PackSize_IsBin; p += 12; - RIF(ParseInt64_MTime(p, item.MTime, item.MTime_IsBin)); p += 12; + RIF(ParseInt64_MTime(p, item.MTime, item.MTime_IsBin)) p += 12; UInt32 checkSum; - RIF(OctalToNumber32(p, checkSum)); + RIF(OctalToNumber32(p, checkSum)) memset(p, ' ', 8); p += 8; item.LinkFlag = *p++; @@ -273,8 +273,8 @@ ReadString(p, NFileHeader::kUserNameSize, item.User); p += NFileHeader::kUserNameSize; ReadString(p, NFileHeader::kGroupNameSize, item.Group); p += NFileHeader::kGroupNameSize; - item.DeviceMajor_Defined = (p[0] != 0); if (item.DeviceMajor_Defined) { RIF(OctalToNumber32(p, item.DeviceMajor)); } p += 8; - item.DeviceMinor_Defined = (p[0] != 0); if (item.DeviceMinor_Defined) { RIF(OctalToNumber32(p, item.DeviceMinor)); } p += 8; + item.DeviceMajor_Defined = (p[0] != 0); if (item.DeviceMajor_Defined) { RIF(OctalToNumber32(p, item.DeviceMajor)) } p += 8; + item.DeviceMinor_Defined = (p[0] != 0); if (item.DeviceMinor_Defined) { RIF(OctalToNumber32(p, item.DeviceMinor)) } p += 8; if (p[0] != 0 && item.IsMagic_ustar_5chars() @@ -338,7 +338,7 @@ Byte isExtended = (Byte)buf[482]; if (isExtended != 0 && isExtended != 1) return S_OK; - RIF(ParseSize(buf + 483, item.Size, item.Size_IsBin)); + RIF(ParseSize(buf + 483, item.Size, item.Size_IsBin)) UInt64 min = 0; for (unsigned i = 0; i < 4; i++) { @@ -350,8 +350,8 @@ break; } CSparseBlock sb; - RIF(ParseSize(p, sb.Offset)); - RIF(ParseSize(p + 12, sb.Size)); + RIF(ParseSize(p, sb.Offset)) + RIF(ParseSize(p + 12, sb.Size)) item.SparseBlocks.Add(sb); if (sb.Offset < min || sb.Offset > item.Size) return S_OK; @@ -367,7 +367,7 @@ while (isExtended != 0) { size_t processedSize = NFileHeader::kRecordSize; - RINOK(ReadStream(SeqStream, buf, &processedSize)); + RINOK(ReadStream(SeqStream, buf, &processedSize)) if (processedSize != NFileHeader::kRecordSize) { error = k_ErrorType_UnexpectedEnd; @@ -378,7 +378,7 @@ if (OpenCallback) { - RINOK(Progress(item, 0)); + RINOK(Progress(item, 0)) } isExtended = (Byte)buf[21 * 24]; @@ -394,8 +394,8 @@ break; } CSparseBlock sb; - RIF(ParseSize(p, sb.Offset)); - RIF(ParseSize(p + 12, sb.Size)); + RIF(ParseSize(p, sb.Offset)) + RIF(ParseSize(p + 12, sb.Size)) item.SparseBlocks.Add(sb); if (sb.Offset < min || sb.Offset > item.Size) return S_OK; @@ -459,7 +459,7 @@ error = k_ErrorType_UnexpectedEnd; return res; } - RINOK(res); + RINOK(res) packSize -= size; @@ -492,7 +492,7 @@ if (InStream) { - RINOK(InStream->Seek((Int64)packSize, STREAM_SEEK_CUR, NULL)); + RINOK(InStream->Seek((Int64)packSize, STREAM_SEEK_CUR, NULL)) return S_OK; } const unsigned kBufSize = 1 << 15; @@ -502,7 +502,7 @@ { if (OpenCallback) { - RINOK(Progress(item, pos)); + RINOK(Progress(item, pos)) } unsigned size = kBufSize; @@ -590,8 +590,8 @@ if (sec >= ((UInt64)1 << 63)) return false; if (isNegative) - sec = -(Int64)sec; - pt.Sec = sec; + sec = (UInt64)-(Int64)sec; + pt.Sec = (Int64)sec; } if (*end == 0) { @@ -617,10 +617,10 @@ if (i < kNsDigits) { ns *= 10; - ns += c - '0'; + ns += (unsigned)(c - '0'); } } - pt.NumDigits = (i < kNsDigits ? i : kNsDigits); + pt.NumDigits = (int)(i < kNsDigits ? i : kNsDigits); while (i < kNsDigits) { ns *= 10; @@ -690,7 +690,7 @@ return false; name.SetFrom(s + offset, i - offset); - val.SetFrom(s + i + 1, size - 1 - (i + 1)); + val.SetFrom(s + i + 1, (unsigned)(size - 1 - (i + 1))); bool parsed = false; if (isFile) @@ -822,29 +822,34 @@ PaxBuf.Init(); PaxBuf_global.Init(); - for (unsigned recordIndex = 0;; recordIndex++) + UInt64 numExtraRecords = 0; + + for (;;) { if (OpenCallback) { - RINOK(Progress(item, 0)); + RINOK(Progress(item, 0)) } - RINOK(GetNextItemReal(item)); + RINOK(GetNextItemReal(item)) // NumRecords++; if (!filled) { if (error == k_ErrorType_OK) - if (item.LongName_WasUsed || - item.LongLink_WasUsed || - item.Num_Pax_Records != 0) + if (numExtraRecords != 0 + || item.LongName_WasUsed + || item.LongLink_WasUsed + || item.Num_Pax_Records != 0) error = k_ErrorType_Corrupted; + return S_OK; } - if (error != k_ErrorType_OK) return S_OK; - + + numExtraRecords++; + const char lf = item.LinkFlag; if (lf == NFileHeader::NLinkFlag::kGnu_LongName || lf == NFileHeader::NLinkFlag::kGnu_LongLink) @@ -874,7 +879,7 @@ */ const unsigned kLongNameSizeMax = (unsigned)1 << 14; - RINOK(ReadDataToBuffer(item, *tb, kLongNameSizeMax)); + RINOK(ReadDataToBuffer(item, *tb, kLongNameSizeMax)) if (error != k_ErrorType_OK) return S_OK; @@ -921,7 +926,7 @@ CTempBuffer *tb = (lf == NFileHeader::NLinkFlag::kGlobal ? &PaxBuf_global : &PaxBuf); - RINOK(ReadDataToBuffer(item, *tb, kParsingPaxSizeMax)); + RINOK(ReadDataToBuffer(item, *tb, kParsingPaxSizeMax)) if (error != k_ErrorType_OK) return S_OK; @@ -951,12 +956,19 @@ } else _is_PaxGlobal_Error = true; - if (isStartHeader) + + if (isStartHeader + && item.Num_Pax_Records == 1 + && numExtraRecords == 1) { // we skip global pax header info after parsing item.HeaderPos += item.HeaderSize; item.HeaderSize = 0; + item.Num_Pax_Records = 0; + numExtraRecords = 0; } + else + _is_PaxGlobal_Error = true; } continue; } @@ -1071,7 +1083,7 @@ if (error != k_ErrorType_OK) _error = error; - RINOK(res); + RINOK(res) if (filled) { diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarIn.h 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarIn.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarIn.h 2022-02-28 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarIn.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // TarIn.h -#ifndef __ARCHIVE_TAR_IN_H -#define __ARCHIVE_TAR_IN_H +#ifndef ZIP7_INC_ARCHIVE_TAR_IN_H +#define ZIP7_INC_ARCHIVE_TAR_IN_H #include "../IArchive.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarItem.h 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarItem.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarItem.h 2022-03-24 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarItem.h 2023-01-17 13:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // TarItem.h -#ifndef __ARCHIVE_TAR_ITEM_H -#define __ARCHIVE_TAR_ITEM_H +#ifndef ZIP7_INC_ARCHIVE_TAR_ITEM_H +#define ZIP7_INC_ARCHIVE_TAR_ITEM_H #include "../../../Common/MyLinux.h" #include "../../../Common/UTFConvert.h" @@ -143,7 +143,7 @@ { memcpy(Magic, posixMode ? NFileHeader::NMagic::k_Posix_ustar_00 : - NFileHeader::NMagic::k_GNU_ustar__, + NFileHeader::NMagic::k_GNU_ustar, 8); } @@ -172,7 +172,7 @@ void Set_LinkFlag_for_File(UInt32 mode) { - Byte lf = NFileHeader::NLinkFlag::kNormal; + char lf = NFileHeader::NLinkFlag::kNormal; if (MY_LIN_S_ISCHR(mode)) lf = NFileHeader::NLinkFlag::kCharacter; else if (MY_LIN_S_ISBLK(mode)) lf = NFileHeader::NLinkFlag::kBlock; else if (MY_LIN_S_ISFIFO(mode)) lf = NFileHeader::NLinkFlag::kFIFO; @@ -225,7 +225,7 @@ bool IsMagic_ustar_5chars() const { for (unsigned i = 0; i < 5; i++) - if (Magic[i] != NFileHeader::NMagic::k_GNU_ustar__[i]) + if (Magic[i] != NFileHeader::NMagic::k_GNU_ustar[i]) return false; return true; } @@ -241,7 +241,7 @@ bool IsMagic_GNU() const { for (unsigned i = 0; i < 8; i++) - if (Magic[i] != NFileHeader::NMagic::k_GNU_ustar__[i]) + if (Magic[i] != NFileHeader::NMagic::k_GNU_ustar[i]) return false; return true; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarOut.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarOut.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarOut.cpp 2022-03-30 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarOut.cpp 2023-03-27 08:00:00.000000000 +0000 @@ -60,7 +60,7 @@ } } -static void WriteOctal_12_Signed(char *s, Int64 val) +static void WriteOctal_12_Signed(char *s, const Int64 val) { if (val >= 0) { @@ -68,10 +68,10 @@ return; } s[0] = s[1] = s[2] = s[3] = (char)(Byte)0xFF; - WriteBin_64bit(s + 4, val); + WriteBin_64bit(s + 4, (UInt64)val); } -static void CopyString(char *dest, const AString &src, unsigned maxSize) +static void CopyString(char *dest, const AString &src, const unsigned maxSize) { unsigned len = src.Len(); if (len == 0) @@ -119,11 +119,11 @@ COPY_STRING_CHECK (cur, (!isPax && !Glob_Name.IsEmpty()) ? Glob_Name : item.Name, - kNameSize); + kNameSize) - WRITE_OCTAL_8_CHECK (cur, item.Mode); cur += 8; // & k_7_oct_digits_Val_Max - WRITE_OCTAL_8_CHECK (cur, item.UID); cur += 8; - WRITE_OCTAL_8_CHECK (cur, item.GID); cur += 8; + WRITE_OCTAL_8_CHECK (cur, item.Mode) cur += 8; // & k_7_oct_digits_Val_Max + WRITE_OCTAL_8_CHECK (cur, item.UID) cur += 8; + WRITE_OCTAL_8_CHECK (cur, item.GID) cur += 8; WriteOctal_12 (cur, /* zero_PackSize ? 0 : */ item.PackSize); cur += 12; WriteOctal_12_Signed (cur, /* zero_MTime ? 0 : */ item.MTime); cur += 12; @@ -135,13 +135,13 @@ *cur++ = item.LinkFlag; - COPY_STRING_CHECK (cur, item.LinkName, kNameSize); + COPY_STRING_CHECK (cur, item.LinkName, kNameSize) memcpy(cur, item.Magic, 8); cur += 8; - COPY_STRING_CHECK (cur, item.User, kUserNameSize); - COPY_STRING_CHECK (cur, item.Group, kGroupNameSize); + COPY_STRING_CHECK (cur, item.User, kUserNameSize) + COPY_STRING_CHECK (cur, item.Group, kGroupNameSize) const bool needDevice = (IsPosixMode && !isPax); @@ -159,7 +159,7 @@ if (!isPax && !Prefix.IsEmpty()) { - COPY_STRING_CHECK (cur, Prefix, kPrefixSize); + COPY_STRING_CHECK (cur, Prefix, kPrefixSize) } if (item.Is_Sparse()) @@ -194,7 +194,7 @@ record[148 + 7] = ' '; // we need it, if we use binary init } - RINOK(Write_Data(record, kRecordSize)); + RINOK(Write_Data(record, kRecordSize)) if (item.Is_Sparse()) { @@ -209,7 +209,7 @@ WriteOctal_12(p + 12, sb.Size); } record[21 * 24] = (char)(i < item.SparseBlocks.Size() ? 1 : 0); - RINOK(Write_Data(record, kRecordSize)); + RINOK(Write_Data(record, kRecordSize)) } } @@ -237,11 +237,11 @@ s.Add_LF(); } - +// pt is defined : (pt.NumDigits >= 0) static void AddPaxTime(AString &s, const char *name, const CPaxTime &pt, const CTimeOptions &options) { - unsigned numDigits = pt.NumDigits; + unsigned numDigits = (unsigned)pt.NumDigits; if (numDigits > options.NumDigitsMax) numDigits = options.NumDigitsMax; @@ -265,14 +265,14 @@ if (pt.Sec < 0) { sec = -sec; - v += '-'; + v.Add_Minus(); if (ns != 0) { ns = 1000*1000*1000 - ns; sec--; } } - v.Add_UInt64(sec); + v.Add_UInt64((UInt64)sec); } if (needNs) @@ -291,7 +291,7 @@ if (!d.IsEmpty()) { - v += '.'; + v.Add_Dot(); v += d; // v += "1234567009999"; // for debug // for (int y = 0; y < 1000; y++) v += '8'; // for debug @@ -467,8 +467,8 @@ // mi.LinkFlag = 'Z'; // for debug mi.PackSize = paxSize; // for (unsigned y = 0; y < 1; y++) { // for debug - RINOK(WriteHeaderReal(mi, true)); // isPax - RINOK(Write_Data_And_Residual(s, paxSize)); + RINOK(WriteHeaderReal(mi, true)) // isPax + RINOK(Write_Data_And_Residual(s, paxSize)) // } // for debug /* we can send (zero_MTime) for compatibility with gnu tar output. @@ -538,8 +538,8 @@ const unsigned nameStreamSize = name->Len() + 1; mi.PackSize = nameStreamSize; // for (unsigned y = 0; y < 3; y++) { // for debug - RINOK(WriteHeaderReal(mi)); - RINOK(Write_Data_And_Residual(name->Ptr(), nameStreamSize)); + RINOK(WriteHeaderReal(mi)) + RINOK(Write_Data_And_Residual(name->Ptr(), nameStreamSize)) // } // for debug @@ -615,7 +615,7 @@ HRESULT COutArchive::Write_Data_And_Residual(const void *data, unsigned size) { - RINOK(Write_Data(data, size)); + RINOK(Write_Data(data, size)) return Write_AfterDataResidual(size); } @@ -636,7 +636,7 @@ for (unsigned i = 0; i < kNumFinishRecords; i++) { - RINOK(Write_Data(record, kRecordSize)); + RINOK(Write_Data(record, kRecordSize)) } return S_OK; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarOut.h 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarOut.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarOut.h 2022-02-22 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarOut.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Archive/TarOut.h -#ifndef __ARCHIVE_TAR_OUT_H -#define __ARCHIVE_TAR_OUT_H +#ifndef ZIP7_INC_ARCHIVE_TAR_OUT_H +#define ZIP7_INC_ARCHIVE_TAR_OUT_H #include "../../../Common/MyCom.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarRegister.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarRegister.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarRegister.cpp 2022-05-04 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarRegister.cpp 2022-12-20 16:00:00.000000000 +0000 @@ -12,7 +12,7 @@ static const Byte k_Signature[] = { 'u', 's', 't', 'a', 'r' }; REGISTER_ARC_IO( - "tar", "tar ova", 0, 0xEE, + "tar", "tar ova", NULL, 0xEE, k_Signature, NFileHeader::kUstarMagic_Offset, NArcInfoFlags::kStartOpen diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarUpdate.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarUpdate.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarUpdate.cpp 2022-03-28 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarUpdate.cpp 2023-03-27 08:00:00.000000000 +0000 @@ -8,6 +8,7 @@ #include "../../Common/LimitedStreams.h" #include "../../Common/ProgressUtils.h" +#include "../../Common/StreamUtils.h" #include "../../Compress/CopyCoder.h" @@ -44,7 +45,7 @@ const unsigned prec = prop.wReserved1; if (prec >= k_PropVar_TimePrec_Base) { - pt.NumDigits = prec - k_PropVar_TimePrec_Base; + pt.NumDigits = (int)(prec - k_PropVar_TimePrec_Base); if (prop.wReserved2 < 100) ns += prop.wReserved2; } @@ -58,7 +59,7 @@ { pt.Clear(); NWindows::NCOM::CPropVariant prop; - RINOK(getProp->GetProperty(pid, &prop)); + RINOK(getProp->GetProperty(pid, &prop)) return Prop_To_PaxTime(prop, pt); } @@ -73,7 +74,7 @@ bool isSet = false; { NWindows::NCOM::CPropVariant prop; - RINOK(getProp->GetProperty(pidId, &prop)); + RINOK(getProp->GetProperty(pidId, &prop)) if (prop.vt == VT_UI4) { isSet = true; @@ -85,7 +86,7 @@ } { NWindows::NCOM::CPropVariant prop; - RINOK(getProp->GetProperty(pidName, &prop)); + RINOK(getProp->GetProperty(pidName, &prop)) if (prop.vt == VT_BSTR) { const UString s = prop.bstrVal; @@ -133,7 +134,7 @@ { defined = false; NWindows::NCOM::CPropVariant prop; - RINOK(getProp->GetProperty(pid, &prop)); + RINOK(getProp->GetProperty(pid, &prop)) if (prop.vt == VT_EMPTY) return S_OK; if (prop.vt == VT_UI4) @@ -158,8 +159,10 @@ outArchive.IsPosixMode = options.PosixMode; outArchive.TimeOptions = options.TimeOptions; - CMyComPtr outSeekStream; - outStream->QueryInterface(IID_IOutStream, (void **)&outSeekStream); + Z7_DECL_CMyComPtr_QI_FROM(IOutStream, outSeekStream, outStream) + Z7_DECL_CMyComPtr_QI_FROM(IStreamSetRestriction, setRestriction, outStream) + Z7_DECL_CMyComPtr_QI_FROM(IArchiveUpdateCallbackFile, opCallback, outStream) + if (outSeekStream) { /* @@ -169,12 +172,10 @@ RINOK(outStream->Write(buf, sizeof(buf), NULL)); */ // we need real outArchive.Pos, if outSeekStream->SetSize() will be used. - RINOK(outSeekStream->Seek(0, STREAM_SEEK_CUR, &outArchive.Pos)); + RINOK(outSeekStream->Seek(0, STREAM_SEEK_CUR, &outArchive.Pos)) } - - - CMyComPtr opCallback; - updateCallback->QueryInterface(IID_IArchiveUpdateCallbackFile, (void **)&opCallback); + if (setRestriction) + RINOK(setRestriction->SetRestriction(0, 0)) UInt64 complexity = 0; @@ -188,7 +189,7 @@ complexity += inputItems[(unsigned)ui.IndexInArc].Get_FullSize_Aligned(); } - RINOK(updateCallback->SetTotal(complexity)); + RINOK(updateCallback->SetTotal(complexity)) NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder; CMyComPtr copyCoder = copyCoderSpec; @@ -198,7 +199,7 @@ lps->Init(updateCallback, true); CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; - CMyComPtr inStreamLimited(streamSpec); + CMyComPtr inStreamLimited(streamSpec); streamSpec->SetStream(inStream); complexity = 0; @@ -208,10 +209,14 @@ for (i = 0;; i++) { lps->InSize = lps->OutSize = complexity; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) if (i == updateItems.Size()) + { + if (outSeekStream && setRestriction) + RINOK(setRestriction->SetRestriction(0, 0)) return outArchive.WriteFinishHeader(); + } const CUpdateItem &ui = updateItems[i]; CItem item; @@ -253,7 +258,7 @@ if (ui.NewData || ui.NewProps) { RINOK(GetPropString(updateCallback, ui.IndexInClient, kpidSymLink, symLink, - options.CodePage, options.UtfFlags, true)); + options.CodePage, options.UtfFlags, true)) if (!symLink.IsEmpty()) { item.LinkFlag = NFileHeader::NLinkFlag::kSymLink; @@ -286,7 +291,7 @@ needWrite = false; else { - RINOK(res); + RINOK(res) if (!fileInStream) { @@ -295,9 +300,7 @@ } else { - CMyComPtr getProps; - CMyComPtr getProp; - fileInStream->QueryInterface(IID_IStreamGetProp, (void **)&getProp); + Z7_DECL_CMyComPtr_QI_FROM(IStreamGetProp, getProp, fileInStream) if (getProp) { if (options.Write_MTime.Val) RINOK(GetTime(getProp, kpidMTime, item.PaxTimes.MTime)) @@ -312,23 +315,23 @@ */ bool defined = false; UInt32 val = 0; - RINOK(GetDevice(getProp, kpidDeviceMajor, val, defined)); + RINOK(GetDevice(getProp, kpidDeviceMajor, val, defined)) if (defined) { item.DeviceMajor = val; item.DeviceMajor_Defined = true; item.DeviceMinor = 0; item.DeviceMinor_Defined = false; - RINOK(GetDevice(getProp, kpidDeviceMinor, item.DeviceMinor, item.DeviceMinor_Defined)); + RINOK(GetDevice(getProp, kpidDeviceMinor, item.DeviceMinor, item.DeviceMinor_Defined)) } } - RINOK(GetUser(getProp, kpidUser, kpidUserId, item.User, item.UID, options.CodePage, options.UtfFlags)); - RINOK(GetUser(getProp, kpidGroup, kpidGroupId, item.Group, item.GID, options.CodePage, options.UtfFlags)); + RINOK(GetUser(getProp, kpidUser, kpidUserId, item.User, item.UID, options.CodePage, options.UtfFlags)) + RINOK(GetUser(getProp, kpidGroup, kpidGroupId, item.Group, item.GID, options.CodePage, options.UtfFlags)) { NWindows::NCOM::CPropVariant prop; - RINOK(getProp->GetProperty(kpidPosixAttrib, &prop)); + RINOK(getProp->GetProperty(kpidPosixAttrib, &prop)) if (prop.vt == VT_EMPTY) item.Mode = MY_LIN_S_IRWXO @@ -346,7 +349,7 @@ { NWindows::NCOM::CPropVariant prop; - RINOK(getProp->GetProperty(kpidSize, &prop)); + RINOK(getProp->GetProperty(kpidSize, &prop)) if (prop.vt != VT_UI8) return E_INVALIDARG; const UInt64 size = prop.uhVal.QuadPart; @@ -361,7 +364,7 @@ } else { - fileInStream->QueryInterface(IID_IStreamGetProps, (void **)&getProps); + Z7_DECL_CMyComPtr_QI_FROM(IStreamGetProps, getProps, fileInStream) if (getProps) { FILETIME mTime, aTime, cTime; @@ -386,7 +389,7 @@ // we must request kpidHardLink after updateCallback->GetStream() AString hardLink; RINOK(GetPropString(updateCallback, ui.IndexInClient, kpidHardLink, hardLink, - options.CodePage, options.UtfFlags, true)); + options.CodePage, options.UtfFlags, true)) if (!hardLink.IsEmpty()) { item.LinkFlag = NFileHeader::NLinkFlag::kHardLink; @@ -408,7 +411,11 @@ { const UInt64 headerPos = outArchive.Pos; // item.PackSize = ((UInt64)1 << 33); // for debug - RINOK(outArchive.WriteHeader(item)); + + if (outSeekStream && setRestriction) + RINOK(setRestriction->SetRestriction(outArchive.Pos, (UInt64)(Int64)-1)) + + RINOK(outArchive.WriteHeader(item)) if (fileInStream) { for (unsigned numPasses = 0;; numPasses++) @@ -424,9 +431,9 @@ } const UInt64 dataPos = outArchive.Pos; - RINOK(copyCoder->Code(fileInStream, outStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(fileInStream, outStream, NULL, NULL, progress)) outArchive.Pos += copyCoderSpec->TotalSize; - RINOK(outArchive.Write_AfterDataResidual(copyCoderSpec->TotalSize)); + RINOK(outArchive.Write_AfterDataResidual(copyCoderSpec->TotalSize)) // if (numPasses >= 10) // for debug if (copyCoderSpec->TotalSize == item.PackSize) @@ -442,11 +449,11 @@ if (!outSeekStream) return E_FAIL; const UInt64 nextPos = outArchive.Pos; - RINOK(outSeekStream->Seek(-(Int64)(nextPos - headerPos), STREAM_SEEK_CUR, NULL)); + RINOK(outSeekStream->Seek(-(Int64)(nextPos - headerPos), STREAM_SEEK_CUR, NULL)) outArchive.Pos = headerPos; item.PackSize = copyCoderSpec->TotalSize; - RINOK(outArchive.WriteHeader(item)); + RINOK(outArchive.WriteHeader(item)) // if (numPasses >= 10) // for debug if (outArchive.Pos == dataPos) @@ -454,7 +461,7 @@ const UInt64 alignedSize = nextPos - dataPos; if (alignedSize != 0) { - RINOK(outSeekStream->Seek(alignedSize, STREAM_SEEK_CUR, NULL)); + RINOK(outSeekStream->Seek((Int64)alignedSize, STREAM_SEEK_CUR, NULL)) outArchive.Pos += alignedSize; } break; @@ -462,12 +469,11 @@ // size of header was changed. // we remove data after header and try new attempt, if required - CMyComPtr fileSeekStream; - fileInStream->QueryInterface(IID_IInStream, (void **)&fileSeekStream); + Z7_DECL_CMyComPtr_QI_FROM(IInStream, fileSeekStream, fileInStream) if (!fileSeekStream) return E_FAIL; - RINOK(fileSeekStream->Seek(0, STREAM_SEEK_SET, NULL)); - RINOK(outSeekStream->SetSize(outArchive.Pos)); + RINOK(InStream_SeekToBegin(fileSeekStream)) + RINOK(outSeekStream->SetSize(outArchive.Pos)) if (item.PackSize == 0) break; } @@ -476,7 +482,7 @@ complexity += item.PackSize; fileInStream.Release(); - RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); + RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)) } else { @@ -518,7 +524,7 @@ item.UID = existItem.UID; item.GID = existItem.GID; - RINOK(outArchive.WriteHeader(item)); + RINOK(outArchive.WriteHeader(item)) size = existItem.Get_PackSize_Aligned(); pos = existItem.Get_DataPos(); } @@ -530,10 +536,12 @@ if (size != 0) { - RINOK(inStream->Seek((Int64)pos, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(inStream, pos)) streamSpec->Init(size); + if (outSeekStream && setRestriction) + RINOK(setRestriction->SetRestriction(0, 0)) // 22.00 : we copy Residual data from old archive to new archive instead of zeroing - RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress)) if (copyCoderSpec->TotalSize != size) return E_FAIL; outArchive.Pos += size; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarUpdate.h 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarUpdate.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Tar/TarUpdate.h 2022-03-24 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Tar/TarUpdate.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // TarUpdate.h -#ifndef __TAR_UPDATE_H -#define __TAR_UPDATE_H +#ifndef ZIP7_INC_TAR_UPDATE_H +#define ZIP7_INC_TAR_UPDATE_H #include "../IArchive.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Udf/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Archive/Udf/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Udf/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Udf/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Udf/UdfHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Udf/UdfHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Udf/UdfHandler.cpp 2022-06-29 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Udf/UdfHandler.cpp 2023-03-26 12:00:00.000000000 +0000 @@ -26,7 +26,7 @@ if (!NWindows::NTime::GetSecondsSince1601(t.GetYear(), d[4], d[5], d[6], d[7], d[8], numSecs)) return; if (t.IsLocal()) - numSecs -= (Int64)((Int32)t.GetMinutesOffset() * 60); + numSecs = (UInt64)((Int64)numSecs - (Int64)((Int32)t.GetMinutesOffset() * 60)); const UInt32 m0 = d[9]; const UInt32 m1 = d[10]; const UInt32 m2 = d[11]; @@ -69,7 +69,7 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -144,15 +144,15 @@ COM_TRY_END } -class CProgressImp: public CProgressVirt +class CProgressImp Z7_final: public CProgressVirt { CMyComPtr _callback; UInt64 _numFiles; UInt64 _numBytes; public: - HRESULT SetTotal(UInt64 numBytes); - HRESULT SetCompleted(UInt64 numFiles, UInt64 numBytes); - HRESULT SetCompleted(); + HRESULT SetTotal(UInt64 numBytes) Z7_override; + HRESULT SetCompleted(UInt64 numFiles, UInt64 numBytes) Z7_override; + HRESULT SetCompleted() Z7_override; CProgressImp(IArchiveOpenCallback *callback): _callback(callback), _numFiles(0), _numBytes(0) {} }; @@ -177,13 +177,13 @@ return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback)) { COM_TRY_BEGIN { Close(); CProgressImp progressImp(callback); - RINOK(_archive.Open(stream, &progressImp)); + RINOK(_archive.Open(stream, &progressImp)) bool showVolName = (_archive.LogVols.Size() > 1); FOR_VECTOR (volIndex, _archive.LogVols) { @@ -209,7 +209,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _inStream.Release(); _archive.Clear(); @@ -217,13 +217,13 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _refs2.Size(); return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -258,9 +258,9 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { - *stream = 0; + *stream = NULL; const CRef2 &ref2 = _refs2[index]; const CLogVol &vol = _archive.LogVols[ref2.Vol]; @@ -318,11 +318,11 @@ return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _refs2.Size(); if (numItems == 0) @@ -357,14 +357,14 @@ for (i = 0; i < numItems; i++) { lps->InSize = lps->OutSize = currentTotalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) const CRef2 &ref2 = _refs2[index]; const CRef &ref = _archive.LogVols[ref2.Vol].FileSets[ref2.Fs].Refs[ref2.Ref]; @@ -373,8 +373,8 @@ if (item.IsDir()) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } currentTotalSize += item.Size; @@ -382,7 +382,7 @@ if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) outStreamSpec->SetStream(realOutStream); realOutStream.Release(); outStreamSpec->Init(item.Size); @@ -395,13 +395,13 @@ opRes = NExtract::NOperationResult::kDataError; else { - RINOK(copyCoder->Code(udfInStream, outStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(udfInStream, outStream, NULL, NULL, progress)) opRes = outStreamSpec->IsFinishedOK() ? NExtract::NOperationResult::kOK: NExtract::NOperationResult::kDataError; } outStreamSpec->ReleaseStream(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } return S_OK; COM_TRY_END @@ -410,12 +410,18 @@ static const UInt32 kIsoStartPos = 0x8000; // 5, { 0, 'N', 'S', 'R', '0' }, -static const Byte k_Signature[] = { 1, 'C', 'D', '0', '0', '1' }; + +static const Byte k_Signature[] = +{ + 8, 0, 'B', 'E', 'A', '0', '1', 1, 0, + 6, 1, 'C', 'D', '0', '0', '1' +}; REGISTER_ARC_I( - "Udf", "udf iso img", 0, 0xE0, + "Udf", "udf iso img", NULL, 0xE0, k_Signature, kIsoStartPos, + NArcInfoFlags::kMultiSignature | NArcInfoFlags::kStartOpen, IsArc_Udf) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Udf/UdfHandler.h 7zip-23.01+dfsg/CPP/7zip/Archive/Udf/UdfHandler.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Udf/UdfHandler.h 2022-06-28 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Udf/UdfHandler.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // UdfHandler.h -#ifndef __UDF_HANDLER_H -#define __UDF_HANDLER_H +#ifndef ZIP7_INC_UDF_HANDLER_H +#define ZIP7_INC_UDF_HANDLER_H #include "../../../Common/MyCom.h" @@ -19,18 +19,12 @@ unsigned Ref; }; -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_1( + IInArchiveGetStream +) CRecordVector _refs2; CMyComPtr _inStream; CInArchive _archive; -public: - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Udf/UdfIn.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Udf/UdfIn.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Udf/UdfIn.cpp 2022-06-29 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Udf/UdfIn.cpp 2023-03-27 09:00:00.000000000 +0000 @@ -27,9 +27,9 @@ #define Get32(p) GetUi32(p) #define Get64(p) GetUi64(p) -#define G16(_offs_, dest) dest = Get16(p + (_offs_)); -#define G32(_offs_, dest) dest = Get32(p + (_offs_)); -#define G64(_offs_, dest) dest = Get64(p + (_offs_)); +#define G16(_offs_, dest) dest = Get16(p + (_offs_)) +#define G32(_offs_, dest) dest = Get32(p + (_offs_)) +#define G64(_offs_, dest) dest = Get64(p + (_offs_)) namespace NArchive { namespace NUdf { @@ -50,7 +50,7 @@ #define kCrc16Poly 0x1021 static UInt16 g_Crc16Table[256]; -static void MY_FAST_CALL Crc16GenerateTable(void) +static void Z7_FASTCALL Crc16GenerateTable(void) { UInt32 i; for (i = 0; i < 256; i++) @@ -62,7 +62,7 @@ } } -static UInt32 MY_FAST_CALL Crc16Calc(const void *data, size_t size) +static UInt32 Z7_FASTCALL Crc16Calc(const void *data, size_t size) { UInt32 v = CRC16_INIT_VAL; const Byte *p = (const Byte *)data; @@ -176,7 +176,7 @@ char temp[16]; ConvertUInt32ToHex(major, temp); s += temp; - s += '.'; + s.Add_Dot(); ConvertUInt32ToHex8Digits(minor, temp); s += &temp[8 - 2]; } @@ -346,7 +346,7 @@ const CLogVol &vol = LogVols[volIndex]; const CPartition &partition = Partitions[vol.PartitionMaps[partitionRef].PartitionIndex]; UInt64 offset = ((UInt64)partition.Pos << SecLogSize) + (UInt64)blockPos * vol.BlockSize; - RINOK(_stream->Seek(offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_stream, offset)) offset += len; UpdatePhySize(offset); const HRESULT res = ReadStream_FALSE(_stream, buf, len); @@ -375,7 +375,7 @@ { const CMyExtent &e = item.Extents[i]; const UInt32 len = e.GetLen(); - RINOK(Read(volIndex, e.PartitionRef, e.Pos, len, (Byte *)buf + pos)); + RINOK(Read(volIndex, e.PartitionRef, e.Pos, len, (Byte *)buf + pos)) pos += len; } return S_OK; @@ -447,6 +447,19 @@ // ECMA 4/14.4 +// UDF 2.3.4 + +/* +File Characteristics: +Deleted bit: + ECMA: If set to ONE, shall mean this File Identifier Descriptor + identifies a file that has been deleted; + UDF: If the space for the file or directory is deallocated, + the implementation shall set the ICB field to zero. + ECMA 167 4/8.6 requires that the File Identifiers of all FIDs in a directory shall be unique. + The implementations shall follow these rules when a Deleted bit is set: + rewrire the compression ID of the File Identifier: 8 -> 254, 16 -> 255. +*/ struct CFileId { @@ -456,7 +469,10 @@ CDString Id; CLongAllocDesc Icb; - bool IsItLinkParent() const { return (FileCharacteristics & FILEID_CHARACS_Parent) != 0; } + bool IsItLink_Dir () const { return (FileCharacteristics & FILEID_CHARACS_Dir) != 0; } + bool IsItLink_Deleted() const { return (FileCharacteristics & FILEID_CHARACS_Deleted) != 0; } + bool IsItLink_Parent () const { return (FileCharacteristics & FILEID_CHARACS_Parent) != 0; } + size_t Parse(const Byte *p, size_t size); }; @@ -466,10 +482,13 @@ if (size < 38) return 0; CTag tag; - RINOK(tag.Parse(p, size)); + if (tag.Parse(p, size) != S_OK) + return 0; if (tag.Id != DESC_TYPE_FileId) return 0; // FileVersion = Get16(p + 16); + // UDF: There shall be only one version of a file as specified below with the value being set to 1. + FileCharacteristics = p[18]; const unsigned idLen = p[19]; Icb.Parse(p + 20); @@ -490,10 +509,10 @@ -HRESULT CInArchive::ReadFileItem(unsigned volIndex, unsigned fsIndex, const CLongAllocDesc &lad, int numRecurseAllowed) +HRESULT CInArchive::ReadFileItem(unsigned volIndex, unsigned fsIndex, const CLongAllocDesc &lad, bool isDir, int numRecurseAllowed) { if (Files.Size() % 100 == 0) - RINOK(_progress->SetCompleted(Files.Size(), _processedProgressBytes)); + RINOK(_progress->SetCompleted(Files.Size(), _processedProgressBytes)) if (numRecurseAllowed-- == 0) return S_FALSE; CFile &file = Files.Back(); @@ -510,15 +529,15 @@ { if (value == kRecursedErrorValue) return S_FALSE; - file.ItemIndex = value; + file.ItemIndex = (int)(Int32)value; } else { value = Items.Size(); - file.ItemIndex = (int)value; + file.ItemIndex = (int)(Int32)value; if (partition.Map.Set(key, kRecursedErrorValue)) return S_FALSE; - RINOK(ReadItem(volIndex, fsIndex, lad, numRecurseAllowed)); + RINOK(ReadItem(volIndex, (int)fsIndex, lad, isDir, numRecurseAllowed)) if (!partition.Map.Set(key, value)) return S_FALSE; } @@ -528,7 +547,7 @@ // (fsIndex = -1) means that it's metadata file -HRESULT CInArchive::ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDesc &lad, int numRecurseAllowed) +HRESULT CInArchive::ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDesc &lad, bool isDir, int numRecurseAllowed) { if (Items.Size() >= kNumItemsMax) return S_FALSE; @@ -541,11 +560,11 @@ return S_FALSE; CByteBuffer buf(size); - RINOK(ReadLad(volIndex, lad, buf)); + RINOK(ReadLad(volIndex, lad, buf)) CTag tag; const Byte *p = buf; - RINOK(tag.Parse(p, size)); + RINOK(tag.Parse(p, size)) item.IsExtended = (tag.Id == DESC_TYPE_ExtendedFile); const size_t kExtendOffset = item.IsExtended ? 40 : 0; @@ -638,6 +657,9 @@ } } + if (isDir != item.IcbTag.IsDir()) + return S_FALSE; + if (item.IcbTag.IsDir()) { if (fsIndex < 0) @@ -646,7 +668,7 @@ if (!item.CheckChunkSizes() || !CheckItemExtents(volIndex, item)) return S_FALSE; CByteBuffer buf2; - RINOK(ReadFromFile(volIndex, item, buf2)); + RINOK(ReadFromFile(volIndex, item, buf2)) item.Size = 0; item.Extents.ClearAndFree(); item.InlineData.Free(); @@ -663,7 +685,10 @@ p2 += cur; size2 -= cur; } - if (!fileId.IsItLinkParent()) + if (fileId.IsItLink_Parent()) + continue; + if (fileId.IsItLink_Deleted()) + continue; { CFile file; // file.FileVersion = fileId.FileVersion; @@ -679,7 +704,8 @@ if (Files.Size() >= kNumFilesMax) return S_FALSE; Files.Add(file); - RINOK(ReadFileItem(volIndex, fsIndex, fileId.Icb, numRecurseAllowed)); + RINOK(ReadFileItem(volIndex, (unsigned)fsIndex, fileId.Icb, + fileId.IsItLink_Dir(), numRecurseAllowed)) } } } @@ -702,7 +728,7 @@ { if ((_numRefs & 0xFFF) == 0) { - RINOK(_progress->SetCompleted()); + RINOK(_progress->SetCompleted()) } if (numRecurseAllowed-- == 0) return S_FALSE; @@ -712,12 +738,12 @@ CRef ref; ref.FileIndex = fileIndex; ref.Parent = parent; - parent = fs.Refs.Size(); + parent = (int)fs.Refs.Size(); fs.Refs.Add(ref); const CItem &item = Items[Files[fileIndex].ItemIndex]; FOR_VECTOR (i, item.SubFiles) { - RINOK(FillRefs(fs, item.SubFiles[i], parent, numRecurseAllowed)); + RINOK(FillRefs(fs, item.SubFiles[i], parent, numRecurseAllowed)) } return S_OK; } @@ -727,9 +753,9 @@ { UInt32 res = k_IsArc_Res_NO; unsigned SecLogSize; - for (SecLogSize = 11;; SecLogSize -= 3) + for (SecLogSize = 11;; SecLogSize -= 2) { - if (SecLogSize < 8) + if (SecLogSize < 9) return res; const UInt32 offset = (UInt32)256 << SecLogSize; const UInt32 bufSize = (UInt32)1 << SecLogSize; @@ -754,7 +780,7 @@ { Clear(); UInt64 fileSize; - RINOK(_stream->Seek(0, STREAM_SEEK_END, &fileSize)); + RINOK(InStream_GetSize_SeekToEnd(_stream, fileSize)) FileSize = fileSize; // Some UDFs contain additional pad zeros (2 KB). @@ -765,7 +791,7 @@ const size_t kBufSize = 1 << 14; Byte buf[kBufSize]; size_t readSize = (fileSize < kBufSize) ? (size_t)fileSize : kBufSize; - RINOK(_stream->Seek(fileSize - readSize, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_stream, fileSize - readSize)) RINOK(ReadStream(_stream, buf, &readSize)); size_t i = readSize; for (;;) @@ -785,20 +811,29 @@ extentVDS.Parse(buf + i + 16); */ + /* + An Anchor Volume Descriptor Pointer structure shall be recorded in at + least 2 of the following 3 locations on the media: + Logical Sector 256. + Logical Sector (N - 256). + N + */ + const size_t kBufSize = 1 << 11; Byte buf[kBufSize]; - for (SecLogSize = 11;; SecLogSize -= 3) + for (SecLogSize = 11;; SecLogSize -= 2) { - if (SecLogSize < 8) + // Windows 10 uses unusual (SecLogSize = 9) + if (SecLogSize < 9) return S_FALSE; const UInt32 offset = (UInt32)256 << SecLogSize; if (offset >= fileSize) continue; - RINOK(_stream->Seek(offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_stream, offset)) const size_t bufSize = (size_t)1 << SecLogSize; size_t readSize = bufSize; - RINOK(ReadStream(_stream, buf, &readSize)); + RINOK(ReadStream(_stream, buf, &readSize)) if (readSize == bufSize) { CTag tag; @@ -834,15 +869,15 @@ const size_t bufSize = (size_t)1 << SecLogSize; { const UInt64 offs = ((UInt64)extentVDS.Pos + location) << SecLogSize; - RINOK(_stream->Seek(offs, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_stream, offs)) const HRESULT res = ReadStream_FALSE(_stream, buf, bufSize); if (res == S_FALSE && offs + bufSize > FileSize) UnexpectedEnd = true; - RINOK(res); + RINOK(res) } CTag tag; - RINOK(tag.Parse(buf, bufSize)); + RINOK(tag.Parse(buf, bufSize)) if (tag.Id == DESC_TYPE_Terminating) break; @@ -1086,14 +1121,26 @@ RINOK(ReadItem(volIndex, -1, // (fsIndex = -1) means that it's metadata lad, - 1)); // numRecurseAllowed + false, // isDir + 1)) // numRecurseAllowed } { const CItem &item = Items.Back(); if (!CheckItemExtents(volIndex, item)) return S_FALSE; if (item.Extents.Size() != 1) - return S_FALSE; + { + if (item.Extents.Size() < 1) + return S_FALSE; + /* Windows 10 writes empty record item.Extents[1]. + we ignore such extent here */ + for (unsigned k = 1; k < item.Extents.Size(); k++) + { + const CMyExtent &e = item.Extents[k]; + if (e.GetLen() != 0) + return S_FALSE; + } + } const CMyExtent &e = item.Extents[0]; const CPartition &part = Partitions[pm.PartitionIndex]; @@ -1126,7 +1173,7 @@ } } - RINOK(_progress->SetTotal(totalSize)); + RINOK(_progress->SetTotal(totalSize)) PRF(printf("\n Read files")); @@ -1143,12 +1190,12 @@ if (nextExtent.GetLen() < 512) return S_FALSE; CByteBuffer buf2(nextExtent.GetLen()); - RINOK(ReadLad(volIndex, nextExtent, buf2)); + RINOK(ReadLad(volIndex, nextExtent, buf2)) const Byte *p = buf2; const size_t size = nextExtent.GetLen(); CTag tag; - RINOK(tag.Parse(p, size)); + RINOK(tag.Parse(p, size)) /* // commented in 22.01 @@ -1191,8 +1238,10 @@ CFileSet &fs = vol.FileSets[fsIndex]; const unsigned fileIndex = Files.Size(); Files.AddNew(); - RINOK(ReadFileItem(volIndex, fsIndex, fs.RootDirICB, kNumRecursionLevelsMax)); - RINOK(FillRefs(fs, fileIndex, -1, kNumRecursionLevelsMax)); + RINOK(ReadFileItem(volIndex, fsIndex, fs.RootDirICB, + true, // isDir + kNumRecursionLevelsMax)) + RINOK(FillRefs(fs, fileIndex, -1, kNumRecursionLevelsMax)) } } @@ -1248,7 +1297,7 @@ UInt64 rem = fileSize - PhySize; const size_t secSize = (size_t)1 << SecLogSize; - RINOK(_stream->Seek(PhySize, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_stream, PhySize)) // some UDF images contain ZEROs before "Anchor Volume Descriptor Pointer" at the end @@ -1261,7 +1310,7 @@ if (readSize > rem) readSize = (size_t)rem; - RINOK(ReadStream(_stream, buf, &readSize)); + RINOK(ReadStream(_stream, buf, &readSize)) if (readSize == 0) break; @@ -1270,8 +1319,9 @@ if (readSize == secSize /* && NoEndAnchor */) { CTag tag; - if (tag.Parse(buf, readSize) == S_OK && - tag.Id == DESC_TYPE_AnchorVolPtr) + if (tag.Parse(buf, readSize) == S_OK + && tag.Id == DESC_TYPE_AnchorVolPtr + && Get32(buf + 12) == (UInt32)((fileSize - rem) >> SecLogSize)) { NoEndAnchor = false; rem -= readSize; @@ -1443,7 +1493,7 @@ , "NetBSD" }; -static void AddOs_Class_Id(UString &s, const char *p) +static void AddOs_Class_Id(UString &s, const Byte *p) { // UDF 2.1.5.3 Implementation Identifier Suffix // Appendix 6.3 Operating System Identifiers. @@ -1451,7 +1501,7 @@ if (osClass != 0) { s += "::"; - s += TypeToString(g_OsClasses, ARRAY_SIZE(g_OsClasses), osClass); + s += TypeToString(g_OsClasses, Z7_ARRAY_SIZE(g_OsClasses), osClass); } const Byte osId = p[1]; if (osId != 0) @@ -1459,7 +1509,7 @@ s += "::"; if (osClass == 4) // unix { - s += TypeToString(g_OsIds_Unix, ARRAY_SIZE(g_OsIds_Unix), osId); + s += TypeToString(g_OsIds_Unix, Z7_ARRAY_SIZE(g_OsIds_Unix), osId); } else s.Add_UInt32(osId); @@ -1552,7 +1602,7 @@ AddComment_RegId(s, "ContentsId", part.ContentsId); AddComment_RegId_Impl(s, "ImplementationId", part.ImplId); AddComment_PropName(s, "AccessType"); - s += TypeToString(g_PartitionTypes, ARRAY_SIZE(g_PartitionTypes), part.AccessType); + s += TypeToString(g_PartitionTypes, Z7_ARRAY_SIZE(g_PartitionTypes), part.AccessType); s.Add_LF(); } AddComment_UInt64(s, "Size", (UInt64)part.Len << SecLogSize); @@ -1663,7 +1713,7 @@ // we break on root file (that probably has empty name) if (ref.Parent < 0) break; - refIndex = ref.Parent; + refIndex = (unsigned)ref.Parent; UpdateWithName(name, GetSpecName(Files[ref.FileIndex].GetName())); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Udf/UdfIn.h 7zip-23.01+dfsg/CPP/7zip/Archive/Udf/UdfIn.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Udf/UdfIn.h 2022-06-29 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Udf/UdfIn.h 2023-03-23 08:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Archive/UdfIn.h -- UDF / ECMA-167 -#ifndef __ARCHIVE_UDF_IN_H -#define __ARCHIVE_UDF_IN_H +#ifndef ZIP7_INC_ARCHIVE_UDF_IN_H +#define ZIP7_INC_ARCHIVE_UDF_IN_H #include "../../../Common/IntToString.h" #include "../../../Common/MyBuffer.h" @@ -72,7 +72,7 @@ { Byte Flags; char Id[23]; - char Suffix[8]; + Byte Suffix[8]; void Parse(const Byte *buf); void AddCommentTo(UString &s) const; @@ -281,9 +281,15 @@ void Parse(const Byte *p); }; + // ECMA 4/14.4.3 +// UDF 2.3.4.2 FileCharacteristics + // const Byte FILEID_CHARACS_Existance = (1 << 0); -const Byte FILEID_CHARACS_Parent = (1 << 3); +const Byte FILEID_CHARACS_Dir = (1 << 1); +const Byte FILEID_CHARACS_Deleted = (1 << 2); +const Byte FILEID_CHARACS_Parent = (1 << 3); +// const Byte FILEID_CHARACS_Metadata = (1 << 4); struct CFile { @@ -423,13 +429,14 @@ }; - -struct CProgressVirt +Z7_PURE_INTERFACES_BEGIN +struct Z7_DECLSPEC_NOVTABLE CProgressVirt { - virtual HRESULT SetTotal(UInt64 numBytes) PURE; - virtual HRESULT SetCompleted(UInt64 numFiles, UInt64 numBytes) PURE; - virtual HRESULT SetCompleted() PURE; + virtual HRESULT SetTotal(UInt64 numBytes) =0; \ + virtual HRESULT SetCompleted(UInt64 numFiles, UInt64 numBytes) =0; \ + virtual HRESULT SetCompleted() =0; \ }; +Z7_PURE_INTERFACES_END class CInArchive { @@ -467,8 +474,8 @@ HRESULT ReadLad(unsigned volIndex, const CLongAllocDesc &lad, Byte *buf); HRESULT ReadFromFile(unsigned volIndex, const CItem &item, CByteBuffer &buf); - HRESULT ReadFileItem(unsigned volIndex, unsigned fsIndex, const CLongAllocDesc &lad, int numRecurseAllowed); - HRESULT ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDesc &lad, int numRecurseAllowed); + HRESULT ReadFileItem(unsigned volIndex, unsigned fsIndex, const CLongAllocDesc &lad, bool isDir, int numRecurseAllowed); + HRESULT ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDesc &lad, bool isDir, int numRecurseAllowed); HRESULT Open2(); HRESULT FillRefs(CFileSet &fs, unsigned fileIndex, int parent, int numRecurseAllowed); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/UefiHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/UefiHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/UefiHandler.cpp 2021-01-26 09:48:13.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/UefiHandler.cpp 2023-03-26 12:00:00.000000000 +0000 @@ -171,14 +171,14 @@ static const char *FindExt(const Byte *p, size_t size) { unsigned i; - for (i = 0; i < ARRAY_SIZE(g_Sigs); i++) + for (i = 0; i < Z7_ARRAY_SIZE(g_Sigs); i++) { const CSigExtPair &pair = g_Sigs[i]; if (size >= pair.sigSize) if (memcmp(p, pair.sig, pair.sigSize) == 0) break; } - if (i == ARRAY_SIZE(g_Sigs)) + if (i == Z7_ARRAY_SIZE(g_Sigs)) return NULL; switch (i) { @@ -212,9 +212,9 @@ static int FindGuid(const Byte *p) { - for (unsigned i = 0; i < ARRAY_SIZE(kGuids); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(kGuids); i++) if (AreGuidsEq(p, kGuids[i])) - return i; + return (int)i; return -1; } @@ -222,7 +222,7 @@ { if (Get32(p + 0x28) != kFvSignature) return false; - for (unsigned i = 0; i < ARRAY_SIZE(k_Guids_FS); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_Guids_FS); i++) if (AreGuidsEq(p + kFfsGuidOffset, k_Guids_FS[i])) return true; return false; @@ -396,7 +396,7 @@ for (UInt32 i = 0; i < size;) { unsigned command = p[i++]; - if (command > ARRAY_SIZE(kExpressionCommands)) + if (command > Z7_ARRAY_SIZE(kExpressionCommands)) return false; res += kExpressionCommands[command]; if (command < 3) @@ -437,9 +437,9 @@ return true; } -#define FLAGS_TO_STRING(pairs, value) FlagsToString(pairs, ARRAY_SIZE(pairs), value) -#define TYPE_TO_STRING(table, value) TypeToString(table, ARRAY_SIZE(table), value) -#define TYPE_PAIR_TO_STRING(table, value) TypePairToString(table, ARRAY_SIZE(table), value) +#define FLAGS_TO_STRING(pairs, value) FlagsToString(pairs, Z7_ARRAY_SIZE(pairs), value) +#define TYPE_TO_STRING(table, value) TypeToString(table, Z7_ARRAY_SIZE(table), value) +#define TYPE_PAIR_TO_STRING(table, value) TypePairToString(table, Z7_ARRAY_SIZE(table), value) static const UInt32 kFileHeaderSize = 24; @@ -559,8 +559,8 @@ } }; -#define G32(_offs_, dest) dest = Get32(p + (_offs_)); -#define G16(_offs_, dest) dest = Get16(p + (_offs_)); +#define G32(_offs_, dest) dest = Get32(p + (_offs_)) +#define G16(_offs_, dest) dest = Get16(p + (_offs_)) struct CCapsuleHeader { @@ -632,14 +632,14 @@ int Parent; int Method; int NameIndex; - int NumChilds; + unsigned NumChilds; bool IsDir; bool Skip; bool ThereAreSubDirs; bool ThereIsUniqueName; bool KeepName; - int BufIndex; + unsigned BufIndex; UInt32 Offset; UInt32 Size; @@ -668,14 +668,14 @@ return Name; char sz[32]; char sz2[32]; - ConvertUInt32ToString(NameIndex, sz); - ConvertUInt32ToString(numChildsInParent - 1, sz2); - int numZeros = (int)strlen(sz2) - (int)strlen(sz); + ConvertUInt32ToString((unsigned)NameIndex, sz); + ConvertUInt32ToString((unsigned)numChildsInParent - 1, sz2); + const int numZeros = (int)strlen(sz2) - (int)strlen(sz); AString res; for (int i = 0; i < numZeros; i++) res += '0'; res += sz; - res += '.'; + res.Add_Dot(); res += Name; return res; } @@ -684,17 +684,16 @@ { AString Name; AString Characts; - int MainIndex; + unsigned MainIndex; int Parent; CItem2(): Parent(-1) {} }; -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_CHandler_IInArchive_1( + IInArchiveGetStream +) CObjectVector _items; CObjectVector _items2; CObjectVector _bufs; @@ -708,20 +707,23 @@ UInt64 _phySize; void AddCommentString(const char *name, UInt32 pos); - int AddItem(const CItem &item); - int AddFileItemWithIndex(CItem &item); - int AddDirItem(CItem &item); + unsigned AddItem(const CItem &item); + unsigned AddFileItemWithIndex(CItem &item); + unsigned AddDirItem(CItem &item); unsigned AddBuf(size_t size); HRESULT DecodeLzma(const Byte *data, size_t inputSize); - HRESULT ParseSections(int bufIndex, UInt32 pos, UInt32 size, int parent, int method, unsigned level, bool &error); + HRESULT ParseSections(unsigned bufIndex, UInt32 pos, + UInt32 size, + int parent, int method, unsigned level, + bool &error); - HRESULT ParseIntelMe(int bufIndex, UInt32 posBase, + HRESULT ParseIntelMe(unsigned bufIndex, UInt32 posBase, UInt32 exactSize, UInt32 limitSize, int parent, int method, unsigned level); - HRESULT ParseVolume(int bufIndex, UInt32 posBase, + HRESULT ParseVolume(unsigned bufIndex, UInt32 posBase, UInt32 exactSize, UInt32 limitSize, int parent, int method, unsigned level); @@ -730,11 +732,9 @@ HRESULT Open2(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *callback); public: CHandler(bool capsuleMode): _capsuleMode(capsuleMode) {} - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); }; + static const Byte kProps[] = { kpidPath, @@ -755,7 +755,7 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -823,7 +823,7 @@ _comment += s; } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -875,23 +875,23 @@ -int CHandler::AddItem(const CItem &item) +unsigned CHandler::AddItem(const CItem &item) { if (_items.Size() >= kNumFilesMax) throw 2; return _items.Add(item); } -int CHandler::AddFileItemWithIndex(CItem &item) +unsigned CHandler::AddFileItemWithIndex(CItem &item) { - int nameIndex = _items.Size(); + unsigned nameIndex = _items.Size(); if (item.Parent >= 0) nameIndex = _items[item.Parent].NumChilds++; - item.NameIndex = nameIndex; + item.NameIndex = (int)nameIndex; return AddItem(item); } -int CHandler::AddDirItem(CItem &item) +unsigned CHandler::AddDirItem(CItem &item) { if (item.Parent >= 0) _items[item.Parent].ThereAreSubDirs = true; @@ -936,7 +936,7 @@ } -HRESULT CHandler::ParseSections(int bufIndex, UInt32 posBase, UInt32 size, int parent, int method, unsigned level, bool &error) +HRESULT CHandler::ParseSections(unsigned bufIndex, UInt32 posBase, UInt32 size, int parent, int method, unsigned level, bool &error) { error = false; @@ -1010,14 +1010,14 @@ if (compressionType == COMPRESSION_TYPE_NONE) { bool error2; - RINOK(ParseSections(bufIndex, newOffset, newSectSize, parent, method, level, error2)); + RINOK(ParseSections(bufIndex, newOffset, newSectSize, parent, method, level, error2)) } else if (compressionType == COMPRESSION_TYPE_LZH) { unsigned newBufIndex = AddBuf(uncompressedSize); CByteBuffer &buf = _bufs[newBufIndex]; - NCompress::NLzh::NDecoder::CCoder *lzhDecoderSpec = 0; + NCompress::NLzh::NDecoder::CCoder *lzhDecoderSpec = NULL; CMyComPtr lzhDecoder; lzhDecoderSpec = new NCompress::NLzh::NDecoder::CCoder; @@ -1066,11 +1066,11 @@ if (res == S_OK) break; } - RINOK(res); + RINOK(res) } bool error2; - RINOK(ParseSections(newBufIndex, 0, uncompressedSize, parent, compressionType, level, error2)); + RINOK(ParseSections(newBufIndex, 0, uncompressedSize, parent, compressionType, level, error2)) } else { @@ -1091,13 +1091,13 @@ } pStart += addSize; - RINOK(DecodeLzma(pStart, newSectSize - addSize)); + RINOK(DecodeLzma(pStart, newSectSize - addSize)) const size_t lzmaUncompressedSize = _bufs.Back().Size(); // if (lzmaUncompressedSize != uncompressedSize) if (lzmaUncompressedSize < uncompressedSize) return S_FALSE; bool error2; - RINOK(ParseSections(_bufs.Size() - 1, 0, (UInt32)lzmaUncompressedSize, parent, compressionType, level, error2)); + RINOK(ParseSections(_bufs.Size() - 1, 0, (UInt32)lzmaUncompressedSize, parent, compressionType, level, error2)) } _methodsMask |= (1 << compressionType); } @@ -1108,15 +1108,15 @@ if (sectSize < kHeaderSize) return S_FALSE; item.SetGuid(p + 4); - UInt32 dataOffset = Get16(p + 4 + kGuidSize); - UInt32 attrib = Get16(p + 4 + kGuidSize + 2); + const UInt32 dataOffset = Get16(p + 4 + kGuidSize); + const UInt32 attrib = Get16(p + 4 + kGuidSize + 2); if (dataOffset > sectSize || dataOffset < kHeaderSize) return S_FALSE; UInt32 newSectSize = sectSize - dataOffset; item.Size = newSectSize; UInt32 newOffset = posBase + pos + dataOffset; item.Offset = newOffset; - UInt32 propsSize = dataOffset - kHeaderSize; + const UInt32 propsSize = dataOffset - kHeaderSize; AddSpaceAndString(item.Characts, FLAGS_TO_STRING(g_GUIDED_SECTION_ATTRIBUTES, attrib)); bool needDir = true; @@ -1129,7 +1129,7 @@ // AddItem(item); const Byte *pStart = bufData + newOffset; // do we need correct pStart here for lzma steram offset? - RINOK(DecodeLzma(pStart, newSectSize)); + RINOK(DecodeLzma(pStart, newSectSize)) _methodsMask |= (1 << COMPRESSION_TYPE_LZMA); newBufIndex = _bufs.Size() - 1; newOffset = 0; @@ -1157,18 +1157,18 @@ int newParent = parent; if (needDir) - newParent = AddDirItem(item); + newParent = (int)AddDirItem(item); bool error2; - RINOK(ParseSections(newBufIndex, newOffset, newSectSize, newParent, newMethod, level, error2)); + RINOK(ParseSections(newBufIndex, newOffset, newSectSize, newParent, newMethod, level, error2)) } else if (type == SECTION_FIRMWARE_VOLUME_IMAGE) { item.KeepName = false; - int newParent = AddDirItem(item); + const int newParent = (int)AddDirItem(item); RINOK(ParseVolume(bufIndex, posBase + pos + 4, sectSize - 4, sectSize - 4, - newParent, method, level)); + newParent, method, level)) } else { @@ -1185,11 +1185,11 @@ { needAdd = false; item.Name = "vol"; - int newParent = AddDirItem(item); + const unsigned newParent = AddDirItem(item); RINOK(ParseVolume(bufIndex, posBase + pos + 4 + kInsydeOffset, sectDataSize - kInsydeOffset, sectDataSize - kInsydeOffset, - newParent, method, level)); + (int)newParent, method, level)) } if (needAdd) @@ -1306,11 +1306,11 @@ if (HeaderLen < kFvHeaderSize || (HeaderLen & 0x7) != 0 || VolSize < HeaderLen) return false; return true; -}; +} HRESULT CHandler::ParseVolume( - int bufIndex, UInt32 posBase, + unsigned bufIndex, UInt32 posBase, UInt32 exactSize, UInt32 limitSize, int parent, int method, unsigned level) { @@ -1382,7 +1382,7 @@ UInt32 rem = (UInt32)ffsHeader.VolSize - pos; if (rem < kFileHeaderSize) break; - pos = (pos + 7) & ~7; + pos = (pos + 7) & ~7u; rem = (UInt32)ffsHeader.VolSize - pos; if (rem < kFileHeaderSize) break; @@ -1457,11 +1457,11 @@ } if (isVolume) { - int newParent = AddDirItem(item); - UInt32 limSize = fh.GetDataSize2(rem); + const unsigned newParent = AddDirItem(item); + const UInt32 limSize = fh.GetDataSize2(rem); // volume.VolSize > fh.Size for some UEFI archives (is it correct UEFI?) // so we will check VolSize for limitSize instead. - RINOK(ParseVolume(bufIndex, offset, sectSize, limSize, newParent, method, level)); + RINOK(ParseVolume(bufIndex, offset, sectSize, limSize, (int)newParent, method, level)) } else AddItem(item); @@ -1477,9 +1477,9 @@ else */ { - int newParent = AddDirItem(item); + const unsigned newParent = AddDirItem(item); bool error2; - RINOK(ParseSections(bufIndex, offset, sectSize, newParent, method, level + 1, error2)); + RINOK(ParseSections(bufIndex, offset, sectSize, (int)newParent, method, level + 1, error2)) if (error2) { // in intel bio example: one FV_FILETYPE_FREEFORM file is wav file (not sections) @@ -1510,12 +1510,13 @@ HRESULT CHandler::ParseIntelMe( - int bufIndex, UInt32 posBase, + unsigned bufIndex, UInt32 posBase, UInt32 exactSize, UInt32 limitSize, - int parent, int method, unsigned level) + int parent, int method, unsigned /* level */) { UNUSED_VAR(limitSize) - level++; + // level++; + const Byte *p = _bufs[bufIndex] + posBase; if (exactSize < 16 + 16) return S_FALSE; @@ -1581,7 +1582,7 @@ { const unsigned kHeaderSize = 80; Byte buf[kHeaderSize]; - RINOK(ReadStream_FALSE(stream, buf, kHeaderSize)); + RINOK(ReadStream_FALSE(stream, buf, kHeaderSize)) if (!_h.Parse(buf)) return S_FALSE; if (_h.CapsuleImageSize < kHeaderSize @@ -1619,7 +1620,7 @@ HRESULT CHandler::OpenFv(IInStream *stream, const UInt64 * /* maxCheckStartPosition */, IArchiveOpenCallback * /* callback */) { Byte buf[kFvHeaderSize]; - RINOK(ReadStream_FALSE(stream, buf, kFvHeaderSize)); + RINOK(ReadStream_FALSE(stream, buf, kFvHeaderSize)) if (!IsFfs(buf)) return S_FALSE; CVolFfsHeader ffsHeader; @@ -1628,10 +1629,10 @@ if (ffsHeader.VolSize > ((UInt32)1 << 30)) return S_FALSE; _phySize = ffsHeader.VolSize; - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(stream)) UInt32 fvSize32 = (UInt32)ffsHeader.VolSize; unsigned bufIndex = AddBuf(fvSize32); - RINOK(ReadStream_FALSE(stream, _bufs[bufIndex], fvSize32)); + RINOK(ReadStream_FALSE(stream, _bufs[bufIndex], fvSize32)) return ParseVolume(bufIndex, 0, fvSize32, fvSize32, -1, -1, 0); } @@ -1640,14 +1641,14 @@ { if (_capsuleMode) { - RINOK(OpenCapsule(stream)); + RINOK(OpenCapsule(stream)) } else { - RINOK(OpenFv(stream, maxCheckStartPosition, callback)); + RINOK(OpenFv(stream, maxCheckStartPosition, callback)) } - unsigned num = _items.Size(); + const unsigned num = _items.Size(); CIntArr numChilds(num); unsigned i; @@ -1657,7 +1658,7 @@ for (i = 0; i < num; i++) { - int parent = _items[i].Parent; + const int parent = _items[i].Parent; if (parent >= 0) numChilds[(unsigned)parent]++; } @@ -1665,7 +1666,7 @@ for (i = 0; i < num; i++) { const CItem &item = _items[i]; - int parent = item.Parent; + const int parent = item.Parent; if (parent >= 0) { CItem &parentItem = _items[(unsigned)parent]; @@ -1718,7 +1719,7 @@ item2.Name = name; item2.Characts = characts2; if (parent >= 0) - item2.Parent = mainToReduced[(unsigned)parent]; + item2.Parent = (int)mainToReduced[(unsigned)parent]; _items2.Add(item2); /* CItem2 item2; @@ -1732,9 +1733,9 @@ return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *inStream, +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 *maxCheckStartPosition, - IArchiveOpenCallback *callback) + IArchiveOpenCallback *callback)) { COM_TRY_BEGIN Close(); @@ -1747,7 +1748,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _phySize = 0; _totalBufsSize = 0; @@ -1761,17 +1762,17 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _items2.Size(); return S_OK; } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _items2.Size(); if (numItems == 0) @@ -1794,22 +1795,22 @@ for (i = 0; i < numItems; i++) { lps->InSize = lps->OutSize = currentTotalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; const CItem &item = _items[_items2[index].MainIndex]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) currentTotalSize += item.Size; if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) if (testMode || item.IsDir) { - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } int res = NExtract::NOperationResult::kDataError; @@ -1817,18 +1818,18 @@ GetStream(index, &inStream); if (inStream) { - RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)) if (copyCoderSpec->TotalSize == item.Size) res = NExtract::NOperationResult::kOK; } realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(res)); + RINOK(extractCallback->SetOperationResult(res)) } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN const CItem &item = _items[_items2[index].MainIndex]; @@ -1860,7 +1861,7 @@ REGISTER_ARC_I_CLS( CHandler(true), - "UEFIc", "scap", 0, 0xD0, + "UEFIc", "scap", NULL, 0xD0, k_Capsule_Signatures, 0, NArcInfoFlags::kMultiSignature | @@ -1880,7 +1881,7 @@ REGISTER_ARC_I_CLS( CHandler(false), - "UEFIf", "uefif", 0, 0xD1, + "UEFIf", "uefif", NULL, 0xD1, k_FFS_Signatures, kFfsGuidOffset, NArcInfoFlags::kMultiSignature | diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/VdiHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/VdiHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/VdiHandler.cpp 2021-12-14 07:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/VdiHandler.cpp 2023-03-06 17:00:00.000000000 +0000 @@ -26,9 +26,7 @@ namespace NArchive { namespace NVdi { -#define SIGNATURE { 0x7F, 0x10, 0xDA, 0xBE } - -static const Byte k_Signature[] = SIGNATURE; +static const Byte k_Signature[] = { 0x7F, 0x10, 0xDA, 0xBE }; static const unsigned k_ClusterBits = 20; static const UInt32 k_ClusterSize = (UInt32)1 << k_ClusterBits; @@ -85,7 +83,7 @@ -class CHandler: public CHandlerImg +Z7_class_CHandler_final: public CHandlerImg { UInt32 _dataOffset; CByteBuffer _table; @@ -99,7 +97,7 @@ HRESULT Seek2(UInt64 offset) { _posInArc = offset; - return Stream->Seek(offset, STREAM_SEEK_SET, NULL); + return InStream_SeekSet(Stream, offset); } HRESULT InitAndSeek() @@ -108,17 +106,17 @@ return Seek2(0); } - HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openCallback); + HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openCallback) Z7_override; public: - INTERFACE_IInArchive_Img(;) + Z7_IFACE_COM7_IMP(IInArchive_Img) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); + Z7_IFACE_COM7_IMP(IInArchiveGetStream) + Z7_IFACE_COM7_IMP(ISequentialInStream) }; -STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -152,7 +150,7 @@ offset += lowBits; if (offset != _posInArc) { - RINOK(Seek2(offset)); + RINOK(Seek2(offset)) } HRESULT res = Stream->Read(data, size, &size); _posInArc += size; @@ -189,7 +187,7 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -209,7 +207,7 @@ case kpidErrorFlags: { UInt32 v = 0; - if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;; + if (!_isArc) v |= kpv_ErrorFlags_IsNotArc; if (_unsupported) v |= kpv_ErrorFlags_UnsupportedMethod; // if (_headerError) v |= kpv_ErrorFlags_HeadersError; if (!Stream && v == 0 && _isArc) @@ -249,7 +247,7 @@ char temp[64]; RawLeGuidToString_Braced(guid, temp); MyStringLower_Ascii(temp); - strcat(temp, ".vdi"); + MyStringCat(temp, ".vdi"); prop = temp; } break; @@ -262,7 +260,7 @@ } -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -284,7 +282,7 @@ { const unsigned kHeaderSize = 512; Byte buf[kHeaderSize]; - RINOK(ReadStream_FALSE(stream, buf, kHeaderSize)); + RINOK(ReadStream_FALSE(stream, buf, kHeaderSize)) if (memcmp(buf + 0x40, k_Signature, sizeof(k_Signature)) != 0) return S_FALSE; @@ -378,8 +376,8 @@ } _table.Alloc(numBytes); - RINOK(stream->Seek(tableOffset, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(stream, _table, numBytes)); + RINOK(InStream_SeekSet(stream, tableOffset)) + RINOK(ReadStream_FALSE(stream, _table, numBytes)) const Byte *data = _table; for (UInt32 i = 0; i < totalBlocks; i++) @@ -399,7 +397,7 @@ } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _table.Free(); _phySize = 0; @@ -416,14 +414,14 @@ } -STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream)) { COM_TRY_BEGIN *stream = NULL; if (_unsupported) return S_FALSE; CMyComPtr streamTemp = this; - RINOK(InitAndSeek()); + RINOK(InitAndSeek()) *stream = streamTemp.Detach(); return S_OK; COM_TRY_END diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/VhdHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/VhdHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/VhdHandler.cpp 2022-02-02 07:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/VhdHandler.cpp 2023-05-28 15:00:00.000000000 +0000 @@ -18,18 +18,17 @@ #define Get32(p) GetBe32(p) #define Get64(p) GetBe64(p) -#define G32(_offs_, dest) dest = Get32(p + (_offs_)); -#define G64(_offs_, dest) dest = Get64(p + (_offs_)); +#define G32(_offs_, dest) dest = Get32(p + (_offs_)) +#define G64(_offs_, dest) dest = Get64(p + (_offs_)) using namespace NWindows; namespace NArchive { namespace NVhd { -#define SIGNATURE { 'c', 'o', 'n', 'e', 'c', 't', 'i', 'x', 0, 0 } - static const unsigned kSignatureSize = 10; -static const Byte kSignature[kSignatureSize] = SIGNATURE; +static const Byte kSignature[kSignatureSize] = + { 'c', 'o', 'n', 'e', 'c', 't', 'i', 'x', 0, 0 }; static const UInt32 kUnusedBlock = 0xFFFFFFFF; @@ -74,7 +73,7 @@ void CFooter::AddTypeString(AString &s) const { - if (Type < ARRAY_SIZE(kDiskTypes)) + if (Type < Z7_ARRAY_SIZE(kDiskTypes)) s += kDiskTypes[Type]; else s.Add_UInt32(Type); @@ -214,7 +213,7 @@ return CheckBlock(p, 1024, 0x24, 0x240 + 8 * 24); } -class CHandler: public CHandlerImg +Z7_class_CHandler_final: public CHandlerImg { UInt64 _posInArcLimit; UInt64 _startOffset; @@ -247,7 +246,6 @@ _phySize = value; } - void Reset_PosInArc() { _posInArc = (UInt64)0 - 1; } HRESULT Seek2(UInt64 offset); HRESULT InitAndSeek(); HRESULT ReadPhy(UInt64 offset, void *data, UInt32 size); @@ -303,26 +301,26 @@ HRESULT Open3(); HRESULT Open2(IInStream *stream, CHandler *child, IArchiveOpenCallback *openArchiveCallback, unsigned level); - HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openArchiveCallback) + HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openArchiveCallback) Z7_override { return Open2(stream, NULL, openArchiveCallback, 0); } - void CloseAtError(); + void CloseAtError() Z7_override; public: - INTERFACE_IInArchive_Img(;) + Z7_IFACE_COM7_IMP(IInArchive_Img) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); + Z7_IFACE_COM7_IMP(IInArchiveGetStream) + Z7_IFACE_COM7_IMP(ISequentialInStream) }; -HRESULT CHandler::Seek2(UInt64 offset) { return Stream->Seek(_startOffset + offset, STREAM_SEEK_SET, NULL); } +HRESULT CHandler::Seek2(UInt64 offset) { return InStream_SeekSet(Stream, _startOffset + offset); } HRESULT CHandler::InitAndSeek() { if (ParentStream) { - RINOK(Parent->InitAndSeek()); + RINOK(Parent->InitAndSeek()) } _virtPos = _posInArc = 0; BitMapTag = kUnusedBlock; @@ -337,7 +335,7 @@ if (offset != _posInArc) { _posInArc = offset; - RINOK(Seek2(offset)); + RINOK(Seek2(offset)) } HRESULT res = ReadStream_FALSE(Stream, data, size); if (res == S_OK) @@ -352,10 +350,10 @@ // Fixed archive uses only footer UInt64 startPos; - RINOK(Stream->Seek(0, STREAM_SEEK_CUR, &startPos)); + RINOK(InStream_GetPos(Stream, startPos)) _startOffset = startPos; Byte header[kHeaderSize]; - RINOK(ReadStream_FALSE(Stream, header, kHeaderSize)); + RINOK(ReadStream_FALSE(Stream, header, kHeaderSize)) bool headerIsOK = Footer.Parse(header); _size = Footer.CurrentSize; @@ -372,15 +370,15 @@ } UInt64 fileSize; - RINOK(Stream->Seek(0, STREAM_SEEK_END, &fileSize)); + RINOK(InStream_GetSize_SeekToEnd(Stream, fileSize)) if (fileSize < kHeaderSize) return S_FALSE; const UInt32 kDynSize = 1024; Byte buf[kDynSize]; - RINOK(Stream->Seek(fileSize - kHeaderSize, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(Stream, buf, kHeaderSize)); + RINOK(InStream_SeekSet(Stream, fileSize - kHeaderSize)) + RINOK(ReadStream_FALSE(Stream, buf, kHeaderSize)) if (!headerIsOK) { @@ -389,6 +387,7 @@ _size = Footer.CurrentSize; if (Footer.ThereIsDynamic()) return S_FALSE; // we can't open Dynamic Archive backward. + // fixed archive _posInArcLimit = Footer.CurrentSize; _phySize = Footer.CurrentSize + kHeaderSize; _startOffset = fileSize - kHeaderSize - Footer.CurrentSize; @@ -407,7 +406,7 @@ _phySize = fileSize - _startOffset; } - RINOK(ReadPhy(Footer.DataOffset, buf, kDynSize)); + RINOK(ReadPhy(Footer.DataOffset, buf, kDynSize)) if (!Dyn.Parse(buf)) return S_FALSE; @@ -430,7 +429,7 @@ unsigned len = (locator.DataLen >> 1); { wchar_t *s = tempString.GetBuf(len); - RINOK(ReadPhy(locator.DataOffset, nameBuf, locator.DataLen)); + RINOK(ReadPhy(locator.DataOffset, nameBuf, locator.DataLen)) unsigned j; for (j = 0; j < len; j++) { @@ -467,7 +466,7 @@ while ((UInt32)Bat.Size() < Dyn.NumBlocks) { - RINOK(ReadPhy(Dyn.TableOffset + (UInt64)Bat.Size() * 4, buf, kSectorSize)); + RINOK(ReadPhy(Dyn.TableOffset + (UInt64)Bat.Size() * 4, buf, kSectorSize)) UpdatePhySize(Dyn.TableOffset + kSectorSize); for (UInt32 j = 0; j < kSectorSize; j += 4) { @@ -495,7 +494,7 @@ return S_OK; } - RINOK(ReadPhy(_phySize, buf, kHeaderSize)); + RINOK(ReadPhy(_phySize, buf, kHeaderSize)) if (memcmp(header, buf, kHeaderSize) == 0) { _posInArcLimit = _phySize; @@ -511,7 +510,7 @@ for (i = 0; i < kSectorSize && buf[i] == 0; i++); if (i == kSectorSize) { - RINOK(ReadPhy(_phySize + kSectorSize, buf, kHeaderSize)); + RINOK(ReadPhy(_phySize + kSectorSize, buf, kHeaderSize)) if (memcmp(header, buf, kHeaderSize) == 0) { _phySize += kSectorSize; @@ -527,7 +526,7 @@ return S_OK; } -STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -540,9 +539,40 @@ } if (size == 0) return S_OK; - UInt32 blockIndex = (UInt32)(_virtPos >> Dyn.BlockSizeLog); - UInt32 blockSectIndex = Bat[blockIndex]; - UInt32 blockSize = (UInt32)1 << Dyn.BlockSizeLog; + + if (Footer.IsFixed()) + { + if (_virtPos > _posInArcLimit) + return S_FALSE; + { + const UInt64 rem = _posInArcLimit - _virtPos; + if (size > rem) + size = (UInt32)rem; + } + HRESULT res = S_OK; + if (_virtPos != _posInArc) + { + _posInArc = _virtPos; + res = Seek2(_virtPos); + } + if (res == S_OK) + { + UInt32 processedSize2 = 0; + res = Stream->Read(data, size, &processedSize2); + if (processedSize) + *processedSize = processedSize2; + _posInArc += processedSize2; + } + if (res != S_OK) + Reset_PosInArc(); + return res; + } + + const UInt32 blockIndex = (UInt32)(_virtPos >> Dyn.BlockSizeLog); + if (blockIndex >= Bat.Size()) + return E_FAIL; // it's some unexpected case + const UInt32 blockSectIndex = Bat[blockIndex]; + const UInt32 blockSize = (UInt32)1 << Dyn.BlockSizeLog; UInt32 offsetInBlock = (UInt32)_virtPos & (blockSize - 1); size = MyMin(blockSize - offsetInBlock, size); @@ -551,7 +581,7 @@ { if (ParentStream) { - RINOK(ParentStream->Seek(_virtPos, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(ParentStream, _virtPos)) res = ParentStream->Read(data, size, &size); } else @@ -559,23 +589,23 @@ } else { - UInt64 newPos = (UInt64)blockSectIndex << kSectorSize_Log; + const UInt64 newPos = (UInt64)blockSectIndex << kSectorSize_Log; if (BitMapTag != blockIndex) { - RINOK(ReadPhy(newPos, BitMap, (UInt32)BitMap.Size())); + RINOK(ReadPhy(newPos, BitMap, (UInt32)BitMap.Size())) BitMapTag = blockIndex; } - RINOK(ReadPhy(newPos + BitMap.Size() + offsetInBlock, data, size)); + RINOK(ReadPhy(newPos + BitMap.Size() + offsetInBlock, data, size)) for (UInt32 cur = 0; cur < size;) { const UInt32 rem = MyMin(0x200 - (offsetInBlock & 0x1FF), size - cur); - UInt32 bmi = offsetInBlock >> kSectorSize_Log; + const UInt32 bmi = offsetInBlock >> kSectorSize_Log; if (((BitMap[bmi >> 3] >> (7 - (bmi & 7))) & 1) == 0) { if (ParentStream) { - RINOK(ParentStream->Seek(_virtPos + cur, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(ParentStream, (Byte *)data + cur, rem)); + RINOK(InStream_SeekSet(ParentStream, _virtPos + cur)) + RINOK(ReadStream_FALSE(ParentStream, (Byte *)data + cur, rem)) } else { @@ -651,10 +681,10 @@ { for (int i = 24; i >= 0; i -= 8) { - Byte b = (Byte)((val >> i) & 0xFF); + const Byte b = (Byte)((val >> i) & 0xFF); if (b < 0x20 || b > 0x7F) break; - *dest++ = b; + *dest++ = (char)b; } *dest = 0; } @@ -669,7 +699,7 @@ } } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -705,7 +735,7 @@ res.Trim(); res.Add_Space(); res.Add_UInt32(Footer.CreatorVersion >> 16); - res += '.'; + res.Add_Dot(); res.Add_UInt32(Footer.CreatorVersion & 0xFFFF); prop = res; break; @@ -776,7 +806,7 @@ if (level > (1 << 12)) // Maybe we need to increase that limit return S_FALSE; - RINOK(Open3()); + RINOK(Open3()) NumLevels = 1; if (child && memcmp(child->Dyn.ParentId, Footer.Id, 16) != 0) @@ -800,9 +830,10 @@ Dyn.RelativeNameWasUsed = useRelative; - CMyComPtr openVolumeCallback; - openArchiveCallback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&openVolumeCallback); - + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveOpenVolumeCallback, + openVolumeCallback, openArchiveCallback) + if (openVolumeCallback) { CMyComPtr nextStream; @@ -881,13 +912,13 @@ // _unexpectedEnd = false; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { CloseAtError(); return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -912,7 +943,7 @@ } -STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream)) { COM_TRY_BEGIN *stream = NULL; @@ -923,14 +954,14 @@ streamSpec->SetStream(Stream); // fixme : check (startOffset = 0) streamSpec->InitAndSeek(_startOffset, Footer.CurrentSize); - RINOK(streamSpec->SeekToStart()); + RINOK(streamSpec->SeekToStart()) *stream = streamTemp.Detach(); return S_OK; } if (!Footer.ThereIsDynamic() || !AreParentsOK()) return S_FALSE; CMyComPtr streamTemp = this; - RINOK(InitAndSeek()); + RINOK(InitAndSeek()) *stream = streamTemp.Detach(); return S_OK; COM_TRY_END diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/VhdxHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/VhdxHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/VhdxHandler.cpp 2021-12-29 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/VhdxHandler.cpp 2023-04-06 11:00:00.000000000 +0000 @@ -20,8 +20,8 @@ #define Get32(p) GetUi32(p) #define Get64(p) GetUi64(p) -#define G32(_offs_, dest) dest = Get32(p + (_offs_)); -#define G64(_offs_, dest) dest = Get64(p + (_offs_)); +#define G32(_offs_, dest) dest = Get32(p + (_offs_)) +#define G64(_offs_, dest) dest = Get64(p + (_offs_)) using namespace NWindows; @@ -33,7 +33,7 @@ static UInt32 g_Crc32c_Table[256]; -static void MY_FAST_CALL Crc32c_GenerateTable() +static void Z7_FASTCALL Crc32c_GenerateTable() { UInt32 i; for (i = 0; i < 256; i++) @@ -46,13 +46,24 @@ } } -UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table); #define CRC32C_INIT_VAL 0xFFFFFFFF -static UInt32 MY_FAST_CALL Crc32c_Calc(const void *data, size_t size) +#define CRC_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) + +// UInt32 Z7_FASTCALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table); +static UInt32 Z7_FASTCALL CrcUpdateT1_vhdx(UInt32 v, const void *data, size_t size, const UInt32 *table) { - return CrcUpdateT1(CRC32C_INIT_VAL, data, size, g_Crc32c_Table) ^ CRC32C_INIT_VAL; + const Byte *p = (const Byte *)data; + const Byte *pEnd = p + size; + for (; p != pEnd; p++) + v = CRC_UPDATE_BYTE_2(v, *p); + return v; +} + +static UInt32 Z7_FASTCALL Crc32c_Calc(const void *data, size_t size) +{ + return CrcUpdateT1_vhdx(CRC32C_INIT_VAL, data, size, g_Crc32c_Table) ^ CRC32C_INIT_VAL; } EXTERN_C_END @@ -61,12 +72,11 @@ namespace NArchive { namespace NVhdx { -static struct C_CRC32c_TableInit { C_CRC32c_TableInit() { Crc32c_GenerateTable(); } } g__CRC32c_TableInit; +static struct C_CRC32c_TableInit { C_CRC32c_TableInit() { Crc32c_GenerateTable(); } } g_CRC32c_TableInit; -#define SIGNATURE { 'v', 'h', 'd', 'x', 'f', 'i', 'l', 'e' } - static const unsigned kSignatureSize = 8; -static const Byte kSignature[kSignatureSize] = SIGNATURE; +static const Byte kSignature[kSignatureSize] = + { 'v', 'h', 'd', 'x', 'f', 'i', 'l', 'e' }; static const unsigned kBitmapSize_Log = 20; static const size_t kBitmapSize = (size_t)1 << kBitmapSize_Log; @@ -105,7 +115,7 @@ { const int v0 = HexToVal(s[0]); if (v0 < 0) return -1; const int v1 = HexToVal(s[1]); if (v1 < 0) return -1; - return ((unsigned)v0 << 4) | (unsigned)v1; + return (int)(((unsigned)v0 << 4) | (unsigned)v1); } @@ -183,7 +193,7 @@ if (!Guids[i].IsEqualTo(h.Guids[i])) return false; return true; - }; + } bool Parse(Byte *p); }; @@ -195,7 +205,7 @@ if (Get32(p) != 0x64616568) // "head" return false; const UInt32 crc = Get32(p + 4); - SetUi32(p + 4, 0); + SetUi32(p + 4, 0) if (Crc32c_Calc(p, kHeader2Size) != crc) return false; G64(8, SequenceNumber); @@ -277,7 +287,7 @@ if (Get32(p) != 0x69676572) // "regi" return false; const UInt32 crc = Get32(p + 4); - SetUi32(p + 4, 0); + SetUi32(p + 4, 0) const UInt32 crc_calced = Crc32c_Calc(p, kRegionSize); if (crc_calced != crc) return false; @@ -372,7 +382,7 @@ if ((Flags1 & 3) != 0) // Reserved2 return false; return true; -}; +} struct CParentPair @@ -406,7 +416,7 @@ { const CParentPair &pair = ParentPairs[i]; if (pair.Key.IsEqualTo(name)) - return i; + return (int)i; } return -1; } @@ -628,7 +638,7 @@ -class CHandler: public CHandlerImg +Z7_class_CHandler_final: public CHandlerImg { UInt64 _phySize; @@ -657,11 +667,11 @@ CMyComPtr ParentStream; CHandler *Parent; UString _errorMessage; - UString _Creator; + UString _creator; bool _nonEmptyLog; bool _isDataContiguous; - // bool _BatOverlap; + // bool _batOverlap; CGuid _parentGuid; bool _parentGuid_IsDefined; @@ -756,15 +766,15 @@ bool CheckBat(); HRESULT Open3(); - HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openArchiveCallback); + HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openArchiveCallback) Z7_override; HRESULT OpenParent(IArchiveOpenCallback *openArchiveCallback, bool &_parentFileWasOpen); - virtual void CloseAtError(); + virtual void CloseAtError() Z7_override; public: - INTERFACE_IInArchive_Img(;) + Z7_IFACE_COM7_IMP(IInArchive_Img) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); + Z7_IFACE_COM7_IMP(IInArchiveGetStream) + Z7_IFACE_COM7_IMP(ISequentialInStream) CHandler(): _child(NULL), @@ -777,7 +787,7 @@ HRESULT CHandler::Seek2(UInt64 offset) { - return Stream->Seek(offset, STREAM_SEEK_SET, NULL); + return InStream_SeekSet(Stream, offset); } @@ -833,8 +843,8 @@ #define SB_BLOCK_NOT_PRESENT 0 #define SB_BLOCK_PRESENT 6 -#define BAT_GET_OFFSET(v) ((v) & ~(UInt64)0xFFFFF); -#define BAT_GET_STATE(v) ((UInt32)(v) & 7); +#define BAT_GET_OFFSET(v) ((v) & ~(UInt64)0xFFFFF) +#define BAT_GET_STATE(v) ((UInt32)(v) & 7) /* The log contains only updates to metadata, bat and region tables The log doesn't contain updates to start header, and 2 headers (first 192 KB of file). @@ -1154,10 +1164,10 @@ HRESULT CHandler::Open3() { { - static const unsigned kHeaderSize = 512; // + 8 + const unsigned kHeaderSize = 512; // + 8 Byte header[kHeaderSize]; - RINOK(Read_FALSE(header, kHeaderSize)); + RINOK(Read_FALSE(header, kHeaderSize)) if (memcmp(header, kSignature, kSignatureSize) != 0) return S_FALSE; @@ -1168,7 +1178,7 @@ const wchar_t c = Get16(p + i); if (c < 0x20 || c > 0x7F) break; - _Creator += c; + _creator += c; } } @@ -1178,8 +1188,8 @@ Byte header[kHeader2Size]; for (unsigned i = 0; i < 2; i++) { - RINOK(Seek2((1 << 16) * (1 + i))); - RINOK(Read_FALSE(header, kHeader2Size)); + RINOK(Seek2((1 << 16) * (1 + i))) + RINOK(Read_FALSE(header, kHeader2Size)) bool headerIsOK = headers[i].Parse(header); if (!headerIsOK) return S_FALSE; @@ -1233,8 +1243,8 @@ { CByteBuffer temp; temp.Alloc(kRegionSize * 2); - RINOK(Seek2((1 << 16) * 3)); - RINOK(Read_FALSE(temp, kRegionSize * 2)); + RINOK(Seek2((1 << 16) * 3)) + RINOK(Read_FALSE(temp, kRegionSize * 2)) unsigned numTables = 1; if (memcmp(temp, temp + kRegionSize, kRegionSize) != 0) { @@ -1249,7 +1259,7 @@ if (regions[i].Parse(temp)) { if (correctRegionIndex < 0) - correctRegionIndex = i; + correctRegionIndex = (int)i; } else { @@ -1281,8 +1291,8 @@ // static const kMetaTableSize = 1 << 16; CByteBuffer temp; { - RINOK(Seek2(e.Offset)); - RINOK(ReadToBuf_FALSE(temp, e.Len)); + RINOK(Seek2(e.Offset)) + RINOK(ReadToBuf_FALSE(temp, e.Len)) } if (!Meta.Parse(temp, temp.Size())) return S_FALSE; @@ -1297,15 +1307,15 @@ return S_FALSE; // UpdatePhySize(e.GetEndPos()); { - RINOK(Seek2(e.Offset)); - RINOK(ReadToBuf_FALSE(Bat.Data, e.Len)); + RINOK(Seek2(e.Offset)) + RINOK(ReadToBuf_FALSE(Bat.Data, e.Len)) } if (!ParseBat()) return S_FALSE; if (!CheckBat()) { AddErrorMessage("BAT overlap"); - // _BatOverlap = true; + // _batOverlap = true; // return S_FALSE; } } @@ -1327,13 +1337,13 @@ { // absolute paths for parent stream can be rejected later in client callback // the order of check by specification: - static const char * const g_ParentKeys[] = + const char * const g_ParentKeys[] = { "relative_path" // "..\..\path2\sub3\parent.vhdx" , "volume_path" // "\\?\Volume{26A21BDA-A627-11D7-9931-806E6F6E6963}\path2\sub3\parent.vhdx") , "absolute_win32_path" // "d:\path2\sub3\parent.vhdx" }; - for (unsigned i = 0; i < ARRAY_SIZE(g_ParentKeys); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_ParentKeys); i++) { const int index = Meta.FindParentKey(g_ParentKeys[i]); if (index < 0) @@ -1368,7 +1378,7 @@ // _posInArc = 0; // Reset_PosInArc(); - // RINOK(Stream->Seek(0, STREAM_SEEK_SET, NULL)); + // RINOK(InStream_SeekToBegin(Stream)) return S_OK; } @@ -1384,7 +1394,7 @@ } } g_Counter; */ -STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)) { // g_NumCalls++; if (processedSize) @@ -1489,7 +1499,7 @@ return S_FALSE; // if (ParentStream) { - RINOK(ParentStream->Seek(_virtPos, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(ParentStream, _virtPos)) size_t processed = size; res = ReadStream(ParentStream, (Byte *)data, &processed); size = (UInt32)processed; @@ -1668,7 +1678,7 @@ -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -1735,8 +1745,8 @@ } case kpidCreatorApp: { - if (!_Creator.IsEmpty()) - prop = _Creator; + if (!_creator.IsEmpty()) + prop = _creator; break; } case kpidId: @@ -1808,7 +1818,7 @@ if (_level >= (1 << 20)) return S_FALSE; - RINOK(Open3()); + RINOK(Open3()) NumLevels = 1; PackSize_Total = GetPackSize(); @@ -1882,12 +1892,11 @@ HRESULT CHandler::OpenParent(IArchiveOpenCallback *openArchiveCallback, bool &_parentFileWasOpen) { _parentFileWasOpen = false; - CMyComPtr openVolumeCallback; - openArchiveCallback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&openVolumeCallback); - + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveOpenVolumeCallback, + openVolumeCallback, openArchiveCallback) if (!openVolumeCallback) return S_FALSE; - { CMyComPtr nextStream; HRESULT res = S_FALSE; @@ -1961,7 +1970,7 @@ UInt64 numBytes = (UInt64)NumUsedBitMaps << kBitmapSize_Log; if (openArchiveCallback && numBytes != 0) { - RINOK(openArchiveCallback->SetTotal(NULL, &numBytes)); + RINOK(openArchiveCallback->SetTotal(NULL, &numBytes)) } numBytes = 0; for (size_t i = ChunkRatio; i < TotalBatEntries; i += ChunkRatio + 1) @@ -1975,12 +1984,12 @@ { if (openArchiveCallback) { - RINOK(openArchiveCallback->SetCompleted(NULL, &numBytes)); + RINOK(openArchiveCallback->SetCompleted(NULL, &numBytes)) } numBytes += kBitmapSize; buf.Alloc(kBitmapSize); - RINOK(Seek2(offset)); - RINOK(Read_FALSE(buf, kBitmapSize)); + RINOK(Seek2(offset)) + RINOK(Read_FALSE(buf, kBitmapSize)) /* for (unsigned i = 0; i < (1 << 20); i+=4) { @@ -2018,11 +2027,11 @@ Parent = NULL; ParentStream.Release(); _errorMessage.Empty(); - _Creator.Empty(); + _creator.Empty(); _nonEmptyLog = false; _parentGuid_IsDefined = false; _isDataContiguous = false; - // _BatOverlap = false; + // _batOverlap = false; ParentNames.Clear(); ParentName_Used.Empty(); @@ -2039,14 +2048,14 @@ _isCyclic_or_CyclicParent = false; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { CloseAtError(); return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -2064,7 +2073,7 @@ } -STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream)) { COM_TRY_BEGIN *stream = NULL; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/VmdkHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/VmdkHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/VmdkHandler.cpp 2022-02-15 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/VmdkHandler.cpp 2023-03-06 17:00:00.000000000 +0000 @@ -31,14 +31,12 @@ #define Get32(p) GetUi32(p) #define Get64(p) GetUi64(p) -#define LE_16(offs, dest) dest = Get16(p + (offs)); -#define LE_32(offs, dest) dest = Get32(p + (offs)); -#define LE_64(offs, dest) dest = Get64(p + (offs)); +#define LE_16(offs, dest) dest = Get16(p + (offs)) +#define LE_32(offs, dest) dest = Get32(p + (offs)) +#define LE_64(offs, dest) dest = Get64(p + (offs)) -#define SIGNATURE { 'K', 'D', 'M', 'V' } - -static const Byte k_Signature[] = SIGNATURE; +static const Byte k_Signature[] = { 'K', 'D', 'M', 'V' }; static const UInt32 k_Flags_NL = (UInt32)1 << 0; // static const UInt32 k_Flags_RGD = (UInt32)1 << 1; @@ -65,10 +63,10 @@ UInt64 gdOffset; UInt64 overHead; - bool Is_NL() const { return (flags & k_Flags_NL) != 0; }; - bool Is_ZeroGrain() const { return (flags & k_Flags_ZeroGrain) != 0; }; - bool Is_Compressed() const { return (flags & k_Flags_Compressed) != 0; }; - bool Is_Marker() const { return (flags & k_Flags_Marker) != 0; }; + bool Is_NL() const { return (flags & k_Flags_NL) != 0; } + bool Is_ZeroGrain() const { return (flags & k_Flags_ZeroGrain) != 0; } + bool Is_Compressed() const { return (flags & k_Flags_Compressed) != 0; } + bool Is_Marker() const { return (flags & k_Flags_Marker) != 0; } bool Parse(const Byte *p); @@ -165,7 +163,7 @@ static const char *GetNextWord(const char *s, AString &dest) { dest.Empty(); - SKIP_SPACES(s); + SKIP_SPACES(s) const char *start = s; for (;; s++) { @@ -180,7 +178,7 @@ static const char *GetNextNumber(const char *s, UInt64 &val) { - SKIP_SPACES(s); + SKIP_SPACES(s) if (*s == 0) return s; const char *end; @@ -228,7 +226,7 @@ if (Type.IsEmpty()) return false; - SKIP_SPACES(s); + SKIP_SPACES(s) if (IsType_ZERO()) return (*s == 0); @@ -243,7 +241,7 @@ FileName.SetFrom(s, (unsigned)(s2 - s)); s = s2 + 1; } - SKIP_SPACES(s); + SKIP_SPACES(s) if (*s == 0) return true; @@ -298,7 +296,7 @@ for (;;) { - char c = 0; + Byte c = 0; if (size != 0) { size--; @@ -369,7 +367,7 @@ UInt64 GetEndOffset() const { return StartOffset + NumBytes; } - bool IsVmdk() const { return !IsZero && !IsFlat; }; + bool IsVmdk() const { return !IsZero && !IsFlat; } // if (IsOK && IsVmdk()), then VMDK header of this extent was read CExtent(): @@ -403,7 +401,7 @@ HRESULT Seek(UInt64 offset) { PosInArc = offset; - return Stream->Seek(offset, STREAM_SEEK_SET, NULL); + return InStream_SeekSet(Stream, offset); } HRESULT InitAndSeek() @@ -422,7 +420,7 @@ }; -class CHandler: public CHandlerImg +Z7_class_CHandler_final: public CHandlerImg { bool _isArc; bool _unsupported; @@ -461,17 +459,17 @@ _virtPos = 0; } - virtual HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openCallback); - virtual void CloseAtError(); + virtual HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openCallback) Z7_override; + virtual void CloseAtError() Z7_override; public: - INTERFACE_IInArchive_Img(;) + Z7_IFACE_COM7_IMP(IInArchive_Img) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); + Z7_IFACE_COM7_IMP(IInArchiveGetStream) + Z7_IFACE_COM7_IMP(ISequentialInStream) }; -STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -569,7 +567,7 @@ UInt64 offset = extent.FlatOffset + vir; if (offset != extent.PosInArc) { - RINOK(extent.Seek(offset)); + RINOK(extent.Seek(offset)) } UInt32 size2 = 0; HRESULT res = extent.Stream->Read(data, size, &size2); @@ -636,13 +634,13 @@ if (offset != extent.PosInArc) { // printf("\n%12x %12x\n", (unsigned)offset, (unsigned)(offset - extent.PosInArc)); - RINOK(extent.Seek(offset)); + RINOK(extent.Seek(offset)) } const size_t kStartSize = 1 << 9; { size_t curSize = kStartSize; - RINOK(extent.Read(_cacheCompressed, &curSize)); + RINOK(extent.Read(_cacheCompressed, &curSize)) // _stream_PackSize += curSize; if (curSize != kStartSize) return S_FALSE; @@ -664,7 +662,7 @@ return S_FALSE; size_t curSize = dataSize2 - kStartSize; const size_t curSize2 = curSize; - RINOK(extent.Read(_cacheCompressed + kStartSize, &curSize)); + RINOK(extent.Read(_cacheCompressed + kStartSize, &curSize)) // _stream_PackSize += curSize; if (curSize != curSize2) return S_FALSE; @@ -680,8 +678,8 @@ _bufOutStreamSpec->Init(_cache, clusterSize); // Do we need to use smaller block than clusterSize for last cluster? - UInt64 blockSize64 = clusterSize; - HRESULT res = _zlibDecoderSpec->Code(_bufInStream, _bufOutStream, NULL, &blockSize64, NULL); + const UInt64 blockSize64 = clusterSize; + HRESULT res = _zlibDecoder->Code(_bufInStream, _bufOutStream, NULL, &blockSize64, NULL); /* if (_bufOutStreamSpec->GetPos() != clusterSize) @@ -699,7 +697,7 @@ res = S_FALSE; } - RINOK(res); + RINOK(res) _cacheCluster = cluster; _cacheExtent = extentIndex; @@ -718,7 +716,7 @@ if (offset != extent.PosInArc) { // printf("\n%12x %12x\n", (unsigned)offset, (unsigned)(offset - extent.PosInArc)); - RINOK(extent.Seek(offset)); + RINOK(extent.Seek(offset)) } UInt32 size2 = 0; HRESULT res = extent.Stream->Read(data, size, &size2); @@ -762,6 +760,7 @@ static const Byte kArcProps[] = { kpidNumVolumes, + kpidTotalPhySize, kpidMethod, kpidClusterSize, kpidHeadersSize, @@ -774,7 +773,7 @@ IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -794,6 +793,17 @@ { case kpidMainSubfile: prop = (UInt32)0; break; case kpidPhySize: if (_phySize != 0) prop = _phySize; break; + case kpidTotalPhySize: + { + UInt64 sum = _phySize; + if (_isMultiVol) + { + FOR_VECTOR (i, _extents) + sum += _extents[i].PhySize; + } + prop = sum; + break; + } case kpidClusterSize: prop = (UInt32)((UInt32)1 << _clusterBitsMax); break; case kpidHeadersSize: if (e) prop = (e->h.overHead << 9); break; case kpidMethod: @@ -896,7 +906,7 @@ case kpidErrorFlags: { UInt32 v = 0; - if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;; + if (!_isArc) v |= kpv_ErrorFlags_IsNotArc; if (_unsupported) v |= kpv_ErrorFlags_UnsupportedMethod; if (_unsupportedSome) v |= kpv_ErrorFlags_UnsupportedMethod; if (_headerError) v |= kpv_ErrorFlags_HeadersError; @@ -913,7 +923,7 @@ } -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -962,9 +972,9 @@ HRESULT CExtent::ReadForHeader(IInStream *stream, UInt64 sector, void *data, size_t numSectors) { sector <<= 9; - RINOK(stream->Seek(sector, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, sector)) size_t size = numSectors << 9; - RINOK(ReadStream_FALSE(stream, data, size)); + RINOK(ReadStream_FALSE(stream, data, size)) UInt64 end = sector + size; if (PhySize < end) PhySize = end; @@ -987,7 +997,7 @@ const unsigned kSectoreSize = 512; Byte buf[kSectoreSize]; size_t headerSize = kSectoreSize; - RINOK(ReadStream(stream, buf, &headerSize)); + RINOK(ReadStream(stream, buf, &headerSize)) if (headerSize < sizeof(k_Signature)) return S_FALSE; @@ -1003,13 +1013,13 @@ return S_FALSE; UInt64 endPos; - RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos)); + RINOK(InStream_GetSize_SeekToEnd(stream, endPos)) if (endPos > (1 << 20)) return S_FALSE; const size_t numBytes = (size_t)endPos; _descriptorBuf.Alloc(numBytes); - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(stream, _descriptorBuf, numBytes)); + RINOK(InStream_SeekToBegin(stream)) + RINOK(ReadStream_FALSE(stream, _descriptorBuf, numBytes)) if (!_descriptor.Parse(_descriptorBuf, _descriptorBuf.Size())) return S_FALSE; @@ -1046,7 +1056,7 @@ if (_descriptor.Extents.Size() > 1) { const UInt64 numFiles = _descriptor.Extents.Size(); - RINOK(openCallback->SetTotal(&numFiles, NULL)); + RINOK(openCallback->SetTotal(&numFiles, NULL)) } } @@ -1117,7 +1127,7 @@ stream = nextStream; headerSize = kSectoreSize; - RINOK(ReadStream(stream, buf, &headerSize)); + RINOK(ReadStream(stream, buf, &headerSize)) if (headerSize != kSectoreSize) continue; @@ -1176,7 +1186,7 @@ _needDeflate = false; _clusterBitsMax = 0; - unsigned numOKs = 0; + // unsigned numOKs = 0; unsigned numUnsupported = 0; FOR_VECTOR (i, _extents) @@ -1186,7 +1196,7 @@ numUnsupported++; if (!e.IsOK) continue; - numOKs++; + // numOKs++; if (e.IsVmdk()) { if (e.NeedDeflate) @@ -1212,7 +1222,7 @@ h.descriptorSize > (1 << 10)) return S_FALSE; DescriptorBuf.Alloc((size_t)h.descriptorSize << 9); - RINOK(ReadForHeader(stream, h.descriptorOffset, DescriptorBuf, (size_t)h.descriptorSize)); + RINOK(ReadForHeader(stream, h.descriptorOffset, DescriptorBuf, (size_t)h.descriptorSize)) if (h.descriptorOffset == 1 && h.Is_Marker() && Get64(DescriptorBuf) == 0) { // We check data as end marker. @@ -1231,7 +1241,7 @@ { // Grain Dir is at end of file UInt64 endPos; - RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos)); + RINOK(InStream_GetSize_SeekToEnd(stream, endPos)) if ((endPos & 511) != 0) return S_FALSE; @@ -1239,8 +1249,8 @@ Byte buf2[kEndSize]; if (endPos < kEndSize) return S_FALSE; - RINOK(stream->Seek(endPos - kEndSize, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(stream, buf2, kEndSize)); + RINOK(InStream_SeekSet(stream, endPos - kEndSize)) + RINOK(ReadStream_FALSE(stream, buf2, kEndSize)) CHeader h2; if (!h2.Parse(buf2 + 512)) @@ -1260,7 +1270,7 @@ PhySize = endPos; } - int grainSize_Log = GetLog(h.grainSize); + const int grainSize_Log = GetLog(h.grainSize); if (grainSize_Log < 3 || grainSize_Log > 30 - 9) // grain size must be >= 4 KB return S_FALSE; if (h.capacity >= ((UInt64)1 << (63 - 9))) @@ -1269,7 +1279,7 @@ return S_FALSE; IsArc = true; - ClusterBits = (9 + grainSize_Log); + ClusterBits = (9 + (unsigned)grainSize_Log); VirtSize = h.capacity << 9; NeedDeflate = (h.algo >= 1); @@ -1281,7 +1291,7 @@ } { - UInt64 overHeadBytes = h.overHead << 9; + const UInt64 overHeadBytes = h.overHead << 9; if (PhySize < overHeadBytes) PhySize = overHeadBytes; } @@ -1290,8 +1300,8 @@ if (h.Is_ZeroGrain()) ZeroSector = 1; - const UInt64 numSectorsPerGde = (UInt64)1 << (grainSize_Log + k_NumMidBits); - const UInt64 numGdeEntries = (h.capacity + numSectorsPerGde - 1) >> (grainSize_Log + k_NumMidBits); + const UInt64 numSectorsPerGde = (UInt64)1 << ((unsigned)grainSize_Log + k_NumMidBits); + const UInt64 numGdeEntries = (h.capacity + numSectorsPerGde - 1) >> ((unsigned)grainSize_Log + k_NumMidBits); CByteBuffer table; if (numGdeEntries != 0) @@ -1320,7 +1330,7 @@ } } - RINOK(ReadForHeader(stream, h.gdOffset, table, numSectors)); + RINOK(ReadForHeader(stream, h.gdOffset, table, numSectors)) } const size_t clusterSize = (size_t)1 << ClusterBits; @@ -1332,12 +1342,12 @@ complexity += (UInt64)numGdeEntries << (k_NumMidBits + 2); { const UInt64 numVols2 = numVols; - RINOK(openCallback->SetTotal((numVols == 1) ? NULL : &numVols2, &complexity)); + RINOK(openCallback->SetTotal((numVols == 1) ? NULL : &numVols2, &complexity)) } if (numVols != 1) { const UInt64 volIndex2 = volIndex; - RINOK(openCallback->SetCompleted(numVols == 1 ? NULL : &volIndex2, &complexityStart)); + RINOK(openCallback->SetCompleted(numVols == 1 ? NULL : &volIndex2, &complexityStart)) } } @@ -1360,7 +1370,7 @@ { const UInt64 comp = complexityStart + ((UInt64)i << (k_NumMidBits + 2)); const UInt64 volIndex2 = volIndex; - RINOK(openCallback->SetCompleted(numVols == 1 ? NULL : &volIndex2, &comp)); + RINOK(openCallback->SetCompleted(numVols == 1 ? NULL : &volIndex2, &comp)) numProcessed_Prev = i; } @@ -1380,7 +1390,7 @@ } buf.Alloc(k_NumMidItems * 4); - RINOK(ReadForHeader(stream, v, buf, k_NumSectors)); + RINOK(ReadForHeader(stream, v, buf, k_NumSectors)) } for (size_t k = 0; k < k_NumMidItems; k++) @@ -1427,7 +1437,7 @@ } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _phySize = 0; @@ -1458,10 +1468,10 @@ } -STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream)) { COM_TRY_BEGIN - *stream = 0; + *stream = NULL; if (_unsupported) return S_FALSE; @@ -1496,7 +1506,7 @@ FOR_VECTOR (i, _extents) { - RINOK(_extents[i].InitAndSeek()); + RINOK(_extents[i].InitAndSeek()) } CMyComPtr streamTemp = this; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Wim/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Archive/Wim/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Wim/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Wim/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Wim/WimHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Wim/WimHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Wim/WimHandler.cpp 2022-03-30 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Wim/WimHandler.cpp 2023-03-26 12:00:00.000000000 +0000 @@ -95,7 +95,7 @@ } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -124,7 +124,7 @@ const CImageInfo &image2 = xml.Images[i]; if (image2.CTimeDefined) if (index < 0 || ::CompareFileTime(&image2.CTime, &xml.Images[index].CTime) < 0) - index = i; + index = (int)i; } if (index >= 0) prop = xml.Images[index].CTime; @@ -141,7 +141,7 @@ const CImageInfo &image2 = xml.Images[i]; if (image2.MTimeDefined) if (index < 0 || ::CompareFileTime(&image2.MTime, &xml.Images[index].MTime) > 0) - index = i; + index = (int)i; } if (index >= 0) prop = xml.Images[index].MTime; @@ -170,11 +170,11 @@ AString res; res.Add_UInt32(ver1); - res += '.'; + res.Add_Dot(); res.Add_UInt32(ver2); if (ver3 != 0) { - res += '.'; + res.Add_Dot(); res.Add_UInt32(ver3); } prop = res; @@ -245,7 +245,7 @@ if (h.PartNumber != 1) { s.Add_UInt32(h.PartNumber); - s += '.'; + s.Add_Dot(); } s += "swm"; prop = s; @@ -267,7 +267,7 @@ { const CHeader &header = _volumes[_xmls[i].VolIndex].Header; unsigned method = header.GetMethod(); - if (method < ARRAY_SIZE(k_Methods)) + if (method < Z7_ARRAY_SIZE(k_Methods)) methodMask |= ((UInt32)1 << method); else methodUnknown = method; @@ -280,7 +280,7 @@ unsigned numMethods = 0; - for (unsigned i = 0; i < ARRAY_SIZE(k_Methods); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_Methods); i++) { if (methodMask & ((UInt32)1 << i)) { @@ -365,8 +365,8 @@ { char temp[32]; - if ((unsigned)method < ARRAY_SIZE(k_Methods)) - strcpy(temp, k_Methods[(unsigned)method]); + if ((unsigned)method < Z7_ARRAY_SIZE(k_Methods)) + MyStringCopy(temp, k_Methods[(unsigned)method]); else ConvertUInt32ToString((UInt32)(unsigned)method, temp); @@ -382,7 +382,7 @@ } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -423,7 +423,7 @@ else */ AString s (FILES_DIR_NAME STRING_PATH_SEPARATOR); - s.Add_UInt32(item.StreamIndex); + s.Add_UInt32((UInt32)(Int32)item.StreamIndex); prop = s; } break; @@ -434,7 +434,7 @@ else { char sz[16]; - ConvertUInt32ToString(item.StreamIndex, sz); + ConvertUInt32ToString((UInt32)(Int32)item.StreamIndex, sz); /* AString s = sz; while (s.Len() < _nameLenForStreams) @@ -558,7 +558,7 @@ if (r.SolidIndex >= 0) { CSolid &ss = _db.Solids[r.SolidIndex]; - MethodToProp(ss.Method, ss.ChunkSizeBits, prop); + MethodToProp(ss.Method, (int)ss.ChunkSizeBits, prop); } } else @@ -567,8 +567,8 @@ int chunkSizeBits = -1; if (r.IsCompressed()) { - method = vol->Header.GetMethod(); - chunkSizeBits = vol->Header.ChunkSizeBits; + method = (int)vol->Header.GetMethod(); + chunkSizeBits = (int)vol->Header.ChunkSizeBits; } MethodToProp(method, chunkSizeBits, prop); } @@ -620,7 +620,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetRootProp(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetRootProp(PROPID propID, PROPVARIANT *value)) { // COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -670,9 +670,9 @@ return S_OK; } -STDMETHODIMP CHandler::GetRootRawProp(PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) +Z7_COM7F_IMF(CHandler::GetRootRawProp(PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType)) { - *data = 0; + *data = NULL; *dataSize = 0; *propType = 0; if (propID == kpidNtSecure && _db.Images.Size() != 0 && _db.NumExcludededItems != 0) @@ -694,20 +694,20 @@ }; -STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) +Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps)) { - *numProps = ARRAY_SIZE(kRawProps); + *numProps = Z7_ARRAY_SIZE(kRawProps); return S_OK; } -STDMETHODIMP CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID) +Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID)) { *propID = kRawProps[index]; - *name = 0; + *name = NULL; return S_OK; } -STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType) +Z7_COM7F_IMF(CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType)) { *parentType = NParentType::kDir; *parent = (UInt32)(Int32)-1; @@ -722,13 +722,13 @@ if (item.Parent >= 0) { if (_db.ExludedItem != item.Parent) - *parent = _db.Items[item.Parent].IndexInSorted; + *parent = (unsigned)_db.Items[item.Parent].IndexInSorted; } else { CImage &image = _db.Images[item.ImageIndex]; if (image.VirtualRootIndex >= 0) - *parent = _db.SortedItems.Size() + _numXmlItems + image.VirtualRootIndex; + *parent = _db.SortedItems.Size() + _numXmlItems + (unsigned)image.VirtualRootIndex; } } else @@ -736,7 +736,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) +Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType)) { *data = NULL; *dataSize = 0; @@ -842,8 +842,8 @@ { int dotPos = name.ReverseFind_Dot(); if (dotPos < 0) - dotPos = name.Len(); - _before.SetFrom(name.Ptr(), dotPos); + dotPos = (int)name.Len(); + _before.SetFrom(name.Ptr(), (unsigned)dotPos); _after = name.Ptr(dotPos); } @@ -856,7 +856,7 @@ } }; -STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *callback) +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *callback)) { COM_TRY_BEGIN @@ -963,7 +963,7 @@ numVolumes = header.NumParts; { NCOM::CPropVariant prop; - RINOK(openVolumeCallback->GetProperty(kpidName, &prop)); + RINOK(openVolumeCallback->GetProperty(kpidName, &prop)) if (prop.vt != VT_BSTR) break; seqName.InitName(prop.bstrVal); @@ -971,7 +971,7 @@ } } - RINOK(_db.FillAndCheck(_volumes)); + RINOK(_db.FillAndCheck(_volumes)) int defaultImageIndex = (int)_defaultImageNumber - 1; bool showImageNumber = (_db.Images.Size() != 1 && defaultImageIndex < 0); @@ -983,8 +983,8 @@ _showImageNumber = showImageNumber; - RINOK(_db.GenerateSortedItems(defaultImageIndex, showImageNumber)); - RINOK(_db.ExtractReparseStreams(_volumes, callback)); + RINOK(_db.GenerateSortedItems(defaultImageIndex, showImageNumber)) + RINOK(_db.ExtractReparseStreams(_volumes, callback)) /* wchar_t sz[16]; @@ -1001,7 +1001,7 @@ } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _firstVolumeIndex = -1; _phySize = 0; @@ -1019,11 +1019,11 @@ } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _db.SortedItems.Size() + _numXmlItems + _db.VirtualRoots.Size() + _numIgnoreItems; @@ -1048,12 +1048,12 @@ else { index -= _db.SortedItems.Size(); - if (index < (UInt32)_numXmlItems) + if (index < _numXmlItems) totalSize += _xmls[index].Data.Size(); } } - RINOK(extractCallback->SetTotal(totalSize)); + RINOK(extractCallback->SetTotal(totalSize)) UInt64 currentTotalUnPacked = 0; UInt64 currentItemUnPacked; @@ -1074,36 +1074,36 @@ lps->InSize = unpacker.TotalPacked; lps->OutSize = currentTotalUnPacked; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) if (i >= numItems) break; UInt32 index = allFilesMode ? i : indices[i]; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; CMyComPtr realOutStream; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) if (index >= _db.SortedItems.Size()) { if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) index -= _db.SortedItems.Size(); - if (index < (UInt32)_numXmlItems) + if (index < _numXmlItems) { const CByteBuffer &data = _xmls[index].Data; currentItemUnPacked = data.Size(); if (realOutStream) { - RINOK(WriteStream(realOutStream, (const Byte *)data, data.Size())); + RINOK(WriteStream(realOutStream, (const Byte *)data, data.Size())) realOutStream.Release(); } } - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } @@ -1114,11 +1114,11 @@ if (!item.IsDir) if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) realOutStream.Release(); RINOK(extractCallback->SetOperationResult(!item.IsDir && _db.ItemHasStream(item) ? NExtract::NOperationResult::kDataError : - NExtract::NOperationResult::kOK)); + NExtract::NOperationResult::kOK)) continue; } @@ -1128,7 +1128,7 @@ if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) Int32 opRes = NExtract::NOperationResult::kOK; if (streamIndex != prevSuccessStreamIndex || realOutStream) @@ -1156,7 +1156,7 @@ } realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } return S_OK; @@ -1164,7 +1164,7 @@ } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _db.SortedItems.Size() + _numXmlItems + @@ -1180,7 +1180,7 @@ _xmlError = false; } -STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) +Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps)) { InitDefaults(); @@ -1197,18 +1197,18 @@ { // some clients write 'x' property. So we support it UInt32 level = 0; - RINOK(ParsePropToUInt32(name.Ptr(1), prop, level)); + RINOK(ParsePropToUInt32(name.Ptr(1), prop, level)) } else if (name.IsEqualTo("is")) { - RINOK(PROPVARIANT_to_bool(prop, _set_showImageNumber)); + RINOK(PROPVARIANT_to_bool(prop, _set_showImageNumber)) _set_use_ShowImageNumber = true; } else if (name.IsEqualTo("im")) { UInt32 image = 9; - RINOK(ParsePropToUInt32(L"", prop, image)); - _defaultImageNumber = image; + RINOK(ParsePropToUInt32(L"", prop, image)) + _defaultImageNumber = (int)image; } else if (name.IsPrefixedBy_Ascii_NoCase("mt")) { @@ -1217,12 +1217,17 @@ { } else - return E_INVALIDARG; + { + bool processed = false; + RINOK(_timeOptions.Parse(name, prop, processed)) + if (!processed) + return E_INVALIDARG; + } } return S_OK; } -STDMETHODIMP CHandler::KeepModeForNextOpen() +Z7_COM7F_IMF(CHandler::KeepModeForNextOpen()) { _keepMode_ShowImageNumber = _showImageNumber; return S_OK; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Wim/WimHandler.h 7zip-23.01+dfsg/CPP/7zip/Archive/Wim/WimHandler.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Wim/WimHandler.h 2015-09-15 11:58:28.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Wim/WimHandler.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,10 +1,12 @@ // WimHandler.h -#ifndef __ARCHIVE_WIM_HANDLER_H -#define __ARCHIVE_WIM_HANDLER_H +#ifndef ZIP7_INC_ARCHIVE_WIM_HANDLER_H +#define ZIP7_INC_ARCHIVE_WIM_HANDLER_H #include "../../../Common/MyCom.h" +#include "../Common/HandlerOut.h" + #include "WimIn.h" namespace NArchive { @@ -12,15 +14,13 @@ static const Int32 kNumImagesMaxUpdate = (1 << 10); -class CHandler: - public IInArchive, - public IArchiveGetRawProps, - public IArchiveGetRootProps, - public IArchiveKeepModeForNextOpen, - public ISetProperties, - public IOutArchive, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_5( + IArchiveGetRawProps + , IArchiveGetRootProps + , IArchiveKeepModeForNextOpen + , ISetProperties + , IOutArchive +) CDatabase _db; UInt32 _version; bool _isOldVersion; @@ -49,11 +49,14 @@ UInt64 _phySize; int _firstVolumeIndex; + CHandlerTimeOptions _timeOptions; + void InitDefaults() { _set_use_ShowImageNumber = false; _set_showImageNumber = false; _defaultImageNumber = -1; + _timeOptions.Init(); } bool IsUpdateSupported() const @@ -83,19 +86,6 @@ HRESULT GetTime(IArchiveUpdateCallback *callback, UInt32 callbackIndex, Int32 arcIndex, PROPID propID, FILETIME &ft); public: CHandler(); - MY_UNKNOWN_IMP6( - IInArchive, - IArchiveGetRawProps, - IArchiveGetRootProps, - IArchiveKeepModeForNextOpen, - ISetProperties, - IOutArchive) - INTERFACE_IInArchive(;) - INTERFACE_IArchiveGetRawProps(;) - INTERFACE_IArchiveGetRootProps(;) - STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps); - STDMETHOD(KeepModeForNextOpen)(); - INTERFACE_IOutArchive(;) }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Wim/WimHandlerOut.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Wim/WimHandlerOut.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Wim/WimHandlerOut.cpp 2022-01-08 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Wim/WimHandlerOut.cpp 2023-03-26 12:00:00.000000000 +0000 @@ -27,8 +27,25 @@ namespace NArchive { namespace NWim { -static int AddUniqHash(const CStreamInfo *streams, CUIntVector &sorted, const Byte *h, int streamIndexForInsert) +static const unsigned k_NumSubVectors_Bits = 12; // must be <= 16 + +struct CSortedIndex +{ + CObjectVector Vectors; + + CSortedIndex() + { + const unsigned k_NumSubVectors = 1 << k_NumSubVectors_Bits; + Vectors.ClearAndReserve(k_NumSubVectors); + for (unsigned i = 0; i < k_NumSubVectors; i++) + Vectors.AddNew(); + } +}; + +static int AddUniqHash(const CStreamInfo *streams, CSortedIndex &sorted2, const Byte *h, int streamIndexForInsert) { + const unsigned hash = (((unsigned)h[0] << 8) | (unsigned)h[1]) >> (16 - k_NumSubVectors_Bits); + CUIntVector &sorted = sorted2.Vectors[hash]; unsigned left = 0, right = sorted.Size(); while (left != right) { @@ -42,7 +59,7 @@ break; if (i == kHashSize) - return index; + return (int)index; if (h[i] < hash2[i]) right = mid; @@ -50,8 +67,8 @@ left = mid + 1; } - if (streamIndexForInsert >= 0) - sorted.Insert(left, streamIndexForInsert); + if (streamIndexForInsert != -1) + sorted.Insert(left, (unsigned)streamIndexForInsert); return -1; } @@ -78,13 +95,13 @@ FILETIME CTime; FILETIME ATime; FILETIME MTime; - UInt32 Attrib; UInt64 FileID; UInt64 VolID; UString Name; UString ShortName; + UInt32 Attrib; int SecurityId; // -1: means no secutity ID bool IsDir; bool Skip; @@ -97,12 +114,19 @@ CMetaItem(): UpdateIndex(-1) , HashIndex(-1) + , Size(0) , FileID(0) , VolID(0) + , Attrib(0) , SecurityId(-1) + , IsDir(false) , Skip(false) , NumSkipAltStreams(0) - {} + { + FILETIME_Clear(CTime); + FILETIME_Clear(ATime); + FILETIME_Clear(MTime); + } }; @@ -128,7 +152,7 @@ const unsigned index = indexes[mid]; const int comp = Compare_HardLink_MetaItems(mi, metaItems[index]); if (comp == 0) - return index; + return (int)index; if (comp < 0) right = mid; else @@ -220,7 +244,7 @@ } -STDMETHODIMP CHandler::GetFileTimeType(UInt32 *type) +Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *type)) { *type = NFileTimeType::kWindows; return S_OK; @@ -229,8 +253,8 @@ HRESULT CHandler::GetOutProperty(IArchiveUpdateCallback *callback, UInt32 callbackIndex, Int32 arcIndex, PROPID propID, PROPVARIANT *value) { - if (arcIndex >= 0) - return GetProperty(arcIndex, propID, value); + if (arcIndex != -1) + return GetProperty((UInt32)arcIndex, propID, value); return callback->GetProperty(callbackIndex, propID, value); } @@ -239,7 +263,7 @@ { ft.dwLowDateTime = ft.dwHighDateTime = 0; NCOM::CPropVariant prop; - RINOK(GetOutProperty(callback, callbackIndex, arcIndex, propID, &prop)); + RINOK(GetOutProperty(callback, callbackIndex, arcIndex, propID, &prop)) if (prop.vt == VT_FILETIME) ft = prop.filetime; else if (prop.vt != VT_EMPTY) @@ -256,7 +280,7 @@ NCOM::CPropVariant prop; if (callback) { - RINOK(callback->GetRootProp(propID, &prop)); + RINOK(callback->GetRootProp(propID, &prop)) if (prop.vt == VT_FILETIME) { ft = prop.filetime; @@ -267,7 +291,7 @@ } if (arcRoot) { - RINOK(arcRoot->GetRootProp(propID, &prop)); + RINOK(arcRoot->GetRootProp(propID, &prop)) if (prop.vt == VT_FILETIME) { ft = prop.filetime; @@ -285,29 +309,29 @@ void CResource::WriteTo(Byte *p) const { - Set64(p, PackSize); + Set64(p, PackSize) p[7] = Flags; - Set64(p + 8, Offset); - Set64(p + 16, UnpackSize); + Set64(p + 8, Offset) + Set64(p + 16, UnpackSize) } void CHeader::WriteTo(Byte *p) const { memcpy(p, kSignature, kSignatureSize); - Set32(p + 8, kHeaderSizeMax); - Set32(p + 0xC, Version); - Set32(p + 0x10, Flags); - Set32(p + 0x14, ChunkSize); + Set32(p + 8, kHeaderSizeMax) + Set32(p + 0xC, Version) + Set32(p + 0x10, Flags) + Set32(p + 0x14, ChunkSize) memcpy(p + 0x18, Guid, 16); - Set16(p + 0x28, PartNumber); - Set16(p + 0x2A, NumParts); - Set32(p + 0x2C, NumImages); + Set16(p + 0x28, PartNumber) + Set16(p + 0x2A, NumParts) + Set32(p + 0x2C, NumImages) OffsetResource.WriteTo(p + 0x30); XmlResource.WriteTo(p + 0x48); MetadataResource.WriteTo(p + 0x60); IntegrityResource.WriteTo(p + 0x7C); - Set32(p + 0x78, BootIndex); + Set32(p + 0x78, BootIndex) memset(p + 0x94, 0, 60); } @@ -315,25 +339,22 @@ void CStreamInfo::WriteTo(Byte *p) const { Resource.WriteTo(p); - Set16(p + 0x18, PartNumber); - Set32(p + 0x1A, RefCount); + Set16(p + 0x18, PartNumber) + Set32(p + 0x1A, RefCount) memcpy(p + 0x1E, Hash, kHashSize); } -class CInStreamWithSha1: - public ISequentialInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + CInStreamWithSha1 + , ISequentialInStream +) CMyComPtr _stream; UInt64 _size; // NCrypto::NSha1::CContext _sha; - CAlignedBuffer _sha; + CAlignedBuffer1 _sha; CSha1 *Sha() { return (CSha1 *)(void *)(Byte *)_sha; } public: - MY_UNKNOWN_IMP1(IInStream) - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - CInStreamWithSha1(): _sha(sizeof(CSha1)) {} void SetStream(ISequentialInStream *stream) { _stream = stream; } void Init() @@ -346,10 +367,10 @@ void Final(Byte *digest) { Sha1_Final(Sha(), digest); } }; -STDMETHODIMP CInStreamWithSha1::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CInStreamWithSha1::Read(void *data, UInt32 size, UInt32 *processedSize)) { UInt32 realProcessedSize; - HRESULT result = _stream->Read(data, size, &realProcessedSize); + const HRESULT result = _stream->Read(data, size, &realProcessedSize); _size += realProcessedSize; Sha1_Update(Sha(), (const Byte *)data, realProcessedSize); if (processedSize) @@ -360,8 +381,8 @@ static void SetFileTimeToMem(Byte *p, const FILETIME &ft) { - Set32(p, ft.dwLowDateTime); - Set32(p + 4, ft.dwHighDateTime); + Set32(p, ft.dwLowDateTime) + Set32(p + 4, ft.dwHighDateTime) } static size_t WriteItem_Dummy(const CMetaItem &item) @@ -372,15 +393,15 @@ // we write fileNameLen + 2 + 2 to be same as original WIM. unsigned fileNameLen2 = (fileNameLen == 0 ? 0 : fileNameLen + 2); - unsigned shortNameLen = item.ShortName.Len() * 2; - unsigned shortNameLen2 = (shortNameLen == 0 ? 2 : shortNameLen + 4); + const unsigned shortNameLen = item.ShortName.Len() * 2; + const unsigned shortNameLen2 = (shortNameLen == 0 ? 2 : shortNameLen + 4); - size_t totalLen = ((kDirRecordSize + fileNameLen2 + shortNameLen2 + 6) & ~7); + size_t totalLen = ((kDirRecordSize + fileNameLen2 + shortNameLen2 + 6) & ~(unsigned)7); if (item.GetNumAltStreams() != 0) { if (!item.IsDir) { - UInt32 curLen = (((0x26 + 0) + 6) & ~7); + const UInt32 curLen = (((0x26 + 0) + 6) & ~(unsigned)7); totalLen += curLen; } FOR_VECTOR (i, item.AltStreams) @@ -390,7 +411,7 @@ continue; fileNameLen = ss.Name.Len() * 2; fileNameLen2 = (fileNameLen == 0 ? 0 : fileNameLen + 2 + 2); - UInt32 curLen = (((0x26 + fileNameLen2) + 6) & ~7); + const UInt32 curLen = (((0x26 + fileNameLen2) + 6) & ~(unsigned)7); totalLen += curLen; } } @@ -407,12 +428,12 @@ unsigned shortNameLen = item.ShortName.Len() * 2; unsigned shortNameLen2 = (shortNameLen == 0 ? 2 : shortNameLen + 4); - size_t totalLen = ((kDirRecordSize + fileNameLen2 + shortNameLen2 + 6) & ~7); + size_t totalLen = ((kDirRecordSize + fileNameLen2 + shortNameLen2 + 6) & ~(unsigned)7); memset(p, 0, totalLen); - Set64(p, totalLen); - Set64(p + 8, item.Attrib); - Set32(p + 0xC, (Int32)item.SecurityId); + Set64(p, totalLen) + Set64(p + 8, item.Attrib) + Set32(p + 0xC, (UInt32)(Int32)item.SecurityId) SetFileTimeToMem(p + 0x28, item.CTime); SetFileTimeToMem(p + 0x30, item.ATime); SetFileTimeToMem(p + 0x38, item.MTime); @@ -425,21 +446,21 @@ if (item.Reparse.Size() != 0) { UInt32 tag = GetUi32(item.Reparse); - Set32(p + 0x58, tag); + Set32(p + 0x58, tag) // Set32(p + 0x5C, 0); // probably it's always ZERO } else if (item.FileID != 0) { - Set64(p + 0x58, item.FileID); + Set64(p + 0x58, item.FileID) } - Set16(p + 0x62, (UInt16)shortNameLen); - Set16(p + 0x64, (UInt16)fileNameLen); + Set16(p + 0x62, (UInt16)shortNameLen) + Set16(p + 0x64, (UInt16)fileNameLen) unsigned i; for (i = 0; i * 2 < fileNameLen; i++) - Set16(p + kDirRecordSize + i * 2, (UInt16)item.Name[i]); + Set16(p + kDirRecordSize + i * 2, (UInt16)item.Name[i]) for (i = 0; i * 2 < shortNameLen; i++) - Set16(p + kDirRecordSize + fileNameLen2 + i * 2, (UInt16)item.ShortName[i]); + Set16(p + kDirRecordSize + fileNameLen2 + i * 2, (UInt16)item.ShortName[i]) if (item.GetNumAltStreams() == 0) { @@ -448,14 +469,14 @@ } else { - Set16(p + 0x60, (UInt16)(item.GetNumAltStreams() + (item.IsDir ? 0 : 1))); + Set16(p + 0x60, (UInt16)(item.GetNumAltStreams() + (item.IsDir ? 0 : 1))) p += totalLen; if (!item.IsDir) { - UInt32 curLen = (((0x26 + 0) + 6) & ~7); + const UInt32 curLen = (((0x26 + 0) + 6) & ~(unsigned)7); memset(p, 0, curLen); - Set64(p, curLen); + Set64(p, curLen) if (item.HashIndex >= 0) memcpy(p + 0x10, streams[item.HashIndex].Hash, kHashSize); totalLen += curLen; @@ -470,15 +491,15 @@ fileNameLen = ss.Name.Len() * 2; fileNameLen2 = (fileNameLen == 0 ? 0 : fileNameLen + 2 + 2); - UInt32 curLen = (((0x26 + fileNameLen2) + 6) & ~7); + UInt32 curLen = (((0x26 + fileNameLen2) + 6) & ~(unsigned)7); memset(p, 0, curLen); - Set64(p, curLen); + Set64(p, curLen) if (ss.HashIndex >= 0) memcpy(p + 0x10, streams[ss.HashIndex].Hash, kHashSize); - Set16(p + 0x24, (UInt16)fileNameLen); + Set16(p + 0x24, (UInt16)fileNameLen) for (i = 0; i * 2 < fileNameLen; i++) - Set16(p + 0x26 + i * 2, (UInt16)ss.Name[i]); + Set16(p + 0x26 + i * 2, (UInt16)ss.Name[i]) totalLen += curLen; p += curLen; } @@ -529,7 +550,7 @@ for (i = 0; i < tree.Dirs.Size(); i++) pos += WriteItem_Dummy(MetaItems[tree.Dirs[i].MetaIndex]); - Set64(dest + pos, 0); + Set64(dest + pos, 0) pos += 8; @@ -544,7 +565,7 @@ posStart += len; if (needCreateTree) { - Set64(dest + posStart - len + 0x10, pos); // subdirOffset + Set64(dest + posStart - len + 0x10, pos) // subdirOffset WriteTree(subDir, dest, pos); } } @@ -557,18 +578,18 @@ { const CMetaItem &mi = MetaItems[tree.MetaIndex]; if (mi.UpdateIndex >= 0) - UpdateIndexes.Add(mi.UpdateIndex); + UpdateIndexes.Add((unsigned)mi.UpdateIndex); FOR_VECTOR (si, mi.AltStreams) - UpdateIndexes.Add(mi.AltStreams[si].UpdateIndex); + UpdateIndexes.Add((unsigned)mi.AltStreams[si].UpdateIndex); } unsigned i; for (i = 0; i < tree.Files.Size(); i++) { const CMetaItem &mi = MetaItems[tree.Files[i]]; - UpdateIndexes.Add(mi.UpdateIndex); + UpdateIndexes.Add((unsigned)mi.UpdateIndex); FOR_VECTOR (si, mi.AltStreams) - UpdateIndexes.Add(mi.AltStreams[si].UpdateIndex); + UpdateIndexes.Add((unsigned)mi.AltStreams[si].UpdateIndex); } for (i = 0; i < tree.Dirs.Size(); i++) @@ -696,7 +717,7 @@ static void AddTrees(CObjectVector &trees, CObjectVector &metaItems, const CMetaItem &ri, int curTreeIndex) { while (curTreeIndex >= (int)trees.Size()) - trees.AddNew().Dirs.AddNew().MetaIndex = metaItems.Add(ri); + trees.AddNew().Dirs.AddNew().MetaIndex = (int)metaItems.Add(ri); } @@ -704,7 +725,7 @@ -STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 numItems, IArchiveUpdateCallback *callback) +Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 numItems, IArchiveUpdateCallback *callback)) { COM_TRY_BEGIN @@ -732,7 +753,7 @@ return E_NOTIMPL; CMyComPtr outStream; - RINOK(outSeqStream->QueryInterface(IID_IOutStream, (void **)&outStream)); + RINOK(outSeqStream->QueryInterface(IID_IOutStream, (void **)&outStream)) if (!outStream) return E_NOTIMPL; if (!callback) @@ -744,7 +765,7 @@ CMetaItem ri; // default DIR item FILETIME ftCur; NTime::GetCurUtcFileTime(ftCur); - ri.MTime = ri.ATime = ri.CTime = ftCur; + // ri.MTime = ri.ATime = ri.CTime = ftCur; ri.Attrib = FILE_ATTRIBUTE_DIRECTORY; ri.IsDir = true; @@ -765,7 +786,7 @@ { UInt32 indexInArchive; Int32 newData, newProps; - RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArchive)); + RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArchive)) if (newProps == 0) { if (indexInArchive >= _db.SortedItems.Size()) @@ -791,7 +812,7 @@ else { NCOM::CPropVariant prop; - RINOK(callback->GetProperty(i, kpidPath, &prop)); + RINOK(callback->GetProperty(i, kpidPath, &prop)) if (prop.vt != VT_BSTR) return E_INVALIDARG; @@ -851,11 +872,11 @@ UInt32 propType = 0; if (getRootProps) { - RINOK(getRootProps->GetRootRawProp(kpidNtSecure, &data, &dataSize, &propType)); + RINOK(getRootProps->GetRootRawProp(kpidNtSecure, &data, &dataSize, &propType)) } if (dataSize == 0 && isUpdate) { - RINOK(GetRootRawProp(kpidNtSecure, &data, &dataSize, &propType)); + RINOK(GetRootRawProp(kpidNtSecure, &data, &dataSize, &propType)) } if (dataSize != 0) { @@ -864,21 +885,21 @@ while (defaultImageIndex >= (int)secureBlocks.Size()) secureBlocks.AddNew(); CUniqBlocks &secUniqBlocks = secureBlocks[defaultImageIndex]; - rootItem.SecurityId = secUniqBlocks.AddUniq((const Byte *)data, dataSize); + rootItem.SecurityId = (int)secUniqBlocks.AddUniq((const Byte *)data, dataSize); } } IArchiveGetRootProps *thisGetRoot = isUpdate ? this : NULL; - RINOK(GetRootTime(getRootProps, thisGetRoot, kpidCTime, rootItem.CTime)); - RINOK(GetRootTime(getRootProps, thisGetRoot, kpidATime, rootItem.ATime)); - RINOK(GetRootTime(getRootProps, thisGetRoot, kpidMTime, rootItem.MTime)); + if (_timeOptions.Write_CTime.Val) RINOK(GetRootTime(getRootProps, thisGetRoot, kpidCTime, rootItem.CTime)) + if (_timeOptions.Write_ATime.Val) RINOK(GetRootTime(getRootProps, thisGetRoot, kpidATime, rootItem.ATime)) + if (_timeOptions.Write_MTime.Val) RINOK(GetRootTime(getRootProps, thisGetRoot, kpidMTime, rootItem.MTime)) { NCOM::CPropVariant prop; if (getRootProps) { - RINOK(getRootProps->GetRootProp(kpidAttrib, &prop)); + RINOK(getRootProps->GetRootProp(kpidAttrib, &prop)) if (prop.vt == VT_UI4) rootItem.Attrib = prop.ulVal; else if (prop.vt != VT_EMPTY) @@ -886,7 +907,7 @@ } if (prop.vt == VT_EMPTY && thisGetRoot) { - RINOK(GetRootProp(kpidAttrib, &prop)); + RINOK(GetRootProp(kpidAttrib, &prop)) if (prop.vt == VT_UI4) rootItem.Attrib = prop.ulVal; else if (prop.vt != VT_EMPTY) @@ -908,7 +929,7 @@ CUpdateItem ui; UInt32 indexInArchive; Int32 newData, newProps; - RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArchive)); + RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArchive)) if (newData == 0 || newProps == 0) { @@ -940,16 +961,16 @@ } if (newData == 0) - ui.InArcIndex = indexInArchive; + ui.InArcIndex = (Int32)indexInArchive; } // we set arcIndex only if we must use old props - Int32 arcIndex = (newProps ? -1 : indexInArchive); + const Int32 arcIndex = (newProps ? -1 : (Int32)indexInArchive); bool isDir = false; { NCOM::CPropVariant prop; - RINOK(GetOutProperty(callback, i, arcIndex, kpidIsDir, &prop)); + RINOK(GetOutProperty(callback, i, arcIndex, kpidIsDir, &prop)) if (prop.vt == VT_BOOL) isDir = (prop.boolVal != VARIANT_FALSE); else if (prop.vt != VT_EMPTY) @@ -959,7 +980,7 @@ bool isAltStream = false; { NCOM::CPropVariant prop; - RINOK(GetOutProperty(callback, i, arcIndex, kpidIsAltStream, &prop)); + RINOK(GetOutProperty(callback, i, arcIndex, kpidIsAltStream, &prop)) if (prop.vt == VT_BOOL) isAltStream = (prop.boolVal != VARIANT_FALSE); else if (prop.vt != VT_EMPTY) @@ -986,11 +1007,11 @@ if (newData) { - RINOK(callback->GetProperty(i, kpidSize, &prop)); + RINOK(callback->GetProperty(i, kpidSize, &prop)) } else { - RINOK(GetProperty(indexInArchive, kpidSize, &prop)); + RINOK(GetProperty(indexInArchive, kpidSize, &prop)) } if (prop.vt == VT_UI8) @@ -1002,7 +1023,7 @@ { NCOM::CPropVariant propPath; const wchar_t *path = NULL; - RINOK(GetOutProperty(callback, i, arcIndex, kpidPath, &propPath)); + RINOK(GetOutProperty(callback, i, arcIndex, kpidPath, &propPath)) if (propPath.vt == VT_BSTR) path = propPath.bstrVal; else if (propPath.vt != VT_EMPTY) @@ -1056,8 +1077,8 @@ CAltStream ss; ss.Size = size; ss.Name = end + 1; - ss.UpdateIndex = db.UpdateItems.Size(); - ui.AltStreamIndex = db.MetaItems[ui.MetaIndex].AltStreams.Add(ss); + ss.UpdateIndex = (int)db.UpdateItems.Size(); + ui.AltStreamIndex = (int)db.MetaItems[ui.MetaIndex].AltStreams.Add(ss); } else if (c == WCHAR_PATH_SEPARATOR || c == L'/') { @@ -1082,7 +1103,7 @@ if (!curItem->FindDir(db.MetaItems, fileName, indexOfDir)) { CDir &dir = curItem->Dirs.InsertNew(indexOfDir); - dir.MetaIndex = db.MetaItems.Add(ri); + dir.MetaIndex = (int)db.MetaItems.Add(ri); db.MetaItems.Back().Name = fileName; } curItem = &curItem->Dirs[indexOfDir]; @@ -1121,7 +1142,7 @@ // we want to support cases of c::substream, where c: is drive name if (colonPos == 1 && fileName[2] == L':' && IS_LETTER_CHAR(fileName[0])) colonPos = 2; - const UString mainName = fileName.Left(colonPos); + const UString mainName = fileName.Left((unsigned)colonPos); unsigned indexOfDir; if (mainName.IsEmpty()) @@ -1132,11 +1153,11 @@ { for (int j = (int)curItem->Files.Size() - 1; j >= 0; j--) { - int metaIndex = curItem->Files[j]; + const unsigned metaIndex = curItem->Files[j]; const CMetaItem &mi = db.MetaItems[metaIndex]; if (CompareFileNames(mainName, mi.Name) == 0) { - ui.MetaIndex = metaIndex; + ui.MetaIndex = (int)metaIndex; break; } } @@ -1147,8 +1168,8 @@ CAltStream ss; ss.Size = size; ss.Name = fileName.Ptr(colonPos + 1); - ss.UpdateIndex = db.UpdateItems.Size(); - ui.AltStreamIndex = db.MetaItems[ui.MetaIndex].AltStreams.Add(ss); + ss.UpdateIndex = (int)db.UpdateItems.Size(); + ui.AltStreamIndex = (int)db.MetaItems[ui.MetaIndex].AltStreams.Add(ss); } } } @@ -1158,7 +1179,7 @@ { if (!isRootImageDir) { - ui.MetaIndex = db.MetaItems.Size(); + ui.MetaIndex = (int)db.MetaItems.Size(); db.MetaItems.AddNew(); } @@ -1166,10 +1187,10 @@ mi.Size = size; mi.IsDir = isDir; mi.Name = fileName; - mi.UpdateIndex = db.UpdateItems.Size(); + mi.UpdateIndex = (int)db.UpdateItems.Size(); { NCOM::CPropVariant prop; - RINOK(GetOutProperty(callback, i, arcIndex, kpidAttrib, &prop)); + RINOK(GetOutProperty(callback, i, arcIndex, kpidAttrib, &prop)) if (prop.vt == VT_EMPTY) mi.Attrib = 0; else if (prop.vt == VT_UI4) @@ -1179,13 +1200,17 @@ if (isDir) mi.Attrib |= FILE_ATTRIBUTE_DIRECTORY; } - RINOK(GetTime(callback, i, arcIndex, kpidCTime, mi.CTime)); - RINOK(GetTime(callback, i, arcIndex, kpidATime, mi.ATime)); - RINOK(GetTime(callback, i, arcIndex, kpidMTime, mi.MTime)); + + if (arcIndex != -1 || _timeOptions.Write_CTime.Val) + RINOK(GetTime(callback, i, arcIndex, kpidCTime, mi.CTime)) + if (arcIndex != -1 || _timeOptions.Write_ATime.Val) + RINOK(GetTime(callback, i, arcIndex, kpidATime, mi.ATime)) + if (arcIndex != -1 || _timeOptions.Write_MTime.Val) + RINOK(GetTime(callback, i, arcIndex, kpidMTime, mi.MTime)) { NCOM::CPropVariant prop; - RINOK(GetOutProperty(callback, i, arcIndex, kpidShortName, &prop)); + RINOK(GetOutProperty(callback, i, arcIndex, kpidShortName, &prop)) if (prop.vt == VT_BSTR) mi.ShortName.SetFromBstr(prop.bstrVal); else if (prop.vt != VT_EMPTY) @@ -1208,7 +1233,7 @@ if (arcIndex >= 0) { - GetRawProp(arcIndex, kpidNtSecure, &data, &dataSize, &propType); + GetRawProp((UInt32)arcIndex, kpidNtSecure, &data, &dataSize, &propType); } else { @@ -1219,7 +1244,7 @@ { if (propType != NPropDataType::kRaw) return E_FAIL; - mi.SecurityId = secUniqBlocks.AddUniq((const Byte *)data, dataSize); + mi.SecurityId = (int)secUniqBlocks.AddUniq((const Byte *)data, dataSize); } data = NULL; @@ -1228,7 +1253,7 @@ if (arcIndex >= 0) { - GetRawProp(arcIndex, kpidNtReparse, &data, &dataSize, &propType); + GetRawProp((UInt32)arcIndex, kpidNtReparse, &data, &dataSize, &propType); } else { @@ -1254,7 +1279,7 @@ curItem->Dirs.InsertNew(indexOfDir).MetaIndex = ui.MetaIndex; } else - curItem->Files.Add(ui.MetaIndex); + curItem->Files.Add((unsigned)ui.MetaIndex); } } @@ -1272,7 +1297,7 @@ if (!isChangedImage[i]) numNewImages = i + 1; - AddTrees(trees, db.MetaItems, ri, numNewImages - 1); + AddTrees(trees, db.MetaItems, ri, (int)numNewImages - 1); for (i = 0; i < trees.Size(); i++) if (i >= isChangedImage.Size() || isChangedImage[i]) @@ -1354,7 +1379,7 @@ complexity += rs.PackSize; } - RINOK(callback->SetTotal(complexity)); + RINOK(callback->SetTotal(complexity)) UInt64 totalComplexity = complexity; NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder; @@ -1381,10 +1406,15 @@ header.ChunkSizeBits = srcHeader.ChunkSizeBits; } + CMyComPtr setRestriction; + outSeqStream->QueryInterface(IID_IStreamSetRestriction, (void **)&setRestriction); + if (setRestriction) + RINOK(setRestriction->SetRestriction(0, kHeaderSizeMax)) + { Byte buf[kHeaderSizeMax]; header.WriteTo(buf); - RINOK(WriteStream(outStream, buf, kHeaderSizeMax)); + RINOK(WriteStream(outStream, buf, kHeaderSizeMax)) } UInt64 curPos = kHeaderSizeMax; @@ -1393,7 +1423,7 @@ CMyComPtr inShaStream = inShaStreamSpec; CLimitedSequentialInStream *inStreamLimitedSpec = NULL; - CMyComPtr inStreamLimited; + CMyComPtr inStreamLimited; if (_volumes.Size() == 2) { inStreamLimitedSpec = new CLimitedSequentialInStream; @@ -1403,7 +1433,7 @@ CRecordVector streams; - CUIntVector sortedHashes; // indexes to streams, sorted by SHA1 + CSortedIndex sortedHashes; // indexes to streams, sorted by SHA1 // ---------- Copy unchanged data streams ---------- @@ -1415,7 +1445,7 @@ const CStreamInfo &siOld = _db.DataStreams[i]; const CResource &rs = siOld.Resource; - unsigned numRefs = streamsRefs[i]; + const unsigned numRefs = streamsRefs[i]; if (numRefs == 0) { @@ -1426,9 +1456,9 @@ } lps->InSize = lps->OutSize = complexity; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) - int streamIndex = streams.Size(); + const unsigned streamIndex = streams.Size(); CStreamInfo s; s.Resource = rs; s.PartNumber = 1; @@ -1462,16 +1492,16 @@ if (!rs.IsSolid() || rs.IsSolidSmall()) { - int find = AddUniqHash(&streams.Front(), sortedHashes, siOld.Hash, streamIndex); - if (find >= 0) + const int find = AddUniqHash(&streams.Front(), sortedHashes, siOld.Hash, (int)streamIndex); + if (find != -1) return E_FAIL; // two streams with same SHA-1 } if (!rs.IsSolid() || rs.IsSolidBig()) { - RINOK(_volumes[siOld.PartNumber].Stream->Seek(rs.Offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_volumes[siOld.PartNumber].Stream, rs.Offset)) inStreamLimitedSpec->Init(rs.PackSize); - RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress)) if (copyCoderSpec->TotalSize != rs.PackSize) return E_FAIL; s.Resource.Offset = curPos; @@ -1490,7 +1520,7 @@ for (i = 0; i < db.UpdateIndexes.Size(); i++) { lps->InSize = lps->OutSize = complexity; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) const CUpdateItem &ui = db.UpdateItems[db.UpdateIndexes[i]]; CMetaItem &mi = db.MetaItems[ui.MetaIndex]; UInt64 size = 0; @@ -1534,9 +1564,9 @@ const CStreamInfo &siOld = _db.DataStreams[item.StreamIndex]; - int index = AddUniqHash(&streams.Front(), sortedHashes, siOld.Hash, -1); + const int index = AddUniqHash(&streams.Front(), sortedHashes, siOld.Hash, -1); // we must have written that stream already - if (index < 0) + if (index == -1) return E_FAIL; if (ui.AltStreamIndex < 0) @@ -1562,7 +1592,7 @@ } else { - RINOK(res); + RINOK(res) int miIndex = -1; @@ -1581,23 +1611,23 @@ if (getProps2->GetProps2(&props) == S_OK) { mi.Attrib = props.Attrib; - mi.CTime = props.CTime; - mi.ATime = props.ATime; - mi.MTime = props.MTime; + if (_timeOptions.Write_CTime.Val) mi.CTime = props.CTime; + if (_timeOptions.Write_ATime.Val) mi.ATime = props.ATime; + if (_timeOptions.Write_MTime.Val) mi.MTime = props.MTime; mi.FileID = props.FileID_Low; if (props.NumLinks <= 1) mi.FileID = 0; mi.VolID = props.VolID; if (mi.FileID != 0) - miIndex = AddToHardLinkList(db.MetaItems, ui.MetaIndex, hlIndexes); + miIndex = AddToHardLinkList(db.MetaItems, (unsigned)ui.MetaIndex, hlIndexes); if (props.Size != size && props.Size != (UInt64)(Int64)-1) { - Int64 delta = (Int64)props.Size - (Int64)size; - Int64 newComplexity = totalComplexity + delta; + const Int64 delta = (Int64)props.Size - (Int64)size; + const Int64 newComplexity = (Int64)totalComplexity + delta; if (newComplexity > 0) { - totalComplexity = newComplexity; + totalComplexity = (UInt64)newComplexity; callback->SetTotal(totalComplexity); } mi.Size = props.Size; @@ -1620,19 +1650,19 @@ return E_FAIL; NCrypto::NSha1::CContext sha1; sha1.Init(); - size_t packSize = mi.Reparse.Size() - 8; + const size_t packSize = mi.Reparse.Size() - 8; sha1.Update((const Byte *)mi.Reparse + 8, packSize); Byte hash[kHashSize]; sha1.Final(hash); - int index = AddUniqHash(&streams.Front(), sortedHashes, hash, streams.Size()); + int index = AddUniqHash(&streams.Front(), sortedHashes, hash, (int)streams.Size()); - if (index >= 0) + if (index != -1) streams[index].RefCount++; else { - index = streams.Size(); - RINOK(WriteStream(outStream, (const Byte *)mi.Reparse + 8, packSize)); + index = (int)streams.Size(); + RINOK(WriteStream(outStream, (const Byte *)mi.Reparse + 8, packSize)) CStreamInfo s; s.Resource.PackSize = packSize; s.Resource.Offset = curPos; @@ -1655,6 +1685,10 @@ else { inShaStreamSpec->SetStream(fileInStream); + + CMyComPtr inSeekStream; + fileInStream.QueryInterface(IID_IInStream, (void **)&inSeekStream); + fileInStream.Release(); inShaStreamSpec->Init(); UInt64 offsetBlockSize = 0; @@ -1670,54 +1704,88 @@ } } */ + + // 22.02: we use additional read-only pass to calculate SHA-1 + bool needWritePass = true; + int index = -1; - RINOK(copyCoder->Code(inShaStream, outStream, NULL, NULL, progress)); - size = copyCoderSpec->TotalSize; - - if (size != 0) + if (inSeekStream /* && !sortedHashes.IsEmpty() */) { - Byte hash[kHashSize]; - UInt64 packSize = offsetBlockSize + size; - inShaStreamSpec->Final(hash); - - int index = AddUniqHash(&streams.Front(), sortedHashes, hash, streams.Size()); - - if (index >= 0) - { - streams[index].RefCount++; - outStream->Seek(-(Int64)packSize, STREAM_SEEK_CUR, &curPos); - outStream->SetSize(curPos); - } + RINOK(copyCoder->Code(inShaStream, NULL, NULL, NULL, progress)) + size = copyCoderSpec->TotalSize; + if (size == 0) + needWritePass = false; else { - index = streams.Size(); - CStreamInfo s; - s.Resource.PackSize = packSize; - s.Resource.Offset = curPos; - s.Resource.UnpackSize = size; - s.Resource.Flags = 0; - /* - if (useResourceCompression) - s.Resource.Flags = NResourceFlags::Compressed; - */ - s.PartNumber = 1; - s.RefCount = 1; - memcpy(s.Hash, hash, kHashSize); - curPos += packSize; + Byte hash[kHashSize]; + inShaStreamSpec->Final(hash); - streams.Add(s); + index = AddUniqHash(&streams.Front(), sortedHashes, hash, -1); + if (index != -1) + { + streams[index].RefCount++; + needWritePass = false; + } + else + { + RINOK(InStream_SeekToBegin(inSeekStream)) + inShaStreamSpec->Init(); + } } - + } + + if (needWritePass) + { + RINOK(copyCoder->Code(inShaStream, outStream, NULL, NULL, progress)) + size = copyCoderSpec->TotalSize; + } + + if (size != 0) + { + if (needWritePass) + { + Byte hash[kHashSize]; + const UInt64 packSize = offsetBlockSize + size; + inShaStreamSpec->Final(hash); + + index = AddUniqHash(&streams.Front(), sortedHashes, hash, (int)streams.Size()); + + if (index != -1) + { + streams[index].RefCount++; + outStream->Seek(-(Int64)packSize, STREAM_SEEK_CUR, &curPos); + outStream->SetSize(curPos); + } + else + { + index = (int)streams.Size(); + CStreamInfo s; + s.Resource.PackSize = packSize; + s.Resource.Offset = curPos; + s.Resource.UnpackSize = size; + s.Resource.Flags = 0; + /* + if (useResourceCompression) + s.Resource.Flags = NResourceFlags::Compressed; + */ + s.PartNumber = 1; + s.RefCount = 1; + memcpy(s.Hash, hash, kHashSize); + curPos += packSize; + + streams.Add(s); + } + } // needWritePass if (ui.AltStreamIndex < 0) mi.HashIndex = index; else mi.AltStreams[ui.AltStreamIndex].HashIndex = index; - } + } // (size != 0) } } fileInStream.Release(); complexity += size; - RINOK(callback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); + RINOK(callback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)) } while (secureBlocks.Size() < numNewImages) @@ -1730,14 +1798,14 @@ for (i = 0; i < numNewImages; i++) { lps->InSize = lps->OutSize = complexity; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) if (i < isChangedImage.Size() && !isChangedImage[i]) { CStreamInfo s = _db.MetaStreams[i]; - RINOK(_volumes[1].Stream->Seek(s.Resource.Offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_volumes[1].Stream, s.Resource.Offset)) inStreamLimitedSpec->Init(s.Resource.PackSize); - RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress)) if (copyCoderSpec->TotalSize != s.Resource.PackSize) return E_FAIL; @@ -1774,14 +1842,14 @@ CByteArr meta(pos); - Set32((Byte *)meta + 4, secBufs.Size()); // num security entries + Set32((Byte *)meta + 4, secBufs.Size()) // num security entries pos = kSecuritySize; if (secBufs.Size() == 0) { // we can write 0 here only if there is no security data, imageX does it, // but some programs expect size = 8 - Set32((Byte *)meta, 8); // size of security data + Set32((Byte *)meta, 8) // size of security data // Set32((Byte *)meta, 0); } else @@ -1789,7 +1857,7 @@ unsigned k; for (k = 0; k < secBufs.Size(); k++, pos += 8) { - Set64(meta + pos, secBufs[k].Size()); + Set64(meta + pos, secBufs[k].Size()) } for (k = 0; k < secBufs.Size(); k++) { @@ -1803,7 +1871,7 @@ } while ((pos & 7) != 0) meta[pos++] = 0; - Set32((Byte *)meta, (UInt32)pos); // size of security data + Set32((Byte *)meta, (UInt32)pos) // size of security data } db.Hashes = &streams.Front(); @@ -1833,14 +1901,14 @@ header.BootIndex = _bootIndex; } - RINOK(WriteStream(outStream, (const Byte *)meta, pos)); + RINOK(WriteStream(outStream, (const Byte *)meta, pos)) meta.Free(); curPos += pos; } } lps->InSize = lps->OutSize = complexity; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) header.OffsetResource.UnpackSize = header.OffsetResource.PackSize = (UInt64)streams.Size() * kStreamInfoSize; header.OffsetResource.Offset = curPos; @@ -1854,7 +1922,7 @@ { Byte buf[kStreamInfoSize]; streams[i].WriteTo(buf); - RINOK(WriteStream(outStream, buf, kStreamInfoSize)); + RINOK(WriteStream(outStream, buf, kStreamInfoSize)) curPos += kStreamInfoSize; } @@ -1862,7 +1930,7 @@ AddTagUInt64_ToString(xml, "TOTALBYTES", curPos); for (i = 0; i < trees.Size(); i++) { - CDir &tree = trees[i]; + const CDir &tree = trees[i]; CXmlItem item; if (_xmls.Size() == 1) @@ -1905,16 +1973,19 @@ UString utf16; if (!ConvertUTF8ToUnicode(xml, utf16)) return S_FALSE; - xmlSize = (utf16.Len() + 1) * 2; + xmlSize = ((size_t)utf16.Len() + 1) * 2; CByteArr xmlBuf(xmlSize); - Set16((Byte *)xmlBuf, 0xFEFF); + Set16((Byte *)xmlBuf, 0xFEFF) for (i = 0; i < (unsigned)utf16.Len(); i++) - Set16((Byte *)xmlBuf + 2 + i * 2, (UInt16)utf16[i]); - RINOK(WriteStream(outStream, (const Byte *)xmlBuf, xmlSize)); + { + Set16((Byte *)xmlBuf + 2 + (size_t)i * 2, (UInt16)utf16[i]) + } + RINOK(WriteStream(outStream, (const Byte *)xmlBuf, xmlSize)) } - header.XmlResource.UnpackSize = header.XmlResource.PackSize = xmlSize; + header.XmlResource.UnpackSize = + header.XmlResource.PackSize = xmlSize; header.XmlResource.Offset = curPos; header.XmlResource.Flags = NResourceFlags::kMetadata; @@ -1923,9 +1994,14 @@ { Byte buf[kHeaderSizeMax]; header.WriteTo(buf); - return WriteStream(outStream, buf, kHeaderSizeMax); + RINOK(WriteStream(outStream, buf, kHeaderSizeMax)) } + if (setRestriction) + RINOK(setRestriction->SetRestriction(0, 0)) + + return S_OK; + COM_TRY_END } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Wim/WimIn.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Wim/WimIn.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Wim/WimIn.cpp 2022-01-07 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Wim/WimIn.cpp 2023-03-26 12:00:00.000000000 +0000 @@ -99,7 +99,7 @@ if (!packBuf.Data) return E_OUTOFMEMORY; - RINOK(ReadStream_FALSE(inStream, packBuf.Data, inSize)); + RINOK(ReadStream_FALSE(inStream, packBuf.Data, inSize)) TotalPacked += inSize; @@ -124,7 +124,7 @@ else { res = lzmsDecoder->Code(packBuf.Data, inSize, unpackBuf.Data, outSize); - unpackedSize = lzmsDecoder->GetUnpackSize();; + unpackedSize = lzmsDecoder->GetUnpackSize(); } } @@ -141,7 +141,7 @@ if (outStream) { - RINOK(WriteStream(outStream, unpackBuf.Data, outSize)); + RINOK(WriteStream(outStream, unpackBuf.Data, outSize)) } return res; @@ -168,7 +168,7 @@ CMyComPtr limitedStream = limitedStreamSpec; limitedStreamSpec->SetStream(inStream); - RINOK(inStream->Seek(resource.Offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(inStream, resource.Offset)) if (resource.PackSize != resource.UnpackSize) return S_FALSE; @@ -221,7 +221,7 @@ size_t cur = chunkSize - offsetInChunk; if (cur > rem) cur = (size_t)rem; - RINOK(WriteStream(outStream, unpackBuf.Data + offsetInChunk, cur)); + RINOK(WriteStream(outStream, unpackBuf.Data + offsetInChunk, cur)) outProcessed += cur; rem -= cur; offsetInChunk = 0; @@ -233,20 +233,20 @@ if (rem == 0) return S_OK; - UInt64 offset = ss.Chunks[chunkIndex]; - UInt64 packSize = ss.GetChunkPackSize(chunkIndex); + const UInt64 offset = ss.Chunks[chunkIndex]; + const UInt64 packSize = ss.GetChunkPackSize(chunkIndex); const CResource &rs = db->DataStreams[ss.StreamIndex].Resource; - RINOK(inStream->Seek(rs.Offset + ss.HeadersSize + offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(inStream, rs.Offset + ss.HeadersSize + offset)) size_t cur = chunkSize; - UInt64 unpackRem = ss.UnpackSize - ((UInt64)chunkIndex << chunkSizeBits); + const UInt64 unpackRem = ss.UnpackSize - ((UInt64)chunkIndex << chunkSizeBits); if (cur > unpackRem) cur = (size_t)unpackRem; _solidIndex = -1; _unpackedChunkIndex = 0; - HRESULT res = UnpackChunk(inStream, ss.Method, chunkSizeBits, (size_t)packSize, cur, NULL); + const HRESULT res = UnpackChunk(inStream, (unsigned)ss.Method, chunkSizeBits, (size_t)packSize, cur, NULL); if (res != S_OK) { @@ -266,11 +266,11 @@ if (cur > rem) cur = (size_t)rem; - RINOK(WriteStream(outStream, unpackBuf.Data + offsetInChunk, cur)); + RINOK(WriteStream(outStream, unpackBuf.Data + offsetInChunk, cur)) if (progress) { - RINOK(progress->SetRatioInfo(&packProcessed, &outProcessed)); + RINOK(progress->SetRatioInfo(&packProcessed, &outProcessed)) packProcessed += packSize; outProcessed += cur; } @@ -311,8 +311,8 @@ if (sizesBufSize != sizesBufSize64) return E_OUTOFMEMORY; sizesBuf.AllocAtLeast(sizesBufSize); - RINOK(inStream->Seek(baseOffset, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(inStream, sizesBuf, sizesBufSize)); + RINOK(InStream_SeekSet(inStream, baseOffset)) + RINOK(ReadStream_FALSE(inStream, sizesBuf, sizesBufSize)) baseOffset += sizesBufSize64; numChunks = (size_t)numChunks64; } @@ -341,11 +341,11 @@ if (inSize != inSize64) return S_FALSE; - RINOK(inStream->Seek(baseOffset + offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(inStream, baseOffset + offset)) if (progress) { - RINOK(progress->SetRatioInfo(&offset, &outProcessed)); + RINOK(progress->SetRatioInfo(&offset, &outProcessed)) } size_t outSize = (size_t)1 << chunkSizeBits; @@ -353,7 +353,7 @@ if (outSize > rem) outSize = (size_t)rem; - RINOK(UnpackChunk(inStream, header.GetMethod(), chunkSizeBits, inSize, outSize, outStream)); + RINOK(UnpackChunk(inStream, header.GetMethod(), chunkSizeBits, inSize, outSize, outStream)) outProcessed += outSize; offset = nextOffset; @@ -494,8 +494,8 @@ void CDatabase::GetItemPath(unsigned index1, bool showImageNumber, NWindows::NCOM::CPropVariant &path) const { unsigned size = 0; - int index = index1; - int imageIndex = Items[index].ImageIndex; + int index = (int)index1; + const int imageIndex = Items[index].ImageIndex; const CImage &image = Images[imageIndex]; unsigned newLevel = 0; @@ -545,7 +545,7 @@ else if (needColon) s[0] = L':'; - index = index1; + index = (int)index1; wchar_t separator = 0; for (;;) @@ -597,7 +597,7 @@ if (OpenCallback && (Items.Size() & 0xFFFF) == 0) { UInt64 numFiles = Items.Size(); - RINOK(OpenCallback->SetCompleted(&numFiles, NULL)); + RINOK(OpenCallback->SetCompleted(&numFiles, NULL)) } const size_t rem = DirSize - pos; @@ -664,7 +664,7 @@ item.Offset = pos; item.Parent = parent; - item.ImageIndex = Images.Size() - 1; + item.ImageIndex = (int)Images.Size() - 1; const unsigned prevIndex = Items.Add(item); @@ -677,7 +677,8 @@ return S_FALSE; const Byte *p2 = DirData + pos; const UInt64 len2 = Get64(p2); - if ((len2 & align) != 0 || rem2 < len2 || len2 < (IsOldVersion ? 0x18 : 0x28)) + if ((len2 & align) != 0 || rem2 < len2 + || len2 < (unsigned)(IsOldVersion ? 0x18 : 0x28)) return S_FALSE; DirProcessed += (size_t)len2; @@ -742,8 +743,8 @@ CItem item2; item2.Offset = pos; item2.IsAltStream = true; - item2.Parent = prevIndex; - item2.ImageIndex = Images.Size() - 1; + item2.Parent = (int)prevIndex; + item2.ImageIndex = (int)Images.Size() - 1; Items.Add(item2); } @@ -775,7 +776,7 @@ if (item.IsDir && subdirOffset != 0) { - RINOK(ParseDirItem((size_t)subdirOffset, prevIndex)); + RINOK(ParseDirItem((size_t)subdirOffset, (int)prevIndex)) } } } @@ -864,7 +865,7 @@ DirStartOffset = DirProcessed = pos; image.StartItem = Items.Size(); - RINOK(ParseDirItem(pos, parent)); + RINOK(ParseDirItem(pos, parent)) image.NumItems = Items.Size() - image.StartItem; if (DirProcessed == DirSize) @@ -899,27 +900,27 @@ ChunkSizeBits = kChunkSizeBits; if (ChunkSize != 0) { - int log = GetLog(ChunkSize); + const int log = GetLog(ChunkSize); if (log < 12) return S_FALSE; - ChunkSizeBits = log; + ChunkSizeBits = (unsigned)log; } } - _IsOldVersion = false; - _IsNewVersion = false; + _isOldVersion = false; + _isNewVersion = false; if (IsSolidVersion()) - _IsNewVersion = true; + _isNewVersion = true; else { if (Version < 0x010900) return S_FALSE; - _IsOldVersion = (Version <= 0x010A00); + _isOldVersion = (Version <= 0x010A00); // We don't know details about 1.11 version. So we use headerSize to guess exact features. if (Version == 0x010B00 && headerSize == 0x60) - _IsOldVersion = true; - _IsNewVersion = (Version >= 0x010D00); + _isOldVersion = true; + _isNewVersion = (Version >= 0x010D00); } unsigned offset; @@ -973,7 +974,7 @@ HRESULT ReadHeader(IInStream *inStream, CHeader &h, UInt64 &phySize) { Byte p[kHeaderSizeMax]; - RINOK(ReadStream_FALSE(inStream, p, kHeaderSizeMax)); + RINOK(ReadStream_FALSE(inStream, p, kHeaderSizeMax)) if (memcmp(p, kSignature, kSignatureSize) != 0) return S_FALSE; return h.Parse(p, phySize); @@ -985,7 +986,7 @@ CByteBuffer offsetBuf; CUnpacker unpacker; - RINOK(unpacker.UnpackData(inStream, h.OffsetResource, h, NULL, offsetBuf, NULL)); + RINOK(unpacker.UnpackData(inStream, h.OffsetResource, h, NULL, offsetBuf, NULL)) const size_t streamInfoSize = h.IsOldVersion() ? kStreamInfoSize + 2 : kStreamInfoSize; { @@ -1087,7 +1088,7 @@ IsOldVersion = h.IsOldVersion(); IsOldVersion9 = (h.Version == 0x10900); - RINOK(ReadStreams(inStream, h, *this)); + RINOK(ReadStreams(inStream, h, *this)) bool needBootMetadata = !h.MetadataResource.IsEmpty(); unsigned numNonDeletedImages = 0; @@ -1101,14 +1102,14 @@ if (h.PartNumber != 1 || si.PartNumber != h.PartNumber) continue; - const int userImage = Images.Size() + GetStartImageIndex(); + const unsigned userImage = Images.Size() + GetStartImageIndex(); CImage &image = Images.AddNew(); SetRootNames(image, userImage); CByteBuffer &metadata = image.Meta; Byte hash[kHashSize]; - RINOK(unpacker.UnpackData(inStream, si.Resource, h, this, metadata, hash)); + RINOK(unpacker.UnpackData(inStream, si.Resource, h, this, metadata, hash)) if (memcmp(hash, si.Hash, kHashSize) != 0 && !(h.IsOldVersion() && IsEmptySha(si.Hash))) @@ -1119,7 +1120,7 @@ if (Items.IsEmpty()) Items.ClearAndReserve(numItemsReserve); - RINOK(ParseImageDirs(metadata, -1)); + RINOK(ParseImageDirs(metadata, -1)) if (needBootMetadata) { @@ -1166,12 +1167,12 @@ } -#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } +#define RINOZ(x) { int _tt_ = (x); if (_tt_ != 0) return _tt_; } static int CompareStreamsByPos(const CStreamInfo *p1, const CStreamInfo *p2, void * /* param */) { - RINOZ(MyCompare(p1->PartNumber, p2->PartNumber)); - RINOZ(MyCompare(p1->Resource.Offset, p2->Resource.Offset)); + RINOZ(MyCompare(p1->PartNumber, p2->PartNumber)) + RINOZ(MyCompare(p1->Resource.Offset, p2->Resource.Offset)) return MyCompare(p1->Resource.PackSize, p2->Resource.PackSize); } @@ -1192,11 +1193,11 @@ unsigned left = 0, right = sorted.Size(); while (left != right) { - unsigned mid = (left + right) / 2; - unsigned streamIndex = sorted[mid]; - UInt32 id2 = streams[streamIndex].Id; + const unsigned mid = (left + right) / 2; + const unsigned streamIndex = sorted[mid]; + const UInt32 id2 = streams[streamIndex].Id; if (id == id2) - return streamIndex; + return (int)streamIndex; if (id < id2) right = mid; else @@ -1210,15 +1211,15 @@ unsigned left = 0, right = sorted.Size(); while (left != right) { - unsigned mid = (left + right) / 2; - unsigned streamIndex = sorted[mid]; + const unsigned mid = (left + right) / 2; + const unsigned streamIndex = sorted[mid]; const Byte *hash2 = streams[streamIndex].Hash; unsigned i; for (i = 0; i < kHashSize; i++) if (hash[i] != hash2[i]) break; if (i == kHashSize) - return streamIndex; + return (int)streamIndex; if (hash[i] < hash2[i]) right = mid; else @@ -1237,8 +1238,8 @@ return i1.IsDir ? -1 : 1; if (i1.IsAltStream != i2.IsAltStream) return i1.IsAltStream ? 1 : -1; - RINOZ(MyCompare(i1.StreamIndex, i2.StreamIndex)); - RINOZ(MyCompare(i1.ImageIndex, i2.ImageIndex)); + RINOZ(MyCompare(i1.StreamIndex, i2.StreamIndex)) + RINOZ(MyCompare(i1.ImageIndex, i2.ImageIndex)) return MyCompare(i1.Offset, i2.Offset); } @@ -1286,7 +1287,7 @@ if (si.RefCount != 1) return S_FALSE; - r.SolidIndex = Solids.Size(); + r.SolidIndex = (int)Solids.Size(); CSolid &ss = Solids.AddNew(); ss.StreamIndex = k; @@ -1300,8 +1301,8 @@ const CVolume &vol = volumes[si.PartNumber]; IInStream *inStream = vol.Stream; - RINOK(inStream->Seek(r.Offset, STREAM_SEEK_SET, NULL)); - RINOK(ReadStream_FALSE(inStream, (Byte *)header, kSolidHeaderSize)); + RINOK(InStream_SeekSet(inStream, r.Offset)) + RINOK(ReadStream_FALSE(inStream, (Byte *)header, kSolidHeaderSize)) ss.UnpackSize = GetUi64(header); @@ -1313,11 +1314,11 @@ return S_FALSE; const UInt32 solidChunkSize = GetUi32(header + 8); - int log = GetLog(solidChunkSize); + const int log = GetLog(solidChunkSize); if (log < 8 || log > 31) return S_FALSE; - ss.ChunkSizeBits = log; - ss.Method = GetUi32(header + 12); + ss.ChunkSizeBits = (unsigned)log; + ss.Method = (Int32)GetUi32(header + 12); UInt64 numChunks64 = (ss.UnpackSize + (((UInt32)1 << ss.ChunkSizeBits) - 1)) >> ss.ChunkSizeBits; UInt64 sizesBufSize64 = 4 * numChunks64; @@ -1327,7 +1328,7 @@ return E_OUTOFMEMORY; sizesBuf.AllocAtLeast(sizesBufSize); - RINOK(ReadStream_FALSE(inStream, sizesBuf, sizesBufSize)); + RINOK(ReadStream_FALSE(inStream, sizesBuf, sizesBufSize)) size_t numChunks = (size_t)numChunks64; ss.Chunks.Alloc(numChunks + 1); @@ -1381,14 +1382,14 @@ CSolid &ss = Solids[solidIndex]; if (r.Offset < ss.SolidOffset) return S_FALSE; - UInt64 relat = r.Offset - ss.SolidOffset; + const UInt64 relat = r.Offset - ss.SolidOffset; if (relat > ss.UnpackSize) return S_FALSE; if (r.PackSize > ss.UnpackSize - relat) return S_FALSE; - r.SolidIndex = solidIndex; + r.SolidIndex = (int)solidIndex; if (ss.FirstSmallStream < 0) - ss.FirstSmallStream = k; + ss.FirstSmallStream = (int)k; sortedByHash.AddInReserved(k); // ss.NumRefs++; @@ -1542,7 +1543,7 @@ { CItem item; item.Offset = 0; - item.StreamIndex = i; + item.StreamIndex = (int)i; item.ImageIndex = -1; Items.Add(item); ThereAreDeletedStreams = true; @@ -1591,7 +1592,7 @@ if (NumExcludededItems != 0) { - ExludedItem = startItem; + ExludedItem = (int)startItem; startItem += NumExcludededItems; } @@ -1603,7 +1604,7 @@ SortedItems.Sort(CompareItems, this); for (i = 0; i < SortedItems.Size(); i++) - Items[SortedItems[i]].IndexInSorted = i; + Items[SortedItems[i]].IndexInSorted = (int)i; if (showImageNumber) for (i = 0; i < Images.Size(); i++) @@ -1611,7 +1612,7 @@ CImage &image = Images[i]; if (image.NumEmptyRootItems != 0) continue; - image.VirtualRootIndex = VirtualRoots.Size(); + image.VirtualRootIndex = (int)VirtualRoots.Size(); VirtualRoots.Add(i); } @@ -1681,7 +1682,7 @@ if ((unpacker.TotalPacked - totalPackedPrev) >= ((UInt32)1 << 16)) { UInt64 numFiles = Items.Size(); - RINOK(openCallback->SetCompleted(&numFiles, &unpacker.TotalPacked)); + RINOK(openCallback->SetCompleted(&numFiles, &unpacker.TotalPacked)) totalPackedPrev = unpacker.TotalPacked; } } @@ -1715,7 +1716,7 @@ if (res == S_FALSE) continue; - RINOK(res); + RINOK(res) if (memcmp(digest, si.Hash, kHashSize) != 0 // && !(h.IsOldVersion() && IsEmptySha(si.Hash)) @@ -1729,11 +1730,11 @@ CByteBuffer &reparse = ReparseItems.AddNew(); reparse.Alloc(8 + buf.Size()); Byte *dest = (Byte *)reparse; - SetUi32(dest, tag); - SetUi32(dest + 4, (UInt32)buf.Size()); + SetUi32(dest, tag) + SetUi32(dest + 4, (UInt32)buf.Size()) if (buf.Size() != 0) memcpy(dest + 8, buf, buf.Size()); - ItemToReparse[itemIndex] = ReparseItems.Size() - 1; + ItemToReparse[itemIndex] = (int)ReparseItems.Size() - 1; } return S_OK; @@ -1856,7 +1857,7 @@ return false; } - imageInfo.ItemIndexInXml = i; + imageInfo.ItemIndexInXml = (int)i; Images.Add(imageInfo); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Wim/WimIn.h 7zip-23.01+dfsg/CPP/7zip/Archive/Wim/WimIn.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Wim/WimIn.h 2018-12-28 10:40:37.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Wim/WimIn.h 2023-03-26 12:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Archive/WimIn.h -#ifndef __ARCHIVE_WIM_IN_H -#define __ARCHIVE_WIM_IN_H +#ifndef ZIP7_INC_ARCHIVE_WIM_IN_H +#define ZIP7_INC_ARCHIVE_WIM_IN_H #include "../../../../C/Alloc.h" @@ -192,7 +192,7 @@ UInt64 UnpackSize; int Method; - int ChunkSizeBits; + unsigned ChunkSizeBits; UInt64 HeadersSize; // size_t NumChunks; @@ -258,8 +258,8 @@ UInt32 NumImages; UInt32 BootIndex; - bool _IsOldVersion; // 1.10- - bool _IsNewVersion; // 1.13+ or 0.14 + bool _isOldVersion; // 1.10- + bool _isNewVersion; // 1.13+ or 0.14 CResource OffsetResource; CResource XmlResource; @@ -295,8 +295,8 @@ return mask; } - bool IsOldVersion() const { return _IsOldVersion; } - bool IsNewVersion() const { return _IsNewVersion; } + bool IsOldVersion() const { return _isOldVersion; } + bool IsNewVersion() const { return _isNewVersion; } bool IsSolidVersion() const { return (Version == k_Version_Solid); } bool AreFromOnArchive(const CHeader &h) @@ -457,7 +457,7 @@ bool RefCountError; bool HeadersError; - bool GetStartImageIndex() const { return IsOldVersion9 ? 0 : 1; } + unsigned GetStartImageIndex() const { return IsOldVersion9 ? 0 : 1; } unsigned GetDirAlignMask() const { return IsOldVersion9 ? 3 : 7; } // User Items can contain all images or just one image from all. diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/XarHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/XarHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/XarHandler.cpp 2021-09-04 11:14:58.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/XarHandler.cpp 2023-03-27 10:00:00.000000000 +0000 @@ -103,11 +103,10 @@ } }; -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_CHandler_IInArchive_1( + IInArchiveGetStream +) UInt64 _dataStartPos; CMyComPtr _inStream; CByteArr _xml; @@ -120,10 +119,6 @@ HRESULT Open2(IInStream *stream); HRESULT Extract(IInStream *stream); -public: - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); }; static const Byte kArcProps[] = @@ -187,7 +182,7 @@ return numSecs * 10000000; } -static int HexToByte(unsigned char c) +static int HexToByte(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'A' && c <= 'F') return c - 'A' + 10; @@ -197,7 +192,7 @@ static bool ParseSha1(const CXmlItem &item, const char *name, Byte *digest) { - int index = item.FindSubTag(name); + const int index = item.FindSubTag(name); if (index < 0) return false; const CXmlItem &checkItem = item.SubItems[index]; @@ -209,8 +204,8 @@ return false; for (unsigned i = 0; i < s.Len(); i += 2) { - int b0 = HexToByte(s[i]); - int b1 = HexToByte(s[i + 1]); + const int b0 = HexToByte(s[i]); + const int b1 = HexToByte(s[i + 1]); if (b0 < 0 || b1 < 0) return false; digest[i / 2] = (Byte)((b0 << 4) | b1); @@ -228,7 +223,7 @@ { CFile file; file.Parent = parent; - parent = files.Size(); + parent = (int)files.Size(); file.Name = item.GetSubStringForTag("name"); const AString type (item.GetSubStringForTag("type")); if (type == "directory") @@ -307,8 +302,7 @@ { const UInt32 kHeaderSize = 0x1C; Byte buf[kHeaderSize]; - RINOK(ReadStream_FALSE(stream, buf, kHeaderSize)); - + RINOK(ReadStream_FALSE(stream, buf, kHeaderSize)) UInt32 size = Get16(buf + 4); // UInt32 ver = Get16(buf + 6); // == 1 if (Get32(buf) != 0x78617221 || size != kHeaderSize) @@ -341,7 +335,7 @@ CMyComPtr outStreamLim(outStreamLimSpec); outStreamLimSpec->Init(_xml, (size_t)unpackSize); - RINOK(zlibCoder->Code(inStreamLim, outStreamLim, NULL, NULL, NULL)); + RINOK(zlibCoder->Code(inStreamLim, outStreamLim, NULL, NULL, NULL)) if (outStreamLimSpec->GetPos() != (size_t)unpackSize) return S_FALSE; @@ -370,7 +364,7 @@ file.UpdateTotalPackSize(totalPackSize); if (file.Name == "Payload" || file.Name == "Content") { - _mainSubfile = i; + _mainSubfile = (Int32)(int)i; numMainFiles++; } else if (file.Name == "PackageInfo") @@ -385,9 +379,9 @@ return S_OK; } -STDMETHODIMP CHandler::Open(IInStream *stream, +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openArchiveCallback */) + IArchiveOpenCallback * /* openArchiveCallback */)) { COM_TRY_BEGIN { @@ -400,7 +394,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _phySize = 0; _inStream.Release(); @@ -412,7 +406,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _files.Size() #ifdef XAR_SHOW_RAW @@ -443,7 +437,7 @@ } } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -460,7 +454,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -486,8 +480,8 @@ case kpidPath: { AString path; - int cur = index; - do + unsigned cur = index; + for (;;) { const CFile &item2 = _files[cur]; if (!path.IsEmpty()) @@ -496,9 +490,10 @@ path.Insert(0, "unknown"); else path.Insert(0, item2.Name); - cur = item2.Parent; + cur = (unsigned)item2.Parent; + if (item2.Parent < 0) + break; } - while (cur >= 0); Utf8StringToProp(path, prop); break; @@ -529,11 +524,11 @@ COM_TRY_END } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _files.Size(); if (numItems == 0) @@ -597,28 +592,28 @@ lps->OutSize = currentUnpTotal; currentPackSize = 0; currentUnpSize = 0; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - UInt32 index = allFilesMode ? i : indices[i]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + const UInt32 index = allFilesMode ? i : indices[i]; + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) if (index < _files.Size()) { const CFile &item = _files[index]; if (item.IsDir) { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->PrepareOperation(askMode)) + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) continue; } } if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) outStreamSha1Spec->SetStream(realOutStream); realOutStream.Release(); @@ -629,7 +624,7 @@ { outStreamSha1Spec->Init(false); outStreamLimSpec->Init(_xmlLen); - RINOK(WriteStream(outStream, _xml, _xmlLen)); + RINOK(WriteStream(outStream, _xml, _xmlLen)) currentPackSize = currentUnpSize = _xmlLen; } else @@ -641,7 +636,7 @@ currentPackSize = item.PackSize; currentUnpSize = item.Size; - RINOK(_inStream->Seek(_dataStartPos + item.Offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_inStream, _dataStartPos + item.Offset)) inStreamSpec->Init(item.PackSize); outStreamSha1Spec->Init(item.Sha1IsDefined); outStreamLimSpec->Init(item.Size); @@ -696,13 +691,13 @@ } } outStreamSha1Spec->ReleaseStream(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } return S_OK; COM_TRY_END } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { *stream = NULL; COM_TRY_BEGIN @@ -726,7 +721,7 @@ static const Byte k_Signature[] = { 'x', 'a', 'r', '!', 0, 0x1C }; REGISTER_ARC_I( - "Xar", "xar pkg xip", 0, 0xE1, + "Xar", "xar pkg xip", NULL, 0xE1, k_Signature, 0, 0, diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/XzHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/XzHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/XzHandler.cpp 2022-05-03 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/XzHandler.cpp 2023-03-27 10:00:00.000000000 +0000 @@ -43,24 +43,39 @@ }; -class CHandler: +Z7_class_CHandler_final: public IInArchive, public IArchiveOpenSeq, public IInArchiveGetStream, public ISetProperties, - - #ifndef EXTRACT_ONLY + #ifndef Z7_EXTRACT_ONLY public IOutArchive, - #endif - + #endif public CMyUnknownImp, + #ifndef Z7_EXTRACT_ONLY + public CMultiMethodProps + #else + public CCommonMethodProps + #endif +{ + Z7_COM_QI_BEGIN2(IInArchive) + Z7_COM_QI_ENTRY(IArchiveOpenSeq) + Z7_COM_QI_ENTRY(IInArchiveGetStream) + Z7_COM_QI_ENTRY(ISetProperties) + #ifndef Z7_EXTRACT_ONLY + Z7_COM_QI_ENTRY(IOutArchive) + #endif + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(IInArchive) + Z7_IFACE_COM7_IMP(IArchiveOpenSeq) + Z7_IFACE_COM7_IMP(IInArchiveGetStream) + Z7_IFACE_COM7_IMP(ISetProperties) + #ifndef Z7_EXTRACT_ONLY + Z7_IFACE_COM7_IMP(IOutArchive) + #endif - #ifndef EXTRACT_ONLY - public CMultiMethodProps - #else - public CCommonMethodProps - #endif -{ CXzStatInfo _stat; // it's stat from backward parsing CXzStatInfo _stat2; // it's data from forward parsing, if the decoder was called SRes _stat2_decode_SRes; @@ -81,7 +96,7 @@ AString _methodsString; - #ifndef EXTRACT_ONLY + #ifndef Z7_EXTRACT_ONLY UInt32 _filterId; UInt64 _numSolidBytes; @@ -89,7 +104,7 @@ void InitXz() { _filterId = 0; - _numSolidBytes = XZ_PROPS__BLOCK_SIZE__AUTO; + _numSolidBytes = XZ_PROPS_BLOCK_SIZE_AUTO; } #endif @@ -97,7 +112,7 @@ void Init() { - #ifndef EXTRACT_ONLY + #ifndef Z7_EXTRACT_ONLY InitXz(); CMultiMethodProps::Init(); #else @@ -114,7 +129,7 @@ ISequentialOutStream *outStream, ICompressProgressInfo *progress) { - #ifndef _7ZIP_ST + #ifndef Z7_ST decoder._numThreads = _numThreads; #endif decoder._memUsage = _memUsage_Decompress; @@ -140,25 +155,6 @@ } public: - MY_QUERYINTERFACE_BEGIN2(IInArchive) - MY_QUERYINTERFACE_ENTRY(IArchiveOpenSeq) - MY_QUERYINTERFACE_ENTRY(IInArchiveGetStream) - MY_QUERYINTERFACE_ENTRY(ISetProperties) - #ifndef EXTRACT_ONLY - MY_QUERYINTERFACE_ENTRY(IOutArchive) - #endif - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IInArchive(;) - STDMETHOD(OpenSeq)(ISequentialInStream *stream); - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); - STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps); - - #ifndef EXTRACT_ONLY - INTERFACE_IOutArchive(;) - #endif - CBlockInfo *_blocks; size_t _blocksArraySize; UInt64 _maxBlocksSize; @@ -172,7 +168,7 @@ HRESULT SeekToPackPos(UInt64 pos) { - return _stream->Seek((Int64)pos, STREAM_SEEK_SET, NULL); + return InStream_SeekSet(_stream, pos); } }; @@ -181,7 +177,7 @@ _blocks(NULL), _blocksArraySize(0) { - #ifndef EXTRACT_ONLY + #ifndef Z7_EXTRACT_ONLY InitXz(); #endif } @@ -259,13 +255,14 @@ { XZ_ID_ARM, "ARM" }, { XZ_ID_ARMT, "ARMT" }, { XZ_ID_SPARC, "SPARC" }, + { XZ_ID_ARM64, "ARM64" }, { XZ_ID_LZMA2, "LZMA2" } }; static void AddMethodString(AString &s, const CXzFilter &f) { const char *p = NULL; - for (unsigned i = 0; i < ARRAY_SIZE(g_NamePairs); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_NamePairs); i++) if (g_NamePairs[i].Id == f.id) { p = g_NamePairs[i].Name; @@ -287,6 +284,8 @@ Lzma2PropToString(s, f.props[0]); else if (f.id == XZ_ID_Delta && f.propsSize == 1) s.Add_UInt32((UInt32)f.props[0] + 1); + else if (f.id == XZ_ID_ARM64 && f.propsSize == 1) + s.Add_UInt32((UInt32)f.props[0] + 16 + 2); else { s += '['; @@ -337,7 +336,7 @@ } } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -394,13 +393,13 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = 1; return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN const CXzStatInfo *stat = GetStat(); @@ -427,9 +426,9 @@ void Init(IArchiveOpenCallback *progress); }; -static SRes OpenCallbackProgress(const ICompressProgress *pp, UInt64 inSize, UInt64 /* outSize */) +static SRes OpenCallbackProgress(ICompressProgressPtr pp, UInt64 inSize, UInt64 /* outSize */) { - COpenCallbackWrap *p = CONTAINER_FROM_VTBL(pp, COpenCallbackWrap, vt); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(COpenCallbackWrap) if (p->OpenCallback) p->Res = p->OpenCallback->SetCompleted(NULL, &inSize); return HRESULT_To_SRes(p->Res, SZ_ERROR_PROGRESS); @@ -551,10 +550,10 @@ } } - RINOK(inStream->Seek(0, STREAM_SEEK_END, &_stat.InSize)); + RINOK(InStream_GetSize_SeekToEnd(inStream, _stat.InSize)) if (callback) { - RINOK(callback->SetTotal(NULL, &_stat.InSize)); + RINOK(callback->SetTotal(NULL, &_stat.InSize)) } CSeekInStreamWrap inStreamImp; @@ -569,7 +568,7 @@ return E_OUTOFMEMORY; lookStream.realStream = &inStreamImp.vt; - LookToRead2_Init(&lookStream); + LookToRead2_INIT(&lookStream) COpenCallbackWrap openWrap; openWrap.Init(callback); @@ -660,7 +659,7 @@ res = SZ_OK; } - RINOK(SRes_to_Open_HRESULT(res)); + RINOK(SRes_to_Open_HRESULT(res)) _stream = inStream; _seqStream = inStream; @@ -670,7 +669,7 @@ -STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *callback) +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *callback)) { COM_TRY_BEGIN { @@ -680,7 +679,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { Close(); _seqStream = stream; @@ -689,7 +688,7 @@ return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { XzStatInfo_Clear(&_stat); XzStatInfo_Clear(&_stat2); @@ -738,12 +737,14 @@ } -class CInStream: - public IInStream, - public CMyUnknownImp -{ -public: +Z7_CLASS_IMP_COM_1( + CInStream + , IInStream +) + Z7_IFACE_COM7_IMP(ISequentialInStream) + UInt64 _virtPos; +public: UInt64 Size; UInt64 _cacheStartPos; size_t _cacheSize; @@ -762,20 +763,15 @@ CHandler *_handlerSpec; CMyComPtr _handler; - MY_UNKNOWN_IMP1(IInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); - - ~CInStream(); + // ~CInStream(); }; - +/* CInStream::~CInStream() { // _cache.Free(); } - +*/ static size_t FindBlock(const CBlockInfo *blocks, size_t numBlocks, UInt64 pos) { @@ -845,7 +841,7 @@ ECoderStatus status; - SRes res = XzUnpacker_Code(&xzu.p, + const SRes res = XzUnpacker_Code(&xzu.p, // dest + outPos, NULL, &outLen, @@ -868,7 +864,7 @@ packRem -= inLen; - BoolInt blockFinished = XzUnpacker_IsBlockFinished(&xzu.p); + const BoolInt blockFinished = XzUnpacker_IsBlockFinished(&xzu.p); if ((inLen == 0 && outLen == 0) || blockFinished) { @@ -882,7 +878,7 @@ } -STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { COM_TRY_BEGIN @@ -906,7 +902,7 @@ if (_virtPos < _cacheStartPos || _virtPos >= _cacheStartPos + _cacheSize) { - size_t bi = FindBlock(_handlerSpec->_blocks, _handlerSpec->_blocksArraySize, _virtPos); + const size_t bi = FindBlock(_handlerSpec->_blocks, _handlerSpec->_blocksArraySize, _virtPos); const CBlockInfo &block = _handlerSpec->_blocks[bi]; const UInt64 unpackSize = _handlerSpec->_blocks[bi + 1].UnpackPos - block.UnpackPos; if (_cache.Size() < unpackSize) @@ -914,16 +910,16 @@ _cacheSize = 0; - RINOK(_handlerSpec->SeekToPackPos(block.PackPos)); + RINOK(_handlerSpec->SeekToPackPos(block.PackPos)) RINOK(DecodeBlock(xz, _handlerSpec->_seqStream, block.StreamFlags, block.PackSize, - (size_t)unpackSize, _cache)); + (size_t)unpackSize, _cache)) _cacheStartPos = block.UnpackPos; _cacheSize = (size_t)unpackSize; } { - size_t offset = (size_t)(_virtPos - _cacheStartPos); - size_t rem = _cacheSize - offset; + const size_t offset = (size_t)(_virtPos - _cacheStartPos); + const size_t rem = _cacheSize - offset; if (size > rem) size = (UInt32)rem; memcpy(data, _cache + offset, size); @@ -937,7 +933,7 @@ } -STDMETHODIMP CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { @@ -958,7 +954,7 @@ static const UInt64 kMaxBlockSize_for_GetStream = (UInt64)1 << 40; -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN @@ -1024,8 +1020,8 @@ -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN if (numItems == 0) @@ -1039,13 +1035,13 @@ extractCallback->SetTotal(stat->InSize); UInt64 currentTotalPacked = 0; - RINOK(extractCallback->SetCompleted(¤tTotalPacked)); + RINOK(extractCallback->SetCompleted(¤tTotalPacked)) CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(0, &realOutStream, askMode)) if (!testMode && !realOutStream) return S_OK; @@ -1060,7 +1056,7 @@ { if (!_stream) return E_FAIL; - RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(_stream)) } else _needSeekToStart = true; @@ -1085,9 +1081,9 @@ -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY -STDMETHODIMP CHandler::GetFileTimeType(UInt32 *timeType) +Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *timeType)) { *timeType = GET_FileTimeType_NotDefined_for_GetFileTimeType; // *timeType = NFileTimeType::kUnix; @@ -1095,8 +1091,8 @@ } -STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, - IArchiveUpdateCallback *updateCallback) +Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, + IArchiveUpdateCallback *updateCallback)) { COM_TRY_BEGIN @@ -1111,17 +1107,25 @@ if (numItems != 1) return E_INVALIDARG; + { + Z7_DECL_CMyComPtr_QI_FROM( + IStreamSetRestriction, + setRestriction, outStream) + if (setRestriction) + RINOK(setRestriction->SetRestriction(0, 0)) + } + Int32 newData, newProps; UInt32 indexInArchive; if (!updateCallback) return E_FAIL; - RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProps, &indexInArchive)); + RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProps, &indexInArchive)) if (IntToBool(newProps)) { { NCOM::CPropVariant prop; - RINOK(updateCallback->GetProperty(0, kpidIsDir, &prop)); + RINOK(updateCallback->GetProperty(0, kpidIsDir, &prop)) if (prop.vt != VT_EMPTY) if (prop.vt != VT_BOOL || prop.boolVal != VARIANT_FALSE) return E_INVALIDARG; @@ -1133,7 +1137,7 @@ UInt64 dataSize; { NCOM::CPropVariant prop; - RINOK(updateCallback->GetProperty(0, kpidSize, &prop)); + RINOK(updateCallback->GetProperty(0, kpidSize, &prop)) if (prop.vt != VT_UI8) return E_INVALIDARG; dataSize = prop.uhVal.QuadPart; @@ -1151,11 +1155,11 @@ /* { NCOM::CPropVariant prop = (UInt64)dataSize; - RINOK(encoderSpec->SetCoderProp(NCoderPropID::kReduceSize, prop)); + RINOK(encoderSpec->SetCoderProp(NCoderPropID::kReduceSize, prop)) } */ - #ifndef _7ZIP_ST + #ifndef Z7_ST UInt32 numThreads = _numThreads; @@ -1181,12 +1185,12 @@ } UInt64 cs = _numSolidBytes; - if (cs != XZ_PROPS__BLOCK_SIZE__AUTO) + if (cs != XZ_PROPS_BLOCK_SIZE_AUTO) oneMethodInfo.AddProp_BlockSize2(cs); cs = oneMethodInfo.Get_Xz_BlockSize(); - if (cs != XZ_PROPS__BLOCK_SIZE__AUTO && - cs != XZ_PROPS__BLOCK_SIZE__SOLID) + if (cs != XZ_PROPS_BLOCK_SIZE_AUTO && + cs != XZ_PROPS_BLOCK_SIZE_SOLID) { const UInt32 lzmaThreads = oneMethodInfo.Get_Lzma_NumThreads(); const UInt32 numBlockThreads_Original = numThreads / lzmaThreads; @@ -1218,16 +1222,16 @@ } xzProps.numTotalThreads = (int)numThreads; - #endif // _7ZIP_ST + #endif // Z7_ST xzProps.blockSize = _numSolidBytes; - if (_numSolidBytes == XZ_PROPS__BLOCK_SIZE__SOLID) + if (_numSolidBytes == XZ_PROPS_BLOCK_SIZE_SOLID) { - xzProps.lzma2Props.blockSize = LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID; + xzProps.lzma2Props.blockSize = LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID; } - RINOK(encoderSpec->SetCheckSize(_crcSize)); + RINOK(encoderSpec->SetCheckSize(_crcSize)) { CXzFilterProps &filter = xzProps.filterProps; @@ -1262,13 +1266,13 @@ FOR_VECTOR (j, m.Props) { const CProp &prop = m.Props[j]; - RINOK(encoderSpec->SetCoderProp(prop.Id, prop.Value)); + RINOK(encoderSpec->SetCoderProp(prop.Id, prop.Value)) } } { CMyComPtr fileInStream; - RINOK(updateCallback->GetStream(0, &fileInStream)); + RINOK(updateCallback->GetStream(0, &fileInStream)) if (!fileInStream) return S_FALSE; { @@ -1281,11 +1285,11 @@ dataSize = size; } } - RINOK(updateCallback->SetTotal(dataSize)); + RINOK(updateCallback->SetTotal(dataSize)) CLocalProgress *lps = new CLocalProgress; CMyComPtr progress = lps; lps->Init(updateCallback, true); - RINOK(encoderSpec->Code(fileInStream, outStream, NULL, NULL, progress)); + RINOK(encoder->Code(fileInStream, outStream, NULL, NULL, progress)) } return updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK); @@ -1294,8 +1298,9 @@ if (indexInArchive != 0) return E_INVALIDARG; - CMyComPtr opCallback; - updateCallback->QueryInterface(IID_IArchiveUpdateCallbackFile, (void **)&opCallback); + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveUpdateCallbackFile, + opCallback, updateCallback) if (opCallback) { RINOK(opCallback->ReportOperation(NEventIndexType::kInArcIndex, 0, NUpdateNotifyOp::kReplicate)) @@ -1305,8 +1310,10 @@ { const CXzStatInfo *stat = GetStat(); if (stat) - RINOK(updateCallback->SetTotal(stat->InSize)); - RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); + { + RINOK(updateCallback->SetTotal(stat->InSize)) + } + RINOK(InStream_SeekToBegin(_stream)) } CLocalProgress *lps = new CLocalProgress; @@ -1328,7 +1335,7 @@ if (name.IsEmpty()) return E_INVALIDARG; - #ifndef EXTRACT_ONLY + #ifndef Z7_EXTRACT_ONLY if (name[0] == L's') { @@ -1349,7 +1356,7 @@ } if (!useStr) { - _numSolidBytes = (isSolid ? XZ_PROPS__BLOCK_SIZE__SOLID : XZ_PROPS__BLOCK_SIZE__AUTO); + _numSolidBytes = (isSolid ? XZ_PROPS_BLOCK_SIZE_SOLID : XZ_PROPS_BLOCK_SIZE_AUTO); return S_OK; } } @@ -1375,7 +1382,7 @@ -STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) +Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps)) { COM_TRY_BEGIN @@ -1383,15 +1390,15 @@ for (UInt32 i = 0; i < numProps; i++) { - RINOK(SetProperty(names[i], values[i])); + RINOK(SetProperty(names[i], values[i])) } - #ifndef EXTRACT_ONLY + #ifndef Z7_EXTRACT_ONLY if (!_filterMethod.MethodName.IsEmpty()) { unsigned k; - for (k = 0; k < ARRAY_SIZE(g_NamePairs); k++) + for (k = 0; k < Z7_ARRAY_SIZE(g_NamePairs); k++) { const CMethodNamePair &pair = g_NamePairs[k]; if (StringsAreEqualNoCase_Ascii(_filterMethod.MethodName, pair.Name)) @@ -1400,7 +1407,7 @@ break; } } - if (k == ARRAY_SIZE(g_NamePairs)) + if (k == Z7_ARRAY_SIZE(g_NamePairs)) return E_INVALIDARG; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/XzHandler.h 7zip-23.01+dfsg/CPP/7zip/Archive/XzHandler.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/XzHandler.h 2017-01-30 14:07:17.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/XzHandler.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // XzHandler.h -#ifndef __XZ_HANDLER_H -#define __XZ_HANDLER_H +#ifndef ZIP7_INC_XZ_HANDLER_H +#define ZIP7_INC_XZ_HANDLER_H namespace NArchive { namespace NXz { diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/ZHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/ZHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/ZHandler.cpp 2015-02-11 09:25:16.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/ZHandler.cpp 2023-03-27 10:00:00.000000000 +0000 @@ -17,17 +17,12 @@ namespace NArchive { namespace NZ { -class CHandler: - public IInArchive, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_0 + CMyComPtr _stream; UInt64 _packSize; // UInt64 _unpackSize; // bool _unpackSize_Defined; -public: - MY_UNKNOWN_IMP1(IInArchive) - INTERFACE_IInArchive(;) }; static const Byte kProps[] = @@ -38,13 +33,13 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps_NO_Table -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = 1; return S_OK; } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { NWindows::NCOM::CPropVariant prop; switch (propID) @@ -55,7 +50,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)) { NWindows::NCOM::CPropVariant prop; switch (propID) @@ -68,22 +63,21 @@ } /* -class CCompressProgressInfoImp: - public ICompressProgressInfo, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CCompressProgressInfoImp + , ICompressProgressInfo +) CMyComPtr Callback; public: - MY_UNKNOWN_IMP1(ICompressProgressInfo) - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); void Init(IArchiveOpenCallback *callback) { Callback = callback; } }; -STDMETHODIMP CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) +Z7_COM7F_IMF(CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize)) { + outSize = outSize; if (Callback) { - UInt64 files = 1; + const UInt64 files = 1; return Callback->SetCompleted(&files, inSize); } return S_OK; @@ -102,23 +96,23 @@ } } -STDMETHODIMP CHandler::Open(IInStream *stream, +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openCallback */) + IArchiveOpenCallback * /* openCallback */)) { COM_TRY_BEGIN { - // RINOK(stream->Seek(0, STREAM_SEEK_CUR, &_streamStartPosition)); + // RINOK(InStream_GetPos(stream, _streamStartPosition)); Byte buffer[NCompress::NZ::kRecommendedCheckSize]; // Byte buffer[1500]; size_t size = NCompress::NZ::kRecommendedCheckSize; // size = 700; - RINOK(ReadStream(stream, buffer, &size)); + RINOK(ReadStream(stream, buffer, &size)) if (!NCompress::NZ::CheckStream(buffer, size)) return S_FALSE; UInt64 endPos; - RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos)); + RINOK(InStream_GetSize_SeekToEnd(stream, endPos)) _packSize = endPos; /* @@ -142,7 +136,7 @@ UInt64 files = 1; RINOK(openCallback->SetTotal(&files, &endPos)); } - RINOK(stream->Seek(_streamStartPosition + kSignatureSize, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(stream, _streamStartPosition + kSignatureSize)) HRESULT res = decoder->Code(stream, outStream, NULL, NULL, openCallback ? compressProgress : NULL); if (res != S_OK) return S_FALSE; @@ -155,7 +149,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _packSize = 0; // _unpackSize_Defined = false; @@ -164,8 +158,8 @@ } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN if (numItems == 0) @@ -177,14 +171,14 @@ UInt64 currentTotalPacked = 0; - RINOK(extractCallback->SetCompleted(¤tTotalPacked)); + RINOK(extractCallback->SetCompleted(¤tTotalPacked)) CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(0, &realOutStream, askMode)) if (!testMode && !realOutStream) return S_OK; @@ -201,7 +195,7 @@ CMyComPtr progress = lps; lps->Init(extractCallback, true); - RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(_stream)) NCompress::NZ::CDecoder *decoderSpec = new NCompress::NZ::CDecoder; CMyComPtr decoder = decoderSpec; @@ -213,7 +207,7 @@ opRes = NExtract::NOperationResult::kDataError; else { - RINOK(result); + RINOK(result) opRes = NExtract::NOperationResult::kOK; } } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipAddCommon.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipAddCommon.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipAddCommon.cpp 2020-11-29 13:55:22.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipAddCommon.cpp 2023-03-25 17:40:00.000000000 +0000 @@ -30,31 +30,22 @@ using namespace NFileHeader; -static const UInt32 kLzmaPropsSize = 5; -static const UInt32 kLzmaHeaderSize = 4 + kLzmaPropsSize; +static const unsigned kLzmaPropsSize = 5; +static const unsigned kLzmaHeaderSize = 4 + kLzmaPropsSize; -class CLzmaEncoder: - public ICompressCoder, - public ICompressSetCoderProperties, - public ICompressSetCoderPropertiesOpt, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_3( + CLzmaEncoder + , ICompressCoder + , ICompressSetCoderProperties + , ICompressSetCoderPropertiesOpt +) public: NCompress::NLzma::CEncoder *EncoderSpec; CMyComPtr Encoder; Byte Header[kLzmaHeaderSize]; - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); - STDMETHOD(SetCoderPropertiesOpt)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); - - MY_UNKNOWN_IMP2( - ICompressSetCoderProperties, - ICompressSetCoderPropertiesOpt) }; -STDMETHODIMP CLzmaEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps) +Z7_COM7F_IMF(CLzmaEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps)) { if (!Encoder) { @@ -64,8 +55,8 @@ CBufPtrSeqOutStream *outStreamSpec = new CBufPtrSeqOutStream; CMyComPtr outStream(outStreamSpec); outStreamSpec->Init(Header + 4, kLzmaPropsSize); - RINOK(EncoderSpec->SetCoderProperties(propIDs, props, numProps)); - RINOK(EncoderSpec->WriteCoderProperties(outStream)); + RINOK(EncoderSpec->SetCoderProperties(propIDs, props, numProps)) + RINOK(EncoderSpec->WriteCoderProperties(outStream)) if (outStreamSpec->GetPos() != kLzmaPropsSize) return E_FAIL; Header[0] = MY_VER_MAJOR; @@ -75,15 +66,15 @@ return S_OK; } -STDMETHODIMP CLzmaEncoder::SetCoderPropertiesOpt(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps) +Z7_COM7F_IMF(CLzmaEncoder::SetCoderPropertiesOpt(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps)) { return EncoderSpec->SetCoderPropertiesOpt(propIDs, props, numProps); } -STDMETHODIMP CLzmaEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CLzmaEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)) { - RINOK(WriteStream(outStream, Header, kLzmaHeaderSize)); + RINOK(WriteStream(outStream, Header, kLzmaHeaderSize)) return Encoder->Code(inStream, outStream, inSize, outSize, progress); } @@ -120,7 +111,7 @@ for (;;) { UInt32 processed; - RINOK(inStream->Read(_buf, kBufSize, &processed)); + RINOK(inStream->Read(_buf, kBufSize, &processed)) if (processed == 0) { resultCRC = CRC_GET_DIGEST(crc); @@ -148,9 +139,9 @@ if (opRes.PackSize < unpackSize) opRes.PackSize = unpackSize; - Byte method = _options.MethodSequence[0]; + const Byte method = _options.MethodSequence[0]; - if (method == NCompressionMethod::kStore && !_options.PasswordIsDefined) + if (method == NCompressionMethod::kStore && !_options.Password_Defined) opRes.PackSize = unpackSize; opRes.CRC = 0; @@ -160,7 +151,7 @@ opRes.ExtractVersion = NCompressionMethod::kExtractVersion_Default; opRes.DescriptorMode = outSeqMode; - if (_options.PasswordIsDefined) + if (_options.Password_Defined) { opRes.ExtractVersion = NCompressionMethod::kExtractVersion_ZipCrypto; if (_options.IsAesMode) @@ -202,10 +193,11 @@ DECL_EXTERNAL_CODECS_LOC_VARS ISequentialInStream *inStream, IOutStream *outStream, bool inSeqMode, bool outSeqMode, - UInt32 fileTime, UInt64 expectedDataSize, + UInt32 fileTime, + UInt64 expectedDataSize, bool expectedDataSize_IsConfirmed, ICompressProgressInfo *progress, CCompressingResult &opRes) { - opRes.LzmaEos = false; + // opRes.LzmaEos = false; if (!inStream) { @@ -229,9 +221,11 @@ } inSecCrcStreamSpec->SetStream(inStream); - inSecCrcStreamSpec->Init(); + inSecCrcStreamSpec->SetFullSize(expectedDataSize_IsConfirmed ? expectedDataSize : (UInt64)(Int64)-1); + // inSecCrcStreamSpec->Init(); unsigned numTestMethods = _options.MethodSequence.Size(); + // numTestMethods != 0 bool descriptorMode = outSeqMode; @@ -240,7 +234,7 @@ // The descriptor allows to use ZipCrypto check field without CRC (InfoZip's modification). if (!outSeqMode) - if (inSeqMode && _options.PasswordIsDefined && !_options.IsAesMode) + if (inSeqMode && _options.Password_Defined && !_options.IsAesMode) descriptorMode = true; opRes.DescriptorMode = descriptorMode; @@ -251,28 +245,27 @@ UInt32 crc = 0; bool crc_IsCalculated = false; - Byte method = 0; CFilterCoder::C_OutStream_Releaser outStreamReleaser; - opRes.ExtractVersion = NCompressionMethod::kExtractVersion_Default; + // opRes.ExtractVersion = NCompressionMethod::kExtractVersion_Default; for (unsigned i = 0; i < numTestMethods; i++) { - opRes.LzmaEos = false; - opRes.ExtractVersion = NCompressionMethod::kExtractVersion_Default; - + inSecCrcStreamSpec->Init(); + if (i != 0) { - if (inStream2) + // if (inStream2) { - inSecCrcStreamSpec->Init(); - RINOK(inStream2->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(inStream2)) } - - RINOK(outStream->SetSize(0)); - RINOK(outStream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(outStream->Seek(0, STREAM_SEEK_SET, NULL)) + RINOK(outStream->SetSize(0)) } - method = _options.MethodSequence[i]; + opRes.LzmaEos = false; + opRes.ExtractVersion = NCompressionMethod::kExtractVersion_Default; + + const Byte method = _options.MethodSequence[i]; if (method == NCompressionMethod::kStore && descriptorMode) { // we still can create descriptor_mode archives with "Store" method, but they are not good for 100% @@ -281,7 +274,7 @@ bool needCode = true; - if (_options.PasswordIsDefined) + if (_options.Password_Defined) { opRes.ExtractVersion = NCompressionMethod::kExtractVersion_ZipCrypto; @@ -298,9 +291,9 @@ { _cryptoStreamSpec->Filter = _filterAesSpec = new NCrypto::NWzAes::CEncoder; _filterAesSpec->SetKeyMode(_options.AesKeyMode); - RINOK(_filterAesSpec->CryptoSetPassword((const Byte *)(const char *)_options.Password, _options.Password.Len())); + RINOK(_filterAesSpec->CryptoSetPassword((const Byte *)(const char *)_options.Password, _options.Password.Len())) } - RINOK(_filterAesSpec->WriteHeader(outStream)); + RINOK(_filterAesSpec->WriteHeader(outStream)) } else { @@ -321,26 +314,26 @@ { if (!crc_IsCalculated) { - RINOK(CalcStreamCRC(inStream, crc)); + RINOK(CalcStreamCRC(inStream, crc)) crc_IsCalculated = true; - RINOK(inStream2->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(inStream2)) inSecCrcStreamSpec->Init(); } check = (crc >> 16); } - RINOK(_filterSpec->WriteHeader_Check16(outStream, (UInt16)check)); + RINOK(_filterSpec->WriteHeader_Check16(outStream, (UInt16)check)) } if (method == NCompressionMethod::kStore) { needCode = false; - RINOK(_cryptoStreamSpec->Code(inCrcStream, outStream, NULL, NULL, progress)); + RINOK(_cryptoStreamSpec->Code(inCrcStream, outStream, NULL, NULL, progress)) } else { - RINOK(_cryptoStreamSpec->SetOutStream(outStream)); - RINOK(_cryptoStreamSpec->InitEncoder()); + RINOK(_cryptoStreamSpec->SetOutStream(outStream)) + RINOK(_cryptoStreamSpec->InitEncoder()) outStreamReleaser.FilterCoder = _cryptoStreamSpec; } } @@ -357,11 +350,11 @@ _copyCoder = _copyCoderSpec; } CMyComPtr outStreamNew; - if (_options.PasswordIsDefined) + if (_options.Password_Defined) outStreamNew = _cryptoStream; else outStreamNew = outStream; - RINOK(_copyCoder->Code(inCrcStream, outStreamNew, NULL, NULL, progress)); + RINOK(_copyCoder->Code(inCrcStream, outStreamNew, NULL, NULL, progress)) break; } @@ -406,7 +399,7 @@ } RINOK(CreateCoder_Id( EXTERNAL_CODECS_LOC_VARS - methodId, true, _compressEncoder)); + methodId, true, _compressEncoder)) if (!_compressEncoder) return E_NOTIMPL; @@ -428,7 +421,7 @@ COneMethodInfo *oneMethodMain = &_options._methods[0]; RINOK(oneMethodMain->SetCoderProps(setCoderProps, - _options._dataSizeReduceDefined ? &_options._dataSizeReduce : NULL)); + _options.DataSizeReduce_Defined ? &_options.DataSizeReduce : NULL)) } } } @@ -440,7 +433,7 @@ opRes.LzmaEos = _isLzmaEos; CMyComPtr outStreamNew; - if (_options.PasswordIsDefined) + if (_options.Password_Defined) outStreamNew = _cryptoStream; else outStreamNew = outStream; @@ -452,41 +445,45 @@ _compressEncoder->QueryInterface(IID_ICompressSetCoderPropertiesOpt, (void **)&optProps); if (optProps) { - PROPID propID = NCoderPropID::kExpectedDataSize; + const PROPID propID = NCoderPropID::kExpectedDataSize; NWindows::NCOM::CPropVariant prop = (UInt64)expectedDataSize; - RINOK(optProps->SetCoderPropertiesOpt(&propID, &prop, 1)); + RINOK(optProps->SetCoderPropertiesOpt(&propID, &prop, 1)) } } try { - RINOK(_compressEncoder->Code(inCrcStream, outStreamNew, NULL, NULL, progress)); + RINOK(_compressEncoder->Code(inCrcStream, outStreamNew, NULL, NULL, progress)) } catch (...) { return E_FAIL; } break; } } // switch end - if (_options.PasswordIsDefined) + if (_options.Password_Defined) { - RINOK(_cryptoStreamSpec->OutStreamFinish()); + RINOK(_cryptoStreamSpec->OutStreamFinish()) } } - if (_options.PasswordIsDefined) + if (_options.Password_Defined) { if (_options.IsAesMode) { - RINOK(_filterAesSpec->WriteFooter(outStream)); + RINOK(_filterAesSpec->WriteFooter(outStream)) } } - RINOK(outStream->Seek(0, STREAM_SEEK_CUR, &opRes.PackSize)); + RINOK(outStream->Seek(0, STREAM_SEEK_CUR, &opRes.PackSize)) { opRes.CRC = inSecCrcStreamSpec->GetCRC(); opRes.UnpackSize = inSecCrcStreamSpec->GetSize(); + opRes.Method = method; } - if (_options.PasswordIsDefined) + if (!inSecCrcStreamSpec->WasFinished()) + return E_FAIL; + + if (_options.Password_Defined) { if (opRes.PackSize < opRes.UnpackSize + (_options.IsAesMode ? _filterAesSpec->GetAddPackSize() : NCrypto::NZip::kHeaderSize)) @@ -496,8 +493,6 @@ break; } - - opRes.Method = method; return S_OK; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipAddCommon.h 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipAddCommon.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipAddCommon.h 2020-11-29 13:54:15.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipAddCommon.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ZipAddCommon.h -#ifndef __ZIP_ADD_COMMON_H -#define __ZIP_ADD_COMMON_H +#ifndef ZIP7_INC_ZIP_ADD_COMMON_H +#define ZIP7_INC_ZIP_ADD_COMMON_H #include "../../ICoder.h" #include "../../IProgress.h" @@ -68,7 +68,8 @@ DECL_EXTERNAL_CODECS_LOC_VARS ISequentialInStream *inStream, IOutStream *outStream, bool inSeqMode, bool outSeqMode, - UInt32 fileTime, UInt64 expectedDataSize, + UInt32 fileTime, + UInt64 expectedDataSize, bool expectedDataSize_IsConfirmed, ICompressProgressInfo *progress, CCompressingResult &opRes); }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipCompressionMode.h 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipCompressionMode.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipCompressionMode.h 2019-10-10 17:34:03.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipCompressionMode.h 2023-05-04 17:00:00.000000000 +0000 @@ -1,11 +1,11 @@ // CompressionMode.h -#ifndef __ZIP_COMPRESSION_MODE_H -#define __ZIP_COMPRESSION_MODE_H +#ifndef ZIP7_INC_ZIP_COMPRESSION_MODE_H +#define ZIP7_INC_ZIP_COMPRESSION_MODE_H #include "../../../Common/MyString.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "../../../Windows/System.h" #endif @@ -34,20 +34,26 @@ struct CCompressionMethodMode: public CBaseProps { CRecordVector MethodSequence; - bool PasswordIsDefined; AString Password; // _Wipe + bool Password_Defined; + bool Force_SeqOutMode; + bool DataSizeReduce_Defined; + UInt64 DataSizeReduce; - UInt64 _dataSizeReduce; - bool _dataSizeReduceDefined; - - bool IsRealAesMode() const { return PasswordIsDefined && IsAesMode; } + bool IsRealAesMode() const { return Password_Defined && IsAesMode; } - CCompressionMethodMode(): PasswordIsDefined(false) + CCompressionMethodMode() { - _dataSizeReduceDefined = false; - _dataSizeReduce = 0; + Password_Defined = false; + Force_SeqOutMode = false; + DataSizeReduce_Defined = false; + DataSizeReduce = 0; } +#ifdef Z7_CPP_IS_SUPPORTED_default + CCompressionMethodMode(const CCompressionMethodMode &) = default; + CCompressionMethodMode& operator =(const CCompressionMethodMode &) = default; +#endif ~CCompressionMethodMode() { Password.Wipe_and_Empty(); } }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipHandler.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipHandler.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipHandler.cpp 2022-05-07 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipHandler.cpp 2023-03-26 11:00:00.000000000 +0000 @@ -19,7 +19,7 @@ #include "../../Compress/CopyCoder.h" -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS #ifndef SUPPORT_LZFSE #define SUPPORT_LZFSE #endif @@ -92,18 +92,20 @@ , "BZip2" , NULL , "LZMA" + /* , NULL , NULL , NULL , NULL , NULL - , "zstd-pk" + , "zstd-pk" // deprecated + */ }; const char * const kMethodNames2[kNumMethodNames2] = { - "zstd-wz" + "zstd" , "MP3" , "xz" , "Jpeg" @@ -129,6 +131,7 @@ { { 0, "Encrypt" }, { 3, "Descriptor" }, + // { 4, "Enhanced" }, // { 5, "Patched" }, { 6, kMethod_StrongCrypto }, { 11, "UTF8" }, @@ -221,7 +224,7 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -343,7 +346,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = m_Items.Size(); return S_OK; @@ -377,7 +380,7 @@ } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -521,7 +524,7 @@ if (extra.GetWzAes(aesField)) { m += kMethod_AES; - m += '-'; + m.Add_Minus(); m.Add_UInt32(((unsigned)aesField.Strength + 1) * 64); id = aesField.Method; isWzAes = true; @@ -537,7 +540,7 @@ f.AlgId = 0; if (extra.GetStrongCrypto(f)) { - const char *s = FindNameForId(k_StrongCryptoPairs, ARRAY_SIZE(k_StrongCryptoPairs), f.AlgId); + const char *s = FindNameForId(k_StrongCryptoPairs, Z7_ARRAY_SIZE(k_StrongCryptoPairs), f.AlgId); if (s) m += s; else @@ -629,7 +632,7 @@ if (flags != 0) { - AString s2 = FlagsToString(g_HeaderCharacts, ARRAY_SIZE(g_HeaderCharacts), flags); + const AString s2 = FlagsToString(g_HeaderCharacts, Z7_ARRAY_SIZE(g_HeaderCharacts), flags); if (!s2.IsEmpty()) { if (!s.IsEmpty()) @@ -690,13 +693,13 @@ /* -STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) +Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps) { *numProps = 0; return S_OK; } -STDMETHODIMP CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID) +Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID) { UNUSED_VAR(index); *propID = 0; @@ -704,7 +707,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType) +Z7_COM7F_IMF(CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType) { *parentType = NParentType::kDir; *parent = (UInt32)(Int32)-1; @@ -720,7 +723,7 @@ return S_OK; } -STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) +Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) { UNUSED_VAR(index); UNUSED_VAR(propID); @@ -767,13 +770,16 @@ } */ -STDMETHODIMP CHandler::Open(IInStream *inStream, - const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *callback) +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, + const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *callback)) { COM_TRY_BEGIN try { Close(); + m_Archive.Force_ReadLocals_Mode = _force_OpenSeq; + // m_Archive.Disable_VolsRead = _force_OpenSeq; + // m_Archive.Disable_FindMarker = _force_OpenSeq; HRESULT res = m_Archive.Open(inStream, maxCheckStartPosition, callback, m_Items); if (res != S_OK) { @@ -787,7 +793,7 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { m_Items.Clear(); m_Archive.Close(); @@ -795,25 +801,16 @@ } -class CLzmaDecoder: - public ICompressCoder, - public ICompressSetFinishMode, - public ICompressGetInStreamProcessedSize, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_3( + CLzmaDecoder + , ICompressCoder + , ICompressSetFinishMode + , ICompressGetInStreamProcessedSize +) public: NCompress::NLzma::CDecoder *DecoderSpec; CMyComPtr Decoder; - MY_UNKNOWN_IMP2( - ICompressSetFinishMode, - ICompressGetInStreamProcessedSize) - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetFinishMode)(UInt32 finishMode); - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); - CLzmaDecoder(); }; @@ -825,14 +822,14 @@ static const unsigned kZipLzmaPropsSize = 4 + LZMA_PROPS_SIZE; -HRESULT CLzmaDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CLzmaDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)) { Byte buf[kZipLzmaPropsSize]; - RINOK(ReadStream_FALSE(inStream, buf, kZipLzmaPropsSize)); + RINOK(ReadStream_FALSE(inStream, buf, kZipLzmaPropsSize)) if (buf[2] != LZMA_PROPS_SIZE || buf[3] != 0) return E_NOTIMPL; - RINOK(DecoderSpec->SetDecoderProperties2(buf + 4, LZMA_PROPS_SIZE)); + RINOK(DecoderSpec->SetDecoderProperties2(buf + 4, LZMA_PROPS_SIZE)) UInt64 inSize2 = 0; if (inSize) { @@ -844,13 +841,13 @@ return Decoder->Code(inStream, outStream, inSize ? &inSize2 : NULL, outSize, progress); } -STDMETHODIMP CLzmaDecoder::SetFinishMode(UInt32 finishMode) +Z7_COM7F_IMF(CLzmaDecoder::SetFinishMode(UInt32 finishMode)) { DecoderSpec->FinishStream = (finishMode != 0); return S_OK; } -STDMETHODIMP CLzmaDecoder::GetInStreamProcessedSize(UInt64 *value) +Z7_COM7F_IMF(CLzmaDecoder::GetInStreamProcessedSize(UInt64 *value)) { *value = DecoderSpec->GetInputProcessedSize() + kZipLzmaPropsSize; return S_OK; @@ -888,11 +885,11 @@ CLzmaDecoder *lzmaDecoderSpec; public: CZipDecoder(): - _zipCryptoDecoderSpec(0), - _pkAesDecoderSpec(0), - _wzAesDecoderSpec(0), - filterStreamSpec(0), - lzmaDecoderSpec(0) + _zipCryptoDecoderSpec(NULL), + _pkAesDecoderSpec(NULL), + _wzAesDecoderSpec(NULL), + filterStreamSpec(NULL), + lzmaDecoderSpec(NULL) {} HRESULT Decode( @@ -901,7 +898,7 @@ ISequentialOutStream *realOutStream, IArchiveExtractCallback *extractCallback, ICompressProgressInfo *compressProgress, - #ifndef _7ZIP_ST + #ifndef Z7_ST UInt32 numThreads, UInt64 memUsage, #endif Int32 &res); @@ -919,7 +916,7 @@ for (;;) { size_t size = kBufSize; - RINOK(ReadStream(stream, buf, &size)); + RINOK(ReadStream(stream, buf, &size)) if (size == 0) return S_OK; thereAreData = true; @@ -927,25 +924,23 @@ if ((packSize - prev) >= (1 << 22)) { prev = packSize; - RINOK(progress->SetRatioInfo(&packSize, &unpackSize)); + RINOK(progress->SetRatioInfo(&packSize, &unpackSize)) } } } -class COutStreamWithPadPKCS7: - public ISequentialOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + COutStreamWithPadPKCS7 + , ISequentialOutStream +) CMyComPtr _stream; UInt64 _size; UInt64 _padPos; UInt32 _padSize; bool _padFailure; public: - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); void SetStream(ISequentialOutStream *stream) { _stream = stream; } void ReleaseStream() { _stream.Release(); } @@ -962,7 +957,7 @@ }; -STDMETHODIMP COutStreamWithPadPKCS7::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(COutStreamWithPadPKCS7::Write(const void *data, UInt32 size, UInt32 *processedSize)) { UInt32 written = 0; HRESULT result = S_OK; @@ -1003,7 +998,7 @@ ISequentialOutStream *realOutStream, IArchiveExtractCallback *extractCallback, ICompressProgressInfo *compressProgress, - #ifndef _7ZIP_ST + #ifndef Z7_ST UInt32 numThreads, UInt64 memUsage, #endif Int32 &res) @@ -1074,7 +1069,7 @@ return S_OK; packSize -= NCrypto::NWzAes::kMacSize; } - RINOK(archive.GetItemStream(item, true, packStream)); + RINOK(archive.GetItemStream(item, true, packStream)) if (!packStream) { res = NExtract::NOperationResult::kUnavailable; @@ -1126,7 +1121,7 @@ } CMyComPtr cryptoSetPassword; - RINOK(cryptoFilter.QueryInterface(IID_ICryptoSetPassword, &cryptoSetPassword)); + RINOK(cryptoFilter.QueryInterface(IID_ICryptoSetPassword, &cryptoSetPassword)) if (!cryptoSetPassword) return E_FAIL; @@ -1136,12 +1131,12 @@ if (getTextPassword) { CMyComBSTR_Wipe password; - RINOK(getTextPassword->CryptoGetTextPassword(&password)); + RINOK(getTextPassword->CryptoGetTextPassword(&password)) AString_Wipe charPassword; if (password) { /* - // 22.00: do we need UTF-8 passwords here ? + // 22.00: do we need UTF-8 passwords here ? if (item.IsUtf8()) // 22.00 { // throw 1; @@ -1226,7 +1221,7 @@ szMethodID = kMethodId_ZipBase + (Byte)id; } - RINOK(CreateCoder_Id(EXTERNAL_CODECS_LOC_VARS szMethodID, false, mi.Coder)); + RINOK(CreateCoder_Id(EXTERNAL_CODECS_LOC_VARS szMethodID, false, mi.Coder)) if (!mi.Coder) { @@ -1241,13 +1236,13 @@ ICompressCoder *coder = mi.Coder; - #ifndef _7ZIP_ST + #ifndef Z7_ST { CMyComPtr setCoderMt; coder->QueryInterface(IID_ICompressSetCoderMt, (void **)&setCoderMt); if (setCoderMt) { - RINOK(setCoderMt->SetNumberOfThreads(numThreads)); + RINOK(setCoderMt->SetNumberOfThreads(numThreads)) } } // if (memUsage != 0) @@ -1256,7 +1251,7 @@ coder->QueryInterface(IID_ICompressSetMemLimit, (void **)&setMemLimit); if (setMemLimit) { - RINOK(setMemLimit->SetMemLimit(memUsage)); + RINOK(setMemLimit->SetMemLimit(memUsage)) } } #endif @@ -1267,7 +1262,7 @@ if (setDecoderProperties) { Byte properties = (Byte)item.Flags; - RINOK(setDecoderProperties->SetDecoderProperties2(&properties, 1)); + RINOK(setDecoderProperties->SetDecoderProperties2(&properties, 1)) } } @@ -1363,7 +1358,7 @@ coder->QueryInterface(IID_ICompressSetFinishMode, (void **)&setFinishMode); if (setFinishMode) { - RINOK(setFinishMode->SetFinishMode(BoolToUInt(true))); + RINOK(setFinishMode->SetFinishMode(BoolToUInt(true))) } const UInt64 coderPackSize = limitedStreamSpec->GetRem(); @@ -1421,12 +1416,12 @@ { readFromFilter = true; inStreamReleaser.FilterCoder = filterStreamSpec; - RINOK(filterStreamSpec->SetInStream(inStream)); + RINOK(filterStreamSpec->SetInStream(inStream)) /* IFilter::Init() does nothing in all zip crypto filters. So we can call any Initialize function in CFilterCoder. */ - RINOK(filterStreamSpec->Init_NoSubFilterInit()); + RINOK(filterStreamSpec->Init_NoSubFilterInit()) // RINOK(filterStreamSpec->SetOutStreamSize(NULL)); } @@ -1448,7 +1443,7 @@ if (getInStreamProcessedSize && setFinishMode) { UInt64 processed; - RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&processed)); + RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&processed)) if (processed != (UInt64)(Int64)-1) { if (pkAesMode) @@ -1474,7 +1469,7 @@ UInt32 processedSize = 0; if (readInStream) { - RINOK(readInStream->ReadUnusedFromInBuf(buf, kBufSize, &processedSize)); + RINOK(readInStream->ReadUnusedFromInBuf(buf, kBufSize, &processedSize)) } if (processedSize > padSize) dataAfterEnd = true; @@ -1532,7 +1527,7 @@ return S_OK; } - RINOK(result); + RINOK(result) } bool crcOK = true; @@ -1600,66 +1595,59 @@ } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - CZipDecoder myDecoder; - UInt64 totalUnPacked = 0, totalPacked = 0; - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = m_Items.Size(); if (numItems == 0) return S_OK; + UInt64 total = 0; // , totalPacked = 0; UInt32 i; for (i = 0; i < numItems; i++) { const CItemEx &item = m_Items[allFilesMode ? i : indices[i]]; - totalUnPacked += item.Size; - totalPacked += item.PackSize; + total += item.Size; + // totalPacked += item.PackSize; } - RINOK(extractCallback->SetTotal(totalUnPacked)); + RINOK(extractCallback->SetTotal(total)) - UInt64 currentTotalUnPacked = 0, currentTotalPacked = 0; - UInt64 currentItemUnPacked, currentItemPacked; + CZipDecoder myDecoder; + UInt64 cur_Unpacked, cur_Packed; CLocalProgress *lps = new CLocalProgress; CMyComPtr progress = lps; lps->Init(extractCallback, false); - for (i = 0; i < numItems; i++, - currentTotalUnPacked += currentItemUnPacked, - currentTotalPacked += currentItemPacked) - { - currentItemUnPacked = 0; - currentItemPacked = 0; - - lps->InSize = currentTotalPacked; - lps->OutSize = currentTotalUnPacked; - RINOK(lps->SetCur()); + for (i = 0;; i++, + lps->OutSize += cur_Unpacked, + lps->InSize += cur_Packed) + { + RINOK(lps->SetCur()) + if (i >= numItems) + return S_OK; + const UInt32 index = allFilesMode ? i : indices[i]; + CItemEx item = m_Items[index]; + cur_Unpacked = item.Size; + cur_Packed = item.PackSize; - CMyComPtr realOutStream; - Int32 askMode = testMode ? + const bool isLocalOffsetOK = m_Archive.IsLocalOffsetOK(item); + const bool skip = !isLocalOffsetOK && !item.IsDir(); + const Int32 askMode = skip ? + NExtract::NAskMode::kSkip : testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - UInt32 index = allFilesMode ? i : indices[i]; - - CItemEx item = m_Items[index]; - bool isLocalOffsetOK = m_Archive.IsLocalOffsetOK(item); - bool skip = !isLocalOffsetOK && !item.IsDir(); - if (skip) - askMode = NExtract::NAskMode::kSkip; - - currentItemUnPacked = item.Size; - currentItemPacked = item.PackSize; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + CMyComPtr realOutStream; + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) if (!isLocalOffsetOK) { - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnavailable)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnavailable)) continue; } @@ -1668,30 +1656,30 @@ if (!item.FromLocal) { bool isAvail = true; - HRESULT res = m_Archive.ReadLocalItemAfterCdItem(item, isAvail, headersError); - if (res == S_FALSE) + const HRESULT hres = m_Archive.Read_LocalItem_After_CdItem(item, isAvail, headersError); + if (hres == S_FALSE) { if (item.IsDir() || realOutStream || testMode) { - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) realOutStream.Release(); RINOK(extractCallback->SetOperationResult( isAvail ? NExtract::NOperationResult::kHeadersError : - NExtract::NOperationResult::kUnavailable)); + NExtract::NOperationResult::kUnavailable)) } continue; } - RINOK(res); + RINOK(hres) } if (item.IsDir()) { // if (!testMode) { - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)) } continue; } @@ -1699,19 +1687,19 @@ if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) Int32 res; - HRESULT hres = myDecoder.Decode( + const HRESULT hres = myDecoder.Decode( EXTERNAL_CODECS_VARS m_Archive, item, realOutStream, extractCallback, progress, - #ifndef _7ZIP_ST + #ifndef Z7_ST _props._numThreads, _props._memUsage_Decompress, #endif res); - RINOK(hres); + RINOK(hres) realOutStream.Release(); if (res == NExtract::NOperationResult::kOK && headersError) @@ -1720,9 +1708,6 @@ RINOK(extractCallback->SetOperationResult(res)) } - lps->InSize = currentTotalPacked; - lps->OutSize = currentTotalUnPacked; - return lps->SetCur(); COM_TRY_END } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipHandler.h 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipHandler.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipHandler.h 2022-05-07 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipHandler.h 2023-03-26 11:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Zip/Handler.h -#ifndef __ZIP_HANDLER_H -#define __ZIP_HANDLER_H +#ifndef ZIP7_INC_ZIP_HANDLER_H +#define ZIP7_INC_ZIP_HANDLER_H #include "../../../Common/DynamicBuffer.h" #include "../../ICoder.h" @@ -23,46 +23,43 @@ extern const char * const kMethodNames2[kNumMethodNames2]; -class CHandler: +class CHandler Z7_final: public IInArchive, // public IArchiveGetRawProps, public IOutArchive, public ISetProperties, - PUBLIC_ISetCompressCodecsInfo + Z7_PUBLIC_ISetCompressCodecsInfo_IFEC public CMyUnknownImp { -public: - MY_QUERYINTERFACE_BEGIN2(IInArchive) - // MY_QUERYINTERFACE_ENTRY(IArchiveGetRawProps) - MY_QUERYINTERFACE_ENTRY(IOutArchive) - MY_QUERYINTERFACE_ENTRY(ISetProperties) - QUERY_ENTRY_ISetCompressCodecsInfo - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IInArchive(;) - // INTERFACE_IArchiveGetRawProps(;) - INTERFACE_IOutArchive(;) - - STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps); - + Z7_COM_QI_BEGIN2(IInArchive) + // Z7_COM_QI_ENTRY(IArchiveGetRawProps) + Z7_COM_QI_ENTRY(IOutArchive) + Z7_COM_QI_ENTRY(ISetProperties) + Z7_COM_QI_ENTRY_ISetCompressCodecsInfo_IFEC + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(IInArchive) + // Z7_IFACE_COM7_IMP(IArchiveGetRawProps) + Z7_IFACE_COM7_IMP(IOutArchive) + Z7_IFACE_COM7_IMP(ISetProperties) DECL_ISetCompressCodecsInfo - CHandler(); private: CObjectVector m_Items; CInArchive m_Archive; CBaseProps _props; + CHandlerTimeOptions TimeOptions; int m_MainMethod; bool m_ForceAesMode; - - CHandlerTimeOptions TimeOptions; - + bool _removeSfxBlock; bool m_ForceLocal; bool m_ForceUtf8; + bool _force_SeqOutMode; // for creation + bool _force_OpenSeq; bool _forceCodePage; UInt32 _specifiedCodePage; @@ -71,13 +68,15 @@ void InitMethodProps() { _props.Init(); - m_MainMethod = -1; - m_ForceAesMode = false; TimeOptions.Init(); TimeOptions.Prec = k_PropVar_TimePrec_0; + m_MainMethod = -1; + m_ForceAesMode = false; _removeSfxBlock = false; m_ForceLocal = false; m_ForceUtf8 = false; + _force_SeqOutMode = false; + _force_OpenSeq = false; _forceCodePage = false; _specifiedCodePage = CP_OEMCP; } @@ -85,6 +84,9 @@ // void MarkAltStreams(CObjectVector &items); HRESULT GetOutProperty(IArchiveUpdateCallback *callback, UInt32 callbackIndex, Int32 arcIndex, PROPID propID, PROPVARIANT *value); + +public: + CHandler(); }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipHandlerOut.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipHandlerOut.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipHandlerOut.cpp 2022-05-07 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipHandlerOut.cpp 2023-03-25 17:00:00.000000000 +0000 @@ -28,7 +28,7 @@ namespace NArchive { namespace NZip { -STDMETHODIMP CHandler::GetFileTimeType(UInt32 *timeType) +Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *timeType)) { *timeType = TimeOptions.Prec; return S_OK; @@ -79,7 +79,7 @@ { filetime.dwHighDateTime = filetime.dwLowDateTime = 0; NCOM::CPropVariant prop; - RINOK(callback->GetProperty(index, propID, &prop)); + RINOK(callback->GetProperty(index, propID, &prop)) if (prop.vt == VT_FILETIME) filetime = prop.filetime; else if (prop.vt != VT_EMPTY) @@ -88,8 +88,8 @@ } -STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, - IArchiveUpdateCallback *callback) +Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, + IArchiveUpdateCallback *callback)) { COM_TRY_BEGIN2 @@ -122,7 +122,7 @@ if (!callback) return E_FAIL; - RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArc)); + RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArc)) name.Empty(); ui.Clear(); @@ -147,7 +147,7 @@ { { NCOM::CPropVariant prop; - RINOK(callback->GetProperty(i, kpidAttrib, &prop)); + RINOK(callback->GetProperty(i, kpidAttrib, &prop)) if (prop.vt == VT_EMPTY) ui.Attrib = 0; else if (prop.vt != VT_UI4) @@ -158,7 +158,7 @@ { NCOM::CPropVariant prop; - RINOK(callback->GetProperty(i, kpidPath, &prop)); + RINOK(callback->GetProperty(i, kpidPath, &prop)) if (prop.vt == VT_EMPTY) { // name.Empty(); @@ -171,7 +171,7 @@ { NCOM::CPropVariant prop; - RINOK(callback->GetProperty(i, kpidIsDir, &prop)); + RINOK(callback->GetProperty(i, kpidIsDir, &prop)) if (prop.vt == VT_EMPTY) ui.IsDir = false; else if (prop.vt != VT_BOOL) @@ -219,9 +219,9 @@ } */ - if (TimeOptions.Write_MTime.Val) RINOK (GetTime (callback, i, kpidMTime, ui.Ntfs_MTime)); - if (TimeOptions.Write_ATime.Val) RINOK (GetTime (callback, i, kpidATime, ui.Ntfs_ATime)); - if (TimeOptions.Write_CTime.Val) RINOK (GetTime (callback, i, kpidCTime, ui.Ntfs_CTime)); + if (TimeOptions.Write_MTime.Val) RINOK (GetTime (callback, i, kpidMTime, ui.Ntfs_MTime)) + if (TimeOptions.Write_ATime.Val) RINOK (GetTime (callback, i, kpidATime, ui.Ntfs_ATime)) + if (TimeOptions.Write_CTime.Val) RINOK (GetTime (callback, i, kpidCTime, ui.Ntfs_CTime)) if (TimeOptions.Prec != k_PropVar_TimePrec_DOS) { @@ -325,7 +325,7 @@ { NCOM::CPropVariant prop; - RINOK(callback->GetProperty(i, kpidComment, &prop)); + RINOK(callback->GetProperty(i, kpidComment, &prop)) if (prop.vt == VT_EMPTY) { // ui.Comment.Free(); @@ -374,7 +374,7 @@ if (!ui.IsDir) { NCOM::CPropVariant prop; - RINOK(callback->GetProperty(i, kpidSize, &prop)); + RINOK(callback->GetProperty(i, kpidSize, &prop)) if (prop.vt != VT_UI8) return E_INVALIDARG; size = prop.uhVal.QuadPart; @@ -396,18 +396,18 @@ } CCompressionMethodMode options; (CBaseProps &)options = _props; - options._dataSizeReduce = largestSize; - options._dataSizeReduceDefined = largestSizeDefined; + options.DataSizeReduce = largestSize; + options.DataSizeReduce_Defined = largestSizeDefined; - options.PasswordIsDefined = false; + options.Password_Defined = false; options.Password.Wipe_and_Empty(); if (getTextPassword) { CMyComBSTR_Wipe password; Int32 passwordIsDefined; - RINOK(getTextPassword->CryptoGetTextPassword2(&passwordIsDefined, &password)); - options.PasswordIsDefined = IntToBool(passwordIsDefined); - if (options.PasswordIsDefined) + RINOK(getTextPassword->CryptoGetTextPassword2(&passwordIsDefined, &password)) + options.Password_Defined = IntToBool(passwordIsDefined); + if (options.Password_Defined) { if (!m_ForceAesMode) options.IsAesMode = thereAreAesUpdates; @@ -439,8 +439,9 @@ { CMethodId methodId; UInt32 numStreams; + bool isFilter; if (FindMethod_Index(EXTERNAL_CODECS_VARS methodName, true, - methodId, numStreams) < 0) + methodId, numStreams, isFilter) < 0) return E_NOTIMPL; if (numStreams != 1) return E_NOTIMPL; @@ -472,6 +473,8 @@ if (mainMethod != NFileHeader::NCompressionMethod::kStore) options.MethodSequence.Add(NFileHeader::NCompressionMethod::kStore); + options.Force_SeqOutMode = _force_SeqOutMode; + CUpdateOptions uo; uo.Write_MTime = TimeOptions.Write_MTime.Val; uo.Write_ATime = TimeOptions.Write_ATime.Val; @@ -493,7 +496,7 @@ -STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) +Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps)) { InitMethodProps(); @@ -540,26 +543,34 @@ else if (name.IsEqualTo("cl")) { - RINOK(PROPVARIANT_to_bool(prop, m_ForceLocal)); + RINOK(PROPVARIANT_to_bool(prop, m_ForceLocal)) if (m_ForceLocal) m_ForceUtf8 = false; } else if (name.IsEqualTo("cu")) { - RINOK(PROPVARIANT_to_bool(prop, m_ForceUtf8)); + RINOK(PROPVARIANT_to_bool(prop, m_ForceUtf8)) if (m_ForceUtf8) m_ForceLocal = false; } else if (name.IsEqualTo("cp")) { UInt32 cp = CP_OEMCP; - RINOK(ParsePropToUInt32(L"", prop, cp)); + RINOK(ParsePropToUInt32(L"", prop, cp)) _forceCodePage = true; _specifiedCodePage = cp; } else if (name.IsEqualTo("rsfx")) { - RINOK(PROPVARIANT_to_bool(prop, _removeSfxBlock)); + RINOK(PROPVARIANT_to_bool(prop, _removeSfxBlock)) + } + else if (name.IsEqualTo("rws")) + { + RINOK(PROPVARIANT_to_bool(prop, _force_SeqOutMode)) + } + else if (name.IsEqualTo("ros")) + { + RINOK(PROPVARIANT_to_bool(prop, _force_OpenSeq)) } else { @@ -573,10 +584,10 @@ else { bool processed = false; - RINOK(TimeOptions.Parse(name, prop, processed)); + RINOK(TimeOptions.Parse(name, prop, processed)) if (!processed) { - RINOK(_props.SetProperty(name, prop)); + RINOK(_props.SetProperty(name, prop)) } } // RINOK(_props.MethodInfo.ParseParamsFromPROPVARIANT(name, prop)); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipHeader.h 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipHeader.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipHeader.h 2022-05-05 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipHeader.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ZipHeader.h -#ifndef __ARCHIVE_ZIP_HEADER_H -#define __ARCHIVE_ZIP_HEADER_H +#ifndef ZIP7_INC_ARCHIVE_ZIP_HEADER_H +#define ZIP7_INC_ARCHIVE_ZIP_HEADER_H #include "../../../Common/MyTypes.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipIn.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipIn.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipIn.cpp 2022-05-06 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipIn.cpp 2023-03-26 11:00:00.000000000 +0000 @@ -11,8 +11,6 @@ #include "../../../Windows/PropVariant.h" -#include "../../Common/StreamUtils.h" - #include "../IArchive.h" #include "ZipIn.h" @@ -28,9 +26,38 @@ namespace NArchive { namespace NZip { -// (kBufferSize >= kDataDescriptorSize64 + 4) +/* we try to use same size of Buffer (1 << 17) for all tasks. + it allow to avoid reallocations and cache clearing. */ + +static const size_t kSeqBufferSize = (size_t)1 << 17; -static const size_t kSeqBufferSize = (size_t)1 << 14; +/* +Open() +{ + _inBufMode = false; + ReadVols() + FindCd(); + TryEcd64() + SeekToVol() + FindMarker() + _inBufMode = true; + ReadHeaders() + _inBufMode = false; + ReadCd() + FindCd() + TryEcd64() + TryReadCd() + { + SeekToVol(); + _inBufMode = true; + } + _inBufMode = true; + ReadLocals() + ReadCdItem() + .... +} +FindCd() writes to Buffer without touching (_inBufMode) +*/ /* if (not defined ZIP_SELF_CHECK) : it reads CD and if error in first pass CD reading, it reads LOCALS-CD-MODE @@ -187,11 +214,14 @@ return Stream->Seek((Int64)offset, STREAM_SEEK_SET, &_streamPos); } + +/* SeekToVol() will keep the cached mode, if new volIndex is + same Vols.StreamIndex volume, and offset doesn't go out of cached region */ + HRESULT CInArchive::SeekToVol(int volIndex, UInt64 offset) { if (volIndex != Vols.StreamIndex) { - InitBuf(); if (IsMultiVol && volIndex >= 0) { if ((unsigned)volIndex >= Vols.Streams.Size()) @@ -221,12 +251,29 @@ return S_OK; } } - InitBuf(); } + InitBuf(); return Seek_SavePos(offset); } +HRESULT CInArchive::AllocateBuffer(size_t size) +{ + if (size <= Buffer.Size()) + return S_OK; + /* in cached mode virtual_pos is not equal to phy_pos (_streamPos) + so we change _streamPos and do Seek() to virtual_pos before cache clearing */ + if (_bufPos != _bufCached) + { + RINOK(Seek_SavePos(GetVirtStreamPos())) + } + InitBuf(); + Buffer.AllocAtLeast(size); + if (!Buffer.IsAllocated()) + return E_OUTOFMEMORY; + return S_OK; +} + // ---------- ReadFromCache ---------- // reads from cache and from Stream // move to next volume can be allowed if (CanStartNewVol) and only before first byte reading @@ -465,7 +512,7 @@ { if (extraSize < 4) { - // 7-Zip before 9.31 created incorrect WsAES Extra in folder's local headers. + // 7-Zip before 9.31 created incorrect WzAES Extra in folder's local headers. // so we return k_IsArc_Res_YES to support such archives. // return k_IsArc_Res_NO; // do we need to support such extra ? return k_IsArc_Res_YES; @@ -508,20 +555,46 @@ -MY_NO_INLINE -static const Byte *FindPK(const Byte *p, const Byte *limit) +/* FindPK_4() is allowed to access data up to and including &limit[3]. + limit[4] access is not allowed. + return: + (return_ptr < limit) : "PK" was found at (return_ptr) + (return_ptr >= limit) : limit was reached or crossed. So no "PK" found before limit +*/ +Z7_NO_INLINE +static const Byte *FindPK_4(const Byte *p, const Byte *limit) { for (;;) { for (;;) { - Byte b0; - b0 = p[0]; if (p >= limit) return p; p++; if (b0 == 0x50) break; - b0 = p[0]; if (p >= limit) return p; p++; if (b0 == 0x50) break; + if (p >= limit) + return limit; + Byte b = p[1]; + if (b == 0x4B) { if (p[0] == 0x50) { return p; } p += 1; break; } + if (b == 0x50) { if (p[2] == 0x4B) { return p + 1; } p += 2; break; } + b = p[3]; + p += 4; + if (b == 0x4B) { if (p[-2]== 0x50) { return p - 2; } p -= 1; break; } + if (b == 0x50) { if (p[0] == 0x4B) { return p - 1; } break; } + } + } + /* + for (;;) + { + for (;;) + { + if (p >= limit) + return limit; + if (*p++ == 0x50) break; + if (*p++ == 0x50) break; + if (*p++ == 0x50) break; + if (*p++ == 0x50) break; } - if (p[0] == 0x4B) + if (*p == 0x4B) return p - 1; } + */ } @@ -554,7 +627,7 @@ if (searchLimit && *searchLimit == 0) { Byte startBuf[kMarkerSize]; - RINOK(ReadFromCache_FALSE(startBuf, kMarkerSize)); + RINOK(ReadFromCache_FALSE(startBuf, kMarkerSize)) UInt32 marker = Get32(startBuf); _signature = marker; @@ -562,7 +635,7 @@ if ( marker == NSignature::kNoSpan || marker == NSignature::kSpan) { - RINOK(ReadFromCache_FALSE(startBuf, kMarkerSize)); + RINOK(ReadFromCache_FALSE(startBuf, kMarkerSize)) _signature = Get32(startBuf); } @@ -579,16 +652,12 @@ return S_OK; } - const size_t kCheckSize = (size_t)1 << 16; // must be smaller than kBufSize - const size_t kBufSize = (size_t)1 << 17; // must be larger than kCheckSize + // zip specification: (_zip_header_size < (1 << 16)) + // so we need such size to check header + const size_t kCheckSize = (size_t)1 << 16; + const size_t kBufSize = (size_t)1 << 17; // (kBufSize must be > kCheckSize) - if (Buffer.Size() < kBufSize) - { - InitBuf(); - Buffer.AllocAtLeast(kBufSize); - if (!Buffer.IsAllocated()) - return E_OUTOFMEMORY; - } + RINOK(AllocateBuffer(kBufSize)) _inBufMode = true; @@ -596,12 +665,13 @@ for (;;) { - RINOK(LookAhead(kBufSize)); + RINOK(LookAhead(kBufSize)) const size_t avail = GetAvail(); size_t limitPos; - const bool isFinished = (avail != kBufSize); + // (avail > kBufSize) is possible, if (Buffer.Size() > kBufSize) + const bool isFinished = (avail < kBufSize); if (isFinished) { const unsigned kMinAllowed = 4; @@ -618,7 +688,7 @@ if (!s.Stream) break; - RINOK(s.SeekToStart()); + RINOK(s.SeekToStart()) InitBuf(); Vols.StreamIndex++; @@ -651,11 +721,15 @@ for (;; p++) { - p = FindPK(p, limit); + p = FindPK_4(p, limit); if (p >= limit) break; - const size_t rem = (size_t)(pStart + avail - p); - UInt32 res = IsArc_Zip_2(p, rem, isFinished); + size_t rem = (size_t)(pStart + avail - p); + /* 22.02 : we limit check size with kCheckSize to be consistent for + any different combination of _bufPos in Buffer and size of Buffer. */ + if (rem > kCheckSize) + rem = kCheckSize; + const UInt32 res = IsArc_Zip_2(p, rem, isFinished); if (res != k_IsArc_Res_NO) { if (rem < kMarkerSize) @@ -689,7 +763,7 @@ { progressPrev = _cnt; // const UInt64 numFiles64 = 0; - RINOK(Callback->SetCompleted(NULL, &_cnt)); + RINOK(Callback->SetCompleted(NULL, &_cnt)) } } @@ -734,6 +808,8 @@ return S_OK; } + // cache is empty + if (!IsMultiVol) { _cnt += offset; @@ -767,7 +843,7 @@ _cnt += offset; return Stream->Seek((Int64)offset, STREAM_SEEK_CUR, &_streamPos); } - RINOK(Seek_SavePos(s.Size)); + RINOK(Seek_SavePos(s.Size)) offset -= rem; _cnt += rem; } @@ -787,7 +863,7 @@ return S_OK; } Stream = s2.Stream; - RINOK(Seek_SavePos(0)); + RINOK(Seek_SavePos(0)) } } @@ -847,7 +923,7 @@ if (!s.Stream) return S_OK; - RINOK(s.SeekToStart()); + RINOK(s.SeekToStart()) Vols.StreamIndex++; _streamPos = 0; @@ -957,7 +1033,7 @@ if (Callback) { const UInt64 numFiles64 = numFiles; - RINOK(Callback->SetCompleted(&numFiles64, &_cnt)); + RINOK(Callback->SetCompleted(&numFiles64, &_cnt)) } } } @@ -1000,6 +1076,7 @@ const UInt32 pair = ReadUInt32(); subBlock.ID = (pair & 0xFFFF); unsigned size = (unsigned)(pair >> 16); + // const unsigned origSize = size; extraSize -= 4; @@ -1068,13 +1145,15 @@ } } + // we can ignore errors, when some zip archiver still write all fields to zip64 extra in local header + // if (&& (cdItem || !isOK || origSize != 8 * 3 + 4 || size != 8 * 1 + 4)) if (!isOK || size != 0) { HeadersWarning = true; extra.Error = true; extra.IsZip64_Error = true; - Skip(size); } + Skip(size); } else { @@ -1092,7 +1171,7 @@ { ExtraMinorError = true; extra.MinorError = true; - // 7-Zip before 9.31 created incorrect WsAES Extra in folder's local headers. + // 7-Zip before 9.31 created incorrect WzAES Extra in folder's local headers. // so we don't return false, but just set warning flag // return false; Skip(extraSize); @@ -1184,9 +1263,10 @@ mask &= 0x7FFF; } - // we can ignore utf8 flag, if name is ascii + // we can ignore utf8 flag, if name is ascii, or if only cdItem has utf8 flag if (mask & NFileHeader::NFlags::kUtf8) - if (i1.Name.IsAscii() && i2_cd.Name.IsAscii()) + if ((i1.Name.IsAscii() && i2_cd.Name.IsAscii()) + || (i2_cd.Flags & NFileHeader::NFlags::kUtf8)) mask &= ~NFileHeader::NFlags::kUtf8; // some bad archive in rare case can use descriptor without descriptor flag in Central Dir @@ -1270,11 +1350,8 @@ } -HRESULT CInArchive::ReadLocalItemAfterCdItem(CItemEx &item, bool &isAvail, bool &headersError) +HRESULT CInArchive::Read_LocalItem_After_CdItem(CItemEx &item, bool &isAvail, bool &headersError) { - InitBuf(); - _inBufMode = false; - isAvail = true; headersError = false; if (item.FromLocal) @@ -1315,13 +1392,16 @@ } } - RINOK(Seek_SavePos(offset)); - - /* - // we can check buf mode + _inBufMode = false; + RINOK(Seek_SavePos(offset)) InitBuf(); + /* + // we can use buf mode with small buffer to reduce + // the number of Read() calls in ReadLocalItem() _inBufMode = true; - Buffer.AllocAtLeast(1 << 10); + Buffer.Alloc(1 << 10); + if (!Buffer.IsAllocated()) + return E_OUTOFMEMORY; */ CItemEx localItem; @@ -1405,7 +1485,7 @@ // size_t processedSize; CanStartNewVol = true; - RINOK(LookAhead(descriptorSize4)); + RINOK(LookAhead(descriptorSize4)) const size_t avail = GetAvail(); if (avail < descriptorSize4) @@ -1429,7 +1509,7 @@ // descriptor signature field is Info-ZIP's extension to pkware Zip specification. // New ZIP specification also allows descriptorSignature. - p = FindPK(p, limit + 1); + p = FindPK_4(p, limit + 1); if (p > limit) break; @@ -1487,7 +1567,7 @@ { progressPrev = _cnt; const UInt64 numFiles64 = numFiles; - RINOK(Callback->SetCompleted(&numFiles64, &_cnt)); + RINOK(Callback->SetCompleted(&numFiles64, &_cnt)) } } } @@ -1501,7 +1581,7 @@ // pkzip's version without descriptor signature is not supported bool isFinished = false; - RINOK(IncreaseRealPosition(item.PackSize, isFinished)); + RINOK(IncreaseRealPosition(item.PackSize, isFinished)) if (isFinished) return S_FALSE; @@ -1548,7 +1628,7 @@ } -HRESULT CInArchive::ReadLocalItemAfterCdItemFull(CItemEx &item) +HRESULT CInArchive::Read_LocalItem_After_CdItem_Full(CItemEx &item) { if (item.FromLocal) return S_OK; @@ -1556,7 +1636,7 @@ { bool isAvail = true; bool headersError = false; - RINOK(ReadLocalItemAfterCdItem(item, isAvail, headersError)); + RINOK(Read_LocalItem_After_CdItem(item, isAvail, headersError)) if (headersError) return S_FALSE; if (item.HasDescriptor()) @@ -1606,14 +1686,22 @@ } +/* +TryEcd64() + (_inBufMode == false) is expected here + so TryEcd64() can't change the Buffer. + if (Ecd64 is not covered by cached region), + TryEcd64() can change cached region ranges (_bufCached, _bufPos) and _streamPos. +*/ + HRESULT CInArchive::TryEcd64(UInt64 offset, CCdInfo &cdInfo) { if (offset >= ((UInt64)1 << 63)) return S_FALSE; Byte buf[kEcd64_FullSize]; - RINOK(SeekToVol(Vols.StreamIndex, offset)); - RINOK(ReadFromCache_FALSE(buf, kEcd64_FullSize)); + RINOK(SeekToVol(Vols.StreamIndex, offset)) + RINOK(ReadFromCache_FALSE(buf, kEcd64_FullSize)) if (Get32(buf) != NSignature::kEcd64) return S_FALSE; @@ -1625,6 +1713,9 @@ } +/* FindCd() doesn't use previous cached region, + but it uses Buffer. So it sets new cached region */ + HRESULT CInArchive::FindCd(bool checkOffsetMode) { CCdInfo &cdInfo = Vols.ecd; @@ -1635,7 +1726,7 @@ // So here we don't use cache data from previous operations . InitBuf(); - RINOK(Stream->Seek(0, STREAM_SEEK_END, &endPos)); + RINOK(InStream_GetSize_SeekToEnd(Stream, endPos)) _streamPos = endPos; // const UInt32 kBufSizeMax2 = ((UInt32)1 << 16) + kEcdSize + kEcd64Locator_Size + kEcd64_FullSize; @@ -1646,15 +1737,9 @@ return S_FALSE; // CByteArr byteBuffer(bufSize); - if (Buffer.Size() < kBufSizeMax) - { - // InitBuf(); - Buffer.AllocAtLeast(kBufSizeMax); - if (!Buffer.IsAllocated()) - return E_OUTOFMEMORY; - } + RINOK(AllocateBuffer(kBufSizeMax)) - RINOK(Seek_SavePos(endPos - bufSize)); + RINOK(Seek_SavePos(endPos - bufSize)) size_t processed = bufSize; HRESULT res = ReadStream(Stream, Buffer, &processed); @@ -1799,14 +1884,14 @@ // _startLocalFromCd_Disk = (UInt32)(Int32)-1; // _startLocalFromCd_Offset = (UInt64)(Int64)-1; - RINOK(SeekToVol(IsMultiVol ? (int)cdInfo.CdDisk : -1, cdOffset)); + RINOK(SeekToVol(IsMultiVol ? (int)cdInfo.CdDisk : -1, cdOffset)) _inBufMode = true; _cnt = 0; if (Callback) { - RINOK(Callback->SetTotal(&cdInfo.NumEntries, IsMultiVol ? &Vols.TotalBytesSize : NULL)); + RINOK(Callback->SetTotal(&cdInfo.NumEntries, IsMultiVol ? &Vols.TotalBytesSize : NULL)) } UInt64 numFileExpected = cdInfo.NumEntries; const UInt64 *totalFilesPtr = &numFileExpected; @@ -1820,7 +1905,7 @@ CanStartNewVol = false; { CItemEx cdItem; - RINOK(ReadCdItem(cdItem)); + RINOK(ReadCdItem(cdItem)) /* if (cdItem.Disk < _startLocalFromCd_Disk || @@ -1854,10 +1939,10 @@ else while (numFiles > numFileExpected) numFileExpected += (UInt32)1 << 16; - RINOK(Callback->SetTotal(totalFilesPtr, NULL)); + RINOK(Callback->SetTotal(totalFilesPtr, NULL)) } - RINOK(Callback->SetCompleted(&numFiles, &_cnt)); + RINOK(Callback->SetCompleted(&numFiles, &_cnt)) } } @@ -1900,7 +1985,7 @@ if (!Vols.ecd_wasRead) { - RINOK(FindCd(checkOffsetMode)); + RINOK(FindCd(checkOffsetMode)) } CCdInfo &cdInfo = Vols.ecd; @@ -2004,7 +2089,7 @@ if (Callback) { - RINOK(Callback->SetTotal(NULL, IsMultiVol ? &Vols.TotalBytesSize : NULL)); + RINOK(Callback->SetTotal(NULL, IsMultiVol ? &Vols.TotalBytesSize : NULL)) } while (_signature == NSignature::kLocalFileHeader) @@ -2023,14 +2108,14 @@ if (item.HasDescriptor()) { - RINOK(FindDescriptor(item, items.Size())); + RINOK(FindDescriptor(item, items.Size())) isFinished = !item.DescriptorWasRead; } else { if (item.PackSize >= ((UInt64)1 << 62)) throw CUnexpectEnd(); - RINOK(IncreaseRealPosition(item.PackSize, isFinished)); + RINOK(IncreaseRealPosition(item.PackSize, isFinished)) } items.Add(item); @@ -2054,7 +2139,7 @@ { progressPrev = _cnt; const UInt64 numFiles = items.Size(); - RINOK(Callback->SetCompleted(&numFiles, &_cnt)); + RINOK(Callback->SetCompleted(&numFiles, &_cnt)) } } @@ -2072,7 +2157,7 @@ UString name; { NWindows::NCOM::CPropVariant prop; - RINOK(volCallback->GetProperty(kpidName, &prop)); + RINOK(volCallback->GetProperty(kpidName, &prop)) if (prop.vt != VT_BSTR) return S_OK; name = prop.bstrVal; @@ -2235,11 +2320,8 @@ } } - UInt64 size; - UInt64 pos; - RINOK(stream->Seek(0, STREAM_SEEK_CUR, &pos)); - RINOK(stream->Seek(0, STREAM_SEEK_END, &size)); - RINOK(stream->Seek((Int64)pos, STREAM_SEEK_SET, NULL)); + UInt64 pos, size; + RINOK(InStream_GetPos_GetSize(stream, pos, size)) while (i >= Vols.Streams.Size()) Vols.Streams.AddNew(); @@ -2270,7 +2352,7 @@ if (!volCallback) return S_OK; - RINOK(Vols.ParseArcName(volCallback)); + RINOK(Vols.ParseArcName(volCallback)) // const int startZIndex = Vols.StartVolIndex; @@ -2324,7 +2406,7 @@ if (cdDisk != zipDisk) { // get volumes required for cd. - RINOK(ReadVols2(volCallback, (unsigned)cdDisk, zipDisk, zipDisk, 0, numMissingVols)); + RINOK(ReadVols2(volCallback, (unsigned)cdDisk, zipDisk, zipDisk, 0, numMissingVols)) if (numMissingVols != 0) { // cdOK = false; @@ -2352,7 +2434,7 @@ { // get volumes that were no requested still const unsigned kNumMissingVolsMax = 1 << 12; - RINOK(ReadVols2(volCallback, 0, cdDisk < 0 ? -1 : cdDisk, zipDisk, kNumMissingVolsMax, numMissingVols)); + RINOK(ReadVols2(volCallback, 0, cdDisk < 0 ? -1 : cdDisk, zipDisk, kNumMissingVolsMax, numMissingVols)) } // if (Vols.StartVolIndex >= 0) @@ -2364,7 +2446,7 @@ || !Vols.Streams[(unsigned)Vols.StartVolIndex].Stream) { // we get volumes starting from StartVolIndex, if they we not requested before know the volume index (if FindCd() was ok) - RINOK(ReadVols2(volCallback, (unsigned)Vols.StartVolIndex, zipDisk, zipDisk, 0, numMissingVols)); + RINOK(ReadVols2(volCallback, (unsigned)Vols.StartVolIndex, zipDisk, zipDisk, 0, numMissingVols)) } } @@ -2377,7 +2459,7 @@ if (zipDisk >= 0) { // we create item in Streams for ZipStream, if we know the volume index (if FindCd() was ok) - RINOK(ReadVols2(volCallback, (unsigned)zipDisk, zipDisk + 1, zipDisk, 0, numMissingVols)); + RINOK(ReadVols2(volCallback, (unsigned)zipDisk, zipDisk + 1, zipDisk, 0, numMissingVols)) } } @@ -2428,7 +2510,7 @@ return S_FALSE; if (NeedSeek) { - RINOK(s.SeekToStart()); + RINOK(s.SeekToStart()) NeedSeek = false; } UInt32 realProcessedSize = 0; @@ -2444,7 +2526,7 @@ } } -STDMETHODIMP CVolStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CVolStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { return Vols->Read(data, size, processedSize); } @@ -2458,14 +2540,10 @@ HRESULT CInArchive::ReadHeaders(CObjectVector &items) { - if (Buffer.Size() < kSeqBufferSize) - { - InitBuf(); - Buffer.AllocAtLeast(kSeqBufferSize); - if (!Buffer.IsAllocated()) - return E_OUTOFMEMORY; - } + // buffer that can be used for cd reading + RINOK(AllocateBuffer(kSeqBufferSize)) + // here we can read small records. So we switch off _inBufMode. _inBufMode = false; HRESULT res = S_OK; @@ -2488,6 +2566,13 @@ UInt64 cdAbsOffset = 0; // absolute cd offset, for LOCALS-CD-MODE only. +if (Force_ReadLocals_Mode) +{ + IsArc = true; + res = S_FALSE; // we will use LOCALS-CD-MODE mode +} +else +{ if (!MarkerIsFound || !MarkerIsSafe) { IsArc = true; @@ -2497,7 +2582,7 @@ else if (res != S_FALSE) return res; } - else + else // (MarkerIsFound && MarkerIsSafe) { // _signature must be kLocalFileHeader or kEcd or kEcd64 @@ -2528,7 +2613,7 @@ return S_FALSE; } - RINOK(Skip64(recordSize - kEcd64_MainSize, 0)); + RINOK(Skip64(recordSize - kEcd64_MainSize, 0)) } ReadSignature(); @@ -2568,7 +2653,7 @@ ArcInfo.Base = (Int64)ArcInfo.MarkerPos; IsArc = true; // check it: we need more tests? - RINOK(SeekToVol(ArcInfo.MarkerVolIndex, ArcInfo.MarkerPos2)); + RINOK(SeekToVol(ArcInfo.MarkerVolIndex, ArcInfo.MarkerPos2)) ReadSignature(); } else @@ -2650,8 +2735,9 @@ } } } - } + } // (MarkerIsFound && MarkerIsSafe) +} // (!onlyLocalsMode) CObjectVector cdItems; @@ -2676,17 +2762,20 @@ HeadersWarning = false; ExtraMinorError = false; - // we can use any mode: with buffer and without buffer - // without buffer : skips packed data : fast for big files : slow for small files - // with buffer : reads packed data : slow for big files : fast for small files - - _inBufMode = false; - // _inBufMode = true; - - InitBuf(); + /* we can use any mode: with buffer and without buffer + without buffer : skips packed data : fast for big files : slow for small files + with buffer : reads packed data : slow for big files : fast for small files + Buffer mode is more effective. */ + // _inBufMode = false; + _inBufMode = true; + // we could change the buffer size here, if we want smaller Buffer. + // RINOK(ReAllocateBuffer(kSeqBufferSize)); + // InitBuf() ArcInfo.Base = 0; + if (!Disable_FindMarker) + { if (!MarkerIsFound) { if (!IsMultiVol) @@ -2695,7 +2784,7 @@ return S_FALSE; // if (StartParsingVol == 0) and we didn't find marker, we use default zero marker. // so we suppose that there is no sfx stub - RINOK(SeekToVol(0, ArcInfo.MarkerPos2)); + RINOK(SeekToVol(0, ArcInfo.MarkerPos2)) } else { @@ -2710,17 +2799,16 @@ */ ArcInfo.Base = (Int64)ArcInfo.MarkerPos2; } - - RINOK(SeekToVol(ArcInfo.MarkerVolIndex, ArcInfo.MarkerPos2)); + RINOK(SeekToVol(ArcInfo.MarkerVolIndex, ArcInfo.MarkerPos2)) } - + } _cnt = 0; ReadSignature(); LocalsWereRead = true; - RINOK(ReadLocals(items)); + RINOK(ReadLocals(items)) if (_signature != NSignature::kCentralFileHeader) { @@ -2775,14 +2863,14 @@ { CItemEx cdItem; - RINOK(ReadCdItem(cdItem)); + RINOK(ReadCdItem(cdItem)) cdItems.Add(cdItem); if (Callback && (cdItems.Size() & 0xFFF) == 0) { const UInt64 numFiles = items.Size(); const UInt64 numBytes = _cnt; - RINOK(Callback->SetCompleted(&numFiles, &numBytes)); + RINOK(Callback->SetCompleted(&numFiles, &numBytes)) } ReadSignature(); if (_signature != NSignature::kCentralFileHeader) @@ -2842,7 +2930,7 @@ cdInfo.ParseEcd64e(buf); } - RINOK(Skip64(recordSize - kEcd64_MainSize, items.Size())); + RINOK(Skip64(recordSize - kEcd64_MainSize, items.Size())) } @@ -2886,12 +2974,12 @@ ecd.Parse(buf); } - COPY_ECD_ITEM_16(ThisDisk); - COPY_ECD_ITEM_16(CdDisk); - COPY_ECD_ITEM_16(NumEntries_in_ThisDisk); - COPY_ECD_ITEM_16(NumEntries); - COPY_ECD_ITEM_32(Size); - COPY_ECD_ITEM_32(Offset); + COPY_ECD_ITEM_16(ThisDisk) + COPY_ECD_ITEM_16(CdDisk) + COPY_ECD_ITEM_16(NumEntries_in_ThisDisk) + COPY_ECD_ITEM_16(NumEntries) + COPY_ECD_ITEM_32(Size) + COPY_ECD_ITEM_32(Offset) bool cdOK = true; @@ -3040,7 +3128,7 @@ if ((i & 0x3FFF) == 0) { const UInt64 numFiles64 = items.Size() + items2.Size(); - RINOK(Callback->SetCompleted(&numFiles64, &_cnt)); + RINOK(Callback->SetCompleted(&numFiles64, &_cnt)) } const CItemEx &cdItem = cdItems[i]; @@ -3093,6 +3181,9 @@ item.ExternalAttrib = cdItem.ExternalAttrib; item.Comment = cdItem.Comment; item.FromCentral = cdItem.FromCentral; + // 22.02: we force utf8 flag, if central header has utf8 flag + if (cdItem.Flags & NFileHeader::NFlags::kUtf8) + item.Flags |= NFileHeader::NFlags::kUtf8; } FOR_VECTOR (k, items2) @@ -3175,8 +3266,8 @@ Close(); UInt64 startPos; - RINOK(stream->Seek(0, STREAM_SEEK_CUR, &startPos)); - RINOK(stream->Seek(0, STREAM_SEEK_END, &ArcInfo.FileEndPos)); + RINOK(InStream_GetPos(stream, startPos)) + RINOK(InStream_GetSize_SeekToEnd(stream, ArcInfo.FileEndPos)) _streamPos = ArcInfo.FileEndPos; StartStream = stream; @@ -3187,18 +3278,30 @@ bool volWasRequested = false; + if (!Disable_VolsRead) if (callback && (startPos == 0 || !searchLimit || *searchLimit != 0)) { // we try to read volumes only if it's first call (offset == 0) or scan is allowed. volWasRequested = true; - RINOK(ReadVols()); + RINOK(ReadVols()) } + if (Disable_FindMarker) + { + RINOK(SeekToVol(-1, startPos)) + StreamRef = stream; + Stream = stream; + MarkerIsFound = true; + MarkerIsSafe = true; + ArcInfo.MarkerPos = startPos; + ArcInfo.MarkerPos2 = startPos; + } + else if (IsMultiVol && Vols.StartParsingVol == 0 && (unsigned)Vols.StartParsingVol < Vols.Streams.Size()) { // only StartParsingVol = 0 is safe search. - RINOK(SeekToVol(0, 0)); + RINOK(SeekToVol(0, 0)) // if (Stream) { // UInt64 limit = 1 << 22; // for sfx @@ -3222,11 +3325,11 @@ && (unsigned)Vols.StartParsingVol < Vols.Streams.Size() && Vols.Streams[(unsigned)Vols.StartParsingVol].Stream) { - RINOK(SeekToVol(Vols.StartParsingVol, Vols.StreamIndex == Vols.StartVolIndex ? startPos : 0)); + RINOK(SeekToVol(Vols.StartParsingVol, Vols.StreamIndex == Vols.StartVolIndex ? startPos : 0)) } else { - RINOK(SeekToVol(-1, startPos)); + RINOK(SeekToVol(-1, startPos)) } // UInt64 limit = 1 << 22; @@ -3242,8 +3345,8 @@ else if (!IsMultiVol) { /* - // if (startPos != 0), probably CD copuld be already tested with another call with (startPos == 0). - // so we don't want to try to open CD again in that ase. + // if (startPos != 0), probably CD could be already tested with another call with (startPos == 0). + // so we don't want to try to open CD again in that case. if (startPos != 0) return res; // we can try to open CD, if there is no Marker and (startPos == 0). @@ -3254,7 +3357,7 @@ if (ArcInfo.IsSpanMode && !volWasRequested) { - RINOK(ReadVols()); + RINOK(ReadVols()) if (IsMultiVol && MarkerIsFound && ArcInfo.MarkerVolIndex < 0) ArcInfo.MarkerVolIndex = Vols.StartVolIndex; } @@ -3271,7 +3374,7 @@ Stream = Vols.Streams[(unsigned)Vols.StartVolIndex].Stream; if (Stream) { - RINOK(Seek_SavePos(curPos)); + RINOK(Seek_SavePos(curPos)) } else IsMultiVol = false; @@ -3287,7 +3390,7 @@ Stream = StartStream; Vols.StreamIndex = -1; InitBuf(); - RINOK(Seek_SavePos(curPos)); + RINOK(Seek_SavePos(curPos)) } ArcInfo.MarkerVolIndex = -1; @@ -3356,7 +3459,7 @@ if (UseDisk_in_SingleVol && item.Disk != EcdVolIndex) return S_OK; pos = (UInt64)((Int64)pos + ArcInfo.Base); - RINOK(StreamRef->Seek((Int64)pos, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(StreamRef, pos)) stream = StreamRef; return S_OK; } @@ -3367,7 +3470,7 @@ IInStream *str2 = Vols.Streams[item.Disk].Stream; if (!str2) return S_OK; - RINOK(str2->Seek((Int64)pos, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(str2, pos)) Vols.NeedSeek = false; Vols.StreamIndex = (int)item.Disk; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipIn.h 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipIn.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipIn.h 2021-07-30 07:34:44.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipIn.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,11 +1,12 @@ // Archive/ZipIn.h -#ifndef __ZIP_IN_H -#define __ZIP_IN_H +#ifndef ZIP7_INC_ZIP_IN_H +#define ZIP7_INC_ZIP_IN_H #include "../../../Common/MyBuffer2.h" #include "../../../Common/MyCom.h" +#include "../../Common/StreamUtils.h" #include "../../IStream.h" #include "ZipHeader.h" @@ -154,7 +155,7 @@ CMyComPtr Stream; UInt64 Size; - HRESULT SeekToStart() const { return Stream->Seek(0, STREAM_SEEK_SET, NULL); } + HRESULT SeekToStart() const { return InStream_SeekToBegin(Stream); } CSubStreamInfo(): Size(0) {} }; @@ -233,16 +234,12 @@ }; -class CVolStream: - public ISequentialInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CVolStream + , ISequentialInStream +) public: CVols *Vols; - - MY_UNKNOWN_IMP1(ISequentialInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); }; @@ -269,6 +266,8 @@ _cnt += skip; } + HRESULT AllocateBuffer(size_t size); + UInt64 GetVirtStreamPos() { return _streamPos - _bufCached + _bufPos; } bool _inBufMode; @@ -353,12 +352,19 @@ UInt32 EcdVolIndex; CVols Vols; + + bool Force_ReadLocals_Mode; + bool Disable_VolsRead; + bool Disable_FindMarker; CInArchive(): IsArcOpen(false), Stream(NULL), StartStream(NULL), - Callback(NULL) + Callback(NULL), + Force_ReadLocals_Mode(false), + Disable_VolsRead(false), + Disable_FindMarker(false) {} UInt64 GetPhySize() const @@ -412,8 +418,8 @@ HRESULT CheckDescriptor(const CItemEx &item); - HRESULT ReadLocalItemAfterCdItem(CItemEx &item, bool &isAvail, bool &headersError); - HRESULT ReadLocalItemAfterCdItemFull(CItemEx &item); + HRESULT Read_LocalItem_After_CdItem(CItemEx &item, bool &isAvail, bool &headersError); + HRESULT Read_LocalItem_After_CdItem_Full(CItemEx &item); HRESULT GetItemStream(const CItemEx &item, bool seekPackData, CMyComPtr &stream); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipItem.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipItem.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipItem.cpp 2022-05-05 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipItem.cpp 2023-03-06 16:00:00.000000000 +0000 @@ -45,7 +45,7 @@ void CExtraSubBlock::PrintInfo(AString &s) const { - for (unsigned i = 0; i < ARRAY_SIZE(g_ExtraTypes); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_ExtraTypes); i++) { const CUInt32PCharPair &pair = g_ExtraTypes[i]; if (pair.Value == ID) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipItem.h 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipItem.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipItem.h 2022-05-05 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipItem.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Archive/ZipItem.h -#ifndef __ARCHIVE_ZIP_ITEM_H -#define __ARCHIVE_ZIP_ITEM_H +#ifndef ZIP7_INC_ARCHIVE_ZIP_ITEM_H +#define ZIP7_INC_ARCHIVE_ZIP_ITEM_H #include "../../../../C/CpuArch.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipOut.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipOut.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipOut.cpp 2022-05-08 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipOut.cpp 2023-03-26 11:00:00.000000000 +0000 @@ -12,6 +12,20 @@ namespace NArchive { namespace NZip { +HRESULT COutArchive::ClearRestriction() +{ + if (SetRestriction) + return SetRestriction->SetRestriction(0, 0); + return S_OK; +} + +HRESULT COutArchive::SetRestrictionFromCurrent() +{ + if (SetRestriction) + return SetRestriction->SetRestriction(m_Base + m_CurPos, (UInt64)(Int64)-1); + return S_OK; +} + HRESULT COutArchive::Create(IOutStream *outStream) { m_CurPos = 0; @@ -97,7 +111,7 @@ } -#define WRITE_32_VAL_SPEC(__v, __isZip64) Write32((__isZip64) ? 0xFFFFFFFF : (UInt32)(__v)); +#define WRITE_32_VAL_SPEC(_v_, _isZip64_) Write32((_isZip64_) ? 0xFFFFFFFF : (UInt32)(_v_)); void COutArchive::WriteUtfName(const CItemOut &item) @@ -192,8 +206,8 @@ size = 0; } - WRITE_32_VAL_SPEC(packSize, isZip64); - WRITE_32_VAL_SPEC(size, isZip64); + WRITE_32_VAL_SPEC(packSize, isZip64) + WRITE_32_VAL_SPEC(size, isZip64) Write16((UInt16)item.Name.Len()); @@ -249,19 +263,19 @@ void COutArchive::WriteDescriptor(const CItemOut &item) { Byte buf[kDataDescriptorSize64]; - SetUi32(buf, NSignature::kDataDescriptor); - SetUi32(buf + 4, item.Crc); + SetUi32(buf, NSignature::kDataDescriptor) + SetUi32(buf + 4, item.Crc) unsigned descriptorSize; if (m_IsZip64) { - SetUi64(buf + 8, item.PackSize); - SetUi64(buf + 16, item.Size); + SetUi64(buf + 8, item.PackSize) + SetUi64(buf + 16, item.Size) descriptorSize = kDataDescriptorSize64; } else { - SetUi32(buf + 8, (UInt32)item.PackSize); - SetUi32(buf + 12, (UInt32)item.Size); + SetUi32(buf + 8, (UInt32)item.PackSize) + SetUi32(buf + 12, (UInt32)item.Size) descriptorSize = kDataDescriptorSize32; } WriteBytes(buf, descriptorSize); @@ -283,8 +297,8 @@ WriteCommonItemInfo(item, isZip64); Write32(item.Crc); - WRITE_32_VAL_SPEC(item.PackSize, isPack64); - WRITE_32_VAL_SPEC(item.Size, isUnPack64); + WRITE_32_VAL_SPEC(item.PackSize, isPack64) + WRITE_32_VAL_SPEC(item.Size, isUnPack64) Write16((UInt16)item.Name.Len()); @@ -306,10 +320,10 @@ const UInt16 commentSize = (UInt16)item.Comment.Size(); Write16(commentSize); - Write16(0); // DiskNumberStart; + Write16(0); // DiskNumberStart Write16(item.InternalAttrib); Write32(item.ExternalAttrib); - WRITE_32_VAL_SPEC(item.LocalHeaderPos, isPosition64); + WRITE_32_VAL_SPEC(item.LocalHeaderPos, isPosition64) WriteBytes((const char *)item.Name, item.Name.Len()); if (isZip64) @@ -332,8 +346,10 @@ WriteBytes(item.Comment, commentSize); } -void COutArchive::WriteCentralDir(const CObjectVector &items, const CByteBuffer *comment) +HRESULT COutArchive::WriteCentralDir(const CObjectVector &items, const CByteBuffer *comment) { + RINOK(ClearRestriction()) + const UInt64 cdOffset = GetCurPos(); FOR_VECTOR (i, items) WriteCentralHeader(items[i]); @@ -357,8 +373,8 @@ Write16(45); // made by version Write16(45); // extract version - Write32(0); // ThisDiskNumber = 0; - Write32(0); // StartCentralDirectoryDiskNumber;; + Write32(0); // ThisDiskNumber + Write32(0); // StartCentralDirectoryDiskNumber Write64((UInt64)items.Size()); Write64((UInt64)items.Size()); Write64((UInt64)cdSize); @@ -373,19 +389,20 @@ } Write32(NSignature::kEcd); - Write16(0); // ThisDiskNumber = 0; - Write16(0); // StartCentralDirectoryDiskNumber; + Write16(0); // ThisDiskNumber + Write16(0); // StartCentralDirectoryDiskNumber Write16((UInt16)(items64 ? 0xFFFF: items.Size())); Write16((UInt16)(items64 ? 0xFFFF: items.Size())); - WRITE_32_VAL_SPEC(cdSize, cdSize64); - WRITE_32_VAL_SPEC(cdOffset, cdOffset64); + WRITE_32_VAL_SPEC(cdSize, cdSize64) + WRITE_32_VAL_SPEC(cdOffset, cdOffset64) const UInt16 commentSize = (UInt16)(comment ? comment->Size() : 0); Write16((UInt16)commentSize); if (commentSize != 0) WriteBytes((const Byte *)*comment, commentSize); m_OutBuffer.FlushWithCheck(); + return S_OK; } void COutArchive::CreateStreamForCompressing(CMyComPtr &outStream) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipOut.h 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipOut.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipOut.h 2022-01-26 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipOut.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ZipOut.h -#ifndef __ZIP_OUT_H -#define __ZIP_OUT_H +#ifndef ZIP7_INC_ZIP_OUT_H +#define ZIP7_INC_ZIP_OUT_H #include "../../../Common/MyCom.h" @@ -74,6 +74,10 @@ void SeekToCurPos(); public: + CMyComPtr SetRestriction; + + HRESULT ClearRestriction(); + HRESULT SetRestrictionFromCurrent(); HRESULT Create(IOutStream *outStream); UInt64 GetCurPos() const { return m_CurPos; } @@ -88,7 +92,7 @@ void WriteDescriptor(const CItemOut &item); - void WriteCentralDir(const CObjectVector &items, const CByteBuffer *comment); + HRESULT WriteCentralDir(const CObjectVector &items, const CByteBuffer *comment); void CreateStreamForCompressing(CMyComPtr &outStream); void CreateStreamForCopying(CMyComPtr &outStream); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipRegister.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipRegister.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipRegister.cpp 2022-05-08 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipRegister.cpp 2022-12-20 16:00:00.000000000 +0000 @@ -17,7 +17,7 @@ 6, 0x50, 0x4B, 0x30, 0x30, 0x50, 0x4B }; // NoSpan REGISTER_ARC_IO( - "zip", "zip z01 zipx jar xpi odt ods docx xlsx epub ipa apk appx", 0, 1, + "zip", "zip z01 zipx jar xpi odt ods docx xlsx epub ipa apk appx", NULL, 1, k_Signature, 0, NArcInfoFlags::kFindSignature diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipUpdate.cpp 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipUpdate.cpp --- 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipUpdate.cpp 2022-05-07 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipUpdate.cpp 2023-03-29 10:00:00.000000000 +0000 @@ -2,6 +2,15 @@ #include "StdAfx.h" +// #define DEBUG_CACHE + +#ifdef DEBUG_CACHE +#include + #define PRF(x) x +#else + #define PRF(x) +#endif + #include "../../../../C/Alloc.h" #include "../../../Common/AutoPtr.h" @@ -15,12 +24,13 @@ #include "../../Common/LimitedStreams.h" #include "../../Common/OutMemStream.h" #include "../../Common/ProgressUtils.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "../../Common/ProgressMt.h" #endif #include "../../Common/StreamUtils.h" #include "../../Compress/CopyCoder.h" +// #include "../../Compress/ZstdEncoderProps.h" #include "ZipAddCommon.h" #include "ZipOut.h" @@ -107,7 +117,7 @@ item.ExtractVersion.HostOS = kExtractHostOS; item.InternalAttrib = 0; // test it - item.SetEncrypted(!isDir && options.PasswordIsDefined); + item.SetEncrypted(!isDir && options.Password_Defined); item.SetDescriptorMode(useDescriptor); if (isDir) @@ -156,7 +166,7 @@ } -#ifndef _7ZIP_ST +#ifndef Z7_ST struct CMtSem { @@ -191,7 +201,7 @@ struct CThreadInfo { - DECL_EXTERNAL_CODECS_LOC_VARS2; + DECL_EXTERNAL_CODECS_LOC_VARS_DECL NWindows::CThread Thread; NWindows::NSynchronization::CAutoResetEvent CompressEvent; @@ -211,19 +221,24 @@ HRESULT Result; CCompressingResult CompressingResult; + bool IsFree; bool InSeqMode; bool OutSeqMode; - bool IsFree; + bool ExpectedDataSize_IsConfirmed; + UInt32 UpdateIndex; UInt32 FileTime; UInt64 ExpectedDataSize; CThreadInfo(): + MtSem(NULL), ExitThread(false), ProgressSpec(NULL), OutStreamSpec(NULL), + IsFree(true), InSeqMode(false), OutSeqMode(false), + ExpectedDataSize_IsConfirmed(false), FileTime(0), ExpectedDataSize((UInt64)(Int64)-1) {} @@ -270,6 +285,7 @@ EXTERNAL_CODECS_LOC_VARS InStream, OutStream, InSeqMode, OutSeqMode, FileTime, ExpectedDataSize, + ExpectedDataSize_IsConfirmed, Progress, CompressingResult); if (Result == S_OK && Progress) @@ -313,7 +329,7 @@ public: CMemBlockManagerMt *Manager; CObjectVector Refs; - CMemRefs(CMemBlockManagerMt *manager): Manager(manager) {} ; + CMemRefs(CMemBlockManagerMt *manager): Manager(manager) {} ~CMemRefs() { FOR_VECTOR (i, Refs) @@ -321,10 +337,11 @@ } }; -class CMtProgressMixer2: - public ICompressProgressInfo, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_NOQIB_1( + CMtProgressMixer2 + , ICompressProgressInfo +) UInt64 ProgressOffset; UInt64 InSizes[2]; UInt64 OutSizes[2]; @@ -333,12 +350,10 @@ bool _inSizeIsMain; public: NWindows::NSynchronization::CCriticalSection CriticalSection; - MY_UNKNOWN_IMP void Create(IProgress *progress, bool inSizeIsMain); void SetProgressOffset(UInt64 progressOffset); void SetProgressOffset_NoLock(UInt64 progressOffset); HRESULT SetRatioInfo(unsigned index, const UInt64 *inSize, const UInt64 *outSize); - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); }; void CMtProgressMixer2::Create(IProgress *progress, bool inSizeIsMain) @@ -367,7 +382,7 @@ NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection); if (index == 0 && RatioProgress) { - RINOK(RatioProgress->SetRatioInfo(inSize, outSize)); + RINOK(RatioProgress->SetRatioInfo(inSize, outSize)) } if (inSize) InSizes[index] = *inSize; @@ -379,21 +394,20 @@ return Progress->SetCompleted(&v); } -STDMETHODIMP CMtProgressMixer2::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) +Z7_COM7F_IMF(CMtProgressMixer2::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize)) { return SetRatioInfo(0, inSize, outSize); } -class CMtProgressMixer: - public ICompressProgressInfo, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_NOQIB_1( + CMtProgressMixer + , ICompressProgressInfo +) public: CMtProgressMixer2 *Mixer2; CMyComPtr RatioProgress; void Create(IProgress *progress, bool inSizeIsMain); - MY_UNKNOWN_IMP - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); }; void CMtProgressMixer::Create(IProgress *progress, bool inSizeIsMain) @@ -403,7 +417,7 @@ Mixer2->Create(progress, inSizeIsMain); } -STDMETHODIMP CMtProgressMixer::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) +Z7_COM7F_IMF(CMtProgressMixer::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize)) { return Mixer2->SetRatioInfo(1, inSize, outSize); } @@ -431,6 +445,8 @@ UInt64 rangeSize; + RINOK(archive.ClearRestriction()) + if (ui.NewProps) { if (item.HasDescriptor()) @@ -456,7 +472,7 @@ CMyComPtr packStream; - RINOK(inArchive->GetItemStream(itemEx, ui.NewProps, packStream)); + RINOK(inArchive->GetItemStream(itemEx, ui.NewProps, packStream)) if (!packStream) return E_NOTIMPL; @@ -470,11 +486,13 @@ } -static void WriteDirHeader(COutArchive &archive, const CCompressionMethodMode *options, +static HRESULT WriteDirHeader(COutArchive &archive, const CCompressionMethodMode *options, const CUpdateItem &ui, CItemOut &item) { SetFileHeader(*options, ui, false, item); + RINOK(archive.ClearRestriction()) archive.WriteLocalHeader(item); + return S_OK; } @@ -485,37 +503,55 @@ { CMyComPtr getProps; fileInStream->QueryInterface(IID_IStreamGetProps, (void **)&getProps); - if (!getProps) - return; - - FILETIME cTime, aTime, mTime; - UInt64 size; - UInt32 attrib; - if (getProps->GetProps(&size, &cTime, &aTime, &mTime, &attrib) != S_OK) - return; + UInt64 size = (UInt64)(Int64)-1; + bool size_WasSet = false; - if (size != item.Size && size != (UInt64)(Int64)-1) + if (getProps) { - const Int64 newComplexity = (Int64)totalComplexity + ((Int64)size - (Int64)item.Size); - if (newComplexity > 0) + FILETIME cTime, aTime, mTime; + UInt32 attrib; + if (getProps->GetProps(&size, &cTime, &aTime, &mTime, &attrib) == S_OK) { - totalComplexity = (UInt64)newComplexity; - updateCallback->SetTotal(totalComplexity); + if (options.Write_MTime) + if (!FILETIME_IsZero(mTime)) + { + item.Ntfs_MTime = mTime; + NTime::UtcFileTime_To_LocalDosTime(mTime, item.Time); + } + + if (options.Write_CTime) if (!FILETIME_IsZero(cTime)) item.Ntfs_CTime = cTime; + if (options.Write_ATime) if (!FILETIME_IsZero(aTime)) item.Ntfs_ATime = aTime; + + item.Attrib = attrib; + size_WasSet = true; } - item.Size = size; } - if (options.Write_MTime) - if (!FILETIME_IsZero(mTime)) + if (!size_WasSet) + { + CMyComPtr streamGetSize; + fileInStream->QueryInterface(IID_IStreamGetSize, (void **)&streamGetSize); + if (streamGetSize) { - item.Ntfs_MTime = mTime; - NTime::UtcFileTime_To_LocalDosTime(mTime, item.Time); + if (streamGetSize->GetSize(&size) == S_OK) + size_WasSet = true; } + } - if (options.Write_CTime) if (!FILETIME_IsZero(cTime)) item.Ntfs_CTime = cTime; - if (options.Write_ATime) if (!FILETIME_IsZero(aTime)) item.Ntfs_ATime = aTime; - - item.Attrib = attrib; + if (size_WasSet && size != (UInt64)(Int64)-1) + { + item.Size_WasSetFromStream = true; + if (size != item.Size) + { + const Int64 newComplexity = (Int64)totalComplexity + ((Int64)size - (Int64)item.Size); + if (newComplexity > 0) + { + totalComplexity = (UInt64)newComplexity; + updateCallback->SetTotal(totalComplexity); + } + item.Size = size; + } + } } @@ -613,7 +649,7 @@ { lps->InSize = unpackSizeTotal; lps->OutSize = packSizeTotal; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CUpdateItem &ui = updateItems[itemIndex]; CItemEx itemEx; CItemOut item; @@ -623,7 +659,7 @@ // Note: for (ui.NewProps && !ui.NewData) it copies Props from old archive, // But we will rewrite all important properties later. But we can keep some properties like Comment itemEx = inputItems[(unsigned)ui.IndexInArc]; - if (inArchive->ReadLocalItemAfterCdItemFull(itemEx) != S_OK) + if (inArchive->Read_LocalItem_After_CdItem_Full(itemEx) != S_OK) return E_NOTIMPL; (CItem &)item = itemEx; } @@ -634,7 +670,7 @@ bool isDir = ui.IsDir; if (isDir) { - WriteDirHeader(archive, options, ui, item); + RINOK(WriteDirHeader(archive, options, ui, item)) } else { @@ -644,10 +680,10 @@ if (res == S_FALSE) { lps->ProgressOffset += ui.Size; - RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); + RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)) continue; } - RINOK(res); + RINOK(res) if (!fileInStream) return E_INVALIDARG; @@ -667,7 +703,7 @@ RINOK(compressor.Set_Pre_CompressionResult( inSeqMode, outSeqMode, ui.Size, - compressingResult)); + compressingResult)) SetFileHeader(*options, ui, compressingResult.DescriptorMode, item); @@ -675,6 +711,7 @@ SetItemInfoFromCompressingResult(compressingResult, options->IsRealAesMode(), options->AesKeyMode, item); + RINOK(archive.SetRestrictionFromCurrent()) archive.WriteLocalHeader(item); CMyComPtr outStream; @@ -684,8 +721,9 @@ EXTERNAL_CODECS_LOC_VARS fileInStream, outStream, inSeqMode, outSeqMode, - ui.Time, ui.Size, - progress, compressingResult)); + ui.Time, + ui.Size, ui.Size_WasSetFromStream, + progress, compressingResult)) if (item.HasDescriptor() != compressingResult.DescriptorMode) return E_FAIL; @@ -695,7 +733,7 @@ archive.WriteLocalHeader_Replace(item); } // if (reportArcProp) RINOK(ReportProps(reportArcProp, ui.IndexInClient, item, options->IsRealAesMode())) - RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); + RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)) unpackSizeTotal += item.Size; packSizeTotal += item.PackSize; } @@ -705,7 +743,7 @@ UInt64 complexity = 0; lps->SendRatio = false; - RINOK(UpdateItemOldData(archive, inArchive, itemEx, ui, item, progress, opCallback, complexity)); + RINOK(UpdateItemOldData(archive, inArchive, itemEx, ui, item, progress, opCallback, complexity)) lps->SendRatio = true; lps->ProgressOffset += complexity; @@ -717,9 +755,9 @@ lps->InSize = unpackSizeTotal; lps->OutSize = packSizeTotal; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) - archive.WriteCentralDir(items, comment); + RINOK(archive.WriteCentralDir(items, comment)) /* CTotalStats stat; @@ -733,6 +771,130 @@ return lps->SetCur(); } +#ifndef Z7_ST + + +static const size_t kBlockSize = 1 << 16; +// kMemPerThread must be >= kBlockSize +// +static const size_t kMemPerThread = (size_t)sizeof(size_t) << 23; +// static const size_t kMemPerThread = (size_t)sizeof(size_t) << 16; // for debug +// static const size_t kMemPerThread = (size_t)1 << 16; // for debug + +/* +in: + nt_Zip >= 1: the starting maximum number of ZIP threads for search +out: + nt_Zip: calculated number of ZIP threads + returns: calculated number of ZSTD threads +*/ +/* +static UInt32 CalcThreads_for_ZipZstd(CZstdEncProps *zstdProps, + UInt64 memLimit, UInt32 totalThreads, + UInt32 &nt_Zip) +{ + for (; nt_Zip > 1; nt_Zip--) + { + UInt64 mem1 = memLimit / nt_Zip; + if (mem1 <= kMemPerThread) + continue; + mem1 -= kMemPerThread; + UInt32 n_ZSTD = ZstdEncProps_GetNumThreads_for_MemUsageLimit( + zstdProps, mem1, totalThreads / nt_Zip); + // we don't allow (nbWorkers == 1) here + if (n_ZSTD <= 1) + n_ZSTD = 0; + zstdProps->nbWorkers = n_ZSTD; + mem1 = ZstdEncProps_GetMemUsage(zstdProps); + if ((mem1 + kMemPerThread) * nt_Zip <= memLimit) + return n_ZSTD; + } + return ZstdEncProps_GetNumThreads_for_MemUsageLimit( + zstdProps, memLimit, totalThreads); +} + + +static UInt32 SetZstdThreads( + const CCompressionMethodMode &options, + COneMethodInfo *oneMethodMain, + UInt32 numThreads, + UInt32 numZipThreads_limit, + UInt64 numFilesToCompress, + UInt64 numBytesToCompress) +{ + NCompress::NZstd::CEncoderProps encoderProps; + RINOK(encoderProps.SetFromMethodProps(*oneMethodMain)); + CZstdEncProps &zstdProps = encoderProps.EncProps; + ZstdEncProps_NormalizeFull(&zstdProps); + if (oneMethodMain->FindProp(NCoderPropID::kNumThreads) >= 0) + { + // threads for ZSTD are fixed + if (zstdProps.nbWorkers > 1) + numThreads /= zstdProps.nbWorkers; + if (numThreads > numZipThreads_limit) + numThreads = numZipThreads_limit; + if (options._memUsage_WasSet + && !options._numThreads_WasForced) + { + const UInt64 mem1 = ZstdEncProps_GetMemUsage(&zstdProps); + const UInt64 numZipThreads = options._memUsage_Compress / (mem1 + kMemPerThread); + if (numThreads > numZipThreads) + numThreads = (UInt32)numZipThreads; + } + return numThreads; + } + { + // threads for ZSTD are not fixed + + // calculate estimated required number of ZST threads per file size statistics + UInt32 t = MY_ZSTDMT_NBWORKERS_MAX; + { + UInt64 averageNumberOfBlocks = 0; + const UInt64 averageSize = numBytesToCompress / numFilesToCompress; + const UInt64 jobSize = zstdProps.jobSize; + if (jobSize != 0) + averageNumberOfBlocks = averageSize / jobSize + 0; + if (t > averageNumberOfBlocks) + t = (UInt32)averageNumberOfBlocks; + } + if (t > numThreads) + t = numThreads; + + // calculate the nuber of zip threads + UInt32 numZipThreads = numThreads; + if (t > 1) + numZipThreads = numThreads / t; + if (numZipThreads > numZipThreads_limit) + numZipThreads = numZipThreads_limit; + if (numZipThreads < 1) + numZipThreads = 1; + { + // recalculate the number of ZSTD threads via the number of ZIP threads + const UInt32 t2 = numThreads / numZipThreads; + if (t < t2) + t = t2; + } + + if (options._memUsage_WasSet + && !options._numThreads_WasForced) + { + t = CalcThreads_for_ZipZstd(&zstdProps, + options._memUsage_Compress, numThreads, numZipThreads); + numThreads = numZipThreads; + } + // we don't use (nbWorkers = 1) here + if (t <= 1) + t = 0; + oneMethodMain->AddProp_NumThreads(t); + return numThreads; + } +} +*/ + +#endif + + + static HRESULT Update2( DECL_EXTERNAL_CODECS_LOC_VARS @@ -755,8 +917,10 @@ bool unknownComplexity = false; UInt64 complexity = 0; + #ifndef Z7_ST UInt64 numFilesToCompress = 0; UInt64 numBytesToCompress = 0; + #endif unsigned i; @@ -769,8 +933,10 @@ unknownComplexity = true; else complexity += ui.Size; + #ifndef Z7_ST numBytesToCompress += ui.Size; numFilesToCompress++; + #endif /* if (ui.Commented) complexity += ui.CommentRange.Size; @@ -779,7 +945,7 @@ else { CItemEx inputItem = inputItems[(unsigned)ui.IndexInArc]; - if (inArchive->ReadLocalItemAfterCdItemFull(inputItem) != S_OK) + if (inArchive->Read_LocalItem_After_CdItem_Full(inputItem) != S_OK) return E_NOTIMPL; complexity += inputItem.GetLocalFullSize(); // complexity += inputItem.GetCentralExtraPlusCommentSize(); @@ -831,10 +997,22 @@ } - #ifndef _7ZIP_ST + #ifndef Z7_ST UInt32 numThreads = options._numThreads; + UInt32 numZipThreads_limit = numThreads; + if (numZipThreads_limit > numFilesToCompress) + numZipThreads_limit = (UInt32)numFilesToCompress; + + if (numZipThreads_limit > 1) + { + const unsigned numFiles_OPEN_MAX = NSystem::Get_File_OPEN_MAX_Reduced_for_3_tasks(); + // printf("\nzip:numFiles_OPEN_MAX =%d\n", (unsigned)numFiles_OPEN_MAX); + if (numZipThreads_limit > numFiles_OPEN_MAX) + numZipThreads_limit = (UInt32)numFiles_OPEN_MAX; + } + { const UInt32 kNumMaxThreads = #ifdef _WIN32 @@ -849,11 +1027,13 @@ if (numThreads > MAXIMUM_WAIT_OBJECTS) // is 64 in Windows numThreads = MAXIMUM_WAIT_OBJECTS; */ + + + /* + // zstd supports (numThreads == 0); if (numThreads < 1) numThreads = 1; - - const size_t kMemPerThread = (size_t)sizeof(size_t) << 23; - const size_t kBlockSize = 1 << 16; + */ bool mtMode = (numThreads > 1); @@ -864,21 +1044,46 @@ if (!mtMode) { + // if (oneMethodMain) { + /* + if (method == NFileHeader::NCompressionMethod::kZstdWz) + { + if (oneMethodMain->FindProp(NCoderPropID::kNumThreads) < 0) + { + // numZstdThreads was not forced in oneMethodMain + if (numThreads >= 1 + && options._memUsage_WasSet + && !options._numThreads_WasForced) + { + NCompress::NZstd::CEncoderProps encoderProps; + RINOK(encoderProps.SetFromMethodProps(*oneMethodMain)) + CZstdEncProps &zstdProps = encoderProps.EncProps; + ZstdEncProps_NormalizeFull(&zstdProps); + numThreads = ZstdEncProps_GetNumThreads_for_MemUsageLimit( + &zstdProps, options._memUsage_Compress, numThreads); + // we allow (nbWorkers = 1) here. + } + oneMethodMain->AddProp_NumThreads(numThreads); + } + } // kZstdWz + */ + // } // oneMethodMain + FOR_VECTOR (mi, options2._methods) { COneMethodInfo &onem = options2._methods[mi]; if (onem.FindProp(NCoderPropID::kNumThreads) < 0) { - // fixme: we should check the number of threads for xz mehod also + // fixme: we should check the number of threads for xz method also // fixed for 9.31. bzip2 default is just one thread. onem.AddProp_NumThreads(numThreads); } } } - else + else // mtMode { - if (method == NFileHeader::NCompressionMethod::kStore && !options.PasswordIsDefined) + if (method == NFileHeader::NCompressionMethod::kStore && !options.Password_Defined) numThreads = 1; if (oneMethodMain) @@ -925,6 +1130,15 @@ } numThreads /= (unsigned)numXzThreads; } + /* + else if (method == NFileHeader::NCompressionMethod::kZstdWz) + { + numThreads = SetZstdThreads(options, + oneMethodMain, numThreads, + numZipThreads_limit, + numFilesToCompress, numBytesToCompress); + } + */ else if ( method == NFileHeader::NCompressionMethod::kDeflate || method == NFileHeader::NCompressionMethod::kDeflate64 @@ -964,8 +1178,8 @@ } } // (oneMethodMain) - if (numThreads > numFilesToCompress) - numThreads = (UInt32)numFilesToCompress; + if (numThreads > numZipThreads_limit) + numThreads = numZipThreads_limit; if (numThreads <= 1) { mtMode = false; @@ -989,13 +1203,15 @@ ); - #ifndef _7ZIP_ST + #ifndef Z7_ST /* CTotalStats stat; stat.Size = 0; stat.PackSize = 0; */ + if (numThreads < 1) + numThreads = 1; CObjectVector items; @@ -1022,7 +1238,7 @@ CUIntVector threadIndices; // list threads in order of updateItems { - RINOK(memManager.AllocateSpaceAlways((size_t)numThreads * (kMemPerThread / kBlockSize))); + RINOK(memManager.AllocateSpaceAlways((size_t)numThreads * (kMemPerThread / kBlockSize))) for (i = 0; i < updateItems.Size(); i++) refs.Refs.Add(CMemBlocks2()); @@ -1035,25 +1251,20 @@ for (i = 0; i < numThreads; i++) { CThreadInfo &threadInfo = threads.Threads[i]; - threadInfo.SetOptions(options2); ; - #ifdef EXTERNAL_CODECS - threadInfo.__externalCodecs = __externalCodecs; + threadInfo.ThreadIndex = i; + threadInfo.SetOptions(options2); + #ifdef Z7_EXTERNAL_CODECS + threadInfo._externalCodecs = _externalCodecs; #endif - RINOK(threadInfo.CreateEvents()); + RINOK(threadInfo.CreateEvents()) threadInfo.OutStreamSpec = new COutMemStream(&memManager); - RINOK(threadInfo.OutStreamSpec->CreateEvents(SYNC_WFMO(&memManager.Synchro))); + RINOK(threadInfo.OutStreamSpec->CreateEvents(SYNC_WFMO(&memManager.Synchro))) threadInfo.OutStream = threadInfo.OutStreamSpec; - threadInfo.IsFree = true; threadInfo.ProgressSpec = new CMtCompressProgress(); threadInfo.Progress = threadInfo.ProgressSpec; threadInfo.ProgressSpec->Init(&mtCompressProgressMixer, i); - threadInfo.InSeqMode = false; - threadInfo.OutSeqMode = false; - threadInfo.FileTime = 0; - threadInfo.ExpectedDataSize = (UInt64)(Int64)-1; - threadInfo.ThreadIndex = i; threadInfo.MtSem = &mtSem; - RINOK(threadInfo.CreateThread()); + RINOK(threadInfo.CreateThread()) } } @@ -1084,7 +1295,7 @@ else { itemEx = inputItems[(unsigned)ui.IndexInArc]; - if (inArchive->ReadLocalItemAfterCdItemFull(itemEx) != S_OK) + if (inArchive->Read_LocalItem_After_CdItem_Full(itemEx) != S_OK) return E_NOTIMPL; (CItem &)item = itemEx; if (item.IsDir() != ui.IsDir) @@ -1105,15 +1316,15 @@ complexity += ui.Size; complexity += kLocalHeaderSize; mtProgressMixerSpec->Mixer2->SetProgressOffset_NoLock(complexity); - RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); + RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)) memRef2.Skip = true; continue; } - RINOK(res); + RINOK(res) if (!fileInStream) return E_INVALIDARG; UpdatePropsFromStream(updateOptions, ui, fileInStream, updateCallback, totalComplexity); - RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); + RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)) } UInt32 k; @@ -1151,6 +1362,7 @@ threadInfo.OutSeqMode = outSeqMode; threadInfo.FileTime = ui.Time; // FileTime is used for ZipCrypto only in seqMode threadInfo.ExpectedDataSize = ui.Size; + threadInfo.ExpectedDataSize_IsConfirmed = ui.Size_WasSetFromStream; threadInfo.CompressEvent.Set(); @@ -1175,7 +1387,7 @@ if (!ui.NewProps || !ui.NewData) { itemEx = inputItems[(unsigned)ui.IndexInArc]; - if (inArchive->ReadLocalItemAfterCdItemFull(itemEx) != S_OK) + if (inArchive->Read_LocalItem_After_CdItem_Full(itemEx) != S_OK) return E_NOTIMPL; (CItem &)item = itemEx; } @@ -1187,7 +1399,7 @@ if (isDir) { - WriteDirHeader(archive, &options, ui, item); + RINOK(WriteDirHeader(archive, &options, ui, item)) } else { @@ -1206,12 +1418,21 @@ SetItemInfoFromCompressingResult(memRef.CompressingResult, options.IsRealAesMode(), options.AesKeyMode, item); + RINOK(archive.ClearRestriction()) archive.WriteLocalHeader(item); // RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); CMyComPtr outStream; archive.CreateStreamForCopying(outStream); memRef.WriteToStream(memManager.GetBlockSize(), outStream); - archive.MoveCurPos(item.PackSize); + // v23: we fixed the bug: we need to write descriptor also + if (item.HasDescriptor()) + { + /* that function doesn't rewrite local header, if item.HasDescriptor(). + it just writes descriptor */ + archive.WriteLocalHeader_Replace(item); + } + else + archive.MoveCurPos(item.PackSize); memRef.FreeOpt(&memManager); /* if (reportArcProp) @@ -1237,7 +1458,7 @@ RINOK(compressor.Set_Pre_CompressionResult( memRef.InSeqMode, outSeqMode, ui.Size, - compressingResult)); + compressingResult)) memRef.PreDescriptorMode = compressingResult.DescriptorMode; SetFileHeader(options, ui, compressingResult.DescriptorMode, item); @@ -1245,6 +1466,7 @@ SetItemInfoFromCompressingResult(compressingResult, options.IsRealAesMode(), options.AesKeyMode, item); // file Size can be 64-bit !!! + RINOK(archive.SetRestrictionFromCurrent()) archive.WriteLocalHeader(item); } @@ -1270,7 +1492,7 @@ CThreadInfo &threadInfo = threads.Threads[(unsigned)ti]; threadInfo.InStream.Release(); threadInfo.IsFree = true; - RINOK(threadInfo.Result); + RINOK(threadInfo.Result) unsigned t = 0; @@ -1293,7 +1515,7 @@ if (memRef.PreDescriptorMode != threadInfo.CompressingResult.DescriptorMode) return E_FAIL; - RINOK(threadInfo.OutStreamSpec->WriteToRealStream()); + RINOK(threadInfo.OutStreamSpec->WriteToRealStream()) threadInfo.OutStreamSpec->ReleaseOutStream(); SetFileHeader(options, ui, threadInfo.CompressingResult.DescriptorMode, item); SetItemInfoFromCompressingResult(threadInfo.CompressingResult, @@ -1324,7 +1546,7 @@ } else { - RINOK(UpdateItemOldData(archive, inArchive, itemEx, ui, item, progress, opCallback, complexity)); + RINOK(UpdateItemOldData(archive, inArchive, itemEx, ui, item, progress, opCallback, complexity)) } items.Add(item); @@ -1333,9 +1555,9 @@ itemIndex++; } - RINOK(mtCompressProgressMixer.SetRatioInfo(0, NULL, NULL)); + RINOK(mtCompressProgressMixer.SetRatioInfo(0, NULL, NULL)) - archive.WriteCentralDir(items, comment); + RINOK(archive.WriteCentralDir(items, comment)) /* if (reportArcProp) @@ -1351,15 +1573,61 @@ #endif } +/* +// we need CSeekOutStream, if we need Seek(0, STREAM_SEEK_CUR) for seqential stream +Z7_CLASS_IMP_COM_1( + CSeekOutStream + , IOutStream +) + Z7_IFACE_COM7_IMP(ISequentialOutStream) + + CMyComPtr _seqStream; + UInt64 _size; +public: + void Init(ISequentialOutStream *seqStream) + { + _size = 0; + _seqStream = seqStream; + } +}; + +Z7_COM7F_IMF(CSeekOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) +{ + UInt32 realProcessedSize; + const HRESULT result = _seqStream->Write(data, size, &realProcessedSize); + _size += realProcessedSize; + if (processedSize) + *processedSize = realProcessedSize; + return result; +} + +Z7_COM7F_IMF(CSeekOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) +{ + if (seekOrigin != STREAM_SEEK_CUR || offset != 0) + return E_NOTIMPL; + if (newPosition) + *newPosition = (UInt64)_size; + return S_OK; +} + +Z7_COM7F_IMF(CSeekOutStream::SetSize(UInt64 newSize)) +{ + UNUSED_VAR(newSize) + return E_NOTIMPL; +} +*/ static const size_t kCacheBlockSize = (1 << 20); static const size_t kCacheSize = (kCacheBlockSize << 2); static const size_t kCacheMask = (kCacheSize - 1); -class CCacheOutStream: - public IOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_2( + CCacheOutStream + , IOutStream + , IStreamSetRestriction +) + Z7_IFACE_COM7_IMP(ISequentialOutStream) + CMyComPtr _stream; CMyComPtr _seqStream; Byte *_cache; @@ -1369,26 +1637,29 @@ UInt64 _phySize; // <= _virtSize UInt64 _cachedPos; // (_cachedPos + _cachedSize) <= _virtSize size_t _cachedSize; + HRESULT _hres; + + UInt64 _restrict_begin; + UInt64 _restrict_end; + UInt64 _restrict_phy; // begin + CMyComPtr _setRestriction; HRESULT MyWrite(size_t size); HRESULT MyWriteBlock() { return MyWrite(kCacheBlockSize - ((size_t)_cachedPos & (kCacheBlockSize - 1))); } + HRESULT WriteNonRestrictedBlocks(); HRESULT FlushCache(); public: CCacheOutStream(): _cache(NULL) {} ~CCacheOutStream(); bool Allocate(); - HRESULT Init(ISequentialOutStream *seqStream, IOutStream *stream); - - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); - STDMETHOD(SetSize)(UInt64 newSize); + HRESULT Init(ISequentialOutStream *seqStream, IOutStream *stream, IStreamSetRestriction *setRestriction); + HRESULT FinalFlush(); }; + bool CCacheOutStream::Allocate() { if (!_cache) @@ -1396,40 +1667,59 @@ return (_cache != NULL); } -HRESULT CCacheOutStream::Init(ISequentialOutStream *seqStream, IOutStream *stream) +HRESULT CCacheOutStream::Init(ISequentialOutStream *seqStream, IOutStream *stream, IStreamSetRestriction *setRestriction) { + _cachedPos = 0; + _cachedSize = 0; + _hres = S_OK; + _restrict_begin = 0; + _restrict_end = 0; + _restrict_phy = 0; _virtPos = 0; - _phyPos = 0; _virtSize = 0; _seqStream = seqStream; _stream = stream; + _setRestriction = setRestriction; if (_stream) { - RINOK(_stream->Seek(0, STREAM_SEEK_CUR, &_virtPos)); - RINOK(_stream->Seek(0, STREAM_SEEK_END, &_virtSize)); - RINOK(_stream->Seek((Int64)_virtPos, STREAM_SEEK_SET, &_virtPos)); + RINOK(_stream->Seek(0, STREAM_SEEK_CUR, &_virtPos)) + RINOK(_stream->Seek(0, STREAM_SEEK_END, &_virtSize)) + RINOK(_stream->Seek((Int64)_virtPos, STREAM_SEEK_SET, &_virtPos)) } _phyPos = _virtPos; _phySize = _virtSize; - _cachedPos = 0; - _cachedSize = 0; return S_OK; } + +/* it writes up to (size) bytes from cache. + (size > _cachedSize) is allowed */ + HRESULT CCacheOutStream::MyWrite(size_t size) { + PRF(printf("\n-- CCacheOutStream::MyWrite %u\n", (unsigned)size)); + if (_hres != S_OK) + return _hres; while (size != 0 && _cachedSize != 0) { if (_phyPos != _cachedPos) { if (!_stream) return E_FAIL; - RINOK(_stream->Seek((Int64)_cachedPos, STREAM_SEEK_SET, &_phyPos)); + _hres = _stream->Seek((Int64)_cachedPos, STREAM_SEEK_SET, &_phyPos); + RINOK(_hres) + if (_phyPos != _cachedPos) + { + _hres = E_FAIL; + return _hres; + } } - size_t pos = (size_t)_cachedPos & kCacheMask; - size_t curSize = MyMin(kCacheSize - pos, _cachedSize); + const size_t pos = (size_t)_cachedPos & kCacheMask; + size_t curSize = kCacheSize - pos; + curSize = MyMin(curSize, _cachedSize); curSize = MyMin(curSize, size); - RINOK(WriteStream(_seqStream, _cache + pos, curSize)); + _hres = WriteStream(_seqStream, _cache + pos, curSize); + RINOK(_hres) _phyPos += curSize; if (_phySize < _phyPos) _phySize = _phyPos; @@ -1437,112 +1727,131 @@ _cachedSize -= curSize; size -= curSize; } + + if (_setRestriction) + if (_restrict_begin == _restrict_end || _cachedPos <= _restrict_begin) + if (_restrict_phy < _cachedPos) + { + _restrict_phy = _cachedPos; + return _setRestriction->SetRestriction(_cachedPos, (UInt64)(Int64)-1); + } return S_OK; } + +HRESULT CCacheOutStream::WriteNonRestrictedBlocks() +{ + for (;;) + { + const size_t size = kCacheBlockSize - ((size_t)_cachedPos & (kCacheBlockSize - 1)); + if (_cachedSize < size) + break; + if (_restrict_begin != _restrict_end && _cachedPos + size > _restrict_begin) + break; + RINOK(MyWrite(size)) + } + return S_OK; +} + + HRESULT CCacheOutStream::FlushCache() { return MyWrite(_cachedSize); } -CCacheOutStream::~CCacheOutStream() +HRESULT CCacheOutStream::FinalFlush() { - FlushCache(); - if (_stream) + _restrict_begin = 0; + _restrict_end = 0; + RINOK(FlushCache()) + if (_stream && _hres == S_OK) { if (_virtSize != _phySize) - _stream->SetSize(_virtSize); + { + // it's unexpected + RINOK(_stream->SetSize(_virtSize)) + } if (_virtPos != _phyPos) - _stream->Seek((Int64)_virtPos, STREAM_SEEK_SET, NULL); + { + RINOK(_stream->Seek((Int64)_virtPos, STREAM_SEEK_SET, NULL)) + } } + return S_OK; +} + + +CCacheOutStream::~CCacheOutStream() +{ ::MidFree(_cache); } -STDMETHODIMP CCacheOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) + +Z7_COM7F_IMF(CCacheOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { + PRF(printf("\n-- CCacheOutStream::Write %u\n", (unsigned)size)); + if (processedSize) *processedSize = 0; if (size == 0) return S_OK; + if (_hres != S_OK) + return _hres; - UInt64 zerosStart = _virtPos; if (_cachedSize != 0) + if (_virtPos < _cachedPos || + _virtPos > _cachedPos + _cachedSize) { - if (_virtPos < _cachedPos) - { - RINOK(FlushCache()); - } - else - { - UInt64 cachedEnd = _cachedPos + _cachedSize; - if (cachedEnd < _virtPos) - { - if (cachedEnd < _phySize) - { - RINOK(FlushCache()); - } - else - zerosStart = cachedEnd; - } - } + RINOK(FlushCache()) } - if (_cachedSize == 0 && _phySize < _virtPos) - _cachedPos = zerosStart = _phySize; - - if (zerosStart != _virtPos) - { - // write zeros to [cachedEnd ... _virtPos) - - for (;;) - { - UInt64 cachedEnd = _cachedPos + _cachedSize; - size_t endPos = (size_t)cachedEnd & kCacheMask; - size_t curSize = kCacheSize - endPos; - if (curSize > _virtPos - cachedEnd) - curSize = (size_t)(_virtPos - cachedEnd); - if (curSize == 0) - break; - while (curSize > (kCacheSize - _cachedSize)) - { - RINOK(MyWriteBlock()); - } - memset(_cache + endPos, 0, curSize); - _cachedSize += curSize; - } - } + // ---------- Writing data to cache ---------- if (_cachedSize == 0) _cachedPos = _virtPos; - size_t pos = (size_t)_virtPos & kCacheMask; + const size_t pos = (size_t)_virtPos & kCacheMask; size = (UInt32)MyMin((size_t)size, kCacheSize - pos); - UInt64 cachedEnd = _cachedPos + _cachedSize; - if (_virtPos != cachedEnd) // _virtPos < cachedEnd + const UInt64 cachedEnd = _cachedPos + _cachedSize; + + // (_virtPos >= _cachedPos) (_virtPos <= cachedEnd) + + if (_virtPos != cachedEnd) + { + // _virtPos < cachedEnd + // we rewrite only existing data in cache. So _cachedSize will be not changed size = (UInt32)MyMin((size_t)size, (size_t)(cachedEnd - _virtPos)); + } else { // _virtPos == cachedEnd + // so we need to add new data to the end of cache if (_cachedSize == kCacheSize) { - RINOK(MyWriteBlock()); + // cache is full. So we flush part of cache + RINOK(MyWriteBlock()) } - size_t startPos = (size_t)_cachedPos & kCacheMask; + // _cachedSize != kCacheSize + // so we have some space for new data in cache + const size_t startPos = (size_t)_cachedPos & kCacheMask; + // we don't allow new data to overwrite old start data in cache. if (startPos > pos) size = (UInt32)MyMin((size_t)size, (size_t)(startPos - pos)); _cachedSize += size; } + memcpy(_cache + pos, data, size); if (processedSize) *processedSize = size; _virtPos += size; if (_virtSize < _virtPos) _virtSize = _virtPos; - return S_OK; + return WriteNonRestrictedBlocks(); } -STDMETHODIMP CCacheOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) + +Z7_COM7F_IMF(CCacheOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { + PRF(printf("\n-- CCacheOutStream::Seek seekOrigin=%d Seek =%u\n", seekOrigin, (unsigned)offset)); switch (seekOrigin) { case STREAM_SEEK_SET: break; @@ -1558,27 +1867,58 @@ return S_OK; } -STDMETHODIMP CCacheOutStream::SetSize(UInt64 newSize) + +Z7_COM7F_IMF(CCacheOutStream::SetSize(UInt64 newSize)) { + if (_hres != S_OK) + return _hres; _virtSize = newSize; - if (newSize < _phySize) - { - if (!_stream) - return E_NOTIMPL; - RINOK(_stream->SetSize(newSize)); - _phySize = newSize; - } + if (newSize <= _cachedPos) { _cachedSize = 0; _cachedPos = newSize; } - if (newSize < _cachedPos + _cachedSize) - _cachedSize = (size_t)(newSize - _cachedPos); + else + { + // newSize > _cachedPos + const UInt64 offset = newSize - _cachedPos; + if (offset <= _cachedSize) + { + _cachedSize = (size_t)offset; + if (_phySize <= newSize) + return S_OK; + } + else + { + // newSize > _cachedPos + _cachedSize + // So we flush cache + RINOK(FlushCache()) + } + } + + if (newSize != _phySize) + { + if (!_stream) + return E_NOTIMPL; + _hres = _stream->SetSize(newSize); + RINOK(_hres) + _phySize = newSize; + } return S_OK; } +Z7_COM7F_IMF(CCacheOutStream::SetRestriction(UInt64 begin, UInt64 end)) +{ + PRF(printf("\n============ CCacheOutStream::SetRestriction %u, %u\n", (unsigned)begin, (unsigned)end)); + _restrict_begin = begin; + _restrict_end = end; + return WriteNonRestrictedBlocks(); +} + + + HRESULT Update( DECL_EXTERNAL_CODECS_LOC_VARS const CObjectVector &inputItems, @@ -1589,21 +1929,36 @@ const CCompressionMethodMode &compressionMethodMode, IArchiveUpdateCallback *updateCallback) { + /* + // it was tested before if (inArchive) { if (!inArchive->CanUpdate()) return E_NOTIMPL; } + */ + CMyComPtr setRestriction; + seqOutStream->QueryInterface(IID_IStreamSetRestriction, (void **)&setRestriction); + if (setRestriction) + { + RINOK(setRestriction->SetRestriction(0, 0)) + } CMyComPtr outStream; + CCacheOutStream *cacheStream; bool outSeqMode; + { CMyComPtr outStreamReal; - seqOutStream->QueryInterface(IID_IOutStream, (void **)&outStreamReal); - if (!outStreamReal) + + if (!compressionMethodMode.Force_SeqOutMode) { - // return E_NOTIMPL; + seqOutStream->QueryInterface(IID_IOutStream, (void **)&outStreamReal); + /* + if (!outStreamReal) + return E_NOTIMPL; + */ } if (inArchive) @@ -1611,42 +1966,62 @@ if (!inArchive->IsMultiVol && inArchive->ArcInfo.Base > 0 && !removeSfx) { IInStream *baseStream = inArchive->GetBaseStream(); - RINOK(baseStream->Seek(0, STREAM_SEEK_SET, NULL)); - RINOK(NCompress::CopyStream_ExactSize(baseStream, seqOutStream, (UInt64)inArchive->ArcInfo.Base, NULL)); + RINOK(InStream_SeekToBegin(baseStream)) + RINOK(NCompress::CopyStream_ExactSize(baseStream, seqOutStream, (UInt64)inArchive->ArcInfo.Base, NULL)) } } - CCacheOutStream *cacheStream = new CCacheOutStream(); - outStream = cacheStream; - if (!cacheStream->Allocate()) - return E_OUTOFMEMORY; - RINOK(cacheStream->Init(seqOutStream, outStreamReal)); + // bool use_cacheStream = true; + // if (use_cacheStream) + { + cacheStream = new CCacheOutStream(); + outStream = cacheStream; + if (!cacheStream->Allocate()) + return E_OUTOFMEMORY; + RINOK(cacheStream->Init(seqOutStream, outStreamReal, setRestriction)) + setRestriction.Release(); + setRestriction = cacheStream; + } + /* + else if (!outStreamReal) + { + CSeekOutStream *seekOutStream = new CSeekOutStream(); + outStream = seekOutStream; + seekOutStream->Init(seqOutStream); + } + else + outStream = outStreamReal; + */ outSeqMode = (outStreamReal == NULL); } COutArchive outArchive; - RINOK(outArchive.Create(outStream)); + outArchive.SetRestriction = setRestriction; + + RINOK(outArchive.Create(outStream)) if (inArchive) { if (!inArchive->IsMultiVol && (Int64)inArchive->ArcInfo.MarkerPos2 > inArchive->ArcInfo.Base) { IInStream *baseStream = inArchive->GetBaseStream(); - RINOK(baseStream->Seek(inArchive->ArcInfo.Base, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(baseStream, (UInt64)inArchive->ArcInfo.Base)) const UInt64 embStubSize = (UInt64)((Int64)inArchive->ArcInfo.MarkerPos2 - inArchive->ArcInfo.Base); - RINOK(NCompress::CopyStream_ExactSize(baseStream, outStream, embStubSize, NULL)); + RINOK(NCompress::CopyStream_ExactSize(baseStream, outStream, embStubSize, NULL)) outArchive.MoveCurPos(embStubSize); } } - return Update2( + RINOK (Update2( EXTERNAL_CODECS_LOC_VARS outArchive, inArchive, inputItems, updateItems, updateOptions, compressionMethodMode, outSeqMode, inArchive ? &inArchive->ArcInfo.Comment : NULL, - updateCallback); + updateCallback)) + + return cacheStream->FinalFlush(); } }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipUpdate.h 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipUpdate.h --- 7zip-22.01+dfsg/CPP/7zip/Archive/Zip/ZipUpdate.h 2022-05-07 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Archive/Zip/ZipUpdate.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ZipUpdate.h -#ifndef __ZIP_UPDATE_H -#define __ZIP_UPDATE_H +#ifndef ZIP7_INC_ZIP_UPDATE_H +#define ZIP7_INC_ZIP_UPDATE_H #include "../../ICoder.h" #include "../IArchive.h" @@ -20,8 +20,8 @@ UInt64 Position; UInt64 Size; - // CUpdateRange() {}; - CUpdateRange(UInt64 position, UInt64 size): Position(position), Size(size) {}; + // CUpdateRange() {} + CUpdateRange(UInt64 position, UInt64 size): Position(position), Size(size) {} }; */ @@ -34,6 +34,7 @@ bool Write_UnixTime; // bool Write_UnixTime_ATime; bool IsUtf8; + bool Size_WasSetFromStream; // bool IsAltStream; int IndexInArc; unsigned IndexInClient; @@ -57,6 +58,7 @@ Write_UnixTime = false; IsUtf8 = false; + Size_WasSetFromStream = false; // IsAltStream = false; Time = 0; Size = 0; @@ -74,6 +76,7 @@ Write_NtfsTime(false), Write_UnixTime(false), IsUtf8(false), + Size_WasSetFromStream(false), // IsAltStream(false), Time(0), Size(0) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone/afxres.h 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone/afxres.h --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone/afxres.h 2003-09-23 18:42:28.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone/afxres.h 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -#include diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone/Alone.dsp 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone/Alone.dsp --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone/Alone.dsp 2021-09-12 11:31:56.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone/Alone.dsp 2023-04-05 10:00:00.000000000 +0000 @@ -44,7 +44,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /Gr /MT /W4 /WX /GX /O1 /I "..\..\..\\" /D "NDEBUG" /D "_MBCS" /D "WIN32" /D "_CONSOLE" /D "WIN_LONG_PATH" /D "_7ZIP_LARGE_PAGES" /D "SUPPORT_DEVICE_FILE" /FAcs /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gr /MT /W4 /WX /GX /O1 /I "..\..\..\\" /D "NDEBUG" /D "_MBCS" /D "WIN32" /D "_CONSOLE" /D "Z7_LONG_PATH" /D "Z7_LARGE_PAGES" /D "Z7_DEVICE_FILE" /FAcs /Yu"StdAfx.h" /FD /c # ADD BASE RSC /l 0x419 /d "NDEBUG" # ADD RSC /l 0x419 /d "NDEBUG" BSC32=bscmake.exe @@ -69,7 +69,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /Gz /MDd /W4 /Gm /GX /ZI /Od /I "..\..\..\\" /D "_DEBUG" /D "_MBCS" /D "WIN32" /D "_CONSOLE" /D "WIN_LONG_PATH" /D "_7ZIP_LARGE_PAGES" /D "SUPPORT_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gz /MDd /W4 /Gm /GX /ZI /Od /I "..\..\..\\" /D "_DEBUG" /D "_MBCS" /D "WIN32" /D "_CONSOLE" /D "Z7_LONG_PATH" /D "Z7_LARGE_PAGES" /D "Z7_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c # SUBTRACT CPP /WX # ADD BASE RSC /l 0x419 /d "_DEBUG" # ADD RSC /l 0x419 /d "_DEBUG" @@ -94,8 +94,8 @@ # PROP Intermediate_Dir "ReleaseU" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" -# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "EXCLUDE_COM" /D "NO_REGISTRY" /Yu"StdAfx.h" /FD /c -# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /I "..\..\..\\" /D "NDEBUG" /D "UNICODE" /D "_UNICODE" /D "WIN32" /D "_CONSOLE" /D "WIN_LONG_PATH" /D "_7ZIP_LARGE_PAGES" /D "SUPPORT_DEVICE_FILE" /Yu"StdAfx.h" /FD /c +# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /I "..\..\..\\" /D "NDEBUG" /D "UNICODE" /D "_UNICODE" /D "WIN32" /D "_CONSOLE" /D "Z7_LONG_PATH" /D "Z7_LARGE_PAGES" /D "Z7_DEVICE_FILE" /Yu"StdAfx.h" /FD /c # ADD BASE RSC /l 0x419 /d "NDEBUG" # ADD RSC /l 0x419 /d "NDEBUG" BSC32=bscmake.exe @@ -121,8 +121,8 @@ # PROP Intermediate_Dir "DebugU" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "EXCLUDE_COM" /D "NO_REGISTRY" /D "_MBCS" /Yu"StdAfx.h" /FD /GZ /c -# ADD CPP /nologo /Gz /MDd /W4 /WX /Gm /GX /ZI /Od /I "..\..\..\\" /D "_DEBUG" /D "_UNICODE" /D "UNICODE" /D "WIN32" /D "_CONSOLE" /D "WIN_LONG_PATH" /D "_7ZIP_LARGE_PAGES" /D "SUPPORT_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gz /MDd /W4 /WX /Gm /GX /ZI /Od /I "..\..\..\\" /D "_DEBUG" /D "_UNICODE" /D "UNICODE" /D "WIN32" /D "_CONSOLE" /D "Z7_LONG_PATH" /D "Z7_LARGE_PAGES" /D "Z7_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c # ADD BASE RSC /l 0x419 /d "_DEBUG" # ADD RSC /l 0x419 /d "_DEBUG" BSC32=bscmake.exe @@ -722,6 +722,14 @@ # End Source File # Begin Source File +SOURCE=..\..\Common\MultiOutStream.cpp +# End Source File +# Begin Source File + +SOURCE=..\..\Common\MultiOutStream.h +# End Source File +# Begin Source File + SOURCE=..\..\Common\OffsetStream.cpp # End Source File # Begin Source File @@ -2311,6 +2319,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\7zWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\Aes.c !IF "$(CFG)" == "Alone - Win32 Release" @@ -3163,6 +3175,34 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\SwapBytes.c + +!IF "$(CFG)" == "Alone - Win32 Release" + +# ADD CPP /O2 +# SUBTRACT CPP /YX /Yc /Yu + +!ELSEIF "$(CFG)" == "Alone - Win32 Debug" + +# SUBTRACT CPP /YX /Yc /Yu + +!ELSEIF "$(CFG)" == "Alone - Win32 ReleaseU" + +# SUBTRACT CPP /YX /Yc /Yu + +!ELSEIF "$(CFG)" == "Alone - Win32 DebugU" + +# SUBTRACT CPP /YX /Yc /Yu + +!ENDIF + +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\SwapBytes.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\Threads.c !IF "$(CFG)" == "Alone - Win32 Release" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone/makefile 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone/makefile --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone/makefile 2021-09-12 07:29:02.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone/makefile 2023-04-05 11:00:00.000000000 +0000 @@ -56,6 +56,7 @@ $O\MemBlocks.obj \ $O\MethodId.obj \ $O\MethodProps.obj \ + $O\MultiOutStream.obj \ $O\OffsetStream.obj \ $O\OutBuffer.obj \ $O\OutMemStream.obj \ @@ -209,6 +210,7 @@ $O\Ppmd8Dec.obj \ $O\Ppmd8Enc.obj \ $O\Sort.obj \ + $O\SwapBytes.obj \ $O\Threads.obj \ $O\Xz.obj \ $O\XzDec.obj \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone/makefile.gcc 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone/makefile.gcc --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone/makefile.gcc 2022-07-14 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone/makefile.gcc 2023-04-05 11:00:00.000000000 +0000 @@ -24,7 +24,7 @@ ifdef ST_MODE -LOCAL_FLAGS_ST = -D_7ZIP_ST +LOCAL_FLAGS_ST = -DZ7_ST ifdef IS_MINGW MT_OBJS = \ @@ -53,9 +53,9 @@ ifdef IS_MINGW LOCAL_FLAGS_SYS = \ - -D_7ZIP_LARGE_PAGES \ - -DWIN_LONG_PATH \ - -DSUPPORT_DEVICE_FILE \ + -DZ7_LARGE_PAGES \ + -DZ7_LONG_PATH \ + -DZ7_DEVICE_FILE \ SYS_OBJS = \ $O/FileSystem.o \ @@ -164,6 +164,7 @@ $O/LimitedStreams.o \ $O/MethodId.o \ $O/MethodProps.o \ + $O/MultiOutStream.o \ $O/OffsetStream.o \ $O/OutBuffer.o \ $O/ProgressUtils.o \ @@ -309,6 +310,7 @@ $O/Ppmd8Dec.o \ $O/Ppmd8Enc.o \ $O/Sort.o \ + $O/SwapBytes.o \ $O/Xz.o \ $O/XzDec.o \ $O/XzEnc.o \ @@ -325,7 +327,7 @@ $O/Sha1Opt.o \ OBJS = \ - $(LZMA_DEC_OPT_OBJS) \ + $(LZMA_DEC_OPT_OBJS) \ $(C_OBJS) \ $(MT_OBJS) \ $(SYS_OBJS) \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone2/makefile 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone2/makefile --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone2/makefile 2022-01-09 19:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone2/makefile 2023-04-05 11:00:00.000000000 +0000 @@ -1,7 +1,7 @@ PROG = 7zz.exe # USE_C_AES = 1 # USE_C_SHA = 1 -CFLAGS = $(CFLAGS) -DPROG_VARIANT_Z +CFLAGS = $(CFLAGS) -DZ7_PROG_VARIANT_Z !include "../Format7zF/Arc.mak" !include "../../UI/Console/Console.mak" @@ -24,5 +24,6 @@ 7ZIP_COMMON_OBJS = $(7ZIP_COMMON_OBJS) \ $O\FilePathAutoRename.obj \ $O\FileStreams.obj \ + $O\MultiOutStream.obj \ !include "../../7zip.mak" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone2/makefile.gcc 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone2/makefile.gcc --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone2/makefile.gcc 2022-07-14 07:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone2/makefile.gcc 2023-04-05 11:00:00.000000000 +0000 @@ -4,7 +4,7 @@ # USE_ASM = 1 # ST_MODE = 1 -CONSOLE_VARIANT_FLAGS=-DPROG_VARIANT_Z +CONSOLE_VARIANT_FLAGS=-DZ7_PROG_VARIANT_Z include ../Format7zF/Arc_gcc.mak @@ -20,9 +20,9 @@ ifdef IS_MINGW LOCAL_FLAGS_SYS = \ - -D_7ZIP_LARGE_PAGES \ - -DWIN_LONG_PATH \ - -DSUPPORT_DEVICE_FILE \ + -DZ7_LARGE_PAGES \ + -DZ7_LONG_PATH \ + -DZ7_DEVICE_FILE \ SYS_OBJS = \ $O/FileSystem.o \ @@ -95,6 +95,7 @@ 7ZIP_COMMON_OBJS_2 = \ $O/FilePathAutoRename.o \ $O/FileStreams.o \ + $O/MultiOutStream.o \ OBJS = \ $(ARC_OBJS) \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone2/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone2/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone2/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone2/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone7z/Alone.dsp 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone7z/Alone.dsp --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone7z/Alone.dsp 2021-12-19 20:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone7z/Alone.dsp 2023-04-05 12:00:00.000000000 +0000 @@ -44,7 +44,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /Gr /MT /W4 /WX /GX /O1 /I "..\..\..\\" /D "NDEBUG" /D "_MBCS" /D "WIN32" /D "_CONSOLE" /D "_7ZIP_LARGE_PAGES" /D "SUPPORT_DEVICE_FILE" /FAcs /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gr /MT /W4 /WX /GX /O1 /I "..\..\..\\" /D "NDEBUG" /D "_MBCS" /D "WIN32" /D "_CONSOLE" /D "Z7_LARGE_PAGES" /D "Z7_DEVICE_FILE" /FAcs /Yu"StdAfx.h" /FD /c # ADD BASE RSC /l 0x419 /d "NDEBUG" # ADD RSC /l 0x419 /d "NDEBUG" BSC32=bscmake.exe @@ -69,7 +69,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /Gr /MDd /W4 /WX /Gm /GX /ZI /Od /I "..\..\..\\" /D "_DEBUG" /D "_MBCS" /D "WIN32" /D "_CONSOLE" /D "_7ZIP_LARGE_PAGES" /D "SUPPORT_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gr /MDd /W4 /WX /Gm /GX /ZI /Od /I "..\..\..\\" /D "_DEBUG" /D "_MBCS" /D "WIN32" /D "_CONSOLE" /D "Z7_LARGE_PAGES" /D "Z7_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c # ADD BASE RSC /l 0x419 /d "_DEBUG" # ADD RSC /l 0x419 /d "_DEBUG" BSC32=bscmake.exe @@ -93,8 +93,8 @@ # PROP Intermediate_Dir "ReleaseU" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" -# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "EXCLUDE_COM" /D "NO_REGISTRY" /Yu"StdAfx.h" /FD /c -# ADD CPP /nologo /Gr /MD /W4 /GX /O1 /I "..\..\..\\" /D "NDEBUG" /D "UNICODE" /D "_UNICODE" /D "WIN32" /D "_CONSOLE" /D "_7ZIP_LARGE_PAGES" /D "SUPPORT_DEVICE_FILE" /Yu"StdAfx.h" /FD /c +# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gr /MD /W4 /GX /O1 /I "..\..\..\\" /D "NDEBUG" /D "UNICODE" /D "_UNICODE" /D "WIN32" /D "_CONSOLE" /D "Z7_LARGE_PAGES" /D "Z7_DEVICE_FILE" /Yu"StdAfx.h" /FD /c # ADD BASE RSC /l 0x419 /d "NDEBUG" # ADD RSC /l 0x419 /d "NDEBUG" BSC32=bscmake.exe @@ -120,8 +120,8 @@ # PROP Intermediate_Dir "DebugU" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "EXCLUDE_COM" /D "NO_REGISTRY" /D "_MBCS" /Yu"StdAfx.h" /FD /GZ /c -# ADD CPP /nologo /Gr /MDd /W4 /Gm /GX /ZI /Od /I "..\..\..\\" /D "_DEBUG" /D "_UNICODE" /D "UNICODE" /D "WIN32" /D "_CONSOLE" /D "_7ZIP_LARGE_PAGES" /D "SUPPORT_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gr /MDd /W4 /Gm /GX /ZI /Od /I "..\..\..\\" /D "_DEBUG" /D "_UNICODE" /D "UNICODE" /D "WIN32" /D "_CONSOLE" /D "Z7_LARGE_PAGES" /D "Z7_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c # ADD BASE RSC /l 0x419 /d "_DEBUG" # ADD RSC /l 0x419 /d "_DEBUG" BSC32=bscmake.exe @@ -144,10 +144,6 @@ # PROP Default_Filter "" # Begin Source File -SOURCE=..\..\UI\Console\ArError.h -# End Source File -# Begin Source File - SOURCE=..\..\UI\Console\BenchCon.cpp # End Source File # Begin Source File @@ -270,6 +266,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\Common.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\ComTry.h # End Source File # Begin Source File @@ -318,6 +318,14 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyBuffer.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\Common\MyBuffer2.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\MyCom.h # End Source File # Begin Source File @@ -342,6 +350,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyTypes.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\MyUnknown.h # End Source File # Begin Source File @@ -526,6 +538,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Windows\NtCheck.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Windows\PropVariant.cpp # End Source File # Begin Source File @@ -550,10 +566,6 @@ # End Source File # Begin Source File -SOURCE=..\..\..\Windows\Synchronization.cpp -# End Source File -# Begin Source File - SOURCE=..\..\..\Windows\Synchronization.h # End Source File # Begin Source File @@ -678,6 +690,14 @@ # End Source File # Begin Source File +SOURCE=..\..\Common\MultiOutStream.cpp +# End Source File +# Begin Source File + +SOURCE=..\..\Common\MultiOutStream.h +# End Source File +# Begin Source File + SOURCE=..\..\Common\OffsetStream.cpp # End Source File # Begin Source File @@ -798,10 +818,6 @@ # End Source File # Begin Source File -SOURCE=..\..\Compress\ByteSwap.h -# End Source File -# Begin Source File - SOURCE=..\..\Compress\CopyCoder.cpp # End Source File # Begin Source File @@ -1122,6 +1138,10 @@ # End Source File # Begin Source File +SOURCE=..\..\UI\Common\ExitCode.h +# End Source File +# Begin Source File + SOURCE=..\..\UI\Common\Extract.cpp # End Source File # Begin Source File @@ -1246,7 +1266,7 @@ # End Source File # Begin Source File -SOURCE=..\..\IMyUnknown.h +SOURCE=..\..\IDecl.h # End Source File # Begin Source File @@ -1473,6 +1493,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\7zWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\Aes.c !IF "$(CFG)" == "Alone - Win32 Release" @@ -1605,6 +1629,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\Compiler.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\CpuArch.c !IF "$(CFG)" == "Alone - Win32 Release" @@ -1902,6 +1930,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\RotateDefs.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\Sha256.c !IF "$(CFG)" == "Alone - Win32 Release" @@ -1935,6 +1967,34 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\SwapBytes.c + +!IF "$(CFG)" == "Alone - Win32 Release" + +# ADD CPP /O2 +# SUBTRACT CPP /YX /Yc /Yu + +!ELSEIF "$(CFG)" == "Alone - Win32 Debug" + +# SUBTRACT CPP /YX /Yc /Yu + +!ELSEIF "$(CFG)" == "Alone - Win32 ReleaseU" + +# SUBTRACT CPP /YX /Yc /Yu + +!ELSEIF "$(CFG)" == "Alone - Win32 DebugU" + +# SUBTRACT CPP /YX /Yc /Yu + +!ENDIF + +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\SwapBytes.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\Threads.c # SUBTRACT CPP /YX /Yc /Yu # End Source File diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone7z/makefile 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone7z/makefile --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone7z/makefile 2021-10-08 12:33:09.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone7z/makefile 2023-04-05 12:00:00.000000000 +0000 @@ -1,8 +1,9 @@ PROG = 7zr.exe # USE_C_AES = 1 +# USE_C_SHA = 1 -CFLAGS = $(CFLAGS) -DPROG_VARIANT_R +CFLAGS = $(CFLAGS) -DZ7_PROG_VARIANT_R COMMON_OBJS = \ $O\CommandLineParser.obj \ @@ -38,7 +39,6 @@ $O\PropVariant.obj \ $O\PropVariantConv.obj \ $O\Registry.obj \ - $O\Synchronization.obj \ $O\System.obj \ $O\SystemInfo.obj \ $O\TimeUtils.obj \ @@ -54,6 +54,7 @@ $O\LimitedStreams.obj \ $O\MethodId.obj \ $O\MethodProps.obj \ + $O\MultiOutStream.obj \ $O\OffsetStream.obj \ $O\OutBuffer.obj \ $O\ProgressUtils.obj \ @@ -143,6 +144,7 @@ $O\MtCoder.obj \ $O\MtDec.obj \ $O\Sort.obj \ + $O\SwapBytes.obj \ $O\Threads.obj \ $O\Xz.obj \ $O\XzDec.obj \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone7z/makefile.gcc 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone7z/makefile.gcc --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone7z/makefile.gcc 2022-07-15 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone7z/makefile.gcc 2023-04-08 10:00:00.000000000 +0000 @@ -1,6 +1,6 @@ PROG = 7zr -CONSOLE_VARIANT_FLAGS=-DPROG_VARIANT_R +CONSOLE_VARIANT_FLAGS=-DZ7_PROG_VARIANT_R # IS_X64 = 1 # USE_ASM = 1 @@ -24,7 +24,7 @@ ifdef ST_MODE -LOCAL_FLAGS_ST = -D_7ZIP_ST +LOCAL_FLAGS_ST = -DZ7_ST ifdef IS_MINGW MT_OBJS = \ @@ -38,7 +38,6 @@ $O/LzFindMt.o \ $O/LzFindOpt.o \ $O/StreamBinder.o \ - $O/Synchronization.o \ $O/VirtThread.o \ $O/Threads.o \ @@ -53,9 +52,9 @@ ifdef IS_MINGW LOCAL_FLAGS_SYS = \ - -D_7ZIP_LARGE_PAGES \ - -DWIN_LONG_PATH \ - -DSUPPORT_DEVICE_FILE \ + -DZ7_LARGE_PAGES \ + -DZ7_LONG_PATH \ + -DZ7_DEVICE_FILE \ SYS_OBJS = \ $O/FileSystem.o \ @@ -76,8 +75,6 @@ $(LOCAL_FLAGS_ST) \ $(LOCAL_FLAGS_SYS) \ -# -D_LZMA_PROB32 - CONSOLE_OBJS = \ $O/BenchCon.o \ @@ -160,6 +157,7 @@ $O/LimitedStreams.o \ $O/MethodId.o \ $O/MethodProps.o \ + $O/MultiOutStream.o \ $O/OffsetStream.o \ $O/OutBuffer.o \ $O/ProgressUtils.o \ @@ -246,7 +244,7 @@ $O/MtDec.o \ $O/Sha256.o \ $O/Sha256Opt.o \ - $O/Sort.o \ + $O/SwapBytes.o \ $O/Xz.o \ $O/XzDec.o \ $O/XzEnc.o \ @@ -260,7 +258,7 @@ OBJS = \ - $(LZMA_DEC_OPT_OBJS) \ + $(LZMA_DEC_OPT_OBJS) \ $(C_OBJS) \ $(MT_OBJS) \ $(SYS_OBJS) \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone7z/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone7z/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Alone7z/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Alone7z/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Fm/FM.dsp 7zip-23.01+dfsg/CPP/7zip/Bundles/Fm/FM.dsp --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Fm/FM.dsp 2021-10-20 12:26:12.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Fm/FM.dsp 2023-04-05 12:00:00.000000000 +0000 @@ -45,7 +45,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_MBCS" /D "WIN32" /D "_WINDOWS" /D "LANG" /D "WIN_LONG_PATH" /D "NEW_FOLDER_INTERFACE" /D "EXTERNAL_CODECS_2" /D "SUPPORT_DEVICE_FILE" /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_MBCS" /D "WIN32" /D "_WINDOWS" /D "Z7_LANG" /D "Z7_LONG_PATH" /D "Z7_EXTERNAL_CODECS_2" /D "Z7_DEVICE_FILE" /Yu"StdAfx.h" /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "NDEBUG" @@ -72,7 +72,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /Gz /MDd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_MBCS" /D "WIN32" /D "_WINDOWS" /D "LANG" /D "WIN_LONG_PATH" /D "NEW_FOLDER_INTERFACE" /D "EXTERNAL_CODECS_2" /D "SUPPORT_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gz /MDd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_MBCS" /D "WIN32" /D "_WINDOWS" /D "Z7_LANG" /D "Z7_LONG_PATH" /D "Z7_EXTERNAL_CODECS_2" /D "Z7_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "_DEBUG" @@ -99,7 +99,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"StdAfx.h" /FD /c -# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "LANG" /D "WIN_LONG_PATH" /D "NEW_FOLDER_INTERFACE" /D "EXTERNAL_CODECS_2" /D "SUPPORT_DEVICE_FILE" /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "Z7_LANG" /D "Z7_LONG_PATH" /D "Z7_EXTERNAL_CODECS_2" /D "Z7_DEVICE_FILE" /Yu"StdAfx.h" /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "NDEBUG" @@ -127,7 +127,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"StdAfx.h" /FD /GZ /c -# ADD CPP /nologo /Gz /MDd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "LANG" /D "WIN_LONG_PATH" /D "NEW_FOLDER_INTERFACE" /D "EXTERNAL_CODECS_2" /D "SUPPORT_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gz /MDd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "Z7_LANG" /D "Z7_LONG_PATH" /D "Z7_EXTERNAL_CODECS_2" /D "Z7_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "_DEBUG" @@ -849,6 +849,14 @@ # End Source File # Begin Source File +SOURCE=..\..\Common\MultiOutStream.cpp +# End Source File +# Begin Source File + +SOURCE=..\..\Common\MultiOutStream.h +# End Source File +# Begin Source File + SOURCE=..\..\Common\OutBuffer.cpp # End Source File # Begin Source File @@ -947,10 +955,19 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\7zStream.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\7zTypes.h # End Source File # Begin Source File +SOURCE=..\..\..\..\C\7zWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\Alloc.c # SUBTRACT CPP /YX /Yc /Yu # End Source File @@ -960,6 +977,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\Compiler.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\CpuArch.c !IF "$(CFG)" == "FM - Win32 Release" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Fm/makefile 7zip-23.01+dfsg/CPP/7zip/Bundles/Fm/makefile --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Fm/makefile 2022-01-09 19:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Fm/makefile 2023-01-30 18:00:00.000000000 +0000 @@ -1,5 +1,7 @@ PROG = 7zFM.exe +CFLAGS = $(CFLAGS) -DZ7_LARGE_PAGES + !include "../Format7zF/Arc.mak" !include "../../UI/FileManager/FM.mak" @@ -36,6 +38,7 @@ 7ZIP_COMMON_OBJS = $(7ZIP_COMMON_OBJS) \ $O\FilePathAutoRename.obj \ $O\FileStreams.obj \ + $O\MultiOutStream.obj \ UI_COMMON_OBJS = \ $O\ArchiveExtractCallback.obj \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Fm/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Bundles/Fm/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Fm/StdAfx.h 2021-01-26 19:26:37.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Fm/StdAfx.h 2023-03-06 19:00:00.000000000 +0000 @@ -1,16 +1,6 @@ -// stdafx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -// #define _WIN32_WINNT 0x0400 -#define _WIN32_WINNT 0x0500 -#define WINVER _WIN32_WINNT - -#include "../../../Common/Common.h" - -#include -#include -#include +// StdAfx.h +#if _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' #endif +#include "../../UI/FileManager/StdAfx.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7z/makefile 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7z/makefile --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7z/makefile 2021-07-15 12:40:09.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7z/makefile 2023-04-05 12:00:00.000000000 +0000 @@ -1,8 +1,8 @@ PROG = 7za.dll DEF_FILE = ../../Archive/Archive2.def CFLAGS = $(CFLAGS) \ - -DDEFLATE_EXTRACT_ONLY \ - -DBZIP2_EXTRACT_ONLY \ + -DZ7_DEFLATE_EXTRACT_ONLY \ + -DZ7_BZIP2_EXTRACT_ONLY \ COMMON_OBJS = \ $O\CRC.obj \ @@ -111,6 +111,7 @@ $O\RandGen.obj \ C_OBJS = \ + $O\7zStream.obj \ $O\Alloc.obj \ $O\Bcj2.obj \ $O\Bcj2Enc.obj \ @@ -134,6 +135,7 @@ $O\Ppmd7Dec.obj \ $O\Ppmd7Enc.obj \ $O\Sort.obj \ + $O\SwapBytes.obj \ $O\Threads.obj \ !include "../../Aes.mak" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7z/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7z/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7z/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7z/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zExtract/makefile 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zExtract/makefile --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zExtract/makefile 2019-08-26 08:49:37.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zExtract/makefile 2023-03-19 18:00:00.000000000 +0000 @@ -1,7 +1,7 @@ PROG = 7zxa.dll DEF_FILE = ../../Archive/Archive2.def CFLAGS = $(CFLAGS) \ - -DEXTRACT_ONLY \ + -DZ7_EXTRACT_ONLY \ COMMON_OBJS = \ $O\CRC.obj \ @@ -91,6 +91,7 @@ $O\MyAesReg.obj \ C_OBJS = \ + $O\7zStream.obj \ $O\Alloc.obj \ $O\Bcj2.obj \ $O\Bra.obj \ @@ -104,6 +105,7 @@ $O\MtDec.obj \ $O\Ppmd7.obj \ $O\Ppmd7Dec.obj \ + $O\SwapBytes.obj \ $O\Threads.obj \ !include "../../Aes.mak" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zExtract/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zExtract/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zExtract/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zExtract/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zExtractR/makefile 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zExtractR/makefile --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zExtractR/makefile 2018-02-25 09:37:02.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zExtractR/makefile 2023-03-19 18:00:00.000000000 +0000 @@ -1,8 +1,8 @@ PROG = 7zxr.dll DEF_FILE = ../../Archive/Archive2.def CFLAGS = $(CFLAGS) \ - -DEXTRACT_ONLY \ - -D_NO_CRYPTO + -DZ7_EXTRACT_ONLY \ + -DZ7_NO_CRYPTO COMMON_OBJS = \ $O\CRC.obj \ @@ -77,6 +77,7 @@ $O\LzmaRegister.obj \ C_OBJS = \ + $O\7zStream.obj \ $O\Alloc.obj \ $O\Bcj2.obj \ $O\Bra.obj \ @@ -88,6 +89,7 @@ $O\Lzma2DecMt.obj \ $O\LzmaDec.obj \ $O\MtDec.obj \ + $O\SwapBytes.obj \ $O\Threads.obj \ !include "../../Crc.mak" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zExtractR/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zExtractR/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zExtractR/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zExtractR/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zF/Arc_gcc.mak 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zF/Arc_gcc.mak --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zF/Arc_gcc.mak 2022-07-14 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zF/Arc_gcc.mak 2023-06-20 07:00:00.000000000 +0000 @@ -14,7 +14,7 @@ ifdef ST_MODE -LOCAL_FLAGS_ST = -D_7ZIP_ST +LOCAL_FLAGS_ST = -DZ7_ST ifdef IS_MINGW MT_OBJS = \ @@ -351,6 +351,7 @@ $O/Sha256Opt.o \ $O/Sha1.o \ $O/Sha1Opt.o \ + $O/SwapBytes.o \ ARC_OBJS = \ $(LZMA_DEC_OPT_OBJS) \ @@ -358,6 +359,7 @@ $(MT_OBJS) \ $(COMMON_OBJS) \ $(WIN_OBJS) \ + $(7ZIP_COMMON_OBJS) \ $(AR_OBJS) \ $(AR_COMMON_OBJS) \ $(7Z_OBJS) \ @@ -373,5 +375,5 @@ $(ZIP_OBJS) \ $(COMPRESS_OBJS) \ $(CRYPTO_OBJS) \ - $(7ZIP_COMMON_OBJS) \ +# we need empty line after last line above diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zF/Arc.mak 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zF/Arc.mak --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zF/Arc.mak 2022-06-15 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zF/Arc.mak 2023-04-05 12:00:00.000000000 +0000 @@ -111,7 +111,6 @@ $O\HandlerOut.obj \ $O\ParseProperties.obj \ - 7Z_OBJS = \ $O\7zCompressionMode.obj \ $O\7zDecode.obj \ @@ -235,7 +234,6 @@ $O\ZlibEncoder.obj \ $O\ZDecoder.obj \ - CRYPTO_OBJS = \ $O\7zAes.obj \ $O\7zAesRegister.obj \ @@ -252,7 +250,6 @@ $O\ZipCrypto.obj \ $O\ZipStrong.obj \ - C_OBJS = \ $O\7zBuf2.obj \ $O\7zStream.obj \ @@ -284,6 +281,7 @@ $O\Ppmd8Dec.obj \ $O\Ppmd8Enc.obj \ $O\Sort.obj \ + $O\SwapBytes.obj \ $O\Threads.obj \ $O\Xz.obj \ $O\XzDec.obj \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zF/Format7z.dsp 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zF/Format7z.dsp --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zF/Format7z.dsp 2022-07-08 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zF/Format7z.dsp 2023-04-05 12:00:00.000000000 +0000 @@ -43,7 +43,7 @@ # PROP Ignore_Export_Lib 1 # PROP Target_Dir "" # ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MY7Z_EXPORTS" /YX /FD /c -# ADD CPP /nologo /Gr /MT /W4 /WX /GX /O1 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MY7Z_EXPORTS" /D "NO_REGISTRY" /D "EXTERNAL_CODECS" /D "_7ZIP_LARGE_PAGES" /D "_7ZIP_ST_9" /FAcs /Yu"StdAfx.h" /FD /GF /c +# ADD CPP /nologo /Gr /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MY7Z_EXPORTS" /D "Z7_EXTERNAL_CODECS" /D "Z7_LARGE_PAGES" /D "Z7_ST_9" /FAcs /Yu"StdAfx.h" /FD /GF /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "NDEBUG" @@ -70,7 +70,7 @@ # PROP Ignore_Export_Lib 1 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MY7Z_EXPORTS" /YX /FD /GZ /c -# ADD CPP /nologo /Gr /MTd /W4 /WX /Gm /GX /ZI /Od /I "..\..\..\..\SDK" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MY7Z_EXPORTS" /D "NO_REGISTRY" /D "EXTERNAL_CODECS" /D "_7ZIP_LARGE_PAGES" /D "_7ZIP_ST_9" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gr /MTd /W4 /WX /Gm /GX /ZI /Od /I "..\..\..\..\SDK" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MY7Z_EXPORTS" /D "Z7_EXTERNAL_CODECS" /D "Z7_LARGE_PAGES" /D "Z7_ST_9" /Yu"StdAfx.h" /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "_DEBUG" @@ -235,6 +235,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\ComTry.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\CRC.cpp # End Source File # Begin Source File @@ -1634,6 +1638,14 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\7zVersion.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\7zWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\Aes.c !IF "$(CFG)" == "7z - Win32 Release" @@ -2214,7 +2226,23 @@ # End Source File # Begin Source File -SOURCE=..\..\..\..\C\StdAfx.h +SOURCE=..\..\..\..\C\SwapBytes.c + +!IF "$(CFG)" == "7z - Win32 Release" + +# ADD CPP /O2 +# SUBTRACT CPP /YX /Yc /Yu + +!ELSEIF "$(CFG)" == "7z - Win32 Debug" + +# SUBTRACT CPP /YX /Yc /Yu + +!ENDIF + +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\SwapBytes.h # End Source File # Begin Source File @@ -2993,6 +3021,10 @@ # End Source File # Begin Source File +SOURCE=..\..\MyVersion.h +# End Source File +# Begin Source File + SOURCE=..\..\PropID.h # End Source File # End Group @@ -3037,6 +3069,14 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Windows\Handle.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\Windows\NtCheck.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Windows\PropVariant.cpp # End Source File # Begin Source File diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zF/makefile 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zF/makefile --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zF/makefile 2013-11-23 17:57:15.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zF/makefile 2023-01-30 18:00:00.000000000 +0000 @@ -1,10 +1,11 @@ PROG = 7z.dll +# USE_C_LZFINDOPT = 1 DEF_FILE = ../../Archive/Archive2.def CFLAGS = $(CFLAGS) \ - -DEXTERNAL_CODECS \ + -DZ7_EXTERNAL_CODECS \ !IFNDEF UNDER_CE -CFLAGS = $(CFLAGS) -D_7ZIP_LARGE_PAGES +CFLAGS = $(CFLAGS) -DZ7_LARGE_PAGES !ENDIF !include "Arc.mak" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zF/makefile.gcc 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zF/makefile.gcc --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zF/makefile.gcc 2022-07-14 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zF/makefile.gcc 2023-01-30 18:00:00.000000000 +0000 @@ -20,7 +20,7 @@ ifdef IS_MINGW LOCAL_FLAGS_WIN = \ - -D_7ZIP_LARGE_PAGES \ + -DZ7_LARGE_PAGES \ $(LOCAL_FLAGS_ST) \ SYS_OBJS = \ @@ -34,7 +34,7 @@ endif LOCAL_FLAGS = \ - -DEXTERNAL_CODECS \ + -DZ7_EXTERNAL_CODECS \ $(LOCAL_FLAGS_WIN) \ $(LOCAL_FLAGS_ST) \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zF/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zF/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zF/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zF/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zR/makefile 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zR/makefile --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zR/makefile 2021-07-15 12:38:50.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zR/makefile 2023-03-19 18:00:00.000000000 +0000 @@ -1,7 +1,7 @@ PROG = 7zra.dll DEF_FILE = ../../Archive/Archive2.def CFLAGS = $(CFLAGS) \ - -D_NO_CRYPTO + -DZ7_NO_CRYPTO COMMON_OBJS = \ $O\CRC.obj \ @@ -92,6 +92,7 @@ $O\LzmaRegister.obj \ C_OBJS = \ + $O\7zStream.obj \ $O\Alloc.obj \ $O\Bcj2.obj \ $O\Bcj2Enc.obj \ @@ -109,6 +110,7 @@ $O\LzmaEnc.obj \ $O\MtCoder.obj \ $O\MtDec.obj \ + $O\SwapBytes.obj \ $O\Threads.obj \ !include "../../Crc.mak" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zR/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zR/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Bundles/Format7zR/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/Format7zR/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/LzmaCon/LzmaAlone.cpp 7zip-23.01+dfsg/CPP/7zip/Bundles/LzmaCon/LzmaAlone.cpp --- 7zip-22.01+dfsg/CPP/7zip/Bundles/LzmaCon/LzmaAlone.cpp 2022-06-09 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/LzmaCon/LzmaAlone.cpp 2023-04-05 12:00:00.000000000 +0000 @@ -1,11 +1,9 @@ -// LzmaAlone.cpp + // LzmaAlone.cpp #include "StdAfx.h" // #include -#include "../../../../C/CpuArch.h" - #if (defined(_WIN32) || defined(OS2) || defined(MSDOS)) && !defined(UNDER_CE) #include #include @@ -14,16 +12,17 @@ #define MY_SET_BINARY_MODE(file) #endif -#include "../../../Common/MyWindows.h" -#include "../../../Common/MyInitGuid.h" - +#include "../../../../C/CpuArch.h" #include "../../../../C/7zVersion.h" #include "../../../../C/Alloc.h" #include "../../../../C/Lzma86.h" +#include "../../../Common/MyWindows.h" +#include "../../../Common/MyInitGuid.h" + #include "../../../Windows/NtCheck.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "../../../Windows/System.h" #endif @@ -41,6 +40,8 @@ #include "../../UI/Console/BenchCon.h" #include "../../UI/Console/ConsoleClose.h" +extern +bool g_LargePagesMode; bool g_LargePagesMode = false; using namespace NCommandLineParser; @@ -219,20 +220,17 @@ Print(kHelpString); } -class CProgressPrint: - public ICompressProgressInfo, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_COM_1( + CProgressPrint, + ICompressProgressInfo +) UInt64 _size1; UInt64 _size2; public: CProgressPrint(): _size1(0), _size2(0) {} void ClosePrint(); - - MY_UNKNOWN_IMP1(ICompressProgressInfo) - - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); }; #define BACK_STR \ @@ -248,7 +246,7 @@ Print(kBackSpaces); } -STDMETHODIMP CProgressPrint::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) +Z7_COM7F_IMF(CProgressPrint::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize)) { if (NConsoleClose::TestBreakSignal()) return E_ABORT; @@ -272,7 +270,7 @@ } -MY_ATTR_NORETURN +Z7_ATTR_NORETURN static void IncorrectCommand() { throw "Incorrect command"; @@ -316,7 +314,7 @@ else { char temp[32]; - ConvertUInt32ToHex(res, temp); + ConvertUInt32ToHex((UInt32)res, temp); PrintErr("Error code = 0x"); PrintErr_LF(temp); } @@ -357,7 +355,7 @@ CParser parser; try { - if (!parser.ParseStrings(kSwitchForms, ARRAY_SIZE(kSwitchForms), commandStrings)) + if (!parser.ParseStrings(kSwitchForms, Z7_ARRAY_SIZE(kSwitchForms), commandStrings)) { PrintError2(parser.ErrorMessage, parser.ErrorLine); return 1; @@ -414,7 +412,7 @@ UInt32 numThreads = (UInt32)(Int32)-1; - #ifndef _7ZIP_ST + #ifndef Z7_ST if (parser[NKey::kMultiThread].ThereIs) { @@ -676,7 +674,7 @@ NCoderPropID::kMatchFinderCycles, }; - const unsigned kNumPropsMax = ARRAY_SIZE(propIDs); + const unsigned kNumPropsMax = Z7_ARRAY_SIZE(propIDs); PROPVARIANT props[kNumPropsMax]; for (int p = 0; p < 6; p++) @@ -757,7 +755,7 @@ throw "SetDecoderProperties error"; UInt64 unpackSize = 0; - for (int i = 0; i < 8; i++) + for (unsigned i = 0; i < 8; i++) unpackSize |= ((UInt64)header[kPropertiesSize + i]) << (8 * i); bool unpackSizeDefined = (unpackSize != (UInt64)(Int64)-1); @@ -792,7 +790,7 @@ return 0; } -int MY_CDECL main(int numArgs, const char *args[]) +int Z7_CDECL main(int numArgs, const char *args[]) { NConsoleClose::CCtrlHandlerSetter ctrlHandlerSetter; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/LzmaCon/LzmaCon.dsp 7zip-23.01+dfsg/CPP/7zip/Bundles/LzmaCon/LzmaCon.dsp --- 7zip-22.01+dfsg/CPP/7zip/Bundles/LzmaCon/LzmaCon.dsp 2021-07-15 13:50:36.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/LzmaCon/LzmaCon.dsp 2023-04-05 13:00:00.000000000 +0000 @@ -132,6 +132,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Windows\NtCheck.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Windows\PropVariant.cpp # End Source File # Begin Source File @@ -148,14 +152,6 @@ # End Source File # Begin Source File -SOURCE=..\..\..\Windows\Synchronization.cpp -# End Source File -# Begin Source File - -SOURCE=..\..\..\Windows\Synchronization.h -# End Source File -# Begin Source File - SOURCE=..\..\..\Windows\System.cpp # End Source File # Begin Source File @@ -188,6 +184,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\Common.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\ComTry.h # End Source File # Begin Source File @@ -216,10 +216,26 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyBuffer.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\Common\MyBuffer2.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\MyCom.h # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyInitGuid.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\Common\MyLinux.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\MyString.cpp # End Source File # Begin Source File @@ -228,6 +244,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyTypes.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\MyUnknown.h # End Source File # Begin Source File @@ -274,6 +294,14 @@ SOURCE=..\..\..\Common\Types.h # End Source File +# Begin Source File + +SOURCE=..\..\..\Common\Wildcard.cpp +# End Source File +# Begin Source File + +SOURCE=..\..\..\Common\Wildcard.h +# End Source File # End Group # Begin Group "7zip Common" @@ -346,14 +374,6 @@ SOURCE=..\..\UI\Common\Bench.h # End Source File -# Begin Source File - -SOURCE=..\..\UI\Common\LoadCodecs.cpp -# End Source File -# Begin Source File - -SOURCE=..\..\UI\Common\LoadCodecs.h -# End Source File # End Group # Begin Group "Console" @@ -398,21 +418,16 @@ # End Source File # Begin Source File -SOURCE=..\..\..\..\C\Alloc.c -# SUBTRACT CPP /YX /Yc /Yu -# End Source File -# Begin Source File - -SOURCE=..\..\..\..\C\Alloc.h +SOURCE=..\..\..\..\C\7zWindows.h # End Source File # Begin Source File -SOURCE=..\..\..\..\C\Bra.c +SOURCE=..\..\..\..\C\Alloc.c # SUBTRACT CPP /YX /Yc /Yu # End Source File # Begin Source File -SOURCE=..\..\..\..\C\Bra.h +SOURCE=..\..\..\..\C\Alloc.h # End Source File # Begin Source File @@ -421,8 +436,7 @@ # End Source File # Begin Source File -SOURCE=..\..\..\..\C\BraIA64.c -# SUBTRACT CPP /YX /Yc /Yu +SOURCE=..\..\..\..\C\Compiler.h # End Source File # Begin Source File @@ -502,6 +516,22 @@ SOURCE=..\..\..\..\C\Threads.h # End Source File # End Group +# Begin Group "7zip" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=..\..\ICoder.h +# End Source File +# Begin Source File + +SOURCE=..\..\IDecl.h +# End Source File +# Begin Source File + +SOURCE=..\..\IProgress.h +# End Source File +# End Group # Begin Source File SOURCE=.\LzmaAlone.cpp diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/LzmaCon/makefile 7zip-23.01+dfsg/CPP/7zip/Bundles/LzmaCon/makefile --- 7zip-22.01+dfsg/CPP/7zip/Bundles/LzmaCon/makefile 2021-07-15 13:44:45.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/LzmaCon/makefile 2023-04-05 13:00:00.000000000 +0000 @@ -1,6 +1,9 @@ PROG = lzma.exe MY_CONSOLE = 1 +# CFLAGS = $(CFLAGS) -DZ7_ST + + CURRENT_OBJS = \ $O\LzmaAlone.obj \ @@ -20,6 +23,7 @@ $O\NewHandler.obj \ $O\StringConvert.obj \ $O\StringToInt.obj \ + $O\Wildcard.obj \ WIN_OBJS = \ $O\FileIO.obj \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/LzmaCon/makefile.gcc 7zip-23.01+dfsg/CPP/7zip/Bundles/LzmaCon/makefile.gcc --- 7zip-22.01+dfsg/CPP/7zip/Bundles/LzmaCon/makefile.gcc 2022-07-15 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/LzmaCon/makefile.gcc 2023-04-05 11:00:00.000000000 +0000 @@ -21,7 +21,7 @@ ifdef ST_MODE -LOCAL_FLAGS_ST = -D_7ZIP_ST +LOCAL_FLAGS_ST = -DZ7_ST else @@ -72,6 +72,7 @@ $O/StringConvert.o \ $O/StringToInt.o \ $O/UTFConvert.o \ + $O/Wildcard.o \ WIN_OBJS = \ $O/FileIO.o \ @@ -110,7 +111,7 @@ $O/Lzma86Enc.o \ OBJS = \ - $(LZMA_DEC_OPT_OBJS) \ + $(LZMA_DEC_OPT_OBJS) \ $(C_OBJS) \ $(MT_OBJS) \ $(SYS_OBJS) \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/LzmaCon/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Bundles/LzmaCon/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Bundles/LzmaCon/StdAfx.h 2013-01-25 07:40:27.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/LzmaCon/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXCon/makefile 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXCon/makefile --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXCon/makefile 2021-03-06 13:39:02.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXCon/makefile 2023-04-05 13:00:00.000000000 +0000 @@ -3,9 +3,9 @@ MY_FIXED = 1 CFLAGS = $(CFLAGS) \ - -DEXTRACT_ONLY \ - -DNO_READ_FROM_CODER \ - -D_SFX \ + -DZ7_EXTRACT_ONLY \ + -DZ7_NO_READ_FROM_CODER \ + -DZ7_SFX \ CURRENT_OBJS = \ $O\SfxCon.obj \ @@ -109,6 +109,7 @@ $O\MyAes.obj \ C_OBJS = \ + $O\7zStream.obj \ $O\Alloc.obj \ $O\Bcj2.obj \ $O\Bra.obj \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXCon/makefile.gcc 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXCon/makefile.gcc --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXCon/makefile.gcc 2022-07-14 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXCon/makefile.gcc 2023-04-05 11:00:00.000000000 +0000 @@ -22,7 +22,7 @@ ifdef ST_MODE -LOCAL_FLAGS_ST = -D_7ZIP_ST +LOCAL_FLAGS_ST = -DZ7_ST ifdef IS_MINGW MT_OBJS = \ @@ -63,9 +63,9 @@ LOCAL_FLAGS = \ $(LOCAL_FLAGS_ST) \ $(LOCAL_FLAGS_SYS) \ - -DEXTRACT_ONLY \ - -DNO_READ_FROM_CODER \ - -D_SFX \ + -DZ7_EXTRACT_ONLY \ + -DZ7_NO_READ_FROM_CODER \ + -DZ7_SFX \ CURRENT_OBJS = \ @@ -172,6 +172,7 @@ $O/MyAes.o \ C_OBJS = \ + $O/7zStream.o \ $O/Alloc.o \ $O/Bcj2.o \ $O/Bra.o \ @@ -179,7 +180,6 @@ $O/BraIA64.o \ $O/CpuArch.o \ $O/Delta.o \ - \ $O/Lzma2Dec.o \ $O/Lzma2DecMt.o \ $O/LzmaDec.o \ @@ -194,7 +194,7 @@ $O/AesOpt.o \ OBJS = \ - $(LZMA_DEC_OPT_OBJS) \ + $(LZMA_DEC_OPT_OBJS) \ $(C_OBJS) \ $(MT_OBJS) \ $(SYS_OBJS) \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXCon/resource.rc 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXCon/resource.rc --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXCon/resource.rc 2005-07-28 16:18:48.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXCon/resource.rc 2022-12-28 17:00:00.000000000 +0000 @@ -2,4 +2,8 @@ MY_VERSION_INFO_APP("7z Console SFX", "7z.sfx") -101 ICON "7z.ico" \ No newline at end of file +101 ICON "7z.ico" + +#ifndef UNDER_CE +1 24 MOVEABLE PURE "../../UI/Console/Console.manifest" +#endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXCon/SfxCon.cpp 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXCon/SfxCon.cpp --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXCon/SfxCon.cpp 2021-12-25 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXCon/SfxCon.cpp 2023-04-05 13:00:00.000000000 +0000 @@ -3,9 +3,9 @@ #include "StdAfx.h" #include "../../../../C/CpuArch.h" +#include "../../../../C/DllSecur.h" #include "../../../Common/MyWindows.h" - #include "../../../Common/MyInitGuid.h" #include "../../../Common/CommandLineParser.h" @@ -28,7 +28,6 @@ #include "../../MyVersion.h" -#include "../../../../C/DllSecur.h" using namespace NWindows; using namespace NFile; @@ -36,8 +35,12 @@ using namespace NCommandLineParser; #ifdef _WIN32 -HINSTANCE g_hInstance = 0; +extern +HINSTANCE g_hInstance; +HINSTANCE g_hInstance = NULL; #endif +extern +int g_CodePage; int g_CodePage = -1; extern CStdOutStream *g_StdStream; @@ -184,14 +187,14 @@ g_StdOut << kHelpString; } -MY_ATTR_NORETURN +Z7_ATTR_NORETURN static void ShowMessageAndThrowException(const char *message, NExitCode::EEnum code) { g_StdOut << message << endl; throw code; } -MY_ATTR_NORETURN +Z7_ATTR_NORETURN static void PrintHelpAndExit() // yyy { PrintHelp(); @@ -370,12 +373,12 @@ } } - bool yesToAll = parser[NKey::kYes].ThereIs; + const bool yesToAll = parser[NKey::kYes].ThereIs; // NExtractMode::EEnum extractMode; // bool isExtractGroupCommand = command.IsFromExtractGroup(extractMode); - bool passwordEnabled = parser[NKey::kPassword].ThereIs; + const bool passwordEnabled = parser[NKey::kPassword].ThereIs; UString password; if (passwordEnabled) @@ -403,7 +406,7 @@ CCodecs *codecs = new CCodecs; CMyComPtr< - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS ICompressCodecsInfo #else IUnknown @@ -421,7 +424,7 @@ CMyComPtr extractCallback = ecs; ecs->Init(g_StdStream, &g_StdErr, g_StdStream); - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO ecs->PasswordIsDefined = passwordEnabled; ecs->Password = password; #endif @@ -430,7 +433,7 @@ COpenCallbackConsole openCallback; openCallback.Init(g_StdStream, g_StdStream); - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO openCallback.PasswordIsDefined = passwordEnabled; openCallback.Password = password; #endif @@ -452,22 +455,33 @@ codecs, CObjectVector(), CIntVector(), v1, v2, wildcardCensorHead, - eo, ecs, ecs, + eo, + ecs, ecs, ecs, // NULL, // hash errorMessage, stat); + + ecs->ClosePercents(); + if (!errorMessage.IsEmpty()) { - (*g_StdStream) << endl << "Error: " << errorMessage;; + (*g_StdStream) << endl << "Error: " << errorMessage; if (result == S_OK) result = E_FAIL; } - if (ecs->NumArcsWithError != 0 || ecs->NumFileErrors != 0) + if ( 0 != ecs->NumCantOpenArcs + || 0 != ecs->NumArcsWithError + || 0 != ecs->NumFileErrors + || 0 != ecs->NumOpenArcErrors) { + if (ecs->NumCantOpenArcs != 0) + (*g_StdStream) << endl << "Can't open as archive" << endl; if (ecs->NumArcsWithError != 0) (*g_StdStream) << endl << "Archive Errors" << endl; if (ecs->NumFileErrors != 0) (*g_StdStream) << endl << "Sub items Errors: " << ecs->NumFileErrors << endl; + if (ecs->NumOpenArcErrors != 0) + (*g_StdStream) << endl << "Open Errors: " << ecs->NumOpenArcErrors << endl; return NExitCode::kFatalError; } if (result != S_OK) @@ -489,7 +503,7 @@ wildcardCensorHead, true, // enableHeaders false, // techMode - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO passwordEnabled, password, #endif numErrors, numWarnings); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXCon/SFXCon.dsp 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXCon/SFXCon.dsp --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXCon/SFXCon.dsp 2019-08-28 17:17:39.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXCon/SFXCon.dsp 2023-04-05 13:00:00.000000000 +0000 @@ -42,7 +42,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "EXTRACT_ONLY" /D "_SFX" /D "NO_READ_FROM_CODER" /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gr /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "Z7_EXTRACT_ONLY" /D "Z7_SFX" /D "Z7_NO_READ_FROM_CODER" /FAcs /Yu"StdAfx.h" /FD /c # ADD BASE RSC /l 0x419 /d "NDEBUG" # ADD RSC /l 0x419 /d "NDEBUG" BSC32=bscmake.exe @@ -67,7 +67,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /Gz /MTd /W4 /WX /Gm /GX /ZI /Od /I "..\..\..\..\\" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "EXTRACT_ONLY" /D "_SFX" /D "NO_READ_FROM_CODER" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gz /MTd /W4 /WX /Gm /GX /ZI /Od /I "..\..\..\..\\" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "Z7_EXTRACT_ONLY" /D "Z7_SFX" /D "Z7_NO_READ_FROM_CODER" /Yu"StdAfx.h" /FD /GZ /c # ADD BASE RSC /l 0x419 /d "_DEBUG" # ADD RSC /l 0x419 /d "_DEBUG" BSC32=bscmake.exe @@ -257,6 +257,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Compress\Bcj2Coder.h +# End Source File +# Begin Source File + SOURCE=..\..\Compress\Bcj2Register.cpp # End Source File # Begin Source File @@ -265,6 +269,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Compress\BcjCoder.h +# End Source File +# Begin Source File + SOURCE=..\..\Compress\BcjRegister.cpp # End Source File # Begin Source File @@ -285,6 +293,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Compress\CopyCoder.h +# End Source File +# Begin Source File + SOURCE=..\..\Compress\CopyRegister.cpp # End Source File # Begin Source File @@ -309,6 +321,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Compress\LzmaDecoder.h +# End Source File +# Begin Source File + SOURCE=..\..\Compress\LzmaRegister.cpp # End Source File # Begin Source File @@ -317,6 +333,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Compress\PpmdDecoder.h +# End Source File +# Begin Source File + SOURCE=..\..\Compress\PpmdRegister.cpp # End Source File # End Group @@ -441,6 +461,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\Common.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\CRC.cpp # End Source File # Begin Source File @@ -457,6 +481,18 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyBuffer.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\Common\MyBuffer2.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\Common\MyCom.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\MyString.cpp # End Source File # Begin Source File @@ -759,6 +795,19 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\7zStream.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\7zTypes.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\7zWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\Aes.c # SUBTRACT CPP /YX /Yc /Yu # End Source File @@ -810,11 +859,19 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\Compiler.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\CpuArch.c # SUBTRACT CPP /YX /Yc /Yu # End Source File # Begin Source File +SOURCE=..\..\..\..\C\CpuArch.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\Delta.c # SUBTRACT CPP /YX /Yc /Yu # End Source File @@ -825,7 +882,18 @@ # Begin Source File SOURCE=..\..\..\..\C\DllSecur.c + +!IF "$(CFG)" == "SFXCon - Win32 Release" + +# ADD CPP /O2 # SUBTRACT CPP /YX /Yc /Yu + +!ELSEIF "$(CFG)" == "SFXCon - Win32 Debug" + +# SUBTRACT CPP /YX /Yc /Yu + +!ENDIF + # End Source File # Begin Source File @@ -905,13 +973,33 @@ SOURCE=..\..\..\..\C\Threads.h # End Source File # End Group +# Begin Group "7zip" + +# PROP Default_Filter "" # Begin Source File -SOURCE=.\7z.ico +SOURCE=..\..\Archive\IArchive.h # End Source File # Begin Source File -SOURCE=..\..\Archive\IArchive.h +SOURCE=..\..\ICoder.h +# End Source File +# Begin Source File + +SOURCE=..\..\IDecl.h +# End Source File +# Begin Source File + +SOURCE=..\..\IPassword.h +# End Source File +# Begin Source File + +SOURCE=..\..\IProgress.h +# End Source File +# End Group +# Begin Source File + +SOURCE=.\7z.ico # End Source File # Begin Source File diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXCon/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXCon/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXCon/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXCon/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.cpp 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.cpp --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.cpp 2020-06-11 12:15:24.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.cpp 2023-03-17 10:00:00.000000000 +0000 @@ -63,7 +63,7 @@ return S_OK; } -STDMETHODIMP CExtractCallbackImp::SetTotal(UInt64 size) +Z7_COM7F_IMF(CExtractCallbackImp::SetTotal(UInt64 size)) { #ifndef _NO_PROGRESS ProgressDialog.Sync.SetProgress(size, 0); @@ -71,10 +71,10 @@ return S_OK; } -STDMETHODIMP CExtractCallbackImp::SetCompleted(const UInt64 *completeValue) +Z7_COM7F_IMF(CExtractCallbackImp::SetCompleted(const UInt64 *completeValue)) { #ifndef _NO_PROGRESS - RINOK(ProgressDialog.Sync.ProcessStopAndPause()); + RINOK(ProgressDialog.Sync.ProcessStopAndPause()) if (completeValue != NULL) ProgressDialog.Sync.SetPos(*completeValue); #endif @@ -92,8 +92,8 @@ } } -STDMETHODIMP CExtractCallbackImp::GetStream(UInt32 index, - ISequentialOutStream **outStream, Int32 askExtractMode) +Z7_COM7F_IMF(CExtractCallbackImp::GetStream(UInt32 index, + ISequentialOutStream **outStream, Int32 askExtractMode)) { #ifndef _NO_PROGRESS if (ProgressDialog.Sync.GetStopped()) @@ -104,7 +104,7 @@ UString fullPath; { NCOM::CPropVariant prop; - RINOK(_archiveHandler->GetProperty(index, kpidPath, &prop)); + RINOK(_archiveHandler->GetProperty(index, kpidPath, &prop)) if (prop.vt == VT_EMPTY) fullPath = _itemDefaultName; else @@ -119,7 +119,7 @@ if (askExtractMode == NArchive::NExtract::NAskMode::kExtract) { NCOM::CPropVariant prop; - RINOK(_archiveHandler->GetProperty(index, kpidAttrib, &prop)); + RINOK(_archiveHandler->GetProperty(index, kpidAttrib, &prop)) if (prop.vt == VT_EMPTY) _processedFileInfo.Attributes = _defaultAttributes; else @@ -129,18 +129,18 @@ _processedFileInfo.Attributes = prop.ulVal; } - RINOK(_archiveHandler->GetProperty(index, kpidIsDir, &prop)); + RINOK(_archiveHandler->GetProperty(index, kpidIsDir, &prop)) _processedFileInfo.IsDir = VARIANT_BOOLToBool(prop.boolVal); bool isAnti = false; { NCOM::CPropVariant propTemp; - RINOK(_archiveHandler->GetProperty(index, kpidIsAnti, &propTemp)); + RINOK(_archiveHandler->GetProperty(index, kpidIsAnti, &propTemp)) if (propTemp.vt == VT_BOOL) isAnti = VARIANT_BOOLToBool(propTemp.boolVal); } - RINOK(_archiveHandler->GetProperty(index, kpidMTime, &prop)); + RINOK(_archiveHandler->GetProperty(index, kpidMTime, &prop)) switch (prop.vt) { case VT_EMPTY: _processedFileInfo.MTime = _defaultMTime; break; @@ -207,13 +207,13 @@ return S_OK; } -STDMETHODIMP CExtractCallbackImp::PrepareOperation(Int32 askExtractMode) +Z7_COM7F_IMF(CExtractCallbackImp::PrepareOperation(Int32 askExtractMode)) { _extractMode = (askExtractMode == NArchive::NExtract::NAskMode::kExtract); return S_OK; } -STDMETHODIMP CExtractCallbackImp::SetOperationResult(Int32 resultEOperationResult) +Z7_COM7F_IMF(CExtractCallbackImp::SetOperationResult(Int32 resultEOperationResult)) { switch (resultEOperationResult) { @@ -237,7 +237,7 @@ if (_outFileStream != NULL) { _outFileStreamSpec->SetMTime(&_processedFileInfo.MTime); - RINOK(_outFileStreamSpec->Close()); + RINOK(_outFileStreamSpec->Close()) } _outFileStream.Release(); if (_extractMode) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.h 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.h --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.h 2013-01-25 07:53:12.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.h 2023-04-03 07:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ExtractCallbackSfx.h -#ifndef __EXTRACT_CALLBACK_SFX_H -#define __EXTRACT_CALLBACK_SFX_H +#ifndef ZIP7_INC_EXTRACT_CALLBACK_SFX_H +#define ZIP7_INC_EXTRACT_CALLBACK_SFX_H #include "resource.h" @@ -19,19 +19,16 @@ #endif #include "../../UI/Common/ArchiveOpenCallback.h" -class CExtractCallbackImp: +class CExtractCallbackImp Z7_final: public IArchiveExtractCallback, public IOpenCallbackUI, public CMyUnknownImp { -public: - - MY_UNKNOWN_IMP - - INTERFACE_IArchiveExtractCallback(;) - INTERFACE_IOpenCallbackUI(;) + Z7_COM_UNKNOWN_IMP_0 + Z7_IFACE_COM7_IMP(IProgress) + Z7_IFACE_COM7_IMP(IArchiveExtractCallback) + Z7_IFACE_IMP(IOpenCallbackUI) -private: CMyComPtr _archiveHandler; FString _directoryPath; UString _filePath; @@ -70,7 +67,7 @@ #ifndef _NO_PROGRESS HRESULT StartProgressDialog(const UString &title, NWindows::CThread &thread) { - ProgressDialog.Create(title, thread, 0); + ProgressDialog.Create(title, thread, NULL); { ProgressDialog.SetText(LangString(IDS_PROGRESS_EXTRACTING)); } @@ -78,7 +75,7 @@ ProgressDialog.Show(SW_SHOWNORMAL); return S_OK; } - virtual ~CExtractCallbackImp() { ProgressDialog.Destroy(); } + ~CExtractCallbackImp() { ProgressDialog.Destroy(); } #endif }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXSetup/ExtractEngine.cpp 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXSetup/ExtractEngine.cpp --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXSetup/ExtractEngine.cpp 2020-06-11 12:15:24.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXSetup/ExtractEngine.cpp 2023-03-20 18:00:00.000000000 +0000 @@ -64,18 +64,14 @@ if (!CreateComplexDir(dirPath)) { - ErrorMessage = MyFormatNew(IDS_CANNOT_CREATE_FOLDER, - #ifdef LANG - 0x02000603, - #endif - fs2us(dirPath)); + ErrorMessage = MyFormatNew(IDS_CANNOT_CREATE_FOLDER, fs2us(dirPath)); Result = E_FAIL; return; } ExtractCallbackSpec->Init(ArchiveLink.GetArchive(), dirPath, (UString)"Default", fi.MTime, 0); - Result = ArchiveLink.GetArchive()->Extract(0, (UInt32)(Int32)-1 , BoolToInt(false), ExtractCallback); + Result = ArchiveLink.GetArchive()->Extract(NULL, (UInt32)(Int32)-1 , BoolToInt(false), ExtractCallback); } void Process() @@ -116,7 +112,9 @@ { t.ExtractCallbackSpec->ProgressDialog.IconID = IDI_ICON; NWindows::CThread thread; - RINOK(thread.Create(CThreadExtracting::MyThreadFunction, &t)); + const WRes wres = thread.Create(CThreadExtracting::MyThreadFunction, &t); + if (wres != 0) + return HRESULT_FROM_WIN32(wres); UString title; LangString(IDS_PROGRESS_EXTRACTING, title); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXSetup/ExtractEngine.h 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXSetup/ExtractEngine.h --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXSetup/ExtractEngine.h 2011-03-01 05:54:26.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXSetup/ExtractEngine.h 2023-01-10 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ExtractEngine.h -#ifndef __EXTRACT_ENGINE_H -#define __EXTRACT_ENGINE_H +#ifndef ZIP7_INC_EXTRACT_ENGINE_H +#define ZIP7_INC_EXTRACT_ENGINE_H #include "../../UI/Common/LoadCodecs.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXSetup/makefile 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXSetup/makefile --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXSetup/makefile 2018-04-23 09:04:16.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXSetup/makefile 2023-03-19 18:00:00.000000000 +0000 @@ -2,11 +2,11 @@ MY_FIXED = 1 CFLAGS = $(CFLAGS) \ - -DNO_REGISTRY \ - -DEXTRACT_ONLY \ - -DNO_READ_FROM_CODER \ - -D_SFX \ - -D_NO_CRYPTO \ + -DZ7_NO_REGISTRY \ + -DZ7_EXTRACT_ONLY \ + -DZ7_NO_READ_FROM_CODER \ + -DZ7_SFX \ + -DZ7_NO_CRYPTO \ CURRENT_OBJS = \ $O\SfxSetup.obj \ @@ -97,6 +97,7 @@ $O\LzmaRegister.obj \ C_OBJS = \ + $O\7zStream.obj \ $O\Alloc.obj \ $O\Bcj2.obj \ $O\Bra.obj \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXSetup/SfxSetup.cpp 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXSetup/SfxSetup.cpp --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXSetup/SfxSetup.cpp 2021-03-06 15:56:47.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXSetup/SfxSetup.cpp 2023-04-05 13:00:00.000000000 +0000 @@ -2,8 +2,9 @@ #include "StdAfx.h" -#include "../../../Common/MyWindows.h" +#include "../../../../C/DllSecur.h" +#include "../../../Common/MyWindows.h" #include "../../../Common/MyInitGuid.h" #include "../../../Common/CommandLineParser.h" @@ -23,19 +24,19 @@ #include "ExtractEngine.h" -#include "../../../../C/DllSecur.h" - #include "resource.h" using namespace NWindows; using namespace NFile; using namespace NDir; +extern +HINSTANCE g_hInstance; HINSTANCE g_hInstance; static CFSTR const kTempDirPrefix = FTEXT("7zS"); -#define _SHELL_EXECUTE +#define MY_SHELL_EXECUTE static bool ReadDataString(CFSTR fileName, LPCSTR startID, LPCSTR endID, AString &stringResult) @@ -73,10 +74,10 @@ break; if (memcmp(buffer + pos, endID, signatureEndSize) == 0) return true; - char b = buffer[pos]; + const Byte b = buffer[pos]; if (b == 0) return false; - stringResult += b; + stringResult += (char)b; pos++; } else @@ -101,13 +102,13 @@ static char kStartID[] = { ',','!','@','I','n','s','t','a','l','l','@','!','U','T','F','-','8','!', 0 }; static char kEndID[] = { ',','!','@','I','n','s','t','a','l','l','E','n','d','@','!', 0 }; -struct CInstallIDInit +static struct CInstallIDInit { CInstallIDInit() { kStartID[0] = ';'; kEndID[0] = ';'; - }; + } } g_CInstallIDInit; @@ -118,11 +119,11 @@ static void ShowErrorMessageSpec(const UString &name) { UString message = NError::MyFormatMessage(::GetLastError()); - int pos = message.Find(L"%1"); + const int pos = message.Find(L"%1"); if (pos >= 0) { - message.Delete(pos, 2); - message.Insert(pos, name); + message.Delete((unsigned)pos, 2); + message.Insert((unsigned)pos, name); } ShowErrorMessage(NULL, message); } @@ -146,7 +147,7 @@ // InitCommonControls(); UString archiveName, switches; - #ifdef _SHELL_EXECUTE + #ifdef MY_SHELL_EXECUTE UString executeFile, executeParameters; #endif NCommandLineParser::SplitCommandLine(GetCommandLineW(), archiveName, switches); @@ -183,23 +184,23 @@ ShowErrorMessage(L"Config failed"); return 1; } - UString friendlyName = GetTextConfigValue(pairs, "Title"); - UString installPrompt = GetTextConfigValue(pairs, "BeginPrompt"); - UString progress = GetTextConfigValue(pairs, "Progress"); + const UString friendlyName = GetTextConfigValue(pairs, "Title"); + const UString installPrompt = GetTextConfigValue(pairs, "BeginPrompt"); + const UString progress = GetTextConfigValue(pairs, "Progress"); if (progress.IsEqualTo_Ascii_NoCase("no")) showProgress = false; - int index = FindTextConfigItem(pairs, "Directory"); + const int index = FindTextConfigItem(pairs, "Directory"); if (index >= 0) dirPrefix = pairs[index].String; if (!installPrompt.IsEmpty() && !assumeYes) { - if (MessageBoxW(0, installPrompt, friendlyName, MB_YESNO | + if (MessageBoxW(NULL, installPrompt, friendlyName, MB_YESNO | MB_ICONQUESTION) != IDYES) return 0; } appLaunched = GetTextConfigValue(pairs, "RunProgram"); - #ifdef _SHELL_EXECUTE + #ifdef MY_SHELL_EXECUTE executeFile = GetTextConfigValue(pairs, "ExecuteFile"); executeParameters = GetTextConfigValue(pairs, "ExecuteParameters"); #endif @@ -216,7 +217,7 @@ CCodecs *codecs = new CCodecs; CMyComPtr compressCodecsInfo = codecs; { - HRESULT result = codecs->Load(); + const HRESULT result = codecs->Load(); if (result != S_OK) { ShowErrorMessage(L"Cannot load codecs"); @@ -245,7 +246,7 @@ { if (errorMessage.IsEmpty()) errorMessage = NError::MyFormatMessage(result); - ::MessageBoxW(0, errorMessage, NWindows::MyLoadString(IDS_EXTRACTION_ERROR_TITLE), MB_ICONERROR); + ::MessageBoxW(NULL, errorMessage, NWindows::MyLoadString(IDS_EXTRACTION_ERROR_TITLE), MB_ICONERROR); } } return 1; @@ -258,8 +259,8 @@ return 1; #endif - HANDLE hProcess = 0; -#ifdef _SHELL_EXECUTE + HANDLE hProcess = NULL; +#ifdef MY_SHELL_EXECUTE if (!executeFile.IsEmpty()) { CSysString filePath (GetSystemString(executeFile)); @@ -280,7 +281,7 @@ executeParameters += switches; } - CSysString parametersSys (GetSystemString(executeParameters)); + const CSysString parametersSys (GetSystemString(executeParameters)); if (parametersSys.IsEmpty()) execInfo.lpParameters = NULL; else @@ -288,7 +289,7 @@ execInfo.lpDirectory = NULL; execInfo.nShow = SW_SHOWNORMAL; - execInfo.hProcess = 0; + execInfo.hProcess = NULL; /* BOOL success = */ ::ShellExecuteEx(&execInfo); UINT32 result = (UINT32)(UINT_PTR)execInfo.hInstApp; if (result <= 32) @@ -319,7 +320,7 @@ appLaunched.Replace(L"%%T" WSTRING_PATH_SEPARATOR, fs2us(s2)); } - UString appNameForError = appLaunched; // actually we need to rtemove parameters also + const UString appNameForError = appLaunched; // actually we need to rtemove parameters also appLaunched.Replace(L"%%T", fs2us(tempDirPath)); @@ -330,20 +331,21 @@ } STARTUPINFO startupInfo; startupInfo.cb = sizeof(startupInfo); - startupInfo.lpReserved = 0; - startupInfo.lpDesktop = 0; - startupInfo.lpTitle = 0; + startupInfo.lpReserved = NULL; + startupInfo.lpDesktop = NULL; + startupInfo.lpTitle = NULL; startupInfo.dwFlags = 0; startupInfo.cbReserved2 = 0; - startupInfo.lpReserved2 = 0; + startupInfo.lpReserved2 = NULL; PROCESS_INFORMATION processInformation; - CSysString appLaunchedSys (GetSystemString(dirPrefix + appLaunched)); + const CSysString appLaunchedSys (GetSystemString(dirPrefix + appLaunched)); - BOOL createResult = CreateProcess(NULL, (LPTSTR)(LPCTSTR)appLaunchedSys, - NULL, NULL, FALSE, 0, NULL, NULL /*tempDir.GetPath() */, - &startupInfo, &processInformation); + const BOOL createResult = CreateProcess(NULL, + appLaunchedSys.Ptr_non_const(), + NULL, NULL, FALSE, 0, NULL, NULL /*tempDir.GetPath() */, + &startupInfo, &processInformation); if (createResult == 0) { if (!assumeYes) @@ -357,7 +359,7 @@ ::CloseHandle(processInformation.hThread); hProcess = processInformation.hProcess; } - if (hProcess != 0) + if (hProcess) { WaitForSingleObject(hProcess, INFINITE); ::CloseHandle(hProcess); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXSetup/SFXSetup.dsp 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXSetup/SFXSetup.dsp --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXSetup/SFXSetup.dsp 2018-02-25 09:26:30.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXSetup/SFXSetup.dsp 2023-04-05 13:00:00.000000000 +0000 @@ -44,7 +44,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /Gz /MT /W4 /WX /GX /O1 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "EXTRACT_ONLY" /D "NO_REGISTRY" /D "_SFX" /D "_NO_CRYPTO" /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gz /MT /W4 /WX /GX /O1 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "Z7_EXTRACT_ONLY" /D "Z7_NO_REGISTRY" /D "Z7_SFX" /D "Z7_NO_CRYPTO" /Yu"StdAfx.h" /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "NDEBUG" @@ -71,7 +71,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /Gz /MTd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "EXTRACT_ONLY" /D "NO_REGISTRY" /D "_SFX" /D "_NO_CRYPTO" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gz /MTd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "Z7_EXTRACT_ONLY" /D "Z7_NO_REGISTRY" /D "Z7_SFX" /D "Z7_NO_CRYPTO" /Yu"StdAfx.h" /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "_DEBUG" @@ -97,8 +97,8 @@ # PROP Intermediate_Dir "ReleaseD" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" -# ADD BASE CPP /nologo /MD /W3 /GX /O1 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "EXTRACT_ONLY" /D "EXCLUDE_COM" /D "NO_REGISTRY" /D "_SFX" /Yu"StdAfx.h" /FD /c -# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "EXTRACT_ONLY" /D "NO_REGISTRY" /D "_SFX" /D "_NO_CRYPTO" /Yu"StdAfx.h" /FD /c +# ADD BASE CPP /nologo /MD /W3 /GX /O1 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "Z7_EXTRACT_ONLY" /D "Z7_NO_REGISTRY" /D "Z7_SFX" /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "Z7_EXTRACT_ONLY" /D "Z7_NO_REGISTRY" /D "Z7_SFX" /D "Z7_NO_CRYPTO" /Yu"StdAfx.h" /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "NDEBUG" @@ -221,6 +221,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Compress\Bcj2Coder.h +# End Source File +# Begin Source File + SOURCE=..\..\Compress\Bcj2Register.cpp # End Source File # Begin Source File @@ -229,6 +233,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Compress\BcjCoder.h +# End Source File +# Begin Source File + SOURCE=..\..\Compress\BcjRegister.cpp # End Source File # Begin Source File @@ -249,6 +257,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Compress\CopyCoder.h +# End Source File +# Begin Source File + SOURCE=..\..\Compress\CopyRegister.cpp # End Source File # Begin Source File @@ -289,6 +301,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\Common.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\CRC.cpp # End Source File # Begin Source File @@ -305,6 +321,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyCom.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\MyString.cpp # End Source File # Begin Source File @@ -464,7 +484,7 @@ SOURCE=..\..\..\Windows\Window.h # End Source File # End Group -# Begin Group "7z Common" +# Begin Group "7zip Common" # PROP Default_Filter "" # Begin Source File @@ -667,6 +687,19 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\7zStream.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\7zTypes.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\7zWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\Alloc.c # SUBTRACT CPP /YX /Yc /Yu # End Source File @@ -704,6 +737,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\Compiler.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\CpuArch.c # SUBTRACT CPP /YX /Yc /Yu # End Source File @@ -775,6 +812,30 @@ SOURCE=..\..\..\..\C\Threads.h # End Source File # End Group +# Begin Group "7zip" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=..\..\Archive\IArchive.h +# End Source File +# Begin Source File + +SOURCE=..\..\ICoder.h +# End Source File +# Begin Source File + +SOURCE=..\..\IDecl.h +# End Source File +# Begin Source File + +SOURCE=..\..\IPassword.h +# End Source File +# Begin Source File + +SOURCE=..\..\IProgress.h +# End Source File +# End Group # Begin Source File SOURCE=.\ExtractCallbackSfx.cpp diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXSetup/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXSetup/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXSetup/StdAfx.h 2013-11-27 09:50:29.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXSetup/StdAfx.h 2023-03-06 19:00:00.000000000 +0000 @@ -1,13 +1,6 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/Common.h" - -#include - -// #define printf(x) NO_PRINTF_(x) -// #define sprintf(x) NO_SPRINTF_(x) - +#if _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' #endif +#include "../../UI/FileManager/StdAfx.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXWin/makefile 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXWin/makefile --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXWin/makefile 2021-08-30 07:28:29.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXWin/makefile 2023-03-19 19:00:00.000000000 +0000 @@ -2,10 +2,10 @@ MY_FIXED = 1 CFLAGS = $(CFLAGS) \ - -DNO_REGISTRY \ - -DEXTRACT_ONLY \ - -DNO_READ_FROM_CODER \ - -D_SFX \ + -DZ7_NO_REGISTRY \ + -DZ7_EXTRACT_ONLY \ + -DZ7_NO_READ_FROM_CODER \ + -DZ7_SFX \ !IFDEF UNDER_CE LIBS = $(LIBS) ceshell.lib Commctrl.lib @@ -131,6 +131,7 @@ $O\MyAes.obj \ C_OBJS = \ + $O\7zStream.obj \ $O\Alloc.obj \ $O\Bcj2.obj \ $O\Bra.obj \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXWin/resource.rc 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXWin/resource.rc --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXWin/resource.rc 2011-09-15 07:04:02.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXWin/resource.rc 2022-12-28 17:00:00.000000000 +0000 @@ -48,3 +48,8 @@ BEGIN IDS_PROP_MTIME "Modified" END + + +#ifndef UNDER_CE +1 24 MOVEABLE PURE "../../UI/GUI/7zG.exe.manifest" +#endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXWin/SfxWin.cpp 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXWin/SfxWin.cpp --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXWin/SfxWin.cpp 2021-12-22 19:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXWin/SfxWin.cpp 2023-04-05 13:00:00.000000000 +0000 @@ -4,7 +4,13 @@ #include "../../../Common/MyWindows.h" +#if defined(__MINGW32__) || defined(__MINGW64__) +#include +#else #include +#endif + +#include "../../../../C/DllSecur.h" #include "../../../Common/MyInitGuid.h" @@ -28,33 +34,36 @@ #include "../../UI/GUI/ExtractGUI.h" #include "../../UI/GUI/ExtractRes.h" -#include "../../../../C/DllSecur.h" - using namespace NWindows; using namespace NFile; using namespace NDir; +extern +HINSTANCE g_hInstance; HINSTANCE g_hInstance; #ifndef UNDER_CE +static DWORD g_ComCtl32Version; static DWORD GetDllVersion(LPCTSTR dllName) { DWORD dwVersion = 0; - HINSTANCE hinstDll = LoadLibrary(dllName); + const HINSTANCE hinstDll = LoadLibrary(dllName); if (hinstDll) { - DLLGETVERSIONPROC pDllGetVersion = (DLLGETVERSIONPROC)GetProcAddress(hinstDll, "DllGetVersion"); - if (pDllGetVersion) + const + DLLGETVERSIONPROC func_DllGetVersion = Z7_GET_PROC_ADDRESS( + DLLGETVERSIONPROC, hinstDll, "DllGetVersion"); + if (func_DllGetVersion) { DLLVERSIONINFO dvi; ZeroMemory(&dvi, sizeof(dvi)); dvi.cbSize = sizeof(dvi); - HRESULT hr = (*pDllGetVersion)(&dvi); + const HRESULT hr = func_DllGetVersion(&dvi); if (SUCCEEDED(hr)) - dwVersion = MAKELONG(dvi.dwMinorVersion, dvi.dwMajorVersion); + dwVersion = (DWORD)MAKELONG(dvi.dwMinorVersion, dvi.dwMajorVersion); } FreeLibrary(hinstDll); } @@ -63,6 +72,8 @@ #endif +extern +bool g_LVN_ITEMACTIVATE_Support; bool g_LVN_ITEMACTIVATE_Support = true; static const wchar_t * const kUnknownExceptionMessage = L"ERROR: Unknown Error!"; @@ -101,7 +112,7 @@ const UString &s = commandStrings[i]; if (s.Len() > 1 && s[0] == '-') { - wchar_t c = MyCharLower_Ascii(s[1]); + const wchar_t c = MyCharLower_Ascii(s[1]); if (c == 'y') { assumeYes = true; @@ -152,7 +163,7 @@ CMyComPtr extractCallback = ecs; ecs->Init(); - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO ecs->PasswordIsDefined = !password.IsEmpty(); ecs->Password = password; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXWin/SFXWin.dsp 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXWin/SFXWin.dsp --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXWin/SFXWin.dsp 2021-08-30 09:40:27.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXWin/SFXWin.dsp 2023-04-05 13:00:00.000000000 +0000 @@ -44,7 +44,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_SFXWIN32" /D "_WINDOWS" /D "_MBCS" /D "EXTRACT_ONLY" /D "NO_REGISTRY" /D "NO_READ_FROM_CODER" /D "_SFX" /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "Z7_EXTRACT_ONLY" /D "Z7_NO_REGISTRY" /D "Z7_NO_READ_FROM_CODER" /D "Z7_SFX" /Yu"StdAfx.h" /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "NDEBUG" @@ -71,7 +71,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /Gz /MTd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_SFXWIN32" /D "_WINDOWS" /D "_MBCS" /D "EXTRACT_ONLY" /D "NO_REGISTRY" /D "NO_READ_FROM_CODER" /D "_SFX" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gz /MTd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "Z7_EXTRACT_ONLY" /D "Z7_NO_REGISTRY" /D "Z7_NO_READ_FROM_CODER" /D "Z7_SFX" /Yu"StdAfx.h" /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "_DEBUG" @@ -97,8 +97,8 @@ # PROP Intermediate_Dir "SFXWin___Win32_ReleaseD" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" -# ADD BASE CPP /nologo /Gz /MT /W3 /GX /O1 /I "..\..\..\\" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "EXTRACT_ONLY" /D "EXCLUDE_COM" /D "NO_REGISTRY" /D "_SFX" /Yu"StdAfx.h" /FD /c -# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_SFXWIN32" /D "_WINDOWS" /D "_MBCS" /D "EXTRACT_ONLY" /D "NO_REGISTRY" /D "NO_READ_FROM_CODER" /D "_SFX" /Yu"StdAfx.h" /FD /c +# ADD BASE CPP /nologo /Gz /MT /W3 /GX /O1 /I "..\..\..\\" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "Z7_EXTRACT_ONLY" /D "Z7_NO_REGISTRY" /D "Z7_SFX" /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "Z7_EXTRACT_ONLY" /D "Z7_NO_REGISTRY" /D "Z7_NO_READ_FROM_CODER" /D "Z7_SFX" /Yu"StdAfx.h" /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "NDEBUG" @@ -221,6 +221,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Compress\Bcj2Coder.h +# End Source File +# Begin Source File + SOURCE=..\..\Compress\Bcj2Register.cpp # End Source File # Begin Source File @@ -229,6 +233,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Compress\BcjCoder.h +# End Source File +# Begin Source File + SOURCE=..\..\Compress\BcjRegister.cpp # End Source File # Begin Source File @@ -249,6 +257,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Compress\CopyCoder.h +# End Source File +# Begin Source File + SOURCE=..\..\Compress\CopyRegister.cpp # End Source File # Begin Source File @@ -277,6 +289,10 @@ # End Source File # Begin Source File +SOURCE=..\..\Compress\PpmdDecoder.h +# End Source File +# Begin Source File + SOURCE=..\..\Compress\PpmdRegister.cpp # End Source File # End Group @@ -677,6 +693,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\Common.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\CRC.cpp # End Source File # Begin Source File @@ -851,6 +871,15 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\7zStream.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\7zWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\Aes.c # SUBTRACT CPP /YX /Yc /Yu # End Source File @@ -902,6 +931,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\Compiler.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\CpuArch.c # SUBTRACT CPP /YX /Yc /Yu # End Source File @@ -993,13 +1026,33 @@ SOURCE=..\..\..\..\C\Threads.h # End Source File # End Group +# Begin Group "7zip" + +# PROP Default_Filter "" # Begin Source File -SOURCE=.\7z.ico +SOURCE=..\..\Archive\IArchive.h # End Source File # Begin Source File -SOURCE=.\7z1.ico +SOURCE=..\..\ICoder.h +# End Source File +# Begin Source File + +SOURCE=..\..\IDecl.h +# End Source File +# Begin Source File + +SOURCE=..\..\IPassword.h +# End Source File +# Begin Source File + +SOURCE=..\..\IProgress.h +# End Source File +# End Group +# Begin Source File + +SOURCE=.\7z.ico # End Source File # Begin Source File diff -Nru 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXWin/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXWin/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Bundles/SFXWin/StdAfx.h 2013-10-29 09:02:25.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Bundles/SFXWin/StdAfx.h 2023-03-06 19:00:00.000000000 +0000 @@ -1,14 +1,6 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/Common.h" - -#include -#include - -// #define printf(x) NO_PRINTF_(x) -// #define sprintf(x) NO_SPRINTF_(x) - +#if _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' #endif +#include "../../UI/FileManager/StdAfx.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/CreateCoder.cpp 7zip-23.01+dfsg/CPP/7zip/Common/CreateCoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/CreateCoder.cpp 2021-08-05 08:12:08.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/CreateCoder.cpp 2023-03-18 12:00:00.000000000 +0000 @@ -19,11 +19,11 @@ const CCodecInfo *g_Codecs[kNumCodecsMax]; // We use g_ExternalCodecs in other stages. -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS /* extern CExternalCodecs g_ExternalCodecs; #define CHECK_GLOBAL_CODECS \ - if (!__externalCodecs || !__externalCodecs->IsSet()) __externalCodecs = &g_ExternalCodecs; + if (!_externalCodecs || !_externalCodecs->IsSet()) _externalCodecs = &g_ExternalCodecs; */ #define CHECK_GLOBAL_CODECS #endif @@ -50,12 +50,12 @@ } -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS static HRESULT ReadNumberOfStreams(ICompressCodecsInfo *codecsInfo, UInt32 index, PROPID propID, UInt32 &res) { NWindows::NCOM::CPropVariant prop; - RINOK(codecsInfo->GetProperty(index, propID, &prop)); + RINOK(codecsInfo->GetProperty(index, propID, &prop)) if (prop.vt == VT_EMPTY) res = 1; else if (prop.vt == VT_UI4) @@ -68,7 +68,7 @@ static HRESULT ReadIsAssignedProp(ICompressCodecsInfo *codecsInfo, UInt32 index, PROPID propID, bool &res) { NWindows::NCOM::CPropVariant prop; - RINOK(codecsInfo->GetProperty(index, propID, &prop)); + RINOK(codecsInfo->GetProperty(index, propID, &prop)) if (prop.vt == VT_EMPTY) res = true; else if (prop.vt == VT_BOOL) @@ -89,13 +89,13 @@ UString s; UInt32 num; - RINOK(GetCodecs->GetNumMethods(&num)); + RINOK(GetCodecs->GetNumMethods(&num)) for (UInt32 i = 0; i < num; i++) { NWindows::NCOM::CPropVariant prop; - RINOK(GetCodecs->GetProperty(i, NMethodPropID::kID, &prop)); + RINOK(GetCodecs->GetProperty(i, NMethodPropID::kID, &prop)) if (prop.vt != VT_UI8) continue; // old Interface info.Id = prop.uhVal.QuadPart; @@ -103,22 +103,22 @@ prop.Clear(); info.Name.Empty(); - RINOK(GetCodecs->GetProperty(i, NMethodPropID::kName, &prop)); + RINOK(GetCodecs->GetProperty(i, NMethodPropID::kName, &prop)) if (prop.vt == VT_BSTR) info.Name.SetFromWStr_if_Ascii(prop.bstrVal); else if (prop.vt != VT_EMPTY) continue; - RINOK(ReadNumberOfStreams(GetCodecs, i, NMethodPropID::kPackStreams, info.NumStreams)); + RINOK(ReadNumberOfStreams(GetCodecs, i, NMethodPropID::kPackStreams, info.NumStreams)) { UInt32 numUnpackStreams = 1; - RINOK(ReadNumberOfStreams(GetCodecs, i, NMethodPropID::kUnpackStreams, numUnpackStreams)); + RINOK(ReadNumberOfStreams(GetCodecs, i, NMethodPropID::kUnpackStreams, numUnpackStreams)) if (numUnpackStreams != 1) continue; } - RINOK(ReadIsAssignedProp(GetCodecs, i, NMethodPropID::kEncoderIsAssigned, info.EncoderIsAssigned)); - RINOK(ReadIsAssignedProp(GetCodecs, i, NMethodPropID::kDecoderIsAssigned, info.DecoderIsAssigned)); - RINOK(ReadIsAssignedProp(GetCodecs, i, NMethodPropID::kIsFilter, info.IsFilter)); + RINOK(ReadIsAssignedProp(GetCodecs, i, NMethodPropID::kEncoderIsAssigned, info.EncoderIsAssigned)) + RINOK(ReadIsAssignedProp(GetCodecs, i, NMethodPropID::kDecoderIsAssigned, info.DecoderIsAssigned)) + RINOK(ReadIsAssignedProp(GetCodecs, i, NMethodPropID::kIsFilter, info.IsFilter)) Codecs.Add(info); } @@ -133,7 +133,7 @@ { NWindows::NCOM::CPropVariant prop; - RINOK(GetHashers->GetHasherProp(i, NMethodPropID::kID, &prop)); + RINOK(GetHashers->GetHasherProp(i, NMethodPropID::kID, &prop)) if (prop.vt != VT_UI8) continue; info.Id = prop.uhVal.QuadPart; @@ -141,7 +141,7 @@ prop.Clear(); info.Name.Empty(); - RINOK(GetHashers->GetHasherProp(i, NMethodPropID::kName, &prop)); + RINOK(GetHashers->GetHasherProp(i, NMethodPropID::kName, &prop)) if (prop.vt == VT_BSTR) info.Name.SetFromWStr_if_Ascii(prop.bstrVal); else if (prop.vt != VT_EMPTY) @@ -162,7 +162,8 @@ const AString &name, bool encode, CMethodId &methodId, - UInt32 &numStreams) + UInt32 &numStreams, + bool &isFilter) { unsigned i; for (i = 0; i < g_NumCodecs; i++) @@ -173,23 +174,25 @@ { methodId = codec.Id; numStreams = codec.NumStreams; + isFilter = codec.IsFilter; return (int)i; } } - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS CHECK_GLOBAL_CODECS - if (__externalCodecs) - for (i = 0; i < __externalCodecs->Codecs.Size(); i++) + if (_externalCodecs) + for (i = 0; i < _externalCodecs->Codecs.Size(); i++) { - const CCodecInfoEx &codec = __externalCodecs->Codecs[i]; + const CCodecInfoEx &codec = _externalCodecs->Codecs[i]; if ((encode ? codec.EncoderIsAssigned : codec.DecoderIsAssigned) && StringsAreEqualNoCase_Ascii(name, codec.Name)) { methodId = codec.Id; numStreams = codec.NumStreams; + isFilter = codec.IsFilter; return (int)(g_NumCodecs + i); } } @@ -212,14 +215,14 @@ return (int)i; } - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS CHECK_GLOBAL_CODECS - if (__externalCodecs) - for (i = 0; i < __externalCodecs->Codecs.Size(); i++) + if (_externalCodecs) + for (i = 0; i < _externalCodecs->Codecs.Size(); i++) { - const CCodecInfoEx &codec = __externalCodecs->Codecs[i]; + const CCodecInfoEx &codec = _externalCodecs->Codecs[i]; if (codec.Id == methodId && (encode ? codec.EncoderIsAssigned : codec.DecoderIsAssigned)) return (int)(g_NumCodecs + i); } @@ -248,14 +251,14 @@ } } - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS CHECK_GLOBAL_CODECS - if (__externalCodecs) - for (i = 0; i < __externalCodecs->Codecs.Size(); i++) + if (_externalCodecs) + for (i = 0; i < _externalCodecs->Codecs.Size(); i++) { - const CCodecInfoEx &codec = __externalCodecs->Codecs[i]; + const CCodecInfoEx &codec = _externalCodecs->Codecs[i]; if (methodId == codec.Id) { name = codec.Name; @@ -284,14 +287,14 @@ } } - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS CHECK_GLOBAL_CODECS - if (__externalCodecs) - for (i = 0; i < __externalCodecs->Hashers.Size(); i++) + if (_externalCodecs) + for (i = 0; i < _externalCodecs->Hashers.Size(); i++) { - const CHasherInfoEx &codec = __externalCodecs->Hashers[i]; + const CHasherInfoEx &codec = _externalCodecs->Hashers[i]; if (StringsAreEqualNoCase_Ascii(name, codec.Name)) { methodId = codec.Id; @@ -313,13 +316,13 @@ for (i = 0; i < g_NumHashers; i++) methods[i] = (*g_Hashers[i]).Id; - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS CHECK_GLOBAL_CODECS - if (__externalCodecs) - for (i = 0; i < __externalCodecs->Hashers.Size(); i++) - methods.Add(__externalCodecs->Hashers[i].Id); + if (_externalCodecs) + for (i = 0; i < _externalCodecs->Hashers.Size(); i++) + methods.Add(_externalCodecs->Hashers[i].Id); #endif } @@ -364,17 +367,17 @@ } } - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS CHECK_GLOBAL_CODECS - if (__externalCodecs) + if (_externalCodecs) { i -= g_NumCodecs; cod.IsExternal = true; - if (i < __externalCodecs->Codecs.Size()) + if (i < _externalCodecs->Codecs.Size()) { - const CCodecInfoEx &codec = __externalCodecs->Codecs[i]; + const CCodecInfoEx &codec = _externalCodecs->Codecs[i]; // if (codec.Id == methodId) { if (encode) @@ -383,15 +386,15 @@ { if (codec.NumStreams == 1) { - HRESULT res = __externalCodecs->GetCodecs->CreateEncoder(i, &IID_ICompressCoder, (void **)&cod.Coder); + const HRESULT res = _externalCodecs->GetCodecs->CreateEncoder(i, &IID_ICompressCoder, (void **)&cod.Coder); if (res != S_OK && res != E_NOINTERFACE && res != CLASS_E_CLASSNOTAVAILABLE) return res; if (cod.Coder) return res; - return __externalCodecs->GetCodecs->CreateEncoder(i, &IID_ICompressFilter, (void **)&filter); + return _externalCodecs->GetCodecs->CreateEncoder(i, &IID_ICompressFilter, (void **)&filter); } cod.NumStreams = codec.NumStreams; - return __externalCodecs->GetCodecs->CreateEncoder(i, &IID_ICompressCoder2, (void **)&cod.Coder2); + return _externalCodecs->GetCodecs->CreateEncoder(i, &IID_ICompressCoder2, (void **)&cod.Coder2); } } else @@ -399,15 +402,15 @@ { if (codec.NumStreams == 1) { - HRESULT res = __externalCodecs->GetCodecs->CreateDecoder(i, &IID_ICompressCoder, (void **)&cod.Coder); + const HRESULT res = _externalCodecs->GetCodecs->CreateDecoder(i, &IID_ICompressCoder, (void **)&cod.Coder); if (res != S_OK && res != E_NOINTERFACE && res != CLASS_E_CLASSNOTAVAILABLE) return res; if (cod.Coder) return res; - return __externalCodecs->GetCodecs->CreateDecoder(i, &IID_ICompressFilter, (void **)&filter); + return _externalCodecs->GetCodecs->CreateDecoder(i, &IID_ICompressFilter, (void **)&filter); } cod.NumStreams = codec.NumStreams; - return __externalCodecs->GetCodecs->CreateDecoder(i, &IID_ICompressCoder2, (void **)&cod.Coder2); + return _externalCodecs->GetCodecs->CreateDecoder(i, &IID_ICompressCoder2, (void **)&cod.Coder2); } } } @@ -424,7 +427,7 @@ CCreatedCoder &cod) { CMyComPtr filter; - HRESULT res = CreateCoder_Index( + const HRESULT res = CreateCoder_Index( EXTERNAL_CODECS_LOC_VARS index, encode, filter, cod); @@ -447,7 +450,7 @@ CMyComPtr &filter, CCreatedCoder &cod) { - int index = FindMethod_Index(EXTERNAL_CODECS_LOC_VARS methodId, encode); + const int index = FindMethod_Index(EXTERNAL_CODECS_LOC_VARS methodId, encode); if (index < 0) return S_OK; return CreateCoder_Index(EXTERNAL_CODECS_LOC_VARS (unsigned)index, encode, filter, cod); @@ -460,7 +463,7 @@ CCreatedCoder &cod) { CMyComPtr filter; - HRESULT res = CreateCoder_Id( + const HRESULT res = CreateCoder_Id( EXTERNAL_CODECS_LOC_VARS methodId, encode, filter, cod); @@ -483,7 +486,7 @@ CMyComPtr &coder) { CCreatedCoder cod; - HRESULT res = CreateCoder_Id( + const HRESULT res = CreateCoder_Id( EXTERNAL_CODECS_LOC_VARS methodId, encode, cod); @@ -524,18 +527,18 @@ } } - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS CHECK_GLOBAL_CODECS - if (!hasher && __externalCodecs) - for (i = 0; i < __externalCodecs->Hashers.Size(); i++) + if (!hasher && _externalCodecs) + for (i = 0; i < _externalCodecs->Hashers.Size(); i++) { - const CHasherInfoEx &codec = __externalCodecs->Hashers[i]; + const CHasherInfoEx &codec = _externalCodecs->Hashers[i]; if (codec.Id == methodId) { name = codec.Name; - return __externalCodecs->GetHashers->CreateHasher((UInt32)i, &hasher); + return _externalCodecs->GetHashers->CreateHasher((UInt32)i, &hasher); } } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/CreateCoder.h 7zip-23.01+dfsg/CPP/7zip/Common/CreateCoder.h --- 7zip-22.01+dfsg/CPP/7zip/Common/CreateCoder.h 2021-08-05 09:09:56.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/CreateCoder.h 2023-03-18 12:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // CreateCoder.h -#ifndef __CREATE_CODER_H -#define __CREATE_CODER_H +#ifndef ZIP7_INC_CREATE_CODER_H +#define ZIP7_INC_CREATE_CODER_H #include "../../Common/MyCom.h" #include "../../Common/MyString.h" @@ -11,10 +11,10 @@ #include "MethodId.h" /* - if EXTERNAL_CODECS is not defined, the code supports only codecs that + if Z7_EXTERNAL_CODECS is not defined, the code supports only codecs that are statically linked at compile-time and link-time. - if EXTERNAL_CODECS is defined, the code supports also codecs from another + if Z7_EXTERNAL_CODECS is defined, the code supports also codecs from another executable modules, that can be linked dynamically at run-time: - EXE module can use codecs from external DLL files. - DLL module can use codecs from external EXE and DLL files. @@ -26,7 +26,7 @@ 2) External codecs */ -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS struct CCodecInfoEx { @@ -46,13 +46,17 @@ AString Name; }; -#define PUBLIC_ISetCompressCodecsInfo public ISetCompressCodecsInfo, -#define QUERY_ENTRY_ISetCompressCodecsInfo MY_QUERYINTERFACE_ENTRY(ISetCompressCodecsInfo) -#define DECL_ISetCompressCodecsInfo STDMETHOD(SetCompressCodecsInfo)(ICompressCodecsInfo *compressCodecsInfo); -#define IMPL_ISetCompressCodecsInfo2(x) \ -STDMETHODIMP x::SetCompressCodecsInfo(ICompressCodecsInfo *compressCodecsInfo) { \ - COM_TRY_BEGIN __externalCodecs.GetCodecs = compressCodecsInfo; return __externalCodecs.Load(); COM_TRY_END } -#define IMPL_ISetCompressCodecsInfo IMPL_ISetCompressCodecsInfo2(CHandler) +#define Z7_PUBLIC_ISetCompressCodecsInfo_IFEC \ + public ISetCompressCodecsInfo, +#define Z7_COM_QI_ENTRY_ISetCompressCodecsInfo_IFEC \ + Z7_COM_QI_ENTRY(ISetCompressCodecsInfo) +#define DECL_ISetCompressCodecsInfo \ + Z7_COM7F_IMP(SetCompressCodecsInfo(ICompressCodecsInfo *compressCodecsInfo)) +#define IMPL_ISetCompressCodecsInfo2(cls) \ + Z7_COM7F_IMF(cls::SetCompressCodecsInfo(ICompressCodecsInfo *compressCodecsInfo)) \ + { COM_TRY_BEGIN _externalCodecs.GetCodecs = compressCodecsInfo; \ + return _externalCodecs.Load(); COM_TRY_END } +#define IMPL_ISetCompressCodecsInfo IMPL_ISetCompressCodecsInfo2(CHandler) struct CExternalCodecs { @@ -83,26 +87,27 @@ extern CExternalCodecs g_ExternalCodecs; -#define EXTERNAL_CODECS_VARS2 (__externalCodecs.IsSet() ? &__externalCodecs : &g_ExternalCodecs) -#define EXTERNAL_CODECS_VARS2_L (&__externalCodecs) +#define EXTERNAL_CODECS_VARS2 (_externalCodecs.IsSet() ? &_externalCodecs : &g_ExternalCodecs) +#define EXTERNAL_CODECS_VARS2_L (&_externalCodecs) #define EXTERNAL_CODECS_VARS2_G (&g_ExternalCodecs) -#define DECL_EXTERNAL_CODECS_VARS CExternalCodecs __externalCodecs; +#define DECL_EXTERNAL_CODECS_VARS CExternalCodecs _externalCodecs; #define EXTERNAL_CODECS_VARS EXTERNAL_CODECS_VARS2, #define EXTERNAL_CODECS_VARS_L EXTERNAL_CODECS_VARS2_L, #define EXTERNAL_CODECS_VARS_G EXTERNAL_CODECS_VARS2_G, -#define DECL_EXTERNAL_CODECS_LOC_VARS2 const CExternalCodecs *__externalCodecs -#define EXTERNAL_CODECS_LOC_VARS2 __externalCodecs +#define DECL_EXTERNAL_CODECS_LOC_VARS2 const CExternalCodecs *_externalCodecs +#define DECL_EXTERNAL_CODECS_LOC_VARS DECL_EXTERNAL_CODECS_LOC_VARS2, +#define DECL_EXTERNAL_CODECS_LOC_VARS_DECL DECL_EXTERNAL_CODECS_LOC_VARS2; -#define DECL_EXTERNAL_CODECS_LOC_VARS DECL_EXTERNAL_CODECS_LOC_VARS2, -#define EXTERNAL_CODECS_LOC_VARS EXTERNAL_CODECS_LOC_VARS2, +#define EXTERNAL_CODECS_LOC_VARS2 _externalCodecs +#define EXTERNAL_CODECS_LOC_VARS EXTERNAL_CODECS_LOC_VARS2, #else -#define PUBLIC_ISetCompressCodecsInfo -#define QUERY_ENTRY_ISetCompressCodecsInfo +#define Z7_PUBLIC_ISetCompressCodecsInfo_IFEC +#define Z7_COM_QI_ENTRY_ISetCompressCodecsInfo_IFEC #define DECL_ISetCompressCodecsInfo #define IMPL_ISetCompressCodecsInfo #define EXTERNAL_CODECS_VARS2 @@ -111,8 +116,9 @@ #define EXTERNAL_CODECS_VARS_L #define EXTERNAL_CODECS_VARS_G #define DECL_EXTERNAL_CODECS_LOC_VARS2 -#define EXTERNAL_CODECS_LOC_VARS2 #define DECL_EXTERNAL_CODECS_LOC_VARS +#define DECL_EXTERNAL_CODECS_LOC_VARS_DECL +#define EXTERNAL_CODECS_LOC_VARS2 #define EXTERNAL_CODECS_LOC_VARS #endif @@ -122,7 +128,8 @@ const AString &name, bool encode, CMethodId &methodId, - UInt32 &numStreams); + UInt32 &numStreams, + bool &isFilter); bool FindMethod( DECL_EXTERNAL_CODECS_LOC_VARS diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/CWrappers.cpp 7zip-23.01+dfsg/CPP/7zip/Common/CWrappers.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/CWrappers.cpp 2021-02-09 19:12:45.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/CWrappers.cpp 2023-05-04 10:00:00.000000000 +0000 @@ -57,9 +57,9 @@ #define CONVERT_PR_VAL(x) (x == PROGRESS_UNKNOWN_VALUE ? NULL : &x) -static SRes CompressProgress(const ICompressProgress *pp, UInt64 inSize, UInt64 outSize) throw() +static SRes CompressProgress(ICompressProgressPtr pp, UInt64 inSize, UInt64 outSize) throw() { - CCompressProgressWrap *p = CONTAINER_FROM_VTBL(pp, CCompressProgressWrap, vt); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CCompressProgressWrap) p->Res = p->Progress->SetRatioInfo(CONVERT_PR_VAL(inSize), CONVERT_PR_VAL(outSize)); return HRESULT_To_SRes(p->Res, SZ_ERROR_PROGRESS); } @@ -73,9 +73,9 @@ static const UInt32 kStreamStepSize = (UInt32)1 << 31; -static SRes MyRead(const ISeqInStream *pp, void *data, size_t *size) throw() +static SRes MyRead(ISeqInStreamPtr pp, void *data, size_t *size) throw() { - CSeqInStreamWrap *p = CONTAINER_FROM_VTBL(pp, CSeqInStreamWrap, vt); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeqInStreamWrap) UInt32 curSize = ((*size < kStreamStepSize) ? (UInt32)*size : kStreamStepSize); p->Res = (p->Stream->Read(data, curSize, &curSize)); *size = curSize; @@ -85,9 +85,9 @@ return HRESULT_To_SRes(p->Res, SZ_ERROR_READ); } -static size_t MyWrite(const ISeqOutStream *pp, const void *data, size_t size) throw() +static size_t MyWrite(ISeqOutStreamPtr pp, const void *data, size_t size) throw() { - CSeqOutStreamWrap *p = CONTAINER_FROM_VTBL(pp, CSeqOutStreamWrap, vt); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeqOutStreamWrap) if (p->Stream) { p->Res = WriteStream(p->Stream, data, size); @@ -118,20 +118,23 @@ } -static SRes InStreamWrap_Read(const ISeekInStream *pp, void *data, size_t *size) throw() +static SRes InStreamWrap_Read(ISeekInStreamPtr pp, void *data, size_t *size) throw() { - CSeekInStreamWrap *p = CONTAINER_FROM_VTBL(pp, CSeekInStreamWrap, vt); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeekInStreamWrap) UInt32 curSize = ((*size < kStreamStepSize) ? (UInt32)*size : kStreamStepSize); p->Res = p->Stream->Read(data, curSize, &curSize); *size = curSize; return (p->Res == S_OK) ? SZ_OK : SZ_ERROR_READ; } -static SRes InStreamWrap_Seek(const ISeekInStream *pp, Int64 *offset, ESzSeek origin) throw() +static SRes InStreamWrap_Seek(ISeekInStreamPtr pp, Int64 *offset, ESzSeek origin) throw() { - CSeekInStreamWrap *p = CONTAINER_FROM_VTBL(pp, CSeekInStreamWrap, vt); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeekInStreamWrap) UInt32 moveMethod; - switch (origin) + /* we need (int)origin to eliminate the clang warning: + default label in switch which covers all enumeration values + [-Wcovered-switch-default */ + switch ((int)origin) { case SZ_SEEK_SET: moveMethod = STREAM_SEEK_SET; break; case SZ_SEEK_CUR: moveMethod = STREAM_SEEK_CUR; break; @@ -188,15 +191,18 @@ return 0; } -static Byte Wrap_ReadByte(const IByteIn *pp) throw() +// #pragma GCC diagnostic ignored "-Winvalid-offsetof" + +static Byte Wrap_ReadByte(IByteInPtr pp) throw() { - CByteInBufWrap *p = CONTAINER_FROM_VTBL_CLS(pp, CByteInBufWrap, vt); + CByteInBufWrap *p = Z7_CONTAINER_FROM_VTBL_CLS(pp, CByteInBufWrap, vt); + // Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CByteInBufWrap) if (p->Cur != p->Lim) return *p->Cur++; return p->ReadByteFromNewBlock(); } -CByteInBufWrap::CByteInBufWrap(): Buf(NULL) +CByteInBufWrap::CByteInBufWrap() throw(): Buf(NULL) { vt.Read = Wrap_ReadByte; } @@ -227,7 +233,7 @@ /* EXTERN_C_BEGIN -void CLookToSequentialWrap_Look(ILookInSeqStream *pp) +void CLookToSequentialWrap_Look(ILookInSeqStreamPtr pp) { CLookToSequentialWrap *p = (CLookToSequentialWrap *)pp->Obj; @@ -281,9 +287,10 @@ return Res; } -static void Wrap_WriteByte(const IByteOut *pp, Byte b) throw() +static void Wrap_WriteByte(IByteOutPtr pp, Byte b) throw() { - CByteOutBufWrap *p = CONTAINER_FROM_VTBL_CLS(pp, CByteOutBufWrap, vt); + CByteOutBufWrap *p = Z7_CONTAINER_FROM_VTBL_CLS(pp, CByteOutBufWrap, vt); + // Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CByteOutBufWrap) Byte *dest = p->Cur; *dest = b; p->Cur = ++dest; @@ -317,16 +324,16 @@ return (Buf != NULL); } -static size_t LookOutWrap_GetOutBuf(const ILookOutStream *pp, void **buf) throw() +static size_t LookOutWrap_GetOutBuf(ILookOutStreamPtr pp, void **buf) throw() { - CLookOutWrap *p = CONTAINER_FROM_VTBL_CLS(pp, CLookOutWrap, vt); + CLookOutWrap *p = Z7_CONTAINER_FROM_VTBL_CLS(pp, CLookOutWrap, vt); *buf = p->Buf; return p->Size; } -static size_t LookOutWrap_Write(const ILookOutStream *pp, size_t size) throw() +static size_t LookOutWrap_Write(ILookOutStreamPtr pp, size_t size) throw() { - CLookOutWrap *p = CONTAINER_FROM_VTBL_CLS(pp, CLookOutWrap, vt); + CLookOutWrap *p = Z7_CONTAINER_FROM_VTBL_CLS(pp, CLookOutWrap, vt); if (p->Res == S_OK && size != 0) { p->Res = WriteStream(p->Stream, p->Buf, size); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/CWrappers.h 7zip-23.01+dfsg/CPP/7zip/Common/CWrappers.h --- 7zip-22.01+dfsg/CPP/7zip/Common/CWrappers.h 2021-01-24 15:35:35.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/CWrappers.h 2023-05-04 09:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // CWrappers.h -#ifndef __C_WRAPPERS_H -#define __C_WRAPPERS_H +#ifndef ZIP7_INC_C_WRAPPERS_H +#define ZIP7_INC_C_WRAPPERS_H #include "../ICoder.h" #include "../../Common/MyCom.h" @@ -63,7 +63,7 @@ bool Extra; HRESULT Res; - CByteInBufWrap(); + CByteInBufWrap() throw(); ~CByteInBufWrap() { Free(); } void Free() throw(); bool Alloc(UInt32 size) throw(); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/FilePathAutoRename.h 7zip-23.01+dfsg/CPP/7zip/Common/FilePathAutoRename.h --- 7zip-22.01+dfsg/CPP/7zip/Common/FilePathAutoRename.h 2013-01-17 09:56:25.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/FilePathAutoRename.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // FilePathAutoRename.h -#ifndef __FILE_PATH_AUTO_RENAME_H -#define __FILE_PATH_AUTO_RENAME_H +#ifndef ZIP7_INC_FILE_PATH_AUTO_RENAME_H +#define ZIP7_INC_FILE_PATH_AUTO_RENAME_H #include "../../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/FileStreams.cpp 7zip-23.01+dfsg/CPP/7zip/Common/FileStreams.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/FileStreams.cpp 2022-07-12 14:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/FileStreams.cpp 2023-05-03 12:00:00.000000000 +0000 @@ -12,17 +12,19 @@ #include // for major()/minor(): -#if defined(__FreeBSD__) || defined(BSD) #include +#if defined(__FreeBSD__) || defined(BSD) || defined(__APPLE__) #else +#ifndef major #include #endif - #endif +#endif // _WIN32 + #include "../../Windows/FileFind.h" -#ifdef SUPPORT_DEVICE_FILE +#ifdef Z7_DEVICE_FILE #include "../../../C/Alloc.h" #include "../../Common/Defs.h" #endif @@ -47,15 +49,15 @@ } -#ifdef SUPPORT_DEVICE_FILE +#ifdef Z7_DEVICE_FILE static const UInt32 kClusterSize = 1 << 18; #endif CInFileStream::CInFileStream(): - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE VirtPos(0), PhyPos(0), - Buf(0), + Buf(NULL), BufSize(0), #endif #ifndef _WIN32 @@ -73,7 +75,7 @@ CInFileStream::~CInFileStream() { - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE MidFree(Buf); #endif @@ -81,11 +83,11 @@ Callback->InFileStream_On_Destroy(this, CallbackRef); } -STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { - #ifdef USE_WIN_FILE + #ifdef Z7_FILE_STREAMS_USE_WIN_FILE - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE if (processedSize) *processedSize = 0; if (size == 0) @@ -96,7 +98,7 @@ { if (VirtPos >= File.Size) return VirtPos == File.Size ? S_OK : E_FAIL; - UInt64 rem = File.Size - VirtPos; + const UInt64 rem = File.Size - VirtPos; if (size > rem) size = (UInt32)rem; } @@ -104,13 +106,13 @@ { const UInt32 mask = kClusterSize - 1; const UInt64 mask2 = ~(UInt64)mask; - UInt64 alignedPos = VirtPos & mask2; + const UInt64 alignedPos = VirtPos & mask2; if (BufSize > 0 && BufStartPos == alignedPos) { - UInt32 pos = (UInt32)VirtPos & mask; + const UInt32 pos = (UInt32)VirtPos & mask; if (pos >= BufSize) return S_OK; - UInt32 rem = MyMin(BufSize - pos, size); + const UInt32 rem = MyMin(BufSize - pos, size); memcpy(data, Buf + pos, rem); VirtPos += rem; if (processedSize) @@ -119,7 +121,7 @@ } bool useBuf = false; - if ((VirtPos & mask) != 0 || ((ptrdiff_t)data & mask) != 0 ) + if ((VirtPos & mask) != 0 || ((size_t)(ptrdiff_t)data & mask) != 0 ) useBuf = true; else { @@ -138,7 +140,7 @@ if (alignedPos != PhyPos) { UInt64 realNewPosition; - bool result = File.Seek((Int64)alignedPos, FILE_BEGIN, realNewPosition); + const bool result = File.Seek((Int64)alignedPos, FILE_BEGIN, realNewPosition); if (!result) return ConvertBoolToHRESULT(result); PhyPos = realNewPosition; @@ -155,7 +157,7 @@ if (!Buf) return E_OUTOFMEMORY; } - bool result = File.Read1(Buf, readSize, BufSize); + const bool result = File.Read1(Buf, readSize, BufSize); if (!result) return ConvertBoolToHRESULT(result); @@ -180,7 +182,7 @@ if (processedSize) *processedSize = realProcessedSize; - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE VirtPos += realProcessedSize; PhyPos += realProcessedSize; #endif @@ -188,7 +190,7 @@ if (result) return S_OK; - #else // USE_WIN_FILE + #else // Z7_FILE_STREAMS_USE_WIN_FILE if (processedSize) *processedSize = 0; @@ -199,7 +201,7 @@ *processedSize = (UInt32)res; return S_OK; } - #endif // USE_WIN_FILE + #endif // Z7_FILE_STREAMS_USE_WIN_FILE { const DWORD error = ::GetLastError(); @@ -212,7 +214,7 @@ } #ifdef UNDER_CE -STDMETHODIMP CStdInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CStdInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { size_t s2 = fread(data, 1, size, stdin); int error = ferror(stdin); @@ -223,7 +225,7 @@ return E_FAIL; } #else -STDMETHODIMP CStdInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CStdInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { #ifdef _WIN32 @@ -259,14 +261,14 @@ #endif -STDMETHODIMP CInFileStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CInFileStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { if (seekOrigin >= 3) return STG_E_INVALIDFUNCTION; - #ifdef USE_WIN_FILE + #ifdef Z7_FILE_STREAMS_USE_WIN_FILE - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE if (File.IsDeviceFile && (File.SizeDefined || seekOrigin != STREAM_SEEK_END)) { switch (seekOrigin) @@ -293,7 +295,7 @@ in case of error. So we don't need additional code below */ // if (!result) { realNewPosition = 0; File.GetPosition(realNewPosition); } - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE PhyPos = VirtPos = realNewPosition; #endif @@ -319,17 +321,19 @@ #endif } -STDMETHODIMP CInFileStream::GetSize(UInt64 *size) +Z7_COM7F_IMF(CInFileStream::GetSize(UInt64 *size)) { return ConvertBoolToHRESULT(File.GetLength(*size)); } -#ifdef USE_WIN_FILE +#ifdef Z7_FILE_STREAMS_USE_WIN_FILE -STDMETHODIMP CInFileStream::GetProps(UInt64 *size, FILETIME *cTime, FILETIME *aTime, FILETIME *mTime, UInt32 *attrib) +Z7_COM7F_IMF(CInFileStream::GetProps(UInt64 *size, FILETIME *cTime, FILETIME *aTime, FILETIME *mTime, UInt32 *attrib)) { if (!_info_WasLoaded) - RINOK(ReloadProps()); + { + RINOK(ReloadProps()) + } const BY_HANDLE_FILE_INFORMATION &info = _info; /* BY_HANDLE_FILE_INFORMATION info; @@ -346,10 +350,12 @@ } } -STDMETHODIMP CInFileStream::GetProps2(CStreamFileProps *props) +Z7_COM7F_IMF(CInFileStream::GetProps2(CStreamFileProps *props)) { if (!_info_WasLoaded) - RINOK(ReloadProps()); + { + RINOK(ReloadProps()) + } const BY_HANDLE_FILE_INFORMATION &info = _info; /* BY_HANDLE_FILE_INFORMATION info; @@ -370,17 +376,19 @@ } } -STDMETHODIMP CInFileStream::GetProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CInFileStream::GetProperty(PROPID propID, PROPVARIANT *value)) { if (!_info_WasLoaded) - RINOK(ReloadProps()); + { + RINOK(ReloadProps()) + } if (!_info_WasLoaded) return S_OK; NWindows::NCOM::CPropVariant prop; - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE if (File.IsDeviceFile) { switch (propID) @@ -436,9 +444,9 @@ } -STDMETHODIMP CInFileStream::ReloadProps() +Z7_COM7F_IMF(CInFileStream::ReloadProps()) { - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE if (File.IsDeviceFile) { memset(&_info, 0, sizeof(_info)); @@ -461,10 +469,12 @@ #elif !defined(_WIN32) -STDMETHODIMP CInFileStream::GetProps(UInt64 *size, FILETIME *cTime, FILETIME *aTime, FILETIME *mTime, UInt32 *attrib) +Z7_COM7F_IMF(CInFileStream::GetProps(UInt64 *size, FILETIME *cTime, FILETIME *aTime, FILETIME *mTime, UInt32 *attrib)) { if (!_info_WasLoaded) - RINOK(ReloadProps()); + { + RINOK(ReloadProps()) + } const struct stat &st = _info; /* struct stat st; @@ -483,10 +493,12 @@ // #include -STDMETHODIMP CInFileStream::GetProps2(CStreamFileProps *props) +Z7_COM7F_IMF(CInFileStream::GetProps2(CStreamFileProps *props)) { if (!_info_WasLoaded) - RINOK(ReloadProps()); + { + RINOK(ReloadProps()) + } const struct stat &st = _info; /* struct stat st; @@ -521,10 +533,12 @@ return S_OK; } -STDMETHODIMP CInFileStream::GetProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CInFileStream::GetProperty(PROPID propID, PROPVARIANT *value)) { if (!_info_WasLoaded) - RINOK(ReloadProps()); + { + RINOK(ReloadProps()) + } if (!_info_WasLoaded) return S_OK; @@ -544,6 +558,11 @@ case kpidMTime: PropVariant_SetFrom_FiTime(prop, ST_MTIME(st)); break; case kpidPosixAttrib: prop = (UInt32)st.st_mode; break; + #if defined(__APPLE__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wsign-conversion" + #endif + case kpidDeviceMajor: { // printf("\nst.st_rdev = %d\n", st.st_rdev); @@ -563,6 +582,10 @@ // prop = (UInt32)123456789; // for debug break; + #if defined(__APPLE__) + #pragma GCC diagnostic pop + #endif + /* case kpidDevice: if (S_ISCHR(st.st_mode) || @@ -632,7 +655,7 @@ } -STDMETHODIMP CInFileStream::ReloadProps() +Z7_COM7F_IMF(CInFileStream::ReloadProps()) { _info_WasLoaded = (File.my_fstat(&_info) == 0); if (!_info_WasLoaded) @@ -653,9 +676,9 @@ return ConvertBoolToHRESULT(File.Close()); } -STDMETHODIMP COutFileStream::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(COutFileStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { - #ifdef USE_WIN_FILE + #ifdef Z7_FILE_STREAMS_USE_WIN_FILE UInt32 realProcessedSize; const bool result = File.Write(data, size, realProcessedSize); @@ -680,12 +703,12 @@ #endif } -STDMETHODIMP COutFileStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(COutFileStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { if (seekOrigin >= 3) return STG_E_INVALIDFUNCTION; - #ifdef USE_WIN_FILE + #ifdef Z7_FILE_STREAMS_USE_WIN_FILE UInt64 realNewPosition = 0; const bool result = File.Seek(offset, seekOrigin, realNewPosition); @@ -705,7 +728,7 @@ #endif } -STDMETHODIMP COutFileStream::SetSize(UInt64 newSize) +Z7_COM7F_IMF(COutFileStream::SetSize(UInt64 newSize)) { return ConvertBoolToHRESULT(File.SetLength_KeepPosition(newSize)); } @@ -717,7 +740,7 @@ #ifdef UNDER_CE -STDMETHODIMP CStdOutFileStream::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CStdOutFileStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { size_t s2 = fwrite(data, 1, size, stdout); if (processedSize) @@ -727,7 +750,7 @@ #else -STDMETHODIMP CStdOutFileStream::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CStdOutFileStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/FileStreams.h 7zip-23.01+dfsg/CPP/7zip/Common/FileStreams.h --- 7zip-22.01+dfsg/CPP/7zip/Common/FileStreams.h 2022-06-09 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/FileStreams.h 2023-04-05 17:00:00.000000000 +0000 @@ -1,10 +1,10 @@ // FileStreams.h -#ifndef __FILE_STREAMS_H -#define __FILE_STREAMS_H +#ifndef ZIP7_INC_FILE_STREAMS_H +#define ZIP7_INC_FILE_STREAMS_H #ifdef _WIN32 -#define USE_WIN_FILE +#define Z7_FILE_STREAMS_USE_WIN_FILE #endif #include "../../Common/MyCom.h" @@ -18,13 +18,27 @@ class CInFileStream; -struct IInFileStream_Callback + +Z7_PURE_INTERFACES_BEGIN +DECLARE_INTERFACE(IInFileStream_Callback) { virtual HRESULT InFileStream_On_Error(UINT_PTR val, DWORD error) = 0; virtual void InFileStream_On_Destroy(CInFileStream *stream, UINT_PTR val) = 0; }; +Z7_PURE_INTERFACES_END + -class CInFileStream: +/* +Z7_CLASS_IMP_COM_5( + CInFileStream + , IInStream + , IStreamGetSize + , IStreamGetProps + , IStreamGetProps2 + , IStreamGetProp +) +*/ +Z7_class_final(CInFileStream) : public IInStream, public IStreamGetSize, public IStreamGetProps, @@ -32,12 +46,30 @@ public IStreamGetProp, public CMyUnknownImp { + Z7_COM_UNKNOWN_IMP_5( + IInStream, + IStreamGetSize, + IStreamGetProps, + IStreamGetProps2, + IStreamGetProp) + + Z7_IFACE_COM7_IMP(ISequentialInStream) + Z7_IFACE_COM7_IMP(IInStream) +public: + Z7_IFACE_COM7_IMP(IStreamGetSize) +private: + Z7_IFACE_COM7_IMP(IStreamGetProps) +public: + Z7_IFACE_COM7_IMP(IStreamGetProps2) + Z7_IFACE_COM7_IMP(IStreamGetProp) + +private: NWindows::NFile::NIO::CInFile File; public: - #ifdef USE_WIN_FILE + #ifdef Z7_FILE_STREAMS_USE_WIN_FILE - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE UInt64 VirtPos; UInt64 PhyPos; UInt64 BufStartPos; @@ -64,9 +96,8 @@ IInFileStream_Callback *Callback; UINT_PTR CallbackRef; - virtual ~CInFileStream(); - CInFileStream(); + ~CInFileStream(); void Set_PreserveATime(bool v) { @@ -89,44 +120,25 @@ _info_WasLoaded = false; return File.OpenShared(fileName, shareForWrite); } - - MY_QUERYINTERFACE_BEGIN2(IInStream) - MY_QUERYINTERFACE_ENTRY(IStreamGetSize) - MY_QUERYINTERFACE_ENTRY(IStreamGetProps) - MY_QUERYINTERFACE_ENTRY(IStreamGetProps2) - MY_QUERYINTERFACE_ENTRY(IStreamGetProp) - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); - - STDMETHOD(GetSize)(UInt64 *size); - STDMETHOD(GetProps)(UInt64 *size, FILETIME *cTime, FILETIME *aTime, FILETIME *mTime, UInt32 *attrib); - STDMETHOD(GetProps2)(CStreamFileProps *props); - STDMETHOD(GetProperty)(PROPID propID, PROPVARIANT *value); - STDMETHOD(ReloadProps)(); }; -class CStdInFileStream: - public ISequentialInStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - virtual ~CStdInFileStream() {} - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); +Z7_CLASS_IMP_NOQIB_1( + CStdInFileStream + , ISequentialInStream +) }; -class COutFileStream: - public IOutStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_COM_1( + COutFileStream + , IOutStream +) + Z7_IFACE_COM7_IMP(ISequentialOutStream) public: + NWindows::NFile::NIO::COutFile File; - virtual ~COutFileStream() {} bool Create(CFSTR fileName, bool createAlways) { ProcessedSize = 0; @@ -148,15 +160,9 @@ } bool SetMTime(const CFiTime *mTime) { return File.SetMTime(mTime); } - MY_UNKNOWN_IMP1(IOutStream) - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); - STDMETHOD(SetSize)(UInt64 newSize); - bool SeekToBegin_bool() { - #ifdef USE_WIN_FILE + #ifdef Z7_FILE_STREAMS_USE_WIN_FILE return File.SeekToBegin(); #else return File.seekToBegin() == 0; @@ -166,18 +172,15 @@ HRESULT GetSize(UInt64 *size); }; -class CStdOutFileStream: - public ISequentialOutStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_NOQIB_1( + CStdOutFileStream + , ISequentialOutStream +) UInt64 _size; public: - MY_UNKNOWN_IMP - UInt64 GetSize() const { return _size; } CStdOutFileStream(): _size(0) {} - virtual ~CStdOutFileStream() {} - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/FilterCoder.cpp 7zip-23.01+dfsg/CPP/7zip/Common/FilterCoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/FilterCoder.cpp 2019-09-10 13:47:24.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/FilterCoder.cpp 2023-03-18 13:00:00.000000000 +0000 @@ -2,6 +2,8 @@ #include "StdAfx.h" +// #include + #include "../../Common/Defs.h" #include "FilterCoder.h" @@ -33,13 +35,17 @@ Some filters (BCJ and others) don't process data at the end of stream in some cases. So the encoder and decoder write such last bytes without change. + + Most filters process all data, if we send aligned size to filter. + But BCJ filter can process up 4 bytes less than sent size. + And ARMT filter can process 2 bytes less than sent size. */ -static const UInt32 kBufSize = 1 << 20; +static const UInt32 kBufSize = 1 << 21; -STDMETHODIMP CFilterCoder::SetInBufSize(UInt32 , UInt32 size) { _inBufSize = size; return S_OK; } -STDMETHODIMP CFilterCoder::SetOutBufSize(UInt32 , UInt32 size) { _outBufSize = size; return S_OK; } +Z7_COM7F_IMF(CFilterCoder::SetInBufSize(UInt32 , UInt32 size)) { _inBufSize = size; return S_OK; } +Z7_COM7F_IMF(CFilterCoder::SetOutBufSize(UInt32 , UInt32 size)) { _outBufSize = size; return S_OK; } HRESULT CFilterCoder::Alloc() { @@ -51,6 +57,7 @@ size &= ~(UInt32)(kMinSize - 1); if (size < kMinSize) size = kMinSize; + // size = (1 << 12); // + 117; // for debug if (!_buf || _bufSize != size) { AllocAligned(size); @@ -63,7 +70,7 @@ HRESULT CFilterCoder::Init_and_Alloc() { - RINOK(Filter->Init()); + RINOK(Filter->Init()) return Alloc(); } @@ -72,78 +79,197 @@ _inBufSize(kBufSize), _outBufSize(kBufSize), _encodeMode(encodeMode), - _outSizeIsDefined(false), + _outSize_Defined(false), _outSize(0), _nowPos64(0) {} -CFilterCoder::~CFilterCoder() -{ -} -STDMETHODIMP CFilterCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CFilterCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress)) { - RINOK(Init_and_Alloc()); - + RINOK(Init_and_Alloc()) + + /* + It's expected that BCJ/ARMT filter can process up to 4 bytes less + than sent data size. For such BCJ/ARMT cases with non-filtered data we: + - write some filtered data to output stream + - move non-written data (filtered and non-filtered data) to start of buffer + - read more new data from input stream to position after end of non-filtered data + - call Filter() for concatenated data in buffer. + + For all cases, even for cases with partial filtering (BCJ/ARMT), + we try to keep real/virtual alignment for all operations + (memmove, Read(), Filter(), Write()). + We use (kAlignSize=64) alignmnent that is larger than (16-bytes) + required for AES filter alignment. + + AES-CBC uses 16-bytes blocks, that is simple case for processing here, + if we call Filter() for aligned size for all calls except of last call (last block). + And now there are no filters that use blocks with non-power2 size, + but we try to support such non-power2 filters too here at Code(). + */ + UInt64 prev = 0; UInt64 nowPos64 = 0; bool inputFinished = false; - UInt32 pos = 0; + UInt32 readPos = 0; + UInt32 filterPos = 0; while (!outSize || nowPos64 < *outSize) { + HRESULT hres = S_OK; if (!inputFinished) { - size_t processedSize = _bufSize - pos; - RINOK(ReadStream(inStream, _buf + pos, &processedSize)); - pos += (UInt32)processedSize; - inputFinished = (pos != _bufSize); + size_t processedSize = _bufSize - readPos; + /* for AES filters we need at least max(16, kAlignSize) bytes in buffer. + But we try to read full buffer to reduce the number of Filter() and Write() calls. + */ + hres = ReadStream(inStream, _buf + readPos, &processedSize); + readPos += (UInt32)processedSize; + inputFinished = (readPos != _bufSize); + if (hres != S_OK) + { + // do we need to stop encoding after reading error? + // if (_encodeMode) return hres; + inputFinished = true; + } } - if (pos == 0) - return S_OK; + if (readPos == 0) + return hres; - UInt32 filtered = Filter->Filter(_buf, pos); - - if (filtered > pos) + /* we set (needMoreInput = true), if it's block-filter (like AES-CBC) + that needs more data for current block filtering: + We read full input buffer with Read(), and _bufSize is aligned, + So the possible cases when we set (needMoreInput = true) are: + 1) decode : filter needs more data after the end of input stream. + another cases are possible for non-power2-block-filter, + because buffer size is not aligned for filter_non_power2_block_size: + 2) decode/encode : filter needs more data from non-finished input stream + 3) encode : filter needs more space for zeros after the end of input stream + */ + bool needMoreInput = false; + + while (readPos != filterPos) + { + /* Filter() is allowed to process part of data. + Here we use the loop to filter as max as possible. + when we call Filter(data, size): + if (size < 16), AES-CTR filter uses internal 16-byte buffer. + new (since v23.00) AES-CTR filter allows (size < 16) for non-last block, + but it will work less efficiently than calls with aligned (size). + We still support old (before v23.00) AES-CTR filters here. + We have aligned (size) for AES-CTR, if it's not last block. + We have aligned (readPos) for any filter, if (!inputFinished). + We also meet the requirements for (data) pointer in Filter() call: + { + (virtual_stream_offset % aligment_size) == (data_ptr % aligment_size) + (aligment_size == 2^N) + (aligment_size >= 16) + } + */ + const UInt32 cur = Filter->Filter(_buf + filterPos, readPos - filterPos); + if (cur == 0) + break; + const UInt32 f = filterPos + cur; + if (cur > readPos - filterPos) + { + // AES-CBC + if (hres != S_OK) + break; + + if (!_encodeMode + || cur > _bufSize - filterPos + || !inputFinished) + { + /* (cur > _bufSize - filterPos) is unexpected for AES filter, if _bufSize is multiply of 16. + But we support this case, if some future filter will use block with non-power2-size. + */ + needMoreInput = true; + break; + } + + /* (_encodeMode && inputFinished). + We add zero bytes as pad in current block after the end of read data. */ + Byte *buf = _buf; + do + buf[readPos] = 0; + while (++readPos != f); + // (readPos) now is (size_of_real_input_data + size_of_zero_pad) + if (cur != Filter->Filter(buf + filterPos, cur)) + return E_FAIL; + } + filterPos = f; + } + + UInt32 size = filterPos; + if (hres == S_OK) { - // AES - if (!inputFinished || filtered > _bufSize) - return E_FAIL; + /* If we need more Read() or Filter() calls, then we need to Write() + some data and move unwritten data to get additional space in buffer. + We try to keep alignment for data moves, Read(), Filter() and Write() calls. + */ + const UInt32 kAlignSize = 1 << 6; + const UInt32 alignedFiltered = filterPos & ~(kAlignSize - 1); + if (inputFinished) + { + if (!needMoreInput) + size = readPos; // for risc/bcj filters in last block we write data after filterPos. + else if (_encodeMode) + size = alignedFiltered; // for non-power2-block-encode-filter + } + else + size = alignedFiltered; + } + + { + UInt32 writeSize = size; + if (outSize) + { + const UInt64 rem = *outSize - nowPos64; + if (writeSize > rem) + writeSize = (UInt32)rem; + } + RINOK(WriteStream(outStream, _buf, writeSize)) + nowPos64 += writeSize; + } + + if (hres != S_OK) + return hres; + + if (inputFinished) + { + if (readPos == size) + return hres; if (!_encodeMode) + { + // block-decode-filter (AES-CBS) has non-full last block + // we don't want unaligned data move for more iterations with this error case. return S_FALSE; - - Byte *buf = _buf; - do - buf[pos] = 0; - while (++pos != filtered); - - if (filtered != Filter->Filter(buf, filtered)) - return E_FAIL; + } } - UInt32 size = (filtered != 0 ? filtered : pos); - if (outSize) + if (size == 0) { - const UInt64 remSize = *outSize - nowPos64; - if (size > remSize) - size = (UInt32)remSize; + // it's unexpected that we have no any move in this iteration. + return E_FAIL; } - - RINOK(WriteStream(outStream, _buf, size)); - nowPos64 += size; - - if (filtered == 0) - return S_OK; - pos -= filtered; - for (UInt32 i = 0; i < pos; i++) - _buf[i] = _buf[filtered++]; + // if (size != 0) + { + if (filterPos < size) + return E_FAIL; // filterPos = 0; else + filterPos -= size; + readPos -= size; + if (readPos != 0) + memmove(_buf, _buf + size, readPos); + } + // printf("\nnowPos64=%x, readPos=%x, filterPos=%x\n", (unsigned)nowPos64, (unsigned)readPos, (unsigned)filterPos); if (progress && (nowPos64 - prev) >= (1 << 22)) { prev = nowPos64; - RINOK(progress->SetRatioInfo(&nowPos64, &nowPos64)); + RINOK(progress->SetRatioInfo(&nowPos64, &nowPos64)) } } @@ -154,13 +280,13 @@ // ---------- Write to Filter ---------- -STDMETHODIMP CFilterCoder::SetOutStream(ISequentialOutStream *outStream) +Z7_COM7F_IMF(CFilterCoder::SetOutStream(ISequentialOutStream *outStream)) { _outStream = outStream; return S_OK; } -STDMETHODIMP CFilterCoder::ReleaseOutStream() +Z7_COM7F_IMF(CFilterCoder::ReleaseOutStream()) { _outStream.Release(); return S_OK; @@ -171,9 +297,9 @@ while (_convSize != 0) { UInt32 num = _convSize; - if (_outSizeIsDefined) + if (_outSize_Defined) { - UInt64 rem = _outSize - _nowPos64; + const UInt64 rem = _outSize - _nowPos64; if (num > rem) num = (UInt32)rem; if (num == 0) @@ -181,21 +307,23 @@ } UInt32 processed = 0; - HRESULT res = _outStream->Write(_buf + _convPos, num, &processed); + const HRESULT res = _outStream->Write(_buf + _convPos, num, &processed); if (processed == 0) return res != S_OK ? res : E_FAIL; _convPos += processed; _convSize -= processed; _nowPos64 += processed; - RINOK(res); + RINOK(res) } - if (_convPos != 0) + const UInt32 convPos = _convPos; + if (convPos != 0) { - UInt32 num = _bufPos - _convPos; + const UInt32 num = _bufPos - convPos; + Byte *buf = _buf; for (UInt32 i = 0; i < num; i++) - _buf[i] = _buf[_convPos + i]; + buf[i] = buf[convPos + i]; _bufPos = num; _convPos = 0; } @@ -203,14 +331,14 @@ return S_OK; } -STDMETHODIMP CFilterCoder::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CFilterCoder::Write(const void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; while (size != 0) { - RINOK(Flush2()); + RINOK(Flush2()) // _convSize is 0 // _convPos is 0 @@ -245,20 +373,22 @@ return S_OK; } -STDMETHODIMP CFilterCoder::OutStreamFinish() +Z7_COM7F_IMF(CFilterCoder::OutStreamFinish()) { for (;;) { - RINOK(Flush2()); + RINOK(Flush2()) if (_bufPos == 0) break; - _convSize = Filter->Filter(_buf, _bufPos); - if (_convSize == 0) - _convSize = _bufPos; - else if (_convSize > _bufPos) + const UInt32 convSize = Filter->Filter(_buf, _bufPos); + _convSize = convSize; + UInt32 bufPos = _bufPos; + if (convSize == 0) + _convSize = bufPos; + else if (convSize > bufPos) { // AES - if (_convSize > _bufSize) + if (convSize > _bufSize) { _convSize = 0; return E_FAIL; @@ -268,9 +398,11 @@ _convSize = 0; return S_FALSE; } - for (; _bufPos < _convSize; _bufPos++) - _buf[_bufPos] = 0; - _convSize = Filter->Filter(_buf, _bufPos); + Byte *buf = _buf; + for (; bufPos < convSize; bufPos++) + buf[bufPos] = 0; + _bufPos = bufPos; + _convSize = Filter->Filter(_buf, bufPos); if (_convSize != _bufPos) return E_FAIL; } @@ -285,7 +417,7 @@ // ---------- Init functions ---------- -STDMETHODIMP CFilterCoder::InitEncoder() +Z7_COM7F_IMF(CFilterCoder::InitEncoder()) { InitSpecVars(); return Init_and_Alloc(); @@ -297,33 +429,33 @@ return Alloc(); } -STDMETHODIMP CFilterCoder::SetOutStreamSize(const UInt64 *outSize) +Z7_COM7F_IMF(CFilterCoder::SetOutStreamSize(const UInt64 *outSize)) { InitSpecVars(); if (outSize) { _outSize = *outSize; - _outSizeIsDefined = true; + _outSize_Defined = true; } return Init_and_Alloc(); } // ---------- Read from Filter ---------- -STDMETHODIMP CFilterCoder::SetInStream(ISequentialInStream *inStream) +Z7_COM7F_IMF(CFilterCoder::SetInStream(ISequentialInStream *inStream)) { _inStream = inStream; return S_OK; } -STDMETHODIMP CFilterCoder::ReleaseInStream() +Z7_COM7F_IMF(CFilterCoder::ReleaseInStream()) { _inStream.Release(); return S_OK; } -STDMETHODIMP CFilterCoder::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CFilterCoder::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -334,9 +466,9 @@ { if (size > _convSize) size = _convSize; - if (_outSizeIsDefined) + if (_outSize_Defined) { - UInt64 rem = _outSize - _nowPos64; + const UInt64 rem = _outSize - _nowPos64; if (size > rem) size = (UInt32)rem; } @@ -349,46 +481,51 @@ break; } - if (_convPos != 0) + const UInt32 convPos = _convPos; + if (convPos != 0) { - UInt32 num = _bufPos - _convPos; + const UInt32 num = _bufPos - convPos; + Byte *buf = _buf; for (UInt32 i = 0; i < num; i++) - _buf[i] = _buf[_convPos + i]; + buf[i] = buf[convPos + i]; _bufPos = num; _convPos = 0; } { size_t readSize = _bufSize - _bufPos; - HRESULT res = ReadStream(_inStream, _buf + _bufPos, &readSize); + const HRESULT res = ReadStream(_inStream, _buf + _bufPos, &readSize); _bufPos += (UInt32)readSize; - RINOK(res); + RINOK(res) } - _convSize = Filter->Filter(_buf, _bufPos); + const UInt32 convSize = Filter->Filter(_buf, _bufPos); + _convSize = convSize; - if (_convSize == 0) + UInt32 bufPos = _bufPos; + + if (convSize == 0) { - if (_bufPos == 0) + if (bufPos == 0) break; // BCJ - _convSize = _bufPos; + _convSize = bufPos; continue; } - if (_convSize > _bufPos) + if (convSize > bufPos) { // AES - if (_convSize > _bufSize) + if (convSize > _bufSize) return E_FAIL; if (!_encodeMode) return S_FALSE; - + Byte *buf = _buf; do - _buf[_bufPos] = 0; - while (++_bufPos != _convSize); - - _convSize = Filter->Filter(_buf, _convSize); + buf[bufPos] = 0; + while (++bufPos != convSize); + _bufPos = bufPos; + _convSize = Filter->Filter(_buf, convSize); if (_convSize != _bufPos) return E_FAIL; } @@ -398,39 +535,43 @@ } -#ifndef _NO_CRYPTO +#ifndef Z7_NO_CRYPTO -STDMETHODIMP CFilterCoder::CryptoSetPassword(const Byte *data, UInt32 size) - { return _SetPassword->CryptoSetPassword(data, size); } +Z7_COM7F_IMF(CFilterCoder::CryptoSetPassword(const Byte *data, UInt32 size)) + { return _setPassword->CryptoSetPassword(data, size); } -STDMETHODIMP CFilterCoder::SetKey(const Byte *data, UInt32 size) - { return _CryptoProperties->SetKey(data, size); } +Z7_COM7F_IMF(CFilterCoder::SetKey(const Byte *data, UInt32 size)) + { return _cryptoProperties->SetKey(data, size); } -STDMETHODIMP CFilterCoder::SetInitVector(const Byte *data, UInt32 size) - { return _CryptoProperties->SetInitVector(data, size); } +Z7_COM7F_IMF(CFilterCoder::SetInitVector(const Byte *data, UInt32 size)) + { return _cryptoProperties->SetInitVector(data, size); } #endif -#ifndef EXTRACT_ONLY - -STDMETHODIMP CFilterCoder::SetCoderProperties(const PROPID *propIDs, - const PROPVARIANT *properties, UInt32 numProperties) - { return _SetCoderProperties->SetCoderProperties(propIDs, properties, numProperties); } +#ifndef Z7_EXTRACT_ONLY -STDMETHODIMP CFilterCoder::WriteCoderProperties(ISequentialOutStream *outStream) - { return _WriteCoderProperties->WriteCoderProperties(outStream); } +Z7_COM7F_IMF(CFilterCoder::SetCoderProperties(const PROPID *propIDs, + const PROPVARIANT *properties, UInt32 numProperties)) + { return _setCoderProperties->SetCoderProperties(propIDs, properties, numProperties); } + +Z7_COM7F_IMF(CFilterCoder::WriteCoderProperties(ISequentialOutStream *outStream)) + { return _writeCoderProperties->WriteCoderProperties(outStream); } + +Z7_COM7F_IMF(CFilterCoder::SetCoderPropertiesOpt(const PROPID *propIDs, + const PROPVARIANT *properties, UInt32 numProperties)) + { return _setCoderPropertiesOpt->SetCoderPropertiesOpt(propIDs, properties, numProperties); } /* -STDMETHODIMP CFilterCoder::ResetSalt() - { return _CryptoResetSalt->ResetSalt(); } +Z7_COM7F_IMF(CFilterCoder::ResetSalt() + { return _cryptoResetSalt->ResetSalt(); } */ -STDMETHODIMP CFilterCoder::ResetInitVector() - { return _CryptoResetInitVector->ResetInitVector(); } +Z7_COM7F_IMF(CFilterCoder::ResetInitVector()) + { return _cryptoResetInitVector->ResetInitVector(); } #endif -STDMETHODIMP CFilterCoder::SetDecoderProperties2(const Byte *data, UInt32 size) - { return _SetDecoderProperties2->SetDecoderProperties2(data, size); } +Z7_COM7F_IMF(CFilterCoder::SetDecoderProperties2(const Byte *data, UInt32 size)) + { return _setDecoderProperties2->SetDecoderProperties2(data, size); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/FilterCoder.h 7zip-23.01+dfsg/CPP/7zip/Common/FilterCoder.h --- 7zip-22.01+dfsg/CPP/7zip/Common/FilterCoder.h 2018-12-30 17:40:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/FilterCoder.h 2023-03-18 13:00:00.000000000 +0000 @@ -1,18 +1,18 @@ // FilterCoder.h -#ifndef __FILTER_CODER_H -#define __FILTER_CODER_H +#ifndef ZIP7_INC_FILTER_CODER_H +#define ZIP7_INC_FILTER_CODER_H #include "../../../C/Alloc.h" #include "../../Common/MyCom.h" #include "../ICoder.h" -#ifndef _NO_CRYPTO +#ifndef Z7_NO_CRYPTO #include "../IPassword.h" #endif -#define MY_QUERYINTERFACE_ENTRY_AG(i, sub0, sub) else if (iid == IID_ ## i) \ +#define Z7_COM_QI_ENTRY_AG(i, sub0, sub) else if (iid == IID_ ## i) \ { if (!sub) RINOK(sub0->QueryInterface(IID_ ## i, (void **)&sub)) \ *outObject = (void *)(i *)this; } @@ -26,7 +26,8 @@ void AllocAligned(size_t size); }; -class CFilterCoder: + +class CFilterCoder Z7_final : public ICompressCoder, public ICompressSetOutStreamSize, @@ -41,14 +42,15 @@ public ICompressSetBufSize, - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO public ICryptoSetPassword, public ICryptoProperties, #endif - #ifndef EXTRACT_ONLY + #ifndef Z7_EXTRACT_ONLY public ICompressSetCoderProperties, public ICompressWriteCoderProperties, + public ICompressSetCoderPropertiesOpt, // public ICryptoResetSalt, public ICryptoResetInitVector, #endif @@ -62,7 +64,7 @@ UInt32 _outBufSize; bool _encodeMode; - bool _outSizeIsDefined; + bool _outSize_Defined; UInt64 _outSize; UInt64 _nowPos64; @@ -78,7 +80,7 @@ _convPos = 0; _convSize = 0; - _outSizeIsDefined = false; + _outSize_Defined = false; _outSize = 0; _nowPos64 = 0; } @@ -87,117 +89,111 @@ HRESULT Init_and_Alloc(); HRESULT Flush2(); - #ifndef _NO_CRYPTO - CMyComPtr _SetPassword; - CMyComPtr _CryptoProperties; + #ifndef Z7_NO_CRYPTO + CMyComPtr _setPassword; + CMyComPtr _cryptoProperties; #endif - #ifndef EXTRACT_ONLY - CMyComPtr _SetCoderProperties; - CMyComPtr _WriteCoderProperties; - // CMyComPtr _CryptoResetSalt; - CMyComPtr _CryptoResetInitVector; + #ifndef Z7_EXTRACT_ONLY + CMyComPtr _setCoderProperties; + CMyComPtr _writeCoderProperties; + CMyComPtr _setCoderPropertiesOpt; + // CMyComPtr _cryptoResetSalt; + CMyComPtr _cryptoResetInitVector; #endif - CMyComPtr _SetDecoderProperties2; + CMyComPtr _setDecoderProperties2; public: CMyComPtr Filter; CFilterCoder(bool encodeMode); - ~CFilterCoder(); - class C_InStream_Releaser + struct C_InStream_Releaser { - public: CFilterCoder *FilterCoder; C_InStream_Releaser(): FilterCoder(NULL) {} ~C_InStream_Releaser() { if (FilterCoder) FilterCoder->ReleaseInStream(); } }; - class C_OutStream_Releaser + struct C_OutStream_Releaser { - public: CFilterCoder *FilterCoder; C_OutStream_Releaser(): FilterCoder(NULL) {} ~C_OutStream_Releaser() { if (FilterCoder) FilterCoder->ReleaseOutStream(); } }; - class C_Filter_Releaser + struct C_Filter_Releaser { - public: CFilterCoder *FilterCoder; C_Filter_Releaser(): FilterCoder(NULL) {} ~C_Filter_Releaser() { if (FilterCoder) FilterCoder->Filter.Release(); } }; +private: + Z7_COM_QI_BEGIN2(ICompressCoder) - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - - MY_QUERYINTERFACE_ENTRY(ICompressSetOutStreamSize) - MY_QUERYINTERFACE_ENTRY(ICompressInitEncoder) + Z7_COM_QI_ENTRY(ICompressSetOutStreamSize) + Z7_COM_QI_ENTRY(ICompressInitEncoder) - MY_QUERYINTERFACE_ENTRY(ICompressSetInStream) - MY_QUERYINTERFACE_ENTRY(ISequentialInStream) + Z7_COM_QI_ENTRY(ICompressSetInStream) + Z7_COM_QI_ENTRY(ISequentialInStream) - MY_QUERYINTERFACE_ENTRY(ICompressSetOutStream) - MY_QUERYINTERFACE_ENTRY(ISequentialOutStream) - MY_QUERYINTERFACE_ENTRY(IOutStreamFinish) + Z7_COM_QI_ENTRY(ICompressSetOutStream) + Z7_COM_QI_ENTRY(ISequentialOutStream) + Z7_COM_QI_ENTRY(IOutStreamFinish) - MY_QUERYINTERFACE_ENTRY(ICompressSetBufSize) + Z7_COM_QI_ENTRY(ICompressSetBufSize) - #ifndef _NO_CRYPTO - MY_QUERYINTERFACE_ENTRY_AG(ICryptoSetPassword, Filter, _SetPassword) - MY_QUERYINTERFACE_ENTRY_AG(ICryptoProperties, Filter, _CryptoProperties) + #ifndef Z7_NO_CRYPTO + Z7_COM_QI_ENTRY_AG(ICryptoSetPassword, Filter, _setPassword) + Z7_COM_QI_ENTRY_AG(ICryptoProperties, Filter, _cryptoProperties) #endif - #ifndef EXTRACT_ONLY - MY_QUERYINTERFACE_ENTRY_AG(ICompressSetCoderProperties, Filter, _SetCoderProperties) - MY_QUERYINTERFACE_ENTRY_AG(ICompressWriteCoderProperties, Filter, _WriteCoderProperties) - // MY_QUERYINTERFACE_ENTRY_AG(ICryptoResetSalt, Filter, _CryptoResetSalt) - MY_QUERYINTERFACE_ENTRY_AG(ICryptoResetInitVector, Filter, _CryptoResetInitVector) + #ifndef Z7_EXTRACT_ONLY + Z7_COM_QI_ENTRY_AG(ICompressSetCoderProperties, Filter, _setCoderProperties) + Z7_COM_QI_ENTRY_AG(ICompressWriteCoderProperties, Filter, _writeCoderProperties) + Z7_COM_QI_ENTRY_AG(ICompressSetCoderPropertiesOpt, Filter, _setCoderPropertiesOpt) + // Z7_COM_QI_ENTRY_AG(ICryptoResetSalt, Filter, _cryptoResetSalt) + Z7_COM_QI_ENTRY_AG(ICryptoResetInitVector, Filter, _cryptoResetInitVector) #endif - MY_QUERYINTERFACE_ENTRY_AG(ICompressSetDecoderProperties2, Filter, _SetDecoderProperties2) - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); + Z7_COM_QI_ENTRY_AG(ICompressSetDecoderProperties2, Filter, _setDecoderProperties2) + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE - STDMETHOD(SetOutStreamSize)(const UInt64 *outSize); - STDMETHOD(InitEncoder)(); - - STDMETHOD(SetInStream)(ISequentialInStream *inStream); - STDMETHOD(ReleaseInStream)(); - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - - STDMETHOD(SetOutStream)(ISequentialOutStream *outStream); - STDMETHOD(ReleaseOutStream)(); - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(OutStreamFinish)(); +public: + Z7_IFACE_COM7_IMP(ICompressCoder) + Z7_IFACE_COM7_IMP(ICompressSetOutStreamSize) + Z7_IFACE_COM7_IMP(ICompressInitEncoder) + Z7_IFACE_COM7_IMP(ICompressSetInStream) +private: + Z7_IFACE_COM7_IMP(ISequentialInStream) +public: + Z7_IFACE_COM7_IMP(ICompressSetOutStream) +private: + Z7_IFACE_COM7_IMP(ISequentialOutStream) +public: + Z7_IFACE_COM7_IMP(IOutStreamFinish) +private: - STDMETHOD(SetInBufSize)(UInt32 streamIndex, UInt32 size); - STDMETHOD(SetOutBufSize)(UInt32 streamIndex, UInt32 size); + Z7_IFACE_COM7_IMP(ICompressSetBufSize) - #ifndef _NO_CRYPTO - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); - - STDMETHOD(SetKey)(const Byte *data, UInt32 size); - STDMETHOD(SetInitVector)(const Byte *data, UInt32 size); + #ifndef Z7_NO_CRYPTO + Z7_IFACE_COM7_IMP(ICryptoSetPassword) + Z7_IFACE_COM7_IMP(ICryptoProperties) + #endif + + #ifndef Z7_EXTRACT_ONLY + Z7_IFACE_COM7_IMP(ICompressSetCoderProperties) + Z7_IFACE_COM7_IMP(ICompressWriteCoderProperties) + Z7_IFACE_COM7_IMP(ICompressSetCoderPropertiesOpt) + // Z7_IFACE_COM7_IMP(ICryptoResetSalt) + Z7_IFACE_COM7_IMP(ICryptoResetInitVector) #endif - #ifndef EXTRACT_ONLY - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, - const PROPVARIANT *properties, UInt32 numProperties); - STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream); - // STDMETHOD(ResetSalt)(); - STDMETHOD(ResetInitVector)(); - #endif - - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - +public: + Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2) HRESULT Init_NoSubFilterInit(); }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/InBuffer.cpp 7zip-23.01+dfsg/CPP/7zip/Common/InBuffer.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/InBuffer.cpp 2022-02-09 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/InBuffer.cpp 2023-04-05 17:00:00.000000000 +0000 @@ -7,10 +7,10 @@ #include "InBuffer.h" CInBufferBase::CInBufferBase() throw(): - _buf(0), - _bufLim(0), - _bufBase(0), - _stream(0), + _buf(NULL), + _bufLim(NULL), + _bufBase(NULL), + _stream(NULL), _processedSize(0), _bufSize(0), _wasFinished(false), @@ -22,18 +22,18 @@ const unsigned kMinBlockSize = 1; if (bufSize < kMinBlockSize) bufSize = kMinBlockSize; - if (_bufBase != 0 && _bufSize == bufSize) + if (_bufBase != NULL && _bufSize == bufSize) return true; Free(); _bufSize = bufSize; _bufBase = (Byte *)::MidAlloc(bufSize); - return (_bufBase != 0); + return (_bufBase != NULL); } void CInBuffer::Free() throw() { ::MidFree(_bufBase); - _bufBase = 0; + _bufBase = NULL; } void CInBufferBase::Init() throw() @@ -42,7 +42,7 @@ _buf = _bufBase; _bufLim = _buf; _wasFinished = false; - #ifdef _NO_EXCEPTIONS + #ifdef Z7_NO_EXCEPTIONS ErrorCode = S_OK; #endif NumExtraBytes = 0; @@ -50,7 +50,7 @@ bool CInBufferBase::ReadBlock() { - #ifdef _NO_EXCEPTIONS + #ifdef Z7_NO_EXCEPTIONS if (ErrorCode != S_OK) return false; #endif @@ -61,8 +61,8 @@ _bufLim = _bufBase; UInt32 processed; // FIX_ME: we can improve it to support (_bufSize >= (1 << 32)) - HRESULT result = _stream->Read(_bufBase, (UInt32)_bufSize, &processed); - #ifdef _NO_EXCEPTIONS + const HRESULT result = _stream->Read(_bufBase, (UInt32)_bufSize, &processed); + #ifdef Z7_NO_EXCEPTIONS ErrorCode = result; #else if (result != S_OK) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/InBuffer.h 7zip-23.01+dfsg/CPP/7zip/Common/InBuffer.h --- 7zip-22.01+dfsg/CPP/7zip/Common/InBuffer.h 2021-01-24 15:38:02.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/InBuffer.h 2023-03-28 11:00:00.000000000 +0000 @@ -1,12 +1,12 @@ // InBuffer.h -#ifndef __IN_BUFFER_H -#define __IN_BUFFER_H +#ifndef ZIP7_INC_IN_BUFFER_H +#define ZIP7_INC_IN_BUFFER_H #include "../../Common/MyException.h" #include "../IStream.h" -#ifndef _NO_EXCEPTIONS +#ifndef Z7_NO_EXCEPTIONS struct CInBufferException: public CSystemException { CInBufferException(HRESULT errorCode): CSystemException(errorCode) {} @@ -31,7 +31,7 @@ Byte ReadByte_FromNewBlock(); public: - #ifdef _NO_EXCEPTIONS + #ifdef Z7_NO_EXCEPTIONS HRESULT ErrorCode; #endif UInt32 NumExtraBytes; @@ -60,7 +60,7 @@ _buf = buf + pos; _bufLim = buf + end; _wasFinished = false; - #ifdef _NO_EXCEPTIONS + #ifdef Z7_NO_EXCEPTIONS ErrorCode = S_OK; #endif NumExtraBytes = 0; @@ -68,7 +68,7 @@ void Init() throw(); - MY_FORCE_INLINE + Z7_FORCE_INLINE bool ReadByte(Byte &b) { if (_buf >= _bufLim) @@ -77,7 +77,7 @@ return true; } - MY_FORCE_INLINE + Z7_FORCE_INLINE bool ReadByte_FromBuf(Byte &b) { if (_buf >= _bufLim) @@ -86,7 +86,7 @@ return true; } - MY_FORCE_INLINE + Z7_FORCE_INLINE Byte ReadByte() { if (_buf >= _bufLim) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/InOutTempBuffer.cpp 7zip-23.01+dfsg/CPP/7zip/Common/InOutTempBuffer.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/InOutTempBuffer.cpp 2019-08-27 18:33:49.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/InOutTempBuffer.cpp 2022-12-19 22:00:00.000000000 +0000 @@ -2,170 +2,236 @@ #include "StdAfx.h" +#include "../../../C/Alloc.h" + #include "InOutTempBuffer.h" + #include "StreamUtils.h" #ifdef USE_InOutTempBuffer_FILE #include "../../../C/7zCrc.h" -using namespace NWindows; -using namespace NFile; -using namespace NDir; - -static const size_t kTempBufSize = (1 << 20); - #define kTempFilePrefixString FTEXT("7zt") -CInOutTempBuffer::~CInOutTempBuffer() -{ - delete []_buf; -} +/* + Total buffer size limit, if we use temp file scheme: + 32-bit: 16 MiB = 1 MiB * 16 buffers + 64-bit: 4 GiB = 1 MiB * 4096 buffers +*/ +static const size_t kNumBufsMax = (size_t)1 << (sizeof(size_t) * 2 - 4); + #endif -CInOutTempBuffer::CInOutTempBuffer() - #ifdef USE_InOutTempBuffer_FILE - : _buf(NULL) - #endif -{ } +static const size_t kBufSize = (size_t)1 << 20; -void CInOutTempBuffer::Create() -{ - #ifdef USE_InOutTempBuffer_FILE - if (!_buf) - _buf = new Byte[kTempBufSize]; - #endif -} -void CInOutTempBuffer::InitWriting() -{ - #ifdef USE_InOutTempBuffer_FILE - _bufPos = 0; +CInOutTempBuffer::CInOutTempBuffer(): + _size(0), + _bufs(NULL), + _numBufs(0), + _numFilled(0) +{ + #ifdef USE_InOutTempBuffer_FILE + _tempFile_Created = false; + _useMemOnly = false; _crc = CRC_INIT_VAL; - _tempFileCreated = false; - #endif - _size = 0; + #endif } +CInOutTempBuffer::~CInOutTempBuffer() +{ + for (size_t i = 0; i < _numBufs; i++) + MyFree(_bufs[i]); + MyFree(_bufs); +} -#ifdef USE_InOutTempBuffer_FILE -static inline HRESULT Get_HRESULT_LastError() +void *CInOutTempBuffer::GetBuf(size_t index) { - #ifdef _WIN32 - DWORD lastError = ::GetLastError(); - if (lastError != 0) - return HRESULT_FROM_WIN32(lastError); - #endif - return E_FAIL; + if (index >= _numBufs) + { + const size_t num = (_numBufs == 0 ? 16 : _numBufs * 2); + void **p = (void **)MyRealloc(_bufs, num * sizeof(void *)); + if (!p) + return NULL; + _bufs = p; + memset(p + _numBufs, 0, (num - _numBufs) * sizeof(void *)); + _numBufs = num; + } + + void *buf = _bufs[index]; + if (!buf) + { + buf = MyAlloc(kBufSize); + if (buf) + _bufs[index] = buf; + } + return buf; } -#endif - HRESULT CInOutTempBuffer::Write_HRESULT(const void *data, UInt32 size) { - #ifdef USE_InOutTempBuffer_FILE - if (size == 0) return S_OK; - size_t cur = kTempBufSize - _bufPos; - if (cur != 0) + + #ifdef USE_InOutTempBuffer_FILE + if (!_tempFile_Created) + #endif + for (;;) // loop for additional attemp to allocate memory after file creation error { - if (cur > size) - cur = size; - memcpy(_buf + _bufPos, data, cur); - _crc = CrcUpdate(_crc, data, cur); - _bufPos += cur; - _size += cur; - size -= (UInt32)cur; - data = ((const Byte *)data) + cur; - } - - if (size == 0) - return S_OK; + #ifdef USE_InOutTempBuffer_FILE + bool allocError = false; + #endif + + for (;;) // loop for writing to buffers + { + const size_t index = (size_t)(_size / kBufSize); + + #ifdef USE_InOutTempBuffer_FILE + if (index >= kNumBufsMax && !_useMemOnly) + break; + #endif + + void *buf = GetBuf(index); + if (!buf) + { + #ifdef USE_InOutTempBuffer_FILE + if (!_useMemOnly) + { + allocError = true; + break; + } + #endif + return E_OUTOFMEMORY; + } + + const size_t offset = (size_t)(_size) & (kBufSize - 1); + size_t cur = kBufSize - offset; + if (cur > size) + cur = size; + memcpy((Byte *)buf + offset, data, cur); + _size += cur; + if (index >= _numFilled) + _numFilled = index + 1; + data = (const void *)((const Byte *)data + cur); + size -= (UInt32)cur; + if (size == 0) + return S_OK; + } - if (!_tempFileCreated) - { - if (!_tempFile.CreateRandomInTempFolder(kTempFilePrefixString, &_outFile)) - return Get_HRESULT_LastError(); - _tempFileCreated = true; + #ifdef USE_InOutTempBuffer_FILE + #ifndef _WIN32 + _outFile.mode_for_Create = 0600; // only owner will have the rights to access this file + #endif + if (_tempFile.CreateRandomInTempFolder(kTempFilePrefixString, &_outFile)) + { + _tempFile_Created = true; + break; + } + _useMemOnly = true; + if (allocError) + return GetLastError_noZero_HRESULT(); + #endif } - UInt32 processed; - if (!_outFile.Write(data, size, processed)) - return Get_HRESULT_LastError(); - _crc = CrcUpdate(_crc, data, processed); - _size += processed; - return (processed == size) ? S_OK : E_FAIL; - - #else - - const size_t newSize = _size + size; - if (newSize < _size) - return E_OUTOFMEMORY; - if (!_dynBuffer.EnsureCapacity(newSize)) - return E_OUTOFMEMORY; - memcpy(((Byte *)_dynBuffer) + _size, data, size); - _size = newSize; - return S_OK; - #endif + #ifdef USE_InOutTempBuffer_FILE + if (!_outFile.WriteFull(data, size)) + return GetLastError_noZero_HRESULT(); + _crc = CrcUpdate(_crc, data, size); + _size += size; + return S_OK; + #endif } HRESULT CInOutTempBuffer::WriteToStream(ISequentialOutStream *stream) { - #ifdef USE_InOutTempBuffer_FILE - - if (!_outFile.Close()) - return E_FAIL; + UInt64 rem = _size; + // if (rem == 0) return S_OK; - UInt64 size = 0; - UInt32 crc = CRC_INIT_VAL; + const size_t numFilled = _numFilled; + _numFilled = 0; - if (_bufPos != 0) - { - RINOK(WriteStream(stream, _buf, _bufPos)); - crc = CrcUpdate(crc, _buf, _bufPos); - size += _bufPos; - } - - if (_tempFileCreated) + for (size_t i = 0; i < numFilled; i++) { - NIO::CInFile inFile; - if (!inFile.Open(_tempFile.GetPath())) + if (rem == 0) return E_FAIL; - while (size < _size) + size_t cur = kBufSize; + if (cur > rem) + cur = (size_t)rem; + RINOK(WriteStream(stream, _bufs[i], cur)) + rem -= cur; + #ifdef USE_InOutTempBuffer_FILE + // we will use _bufs[0] later for writing from temp file + if (i != 0 || !_tempFile_Created) + #endif { - UInt32 processed; - if (!inFile.ReadPart(_buf, kTempBufSize, processed)) - return E_FAIL; - if (processed == 0) - break; - RINOK(WriteStream(stream, _buf, processed)); - crc = CrcUpdate(crc, _buf, processed); - size += processed; + MyFree(_bufs[i]); + _bufs[i] = NULL; } } - return (_crc == crc && size == _size) ? S_OK : E_FAIL; - #else - return WriteStream(stream, (const Byte *)_dynBuffer, _size); + #ifdef USE_InOutTempBuffer_FILE - #endif -} + if (rem == 0) + return _tempFile_Created ? E_FAIL : S_OK; -/* -STDMETHODIMP CSequentialOutTempBufferImp::Write(const void *data, UInt32 size, UInt32 *processed) -{ - if (!_buf->Write(data, size)) - { - if (processed) - *processed = 0; + if (!_tempFile_Created) return E_FAIL; + + if (!_outFile.Close()) + return GetLastError_noZero_HRESULT(); + + HRESULT hres; + void *buf = GetBuf(0); // index + if (!buf) + hres = E_OUTOFMEMORY; + else + { + NWindows::NFile::NIO::CInFile inFile; + if (!inFile.Open(_tempFile.GetPath())) + hres = GetLastError_noZero_HRESULT(); + else + { + UInt32 crc = CRC_INIT_VAL; + for (;;) + { + size_t processed; + if (!inFile.ReadFull(buf, kBufSize, processed)) + { + hres = GetLastError_noZero_HRESULT(); + break; + } + if (processed == 0) + { + // we compare crc without CRC_GET_DIGEST + hres = (_crc == crc ? S_OK : E_FAIL); + break; + } + size_t n = processed; + if (n > rem) + n = (size_t)rem; + hres = WriteStream(stream, buf, n); + if (hres != S_OK) + break; + crc = CrcUpdate(crc, buf, n); + rem -= n; + if (n != processed) + { + hres = E_FAIL; + break; + } + } + } } - if (processed) - *processed = size; - return S_OK; + + // _tempFile.DisableDeleting(); // for debug + _tempFile.Remove(); + RINOK(hres) + + #endif + + return rem == 0 ? S_OK : E_FAIL; } -*/ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/InOutTempBuffer.h 7zip-23.01+dfsg/CPP/7zip/Common/InOutTempBuffer.h --- 7zip-22.01+dfsg/CPP/7zip/Common/InOutTempBuffer.h 2019-08-27 18:32:03.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/InOutTempBuffer.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,66 +1,45 @@ // InOutTempBuffer.h -#ifndef __IN_OUT_TEMP_BUFFER_H -#define __IN_OUT_TEMP_BUFFER_H +#ifndef ZIP7_INC_IN_OUT_TEMP_BUFFER_H +#define ZIP7_INC_IN_OUT_TEMP_BUFFER_H -#ifdef _WIN32 -// #define USE_InOutTempBuffer_FILE -#endif +// #ifdef _WIN32 +#define USE_InOutTempBuffer_FILE +// #endif #ifdef USE_InOutTempBuffer_FILE #include "../../Windows/FileDir.h" -#else -#include "StreamObjects.h" #endif #include "../IStream.h" class CInOutTempBuffer { - #ifdef USE_InOutTempBuffer_FILE + UInt64 _size; + void **_bufs; + size_t _numBufs; + size_t _numFilled; + + #ifdef USE_InOutTempBuffer_FILE + bool _tempFile_Created; + bool _useMemOnly; + UInt32 _crc; + // COutFile object must be declared after CTempFile object for correct destructor order NWindows::NFile::NDir::CTempFile _tempFile; NWindows::NFile::NIO::COutFile _outFile; - bool _tempFileCreated; - Byte *_buf; - size_t _bufPos; - UInt64 _size; - UInt32 _crc; - #else - - CByteDynBuffer _dynBuffer; - size_t _size; - - #endif + #endif - CLASS_NO_COPY(CInOutTempBuffer); + void *GetBuf(size_t index); + + Z7_CLASS_NO_COPY(CInOutTempBuffer) public: CInOutTempBuffer(); - void Create(); - - #ifdef USE_InOutTempBuffer_FILE ~CInOutTempBuffer(); - #endif - - void InitWriting(); HRESULT Write_HRESULT(const void *data, UInt32 size); HRESULT WriteToStream(ISequentialOutStream *stream); UInt64 GetDataSize() const { return _size; } }; -/* -class CSequentialOutTempBufferImp: - public ISequentialOutStream, - public CMyUnknownImp -{ - CInOutTempBuffer *_buf; -public: - void Init(CInOutTempBuffer *buffer) { _buf = buffer; } - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); -}; -*/ - #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/LimitedStreams.cpp 7zip-23.01+dfsg/CPP/7zip/Common/LimitedStreams.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/LimitedStreams.cpp 2022-02-01 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/LimitedStreams.cpp 2023-01-28 17:00:00.000000000 +0000 @@ -6,7 +6,7 @@ #include "LimitedStreams.h" -STDMETHODIMP CLimitedSequentialInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CLimitedSequentialInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { UInt32 realProcessedSize = 0; { @@ -27,7 +27,7 @@ return result; } -STDMETHODIMP CLimitedInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CLimitedInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -46,7 +46,7 @@ if (newPos != _physPos) { _physPos = newPos; - RINOK(SeekToPhys()); + RINOK(SeekToPhys()) } HRESULT res = _stream->Read(data, size, &size); if (processedSize) @@ -56,7 +56,7 @@ return res; } -STDMETHODIMP CLimitedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CLimitedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { @@ -75,17 +75,17 @@ HRESULT CreateLimitedInStream(IInStream *inStream, UInt64 pos, UInt64 size, ISequentialInStream **resStream) { - *resStream = 0; + *resStream = NULL; CLimitedInStream *streamSpec = new CLimitedInStream; CMyComPtr streamTemp = streamSpec; streamSpec->SetStream(inStream); - RINOK(streamSpec->InitAndSeek(pos, size)); + RINOK(streamSpec->InitAndSeek(pos, size)) streamSpec->SeekToStart(); *resStream = streamTemp.Detach(); return S_OK; } -STDMETHODIMP CClusterInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CClusterInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -110,7 +110,7 @@ if (newPos != _physPos) { _physPos = newPos; - RINOK(SeekToPhys()); + RINOK(SeekToPhys()) } _curRem = blockSize - offsetInBlock; @@ -130,7 +130,7 @@ return res; } -STDMETHODIMP CClusterInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CClusterInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { @@ -150,7 +150,7 @@ } -STDMETHODIMP CExtentsStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CExtentsStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -201,7 +201,7 @@ if (_phyPos != phy) { _phyPos = (UInt64)0 - 1; // we don't trust seek_pos in case of error - RINOK(Stream->Seek((Int64)phy, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(Stream, phy)) _phyPos = phy; } } @@ -218,7 +218,7 @@ } -STDMETHODIMP CExtentsStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CExtentsStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { @@ -236,7 +236,7 @@ } -STDMETHODIMP CLimitedSequentialOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CLimitedSequentialOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { HRESULT result = S_OK; if (processedSize) @@ -263,7 +263,7 @@ } -STDMETHODIMP CTailInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CTailInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { UInt32 cur; HRESULT res = Stream->Read(data, size, &cur); @@ -273,7 +273,7 @@ return res; } -STDMETHODIMP CTailInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CTailInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { @@ -282,7 +282,7 @@ case STREAM_SEEK_END: { UInt64 pos = 0; - RINOK(Stream->Seek(offset, STREAM_SEEK_END, &pos)); + RINOK(Stream->Seek(offset, STREAM_SEEK_END, &pos)) if (pos < Offset) return HRESULT_WIN32_ERROR_NEGATIVE_SEEK; _virtPos = pos - Offset; @@ -297,10 +297,10 @@ _virtPos = (UInt64)offset; if (newPosition) *newPosition = _virtPos; - return Stream->Seek((Int64)(Offset + _virtPos), STREAM_SEEK_SET, NULL); + return InStream_SeekSet(Stream, Offset + _virtPos); } -STDMETHODIMP CLimitedCachedInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CLimitedCachedInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -329,7 +329,7 @@ if (newPos != _physPos) { _physPos = newPos; - RINOK(SeekToPhys()); + RINOK(SeekToPhys()) } res = _stream->Read(data, size, &size); _physPos += size; @@ -340,7 +340,7 @@ return res; } -STDMETHODIMP CLimitedCachedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CLimitedCachedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { @@ -357,7 +357,7 @@ return S_OK; } -STDMETHODIMP CTailOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CTailOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { UInt32 cur; HRESULT res = Stream->Write(data, size, &cur); @@ -369,7 +369,7 @@ return res; } -STDMETHODIMP CTailOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CTailOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { @@ -386,7 +386,7 @@ return Stream->Seek((Int64)(Offset + _virtPos), STREAM_SEEK_SET, NULL); } -STDMETHODIMP CTailOutStream::SetSize(UInt64 newSize) +Z7_COM7F_IMF(CTailOutStream::SetSize(UInt64 newSize)) { _virtSize = newSize; return Stream->SetSize(Offset + newSize); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/LimitedStreams.h 7zip-23.01+dfsg/CPP/7zip/Common/LimitedStreams.h --- 7zip-22.01+dfsg/CPP/7zip/Common/LimitedStreams.h 2022-02-01 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/LimitedStreams.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,17 +1,19 @@ // LimitedStreams.h -#ifndef __LIMITED_STREAMS_H -#define __LIMITED_STREAMS_H +#ifndef ZIP7_INC_LIMITED_STREAMS_H +#define ZIP7_INC_LIMITED_STREAMS_H #include "../../Common/MyBuffer.h" #include "../../Common/MyCom.h" #include "../../Common/MyVector.h" #include "../IStream.h" -class CLimitedSequentialInStream: - public ISequentialInStream, - public CMyUnknownImp -{ +#include "StreamUtils.h" + +Z7_CLASS_IMP_COM_1( + CLimitedSequentialInStream + , ISequentialInStream +) CMyComPtr _stream; UInt64 _size; UInt64 _pos; @@ -25,26 +27,22 @@ _pos = 0; _wasFinished = false; } - - MY_UNKNOWN_IMP1(ISequentialInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); UInt64 GetSize() const { return _pos; } UInt64 GetRem() const { return _size - _pos; } bool WasFinished() const { return _wasFinished; } }; -class CLimitedInStream: - public IInStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_IInStream( + CLimitedInStream +) CMyComPtr _stream; UInt64 _virtPos; UInt64 _physPos; UInt64 _size; UInt64 _startOffset; - HRESULT SeekToPhys() { return _stream->Seek((Int64)_physPos, STREAM_SEEK_SET, NULL); } + HRESULT SeekToPhys() { return InStream_SeekSet(_stream, _physPos); } public: void SetStream(IInStream *stream) { _stream = stream; } HRESULT InitAndSeek(UInt64 startOffset, UInt64 size) @@ -55,21 +53,15 @@ _size = size; return SeekToPhys(); } - - MY_UNKNOWN_IMP2(ISequentialInStream, IInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); - HRESULT SeekToStart() { return Seek(0, STREAM_SEEK_SET, NULL); } }; HRESULT CreateLimitedInStream(IInStream *inStream, UInt64 pos, UInt64 size, ISequentialInStream **resStream); -class CClusterInStream: - public IInStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_IInStream( + CClusterInStream +) UInt64 _virtPos; UInt64 _physPos; UInt32 _curRem; @@ -80,7 +72,7 @@ CRecordVector Vector; UInt64 StartOffset; - HRESULT SeekToPhys() { return Stream->Seek((Int64)_physPos, STREAM_SEEK_SET, NULL); } + HRESULT SeekToPhys() { return InStream_SeekSet(Stream, _physPos); } HRESULT InitAndSeek() { @@ -94,11 +86,6 @@ } return S_OK; } - - MY_UNKNOWN_IMP2(ISequentialInStream, IInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); }; @@ -114,23 +101,18 @@ bool Is_ZeroFill() const { return Phy == k_SeekExtent_Phy_Type_ZeroFill; } }; -class CExtentsStream: - public IInStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_IInStream( + CExtentsStream +) UInt64 _virtPos; UInt64 _phyPos; unsigned _prevExtentIndex; - public: CMyComPtr Stream; CRecordVector Extents; - MY_UNKNOWN_IMP2(ISequentialInStream, IInStream) - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); void ReleaseStream() { Stream.Release(); } - void Init() { _virtPos = 0; @@ -141,17 +123,15 @@ -class CLimitedSequentialOutStream: - public ISequentialOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CLimitedSequentialOutStream + , ISequentialOutStream +) CMyComPtr _stream; UInt64 _size; bool _overflow; bool _overflowIsAllowed; public: - MY_UNKNOWN_IMP1(ISequentialOutStream) - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); void SetStream(ISequentialOutStream *stream) { _stream = stream; } void ReleaseStream() { _stream.Release(); } void Init(UInt64 size, bool overflowIsAllowed = false) @@ -165,10 +145,9 @@ }; -class CTailInStream: - public IInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_IInStream( + CTailInStream +) UInt64 _virtPos; public: CMyComPtr Stream; @@ -178,19 +157,13 @@ { _virtPos = 0; } - - MY_UNKNOWN_IMP2(ISequentialInStream, IInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); - - HRESULT SeekToStart() { return Stream->Seek((Int64)Offset, STREAM_SEEK_SET, NULL); } + HRESULT SeekToStart() { return InStream_SeekSet(Stream, Offset); } }; -class CLimitedCachedInStream: - public IInStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_IInStream( + CLimitedCachedInStream +) CMyComPtr _stream; UInt64 _virtPos; UInt64 _physPos; @@ -201,8 +174,7 @@ size_t _cacheSize; size_t _cachePhyPos; - - HRESULT SeekToPhys() { return _stream->Seek((Int64)_physPos, STREAM_SEEK_SET, NULL); } + HRESULT SeekToPhys() { return InStream_SeekSet(_stream, _physPos); } public: CByteBuffer Buffer; @@ -223,37 +195,27 @@ return SeekToPhys(); } - MY_UNKNOWN_IMP2(ISequentialInStream, IInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); - HRESULT SeekToStart() { return Seek(0, STREAM_SEEK_SET, NULL); } }; -class CTailOutStream: + +class CTailOutStream Z7_final : public IOutStream, public CMyUnknownImp { + Z7_IFACES_IMP_UNK_2(ISequentialOutStream, IOutStream) + UInt64 _virtPos; UInt64 _virtSize; public: CMyComPtr Stream; UInt64 Offset; - virtual ~CTailOutStream() {} - - MY_UNKNOWN_IMP2(ISequentialOutStream, IOutStream) - void Init() { _virtPos = 0; _virtSize = 0; } - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); - STDMETHOD(SetSize)(UInt64 newSize); }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/LockedStream.h 7zip-23.01+dfsg/CPP/7zip/Common/LockedStream.h --- 7zip-22.01+dfsg/CPP/7zip/Common/LockedStream.h 2014-12-27 17:19:45.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/LockedStream.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,6 +1,6 @@ // LockedStream.h -#ifndef __LOCKED_STREAM_H -#define __LOCKED_STREAM_H +#ifndef ZIP7_INC_LOCKED_STREAM_H +#define ZIP7_INC_LOCKED_STREAM_H #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/MemBlocks.cpp 7zip-23.01+dfsg/CPP/7zip/Common/MemBlocks.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/MemBlocks.cpp 2021-06-05 11:26:14.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/MemBlocks.cpp 2023-01-10 11:00:00.000000000 +0000 @@ -34,8 +34,8 @@ void CMemBlockManager::FreeSpace() { ::MidFree(_data); - _data = 0; - _headFree= 0; + _data = NULL; + _headFree= NULL; } void *CMemBlockManager::AllocateBlock() @@ -157,7 +157,7 @@ curSize = (size_t)totalSize; if (blockIndex >= Blocks.Size()) return E_FAIL; - RINOK(WriteStream(outStream, Blocks[blockIndex], curSize)); + RINOK(WriteStream(outStream, Blocks[blockIndex], curSize)) totalSize -= curSize; } return S_OK; @@ -207,7 +207,7 @@ blocks.Blocks.Add(Blocks[i]); else FreeBlock(i, memManager); - Blocks[i] = 0; + Blocks[i] = NULL; totalSize += blockSize; } blocks.TotalSize = TotalSize; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/MemBlocks.h 7zip-23.01+dfsg/CPP/7zip/Common/MemBlocks.h --- 7zip-22.01+dfsg/CPP/7zip/Common/MemBlocks.h 2021-01-24 15:52:08.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/MemBlocks.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // MemBlocks.h -#ifndef __MEM_BLOCKS_H -#define __MEM_BLOCKS_H +#ifndef ZIP7_INC_MEM_BLOCKS_H +#define ZIP7_INC_MEM_BLOCKS_H #include "../../Common/MyVector.h" @@ -30,7 +30,7 @@ { NWindows::NSynchronization::CCriticalSection _criticalSection; public: - SYNC_OBJ_DECL(Synchro); + SYNC_OBJ_DECL(Synchro) NWindows::NSynchronization::CSemaphore_WFMO Semaphore; CMemBlockManagerMt(size_t blockSize = (1 << 20)): CMemBlockManager(blockSize) {} @@ -62,7 +62,7 @@ { bool LockMode; - CMemLockBlocks(): LockMode(true) {}; + CMemLockBlocks(): LockMode(true) {} void Free(CMemBlockManagerMt *memManager); void FreeBlock(unsigned index, CMemBlockManagerMt *memManager); // HRes SwitchToNoLockMode(CMemBlockManagerMt *memManager); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/MethodId.h 7zip-23.01+dfsg/CPP/7zip/Common/MethodId.h --- 7zip-22.01+dfsg/CPP/7zip/Common/MethodId.h 2013-01-17 07:40:40.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/MethodId.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // MethodId.h -#ifndef __7Z_METHOD_ID_H -#define __7Z_METHOD_ID_H +#ifndef ZIP7_INC_7Z_METHOD_ID_H +#define ZIP7_INC_7Z_METHOD_ID_H #include "../../Common/MyTypes.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/MethodProps.cpp 7zip-23.01+dfsg/CPP/7zip/Common/MethodProps.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/MethodProps.cpp 2021-11-17 19:21:36.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/MethodProps.cpp 2023-05-06 05:00:00.000000000 +0000 @@ -379,14 +379,14 @@ // the following are related to NCoderPropID::EEnum values - +// NCoderPropID::k_NUM_DEFINED static const CNameToPropID g_NameToPropID[] = { { VT_UI4, "" }, { VT_UI4, "d" }, { VT_UI4, "mem" }, { VT_UI4, "o" }, - { VT_UI4, "c" }, + { VT_UI8, "c" }, { VT_UI4, "pb" }, { VT_UI4, "lc" }, { VT_UI4, "lp" }, @@ -400,15 +400,57 @@ { VT_UI4, "x" }, { VT_UI8, "reduce" }, { VT_UI8, "expect" }, - { VT_UI4, "b" }, + { VT_UI8, "cc" }, // "cc" in v23, "b" in v22.01 { VT_UI4, "check" }, { VT_BSTR, "filter" }, - { VT_UI8, "memuse" } + { VT_UI8, "memuse" }, + { VT_UI8, "aff" }, + { VT_UI4, "offset" }, + { VT_UI4, "zhb" } + /* + , + // { VT_UI4, "zhc" }, + // { VT_UI4, "zhd" }, + // { VT_UI4, "zcb" }, + { VT_UI4, "dc" }, + { VT_UI4, "zx" }, + { VT_UI4, "zf" }, + { VT_UI4, "zmml" }, + { VT_UI4, "zov" }, + { VT_BOOL, "zmfr" }, + { VT_BOOL, "zle" }, // long enable + // { VT_UI4, "zldb" }, + { VT_UI4, "zld" }, + { VT_UI4, "zlhb" }, + { VT_UI4, "zlmml" }, + { VT_UI4, "zlbb" }, + { VT_UI4, "zlhrb" }, + { VT_BOOL, "zwus" }, + { VT_BOOL, "zshp" }, + { VT_BOOL, "zshs" }, + { VT_BOOL, "zshe" }, + { VT_BOOL, "zshg" }, + { VT_UI4, "zpsm" } + */ + // { VT_UI4, "mcb" }, // mc log version + // { VT_UI4, "ztlen" }, // fb ? }; +/* +#if defined(static_assert) || (defined(__cplusplus) && __cplusplus >= 200410L) || (defined(_MSC_VER) && _MSC_VER >= 1600) + +#if (defined(__cplusplus) && __cplusplus < 201103L) \ + && defined(__clang__) && __clang_major__ >= 4 +#pragma GCC diagnostic ignored "-Wc11-extensions" +#endif + static_assert(Z7_ARRAY_SIZE(g_NameToPropID) == NCoderPropID::k_NUM_DEFINED, + "g_NameToPropID doesn't match NCoderPropID enum"); +#endif +*/ + static int FindPropIdExact(const UString &name) { - for (unsigned i = 0; i < ARRAY_SIZE(g_NameToPropID); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_NameToPropID); i++) if (StringsAreEqualNoCase_Ascii(name, g_NameToPropID[i].Name)) return (int)i; return -1; @@ -493,6 +535,10 @@ case NCoderPropID::kUsedMemorySize: case NCoderPropID::kBlockSize: case NCoderPropID::kBlockSize2: + /* + case NCoderPropID::kChainSize: + case NCoderPropID::kLdmWindowSize: + */ // case NCoderPropID::kReduceSize: return true; } @@ -503,14 +549,19 @@ { int index = FindPropIdExact(name); if (index < 0) - return E_INVALIDARG; + { + // 'b' was used as NCoderPropID::kBlockSize2 before v23 + if (!name.IsEqualTo_Ascii_NoCase("b") || value.Find(L':') >= 0) + return E_INVALIDARG; + index = NCoderPropID::kBlockSize2; + } const CNameToPropID &nameToPropID = g_NameToPropID[(unsigned)index]; CProp prop; prop.Id = (unsigned)index; if (IsLogSizeProp(prop.Id)) { - RINOK(StringToDictSize(value, prop.Value)); + RINOK(StringToDictSize(value, prop.Value)) } else { @@ -561,7 +612,7 @@ const UString ¶m = params[i]; UString name, value; SplitParam(param, name, value); - RINOK(SetParam(name, value)); + RINOK(SetParam(name, value)) } return S_OK; } @@ -582,7 +633,7 @@ } // {realName}=value - int index = FindPropIdExact(realName); + const int index = FindPropIdExact(realName); if (index < 0) return E_INVALIDARG; const CNameToPropID &nameToPropID = g_NameToPropID[(unsigned)index]; @@ -591,7 +642,7 @@ if (IsLogSizeProp(prop.Id)) { - RINOK(PROPVARIANT_to_DictSize(value, prop.Value)); + RINOK(PROPVARIANT_to_DictSize(value, prop.Value)) } else { diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/MethodProps.h 7zip-23.01+dfsg/CPP/7zip/Common/MethodProps.h --- 7zip-22.01+dfsg/CPP/7zip/Common/MethodProps.h 2021-11-19 07:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/MethodProps.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // MethodProps.h -#ifndef __7Z_METHOD_PROPS_H -#define __7Z_METHOD_PROPS_H +#ifndef ZIP7_INC_7Z_METHOD_PROPS_H +#define ZIP7_INC_7Z_METHOD_PROPS_H #include "../../Common/MyString.h" #include "../../Common/Defs.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/MultiOutStream.cpp 7zip-23.01+dfsg/CPP/7zip/Common/MultiOutStream.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/MultiOutStream.cpp 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/MultiOutStream.cpp 2023-03-06 12:00:00.000000000 +0000 @@ -0,0 +1,849 @@ +// MultiOutStream.cpp + +#include "StdAfx.h" + +// #define DEBUG_VOLUMES + +#ifdef DEBUG_VOLUMES +#include + #define PRF(x) x; +#else + #define PRF(x) +#endif + +#include "../../Common/ComTry.h" + +#include "../../Windows/FileDir.h" +#include "../../Windows/FileFind.h" +#include "../../Windows/System.h" + +#include "MultiOutStream.h" + +using namespace NWindows; +using namespace NFile; +using namespace NDir; + +static const unsigned k_NumVols_MAX = k_VectorSizeMax - 1; + // 2; // for debug + +/* +#define UPDATE_HRES(hres, x) \ + { const HRESULT res2 = (x); if (hres == SZ_OK) hres = res2; } +*/ + +HRESULT CMultiOutStream::Destruct() +{ + COM_TRY_BEGIN + HRESULT hres = S_OK; + HRESULT hres3 = S_OK; + + while (!Streams.IsEmpty()) + { + try + { + HRESULT hres2; + if (NeedDelete) + { + /* we could call OptReOpen_and_SetSize() to test that we try to delete correct file, + but we cannot guarantee that (RealSize) will be correct after Write() or another failures. + And we still want to delete files even for such cases. + So we don't check for OptReOpen_and_SetSize() here: */ + // if (OptReOpen_and_SetSize(Streams.Size() - 1, 0) == S_OK) + hres2 = CloseStream_and_DeleteFile(Streams.Size() - 1); + } + else + { + hres2 = CloseStream(Streams.Size() - 1); + } + if (hres == S_OK) + hres = hres2; + } + catch(...) + { + hres3 = E_OUTOFMEMORY; + } + + { + /* Stream was released in CloseStream_*() above already, and it was removed from linked list + it's some unexpected case, if Stream is still attached here. + So the following code is optional: */ + CVolStream &s = Streams.Back(); + if (s.Stream) + { + if (hres3 == S_OK) + hres3 = E_FAIL; + s.Stream.Detach(); + /* it will be not failure, even if we call RemoveFromLinkedList() + twice for same CVolStream in this Destruct() function */ + RemoveFromLinkedList(Streams.Size() - 1); + } + } + Streams.DeleteBack(); + // Delete_LastStream_Records(); + } + + if (hres == S_OK) + hres = hres3; + if (hres == S_OK && NumListItems != 0) + hres = E_FAIL; + return hres; + COM_TRY_END +} + + +CMultiOutStream::~CMultiOutStream() +{ + // we try to avoid exception in destructors + Destruct(); +} + + +void CMultiOutStream::Init(const CRecordVector &sizes) +{ + Streams.Clear(); + InitLinkedList(); + Sizes = sizes; + NeedDelete = true; + MTime_Defined = false; + FinalVol_WasReopen = false; + NumOpenFiles_AllowedMax = NSystem::Get_File_OPEN_MAX_Reduced_for_3_tasks(); + + _streamIndex = 0; + _offsetPos = 0; + _absPos = 0; + _length = 0; + _absLimit = (UInt64)(Int64)-1; + + _restrict_Begin = 0; + _restrict_End = (UInt64)(Int64)-1; + _restrict_Global = 0; + + UInt64 sum = 0; + unsigned i = 0; + for (i = 0; i < Sizes.Size(); i++) + { + if (i >= k_NumVols_MAX) + { + _absLimit = sum; + break; + } + const UInt64 size = Sizes[i]; + const UInt64 next = sum + size; + if (next < sum) + break; + sum = next; + } + + // if (Sizes.IsEmpty()) throw "no volume sizes"; + const UInt64 size = Sizes.Back(); + if (size == 0) + throw "zero size last volume"; + + if (i == Sizes.Size()) + if ((_absLimit - sum) / size >= (k_NumVols_MAX - i)) + _absLimit = sum + (k_NumVols_MAX - i) * size; +} + + +/* IsRestricted(): + we must call only if volume is full (s.RealSize==VolSize) or finished. + the function doesn't use VolSize and it uses s.RealSize instead. + it returns true : if stream is restricted, and we can't close that stream + it returns false : if there is no restriction, and we can close that stream + Note: (RealSize == 0) (empty volume) on restriction bounds are supposed as non-restricted +*/ +bool CMultiOutStream::IsRestricted(const CVolStream &s) const +{ + if (s.Start < _restrict_Global) + return true; + if (_restrict_Begin == _restrict_End) + return false; + if (_restrict_Begin <= s.Start) + return _restrict_End > s.Start; + return _restrict_Begin < s.Start + s.RealSize; +} + +/* +// this function check also _length and volSize +bool CMultiOutStream::IsRestricted_for_Close(unsigned index) const +{ + const CVolStream &s = Streams[index]; + if (_length <= s.Start) // we don't close streams after the end, because we still can write them later + return true; + // (_length > s.Start) + const UInt64 volSize = GetVolSize_for_Stream(index); + if (volSize == 0) + return IsRestricted_Empty(s); + if (_length - s.Start < volSize) + return true; + return IsRestricted(s); +} +*/ + +FString CMultiOutStream::GetFilePath(unsigned index) +{ + FString name; + name.Add_UInt32(index + 1); + while (name.Len() < 3) + name.InsertAtFront(FTEXT('0')); + name.Insert(0, Prefix); + return name; +} + + +// we close stream, but we still keep item in Streams[] vector +HRESULT CMultiOutStream::CloseStream(unsigned index) +{ + CVolStream &s = Streams[index]; + if (s.Stream) + { + RINOK(s.StreamSpec->Close()) + // the following two commands must be called together: + s.Stream.Release(); + RemoveFromLinkedList(index); + } + return S_OK; +} + + +// we close stream and delete file, but we still keep item in Streams[] vector +HRESULT CMultiOutStream::CloseStream_and_DeleteFile(unsigned index) +{ + PRF(printf("\n====== %u, CloseStream_AndDelete \n", index)); + RINOK(CloseStream(index)) + FString path = GetFilePath(index); + path += Streams[index].Postfix; + // we can checki that file exist + // if (NFind::DoesFileExist_Raw(path)) + if (!DeleteFileAlways(path)) + return GetLastError_noZero_HRESULT(); + return S_OK; +} + + +HRESULT CMultiOutStream::CloseStream_and_FinalRename(unsigned index) +{ + PRF(printf("\n====== %u, CloseStream_and_FinalRename \n", index)); + CVolStream &s = Streams[index]; + // HRESULT res = S_OK; + bool mtime_WasSet = false; + if (MTime_Defined && s.Stream) + { + if (s.StreamSpec->SetMTime(&MTime)) + mtime_WasSet = true; + // else res = GetLastError_noZero_HRESULT(); + } + + RINOK(CloseStream(index)) + if (s.Postfix.IsEmpty()) // if Postfix is empty, the path is already final + return S_OK; + const FString path = GetFilePath(index); + FString tempPath = path; + tempPath += s.Postfix; + + if (MTime_Defined && !mtime_WasSet) + { + if (!SetDirTime(tempPath, NULL, NULL, &MTime)) + { + // res = GetLastError_noZero_HRESULT(); + } + } + if (!MyMoveFile(tempPath, path)) + return GetLastError_noZero_HRESULT(); + /* we clear CVolStream::Postfix. So we will not use Temp path + anymore for this stream, and we will work only with final path */ + s.Postfix.Empty(); + // we can ignore set_mtime error or we can return it + return S_OK; + // return res; +} + + +HRESULT CMultiOutStream::PrepareToOpenNew() +{ + if (NumListItems < NumOpenFiles_AllowedMax) + return S_OK; + /* when we create zip archive: in most cases we need only starting + data of restricted region for rewriting zip's local header. + So here we close latest created volume (from Head), and we try to + keep oldest volumes that will be used for header rewriting later. */ + const int index = Head; + if (index == -1) + return E_FAIL; + PRF(printf("\n== %u, PrepareToOpenNew::CloseStream, NumListItems =%u \n", index, NumListItems)); + /* we don't expect non-restricted stream here in normal cases (if _restrict_Global was not changed). + if there was non-restricted stream, it should be closed before */ + // if (!IsRestricted_for_Close(index)) return CloseStream_and_FinalRename(index); + return CloseStream((unsigned)index); +} + + +HRESULT CMultiOutStream::CreateNewStream(UInt64 newSize) +{ + PRF(printf("\n== %u, CreateNewStream, size =%u \n", Streams.Size(), (unsigned)newSize)); + + if (Streams.Size() >= k_NumVols_MAX) + return E_INVALIDARG; // E_OUTOFMEMORY + + RINOK(PrepareToOpenNew()) + CVolStream s; + s.StreamSpec = new COutFileStream; + s.Stream = s.StreamSpec; + const FString path = GetFilePath(Streams.Size()); + + if (NFind::DoesFileExist_Raw(path)) + return HRESULT_FROM_WIN32(ERROR_ALREADY_EXISTS); + if (!CreateTempFile2(path, false, s.Postfix, &s.StreamSpec->File)) + return GetLastError_noZero_HRESULT(); + + s.Start = GetGlobalOffset_for_NewStream(); + s.Pos = 0; + s.RealSize = 0; + + const unsigned index = Streams.Add(s); + InsertToLinkedList(index); + + if (newSize != 0) + return s.SetSize2(newSize); + return S_OK; +} + + +HRESULT CMultiOutStream::CreateStreams_If_Required(unsigned streamIndex) +{ + // UInt64 lastStreamSize = 0; + for (;;) + { + const unsigned numStreamsBefore = Streams.Size(); + if (streamIndex < numStreamsBefore) + return S_OK; + UInt64 newSize; + if (streamIndex == numStreamsBefore) + { + // it's final volume that will be used for real writing. + /* SetSize(_offsetPos) is not required, + because the file Size will be set later by calling Seek() with Write() */ + newSize = 0; // lastStreamSize; + } + else + { + // it's intermediate volume. So we need full volume size + newSize = GetVolSize_for_Stream(numStreamsBefore); + } + + RINOK(CreateNewStream(newSize)) + + // optional check + if (numStreamsBefore + 1 != Streams.Size()) return E_FAIL; + + if (streamIndex != numStreamsBefore) + { + // it's intermediate volume. So we can close it, if it's non-restricted + bool isRestricted; + { + const CVolStream &s = Streams[numStreamsBefore]; + if (newSize == 0) + isRestricted = IsRestricted_Empty(s); + else + isRestricted = IsRestricted(s); + } + if (!isRestricted) + { + RINOK(CloseStream_and_FinalRename(numStreamsBefore)) + } + } + } +} + + +HRESULT CMultiOutStream::ReOpenStream(unsigned streamIndex) +{ + PRF(printf("\n====== %u, ReOpenStream \n", streamIndex)); + RINOK(PrepareToOpenNew()) + CVolStream &s = Streams[streamIndex]; + + FString path = GetFilePath(streamIndex); + path += s.Postfix; + + s.StreamSpec = new COutFileStream; + s.Stream = s.StreamSpec; + s.Pos = 0; + + HRESULT hres; + if (s.StreamSpec->Open(path, OPEN_EXISTING)) + { + if (s.Postfix.IsEmpty()) + { + /* it's unexpected case that we open finished volume. + It can mean that the code for restriction is incorrect */ + FinalVol_WasReopen = true; + } + UInt64 realSize = 0; + hres = s.StreamSpec->GetSize(&realSize); + if (hres == S_OK) + { + if (realSize == s.RealSize) + { + InsertToLinkedList(streamIndex); + return S_OK; + } + // file size was changed between Close() and ReOpen() + // we must release Stream to be consistent with linked list + hres = E_FAIL; + } + } + else + hres = GetLastError_noZero_HRESULT(); + s.Stream.Release(); + s.StreamSpec = NULL; + return hres; +} + + +/* Sets size of stream, if new size is not equal to old size (RealSize). + If stream was closed and size change is required, it reopens the stream. */ + +HRESULT CMultiOutStream::OptReOpen_and_SetSize(unsigned index, UInt64 size) +{ + CVolStream &s = Streams[index]; + if (size == s.RealSize) + return S_OK; + if (!s.Stream) + { + RINOK(ReOpenStream(index)) + } + PRF(printf("\n== %u, OptReOpen_and_SetSize, size =%u RealSize = %u\n", index, (unsigned)size, (unsigned)s.RealSize)); + // comment it to debug tail after data + return s.SetSize2(size); +} + + +/* +call Normalize_finalMode(false), if _length was changed. + for all streams starting after _length: + - it sets zero size + - it still keeps file open + Note: after _length reducing with CMultiOutStream::SetSize() we can + have very big number of empty streams at the end of Streams[] list. + And Normalize_finalMode() will runs all these empty streams of Streams[] vector. + So it can be ineffective, if we call Normalize_finalMode() many + times after big reducing of (_length). + +call Normalize_finalMode(true) to set final presentations of all streams + for all streams starting after _length: + - it sets zero size + - it removes file + - it removes CVolStream object from Streams[] vector + +Note: we don't remove zero sized first volume, if (_length == 0) +*/ + +HRESULT CMultiOutStream::Normalize_finalMode(bool finalMode) +{ + PRF(printf("\n== Normalize_finalMode: _length =%d \n", (unsigned)_length)); + + unsigned i = Streams.Size(); + + UInt64 offset = 0; + + /* At first we normalize (reduce or increase) the sizes of all existing + streams in Streams[] that can be affected by changed _length. + And we remove tailing zero-size streams, if (finalMode == true) */ + while (i != 0) + { + offset = Streams[--i].Start; // it's last item in Streams[] + // we don't want to remove first volume + if (offset < _length || i == 0) + { + const UInt64 volSize = GetVolSize_for_Stream(i); + UInt64 size = _length - offset; // (size != 0) here + if (size > volSize) + size = volSize; + RINOK(OptReOpen_and_SetSize(i, size)) + if (_length - offset <= volSize) + return S_OK; + // _length - offset > volSize + offset += volSize; + // _length > offset + break; + // UPDATE_HRES(res, OptReOpen_and_SetSize(i, size)); + } + + /* we Set Size of stream to zero even for (finalMode==true), although + that stream will be deleted in next commands */ + // UPDATE_HRES(res, OptReOpen_and_SetSize(i, 0)); + RINOK(OptReOpen_and_SetSize(i, 0)) + if (finalMode) + { + RINOK(CloseStream_and_DeleteFile(i)) + /* CVolStream::Stream was released above already, and it was + removed from linked list. So we don't need to update linked list + structure, when we delete last item in Streams[] */ + Streams.DeleteBack(); + // Delete_LastStream_Records(); + } + } + + /* now we create new zero-filled streams to cover all data up to _length */ + + if (_length == 0) + return S_OK; + + // (offset) is start offset of next stream after existing Streams[] + + for (;;) + { + // _length > offset + const UInt64 volSize = GetVolSize_for_Stream(Streams.Size()); + UInt64 size = _length - offset; // (size != 0) here + if (size > volSize) + size = volSize; + RINOK(CreateNewStream(size)) + if (_length - offset <= volSize) + return S_OK; + // _length - offset > volSize) + offset += volSize; + // _length > offset + } +} + + +HRESULT CMultiOutStream::FinalFlush_and_CloseFiles(unsigned &numTotalVolumesRes) +{ + // at first we remove unused zero-sized streams after _length + HRESULT res = Normalize_finalMode(true); + numTotalVolumesRes = Streams.Size(); + FOR_VECTOR (i, Streams) + { + const HRESULT res2 = CloseStream_and_FinalRename(i); + if (res == S_OK) + res = res2; + } + if (NumListItems != 0 && res == S_OK) + res = E_FAIL; + return res; +} + + +bool CMultiOutStream::SetMTime_Final(const CFiTime &mTime) +{ + // we will set mtime only if new value differs from previous + if (!FinalVol_WasReopen && MTime_Defined && Compare_FiTime(&MTime, &mTime) == 0) + return true; + bool res = true; + FOR_VECTOR (i, Streams) + { + CVolStream &s = Streams[i]; + if (s.Stream) + { + if (!s.StreamSpec->SetMTime(&mTime)) + res = false; + } + else + { + if (!SetDirTime(GetFilePath(i), NULL, NULL, &mTime)) + res = false; + } + } + return res; +} + + +Z7_COM7F_IMF(CMultiOutStream::SetSize(UInt64 newSize)) +{ + COM_TRY_BEGIN + if ((Int64)newSize < 0) + return HRESULT_WIN32_ERROR_NEGATIVE_SEEK; + if (newSize > _absLimit) + { + /* big seek value was sent to SetSize() or to Seek()+Write(). + It can mean one of two situations: + 1) some incorrect code called it with big seek value. + 2) volume size was small, and we have too big number of volumes + */ + /* in Windows SetEndOfFile() can return: + ERROR_NEGATIVE_SEEK: for >= (1 << 63) + ERROR_INVALID_PARAMETER: for > (16 TiB - 64 KiB) + ERROR_DISK_FULL: for <= (16 TiB - 64 KiB) + */ + // return E_FAIL; + // return E_OUTOFMEMORY; + return E_INVALIDARG; + } + + if (newSize > _length) + { + // we don't expect such case. So we just define global restriction */ + _restrict_Global = newSize; + } + else if (newSize < _restrict_Global) + _restrict_Global = newSize; + + PRF(printf("\n== SetSize, size =%u \n", (unsigned)newSize)); + + _length = newSize; + return Normalize_finalMode(false); + + COM_TRY_END +} + + +Z7_COM7F_IMF(CMultiOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) +{ + COM_TRY_BEGIN + if (processedSize) + *processedSize = 0; + if (size == 0) + return S_OK; + + if (_absPos > _length) + { + // it create data only up to _absPos. + // but we still can need additional new streams, if _absPos at range of volume + RINOK(SetSize(_absPos)) + } + + while (size != 0) + { + UInt64 volSize; + { + if (_streamIndex < Sizes.Size() - 1) + { + volSize = Sizes[_streamIndex]; + if (_offsetPos >= volSize) + { + _offsetPos -= volSize; + _streamIndex++; + continue; + } + } + else + { + volSize = Sizes[Sizes.Size() - 1]; + if (_offsetPos >= volSize) + { + const UInt64 v = _offsetPos / volSize; + if (v >= ((UInt32)(Int32)-1) - _streamIndex) + return E_INVALIDARG; + // throw 202208; + _streamIndex += (unsigned)v; + _offsetPos -= (unsigned)v * volSize; + } + if (_streamIndex >= k_NumVols_MAX) + return E_INVALIDARG; + } + } + + // (_offsetPos < volSize) here + + /* we can need to create one or more streams here, + vol_size for some streams is allowed to be 0. + Also we close some new created streams, if they are non-restricted */ + // file Size will be set later by calling Seek() with Write() + + /* the case (_absPos > _length) was processed above with SetSize(_absPos), + so here it's expected. that we can create optional zero-size streams and then _streamIndex */ + RINOK(CreateStreams_If_Required(_streamIndex)) + + CVolStream &s = Streams[_streamIndex]; + + PRF(printf("\n%d, == Write : Pos = %u, RealSize = %u size =%u \n", + _streamIndex, (unsigned)s.Pos, (unsigned)s.RealSize, size)); + + if (!s.Stream) + { + RINOK(ReOpenStream(_streamIndex)) + } + if (_offsetPos != s.Pos) + { + RINOK(s.Stream->Seek((Int64)_offsetPos, STREAM_SEEK_SET, NULL)) + s.Pos = _offsetPos; + } + + UInt32 curSize = size; + { + const UInt64 rem = volSize - _offsetPos; + if (curSize > rem) + curSize = (UInt32)rem; + } + // curSize != 0 + UInt32 realProcessed = 0; + + HRESULT hres = s.Stream->Write(data, curSize, &realProcessed); + + data = (const void *)((const Byte *)data + realProcessed); + size -= realProcessed; + s.Pos += realProcessed; + _offsetPos += realProcessed; + _absPos += realProcessed; + if (_length < _absPos) + _length = _absPos; + if (s.RealSize < _offsetPos) + s.RealSize = _offsetPos; + if (processedSize) + *processedSize += realProcessed; + + if (s.Pos == volSize) + { + bool isRestricted; + if (volSize == 0) + isRestricted = IsRestricted_Empty(s); + else + isRestricted = IsRestricted(s); + if (!isRestricted) + { + const HRESULT res2 = CloseStream_and_FinalRename(_streamIndex); + if (hres == S_OK) + hres = res2; + } + _streamIndex++; + _offsetPos = 0; + } + + RINOK(hres) + if (realProcessed == 0 && curSize != 0) + return E_FAIL; + // break; + } + return S_OK; + COM_TRY_END +} + + +Z7_COM7F_IMF(CMultiOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) +{ + PRF(printf("\n-- Seek seekOrigin=%u Seek =%u\n", seekOrigin, (unsigned)offset)); + + switch (seekOrigin) + { + case STREAM_SEEK_SET: break; + case STREAM_SEEK_CUR: offset += _absPos; break; + case STREAM_SEEK_END: offset += _length; break; + default: return STG_E_INVALIDFUNCTION; + } + if (offset < 0) + return HRESULT_WIN32_ERROR_NEGATIVE_SEEK; + if ((UInt64)offset != _absPos) + { + _absPos = (UInt64)offset; + _offsetPos = (UInt64)offset; + _streamIndex = 0; + } + if (newPosition) + *newPosition = (UInt64)offset; + return S_OK; +} + + +// result value will be saturated to (UInt32)(Int32)-1 + +unsigned CMultiOutStream::GetStreamIndex_for_Offset(UInt64 offset, UInt64 &relOffset) const +{ + const unsigned last = Sizes.Size() - 1; + for (unsigned i = 0; i < last; i++) + { + const UInt64 size = Sizes[i]; + if (offset < size) + { + relOffset = offset; + return i; + } + offset -= size; + } + const UInt64 size = Sizes[last]; + const UInt64 v = offset / size; + if (v >= ((UInt32)(Int32)-1) - last) + return (UInt32)(Int32)-1; // saturation + relOffset = offset - (unsigned)v * size; + return last + (unsigned)(v); +} + + +Z7_COM7F_IMF(CMultiOutStream::SetRestriction(UInt64 begin, UInt64 end)) +{ + COM_TRY_BEGIN + + // begin = end = 0; // for debug + + PRF(printf("\n==================== CMultiOutStream::SetRestriction %u, %u\n", (unsigned)begin, (unsigned)end)); + if (begin > end) + { + // these value are FAILED values. + return E_FAIL; + // return E_INVALIDARG; + /* + // or we can ignore error with 3 ways: no change, non-restricted, saturation: + end = begin; // non-restricted + end = (UInt64)(Int64)-1; // saturation: + return S_OK; + */ + } + UInt64 b = _restrict_Begin; + UInt64 e = _restrict_End; + _restrict_Begin = begin; + _restrict_End = end; + + if (b == e) // if there were no restriction before + return S_OK; // no work to derestrict now. + + /* [b, e) is previous restricted region. So all volumes that + intersect that [b, e) region are candidats for derestriction */ + + if (begin != end) // if there is new non-empty restricted region + { + /* Now we will try to reduce or change (b) and (e) bounds + to reduce main loop that checks volumes for derestriction. + We still use one big derestriction region in main loop, although + in some cases we could have two smaller derestriction regions. + Also usually restriction region cannot move back from previous start position, + so (b <= begin) is expected here for normal cases */ + if (b == begin) // if same low bounds + b = end; // we need to derestrict only after the end of new restricted region + if (e == end) // if same high bounds + e = begin; // we need to derestrict only before the begin of new restricted region + } + + if (b > e) // || b == (UInt64)(Int64)-1 + return S_OK; + + /* Here we close finished volumes that are not restricted anymore. + We close (low number) volumes at first. */ + + UInt64 offset; + unsigned index = GetStreamIndex_for_Offset(b, offset); + + for (; index < Streams.Size(); index++) + { + { + const CVolStream &s = Streams[index]; + if (_length <= s.Start) + break; // we don't close streams after _length + // (_length > s.Start) + const UInt64 volSize = GetVolSize_for_Stream(index); + if (volSize == 0) + { + if (e < s.Start) + break; + // we don't close empty stream, if next byte [s.Start, s.Start] is restricted + if (IsRestricted_Empty(s)) + continue; + } + else + { + if (e <= s.Start) + break; + // we don't close non full streams + if (_length - s.Start < volSize) + break; + // (volSize == s.RealSize) is expected here. So no need to check it + // if (volSize != s.RealSize) break; + if (IsRestricted(s)) + continue; + } + } + RINOK(CloseStream_and_FinalRename(index)) + } + + return S_OK; + COM_TRY_END +} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/MultiOutStream.h 7zip-23.01+dfsg/CPP/7zip/Common/MultiOutStream.h --- 7zip-22.01+dfsg/CPP/7zip/Common/MultiOutStream.h 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/MultiOutStream.h 2023-04-05 17:00:00.000000000 +0000 @@ -0,0 +1,160 @@ +// MultiOutStream.h + +#ifndef ZIP7_INC_MULTI_OUT_STREAM_H +#define ZIP7_INC_MULTI_OUT_STREAM_H + +#include "FileStreams.h" + +Z7_CLASS_IMP_COM_2( + CMultiOutStream + , IOutStream + , IStreamSetRestriction +) + Z7_IFACE_COM7_IMP(ISequentialOutStream) + + Z7_CLASS_NO_COPY(CMultiOutStream) + + struct CVolStream + { + COutFileStream *StreamSpec; + CMyComPtr Stream; + UInt64 Start; // start pos of current Stream in global stream + UInt64 Pos; // pos in current Stream + UInt64 RealSize; + int Next; // next older + int Prev; // prev newer + AString Postfix; + + HRESULT SetSize2(UInt64 size) + { + const HRESULT res = Stream->SetSize(size); + if (res == SZ_OK) + RealSize = size; + return res; + } + }; + + unsigned _streamIndex; // (_streamIndex >= Stream.Size()) is allowed in some internal code + UInt64 _offsetPos; // offset relative to Streams[_streamIndex] volume. (_offsetPos >= volSize is allowed) + UInt64 _absPos; + UInt64 _length; // virtual Length + UInt64 _absLimit; + + CObjectVector Streams; + CRecordVector Sizes; + + UInt64 _restrict_Begin; + UInt64 _restrict_End; + UInt64 _restrict_Global; + + unsigned NumOpenFiles_AllowedMax; + + // ----- Double Linked List ----- + + unsigned NumListItems; + int Head; // newest + int Tail; // oldest + + void InitLinkedList() + { + Head = -1; + Tail = -1; + NumListItems = 0; + } + + void InsertToLinkedList(unsigned index) + { + { + CVolStream &node = Streams[index]; + node.Next = Head; + node.Prev = -1; + } + if (Head != -1) + Streams[(unsigned)Head].Prev = (int)index; + else + { + // if (Tail != -1) throw 1; + Tail = (int)index; + } + Head = (int)index; + NumListItems++; + } + + void RemoveFromLinkedList(unsigned index) + { + CVolStream &s = Streams[index]; + if (s.Next != -1) Streams[(unsigned)s.Next].Prev = s.Prev; else Tail = s.Prev; + if (s.Prev != -1) Streams[(unsigned)s.Prev].Next = s.Next; else Head = s.Next; + s.Next = -1; // optional + s.Prev = -1; // optional + NumListItems--; + } + + /* + void Delete_LastStream_Records() + { + if (Streams.Back().Stream) + RemoveFromLinkedList(Streams.Size() - 1); + Streams.DeleteBack(); + } + */ + + UInt64 GetVolSize_for_Stream(unsigned i) const + { + const unsigned last = Sizes.Size() - 1; + return Sizes[i < last ? i : last]; + } + UInt64 GetGlobalOffset_for_NewStream() const + { + return Streams.Size() == 0 ? 0: + Streams.Back().Start + + GetVolSize_for_Stream(Streams.Size() - 1); + } + unsigned GetStreamIndex_for_Offset(UInt64 offset, UInt64 &relOffset) const; + bool IsRestricted(const CVolStream &s) const; + bool IsRestricted_Empty(const CVolStream &s) const + { + // (s) must be stream that has (VolSize == 0). + // we treat empty stream as restricted, if next byte is restricted. + if (s.Start < _restrict_Global) + return true; + return + (_restrict_Begin != _restrict_End) + && (_restrict_Begin <= s.Start) + && (_restrict_Begin == s.Start || _restrict_End > s.Start); + } + // bool IsRestricted_for_Close(unsigned index) const; + FString GetFilePath(unsigned index); + + HRESULT CloseStream(unsigned index); + HRESULT CloseStream_and_DeleteFile(unsigned index); + HRESULT CloseStream_and_FinalRename(unsigned index); + + HRESULT PrepareToOpenNew(); + HRESULT CreateNewStream(UInt64 newSize); + HRESULT CreateStreams_If_Required(unsigned streamIndex); + HRESULT ReOpenStream(unsigned streamIndex); + HRESULT OptReOpen_and_SetSize(unsigned index, UInt64 size); + + HRESULT Normalize_finalMode(bool finalMode); +public: + FString Prefix; + CFiTime MTime; + bool MTime_Defined; + bool FinalVol_WasReopen; + bool NeedDelete; + + CMultiOutStream() {} + ~CMultiOutStream(); + void Init(const CRecordVector &sizes); + bool SetMTime_Final(const CFiTime &mTime); + UInt64 GetSize() const { return _length; } + /* it makes final flushing, closes open files and renames to final name if required + but it still keeps Streams array of all closed files. + So we still can delete all files later, if required */ + HRESULT FinalFlush_and_CloseFiles(unsigned &numTotalVolumesRes); + // Destruct object without exceptions + HRESULT Destruct(); +}; + +#endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/OffsetStream.cpp 7zip-23.01+dfsg/CPP/7zip/Common/OffsetStream.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/OffsetStream.cpp 2021-05-08 09:24:40.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/OffsetStream.cpp 2023-04-05 14:00:00.000000000 +0000 @@ -2,8 +2,6 @@ #include "StdAfx.h" -#include "../../Common/Defs.h" - #include "OffsetStream.h" HRESULT COffsetOutStream::Init(IOutStream *stream, UInt64 offset) @@ -13,12 +11,12 @@ return _stream->Seek((Int64)offset, STREAM_SEEK_SET, NULL); } -STDMETHODIMP COffsetOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(COffsetOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { return _stream->Write(data, size, processedSize); } -STDMETHODIMP COffsetOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(COffsetOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { if (seekOrigin == STREAM_SEEK_SET) { @@ -27,13 +25,13 @@ offset += _offset; } UInt64 absoluteNewPosition = 0; // =0 for gcc-10 - HRESULT result = _stream->Seek(offset, seekOrigin, &absoluteNewPosition); + const HRESULT result = _stream->Seek(offset, seekOrigin, &absoluteNewPosition); if (newPosition) *newPosition = absoluteNewPosition - _offset; return result; } -STDMETHODIMP COffsetOutStream::SetSize(UInt64 newSize) +Z7_COM7F_IMF(COffsetOutStream::SetSize(UInt64 newSize)) { return _stream->SetSize(_offset + newSize); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/OffsetStream.h 7zip-23.01+dfsg/CPP/7zip/Common/OffsetStream.h --- 7zip-22.01+dfsg/CPP/7zip/Common/OffsetStream.h 2013-01-17 08:06:15.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/OffsetStream.h 2023-04-05 14:00:00.000000000 +0000 @@ -1,26 +1,22 @@ // OffsetStream.h -#ifndef __OFFSET_STREAM_H -#define __OFFSET_STREAM_H +#ifndef ZIP7_INC_OFFSET_STREAM_H +#define ZIP7_INC_OFFSET_STREAM_H #include "../../Common/MyCom.h" #include "../IStream.h" -class COffsetOutStream: - public IOutStream, - public CMyUnknownImp -{ - UInt64 _offset; +Z7_CLASS_IMP_NOQIB_1( + COffsetOutStream + , IOutStream +) + Z7_IFACE_COM7_IMP(ISequentialOutStream) + CMyComPtr _stream; + UInt64 _offset; public: HRESULT Init(IOutStream *stream, UInt64 offset); - - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); - STDMETHOD(SetSize)(UInt64 newSize); }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/OutBuffer.cpp 7zip-23.01+dfsg/CPP/7zip/Common/OutBuffer.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/OutBuffer.cpp 2014-12-30 19:15:44.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/OutBuffer.cpp 2023-04-05 14:00:00.000000000 +0000 @@ -11,18 +11,18 @@ const UInt32 kMinBlockSize = 1; if (bufSize < kMinBlockSize) bufSize = kMinBlockSize; - if (_buf != 0 && _bufSize == bufSize) + if (_buf && _bufSize == bufSize) return true; Free(); _bufSize = bufSize; _buf = (Byte *)::MidAlloc(bufSize); - return (_buf != 0); + return (_buf != NULL); } void COutBuffer::Free() throw() { ::MidFree(_buf); - _buf = 0; + _buf = NULL; } void COutBuffer::Init() throw() @@ -32,7 +32,7 @@ _pos = 0; _processedSize = 0; _overDict = false; - #ifdef _NO_EXCEPTIONS + #ifdef Z7_NO_EXCEPTIONS ErrorCode = S_OK; #endif } @@ -51,17 +51,17 @@ // _streamPos < _bufSize UInt32 size = (_streamPos >= _pos) ? (_bufSize - _streamPos) : (_pos - _streamPos); HRESULT result = S_OK; - #ifdef _NO_EXCEPTIONS + #ifdef Z7_NO_EXCEPTIONS result = ErrorCode; #endif - if (_buf2 != 0) + if (_buf2) { memcpy(_buf2, _buf + _streamPos, size); _buf2 += size; } - if (_stream != 0 - #ifdef _NO_EXCEPTIONS + if (_stream + #ifdef Z7_NO_EXCEPTIONS && (ErrorCode == S_OK) #endif ) @@ -85,14 +85,14 @@ HRESULT COutBuffer::Flush() throw() { - #ifdef _NO_EXCEPTIONS + #ifdef Z7_NO_EXCEPTIONS if (ErrorCode != S_OK) return ErrorCode; #endif while (_streamPos != _pos) { - HRESULT result = FlushPart(); + const HRESULT result = FlushPart(); if (result != S_OK) return result; } @@ -101,8 +101,8 @@ void COutBuffer::FlushWithCheck() { - HRESULT result = Flush(); - #ifdef _NO_EXCEPTIONS + const HRESULT result = Flush(); + #ifdef Z7_NO_EXCEPTIONS ErrorCode = result; #else if (result != S_OK) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/OutBuffer.h 7zip-23.01+dfsg/CPP/7zip/Common/OutBuffer.h --- 7zip-22.01+dfsg/CPP/7zip/Common/OutBuffer.h 2017-01-24 08:57:32.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/OutBuffer.h 2023-03-28 11:00:00.000000000 +0000 @@ -1,13 +1,13 @@ // OutBuffer.h -#ifndef __OUT_BUFFER_H -#define __OUT_BUFFER_H +#ifndef ZIP7_INC_OUT_BUFFER_H +#define ZIP7_INC_OUT_BUFFER_H #include "../IStream.h" #include "../../Common/MyCom.h" #include "../../Common/MyException.h" -#ifndef _NO_EXCEPTIONS +#ifndef Z7_NO_EXCEPTIONS struct COutBufferException: public CSystemException { COutBufferException(HRESULT errorCode): CSystemException(errorCode) {} @@ -29,11 +29,11 @@ HRESULT FlushPart() throw(); public: - #ifdef _NO_EXCEPTIONS + #ifdef Z7_NO_EXCEPTIONS HRESULT ErrorCode; #endif - COutBuffer(): _buf(0), _pos(0), _stream(0), _buf2(0) {} + COutBuffer(): _buf(NULL), _pos(0), _stream(NULL), _buf2(NULL) {} ~COutBuffer() { Free(); } bool Create(UInt32 bufSize) throw(); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/OutMemStream.cpp 7zip-23.01+dfsg/CPP/7zip/Common/OutMemStream.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/OutMemStream.cpp 2021-04-01 12:11:25.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/OutMemStream.cpp 2023-04-05 14:00:00.000000000 +0000 @@ -31,13 +31,13 @@ HRESULT COutMemStream::WriteToRealStream() { - RINOK(Blocks.WriteToStream(_memManager->GetBlockSize(), OutSeqStream)); + RINOK(Blocks.WriteToStream(_memManager->GetBlockSize(), OutSeqStream)) Blocks.Free(_memManager); return S_OK; } -STDMETHODIMP COutMemStream::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(COutMemStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { if (_realStreamMode) return OutSeqStream->Write(data, size, processedSize); @@ -58,7 +58,7 @@ size -= (UInt32)curSize; _curBlockPos += curSize; - UInt64 pos64 = GetPos(); + const UInt64 pos64 = GetPos(); if (pos64 > Blocks.TotalSize) Blocks.TotalSize = pos64; if (_curBlockPos == _memManager->GetBlockSize()) @@ -83,9 +83,9 @@ case (WAIT_OBJECT_0 + 1): { _realStreamMode = true; - RINOK(WriteToRealStream()); + RINOK(WriteToRealStream()) UInt32 processedSize2; - HRESULT res = OutSeqStream->Write(data, size, &processedSize2); + const HRESULT res = OutSeqStream->Write(data, size, &processedSize2); if (processedSize) *processedSize += processedSize2; return res; @@ -103,7 +103,7 @@ { if (waitResult == WAIT_FAILED) { - DWORD res = ::GetLastError(); + const DWORD res = ::GetLastError(); if (res != 0) return HRESULT_FROM_WIN32(res); } @@ -118,7 +118,7 @@ return S_OK; } -STDMETHODIMP COutMemStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(COutMemStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { if (_realStreamMode) { @@ -145,7 +145,7 @@ return S_OK; } -STDMETHODIMP COutMemStream::SetSize(UInt64 newSize) +Z7_COM7F_IMF(COutMemStream::SetSize(UInt64 newSize)) { if (_realStreamMode) { diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/OutMemStream.h 7zip-23.01+dfsg/CPP/7zip/Common/OutMemStream.h --- 7zip-22.01+dfsg/CPP/7zip/Common/OutMemStream.h 2020-10-14 17:36:56.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/OutMemStream.h 2023-04-05 14:00:00.000000000 +0000 @@ -1,19 +1,21 @@ // OutMemStream.h -#ifndef __OUT_MEM_STREAM_H -#define __OUT_MEM_STREAM_H +#ifndef ZIP7_INC_OUT_MEM_STREAM_H +#define ZIP7_INC_OUT_MEM_STREAM_H #include "../../Common/MyCom.h" #include "MemBlocks.h" -class COutMemStream: - public IOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + COutMemStream + , IOutStream +) + Z7_IFACE_COM7_IMP(ISequentialOutStream) + CMemBlockManagerMt *_memManager; - unsigned _curBlockIndex; size_t _curBlockPos; + unsigned _curBlockIndex; bool _realStreamMode; bool _unlockEventWasSent; @@ -24,14 +26,13 @@ HRESULT StopWriteResult; CMemLockBlocks Blocks; - UInt64 GetPos() const { return (UInt64)_curBlockIndex * _memManager->GetBlockSize() + _curBlockPos; } - CMyComPtr OutSeqStream; CMyComPtr OutStream; + UInt64 GetPos() const { return (UInt64)_curBlockIndex * _memManager->GetBlockSize() + _curBlockPos; } + public: - HRes CreateEvents(SYNC_PARAM_DECL(synchro)) { WRes wres = StopWritingEvent.CreateIfNotCreated_Reset(SYNC_WFMO(synchro)); @@ -98,12 +99,6 @@ StopWriteResult = res; StopWritingEvent.Set(); } - - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); - STDMETHOD(SetSize)(UInt64 newSize); }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/ProgressMt.cpp 7zip-23.01+dfsg/CPP/7zip/Common/ProgressMt.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/ProgressMt.cpp 2021-01-24 15:59:56.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/ProgressMt.cpp 2023-04-05 14:00:00.000000000 +0000 @@ -31,13 +31,13 @@ NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection); if (inSize) { - UInt64 diff = *inSize - InSizes[index]; + const UInt64 diff = *inSize - InSizes[index]; InSizes[index] = *inSize; TotalInSize += diff; } if (outSize) { - UInt64 diff = *outSize - OutSizes[index]; + const UInt64 diff = *outSize - OutSizes[index]; OutSizes[index] = *outSize; TotalOutSize += diff; } @@ -47,7 +47,7 @@ } -STDMETHODIMP CMtCompressProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) +Z7_COM7F_IMF(CMtCompressProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize)) { return _progress->SetRatioInfo(_index, inSize, outSize); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/ProgressMt.h 7zip-23.01+dfsg/CPP/7zip/Common/ProgressMt.h --- 7zip-22.01+dfsg/CPP/7zip/Common/ProgressMt.h 2021-01-24 15:59:50.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/ProgressMt.h 2023-04-05 14:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ProgressMt.h -#ifndef __PROGRESSMT_H -#define __PROGRESSMT_H +#ifndef ZIP7_INC_PROGRESSMT_H +#define ZIP7_INC_PROGRESSMT_H #include "../../Common/MyCom.h" #include "../../Common/MyVector.h" @@ -24,12 +24,13 @@ HRESULT SetRatioInfo(unsigned index, const UInt64 *inSize, const UInt64 *outSize); }; -class CMtCompressProgress: - public ICompressProgressInfo, - public CMyUnknownImp -{ - CMtCompressProgressMixer *_progress; + +Z7_CLASS_IMP_NOQIB_1( + CMtCompressProgress + , ICompressProgressInfo +) unsigned _index; + CMtCompressProgressMixer *_progress; public: void Init(CMtCompressProgressMixer *progress, unsigned index) { @@ -37,10 +38,6 @@ _index = index; } void Reinit() { _progress->Reinit(_index); } - - MY_UNKNOWN_IMP - - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/ProgressUtils.cpp 7zip-23.01+dfsg/CPP/7zip/Common/ProgressUtils.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/ProgressUtils.cpp 2015-02-13 07:34:31.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/ProgressUtils.cpp 2023-04-05 14:00:00.000000000 +0000 @@ -5,11 +5,11 @@ #include "ProgressUtils.h" CLocalProgress::CLocalProgress(): + SendRatio(true), + SendProgress(true), ProgressOffset(0), InSize(0), - OutSize(0), - SendRatio(true), - SendProgress(true) + OutSize(0) {} void CLocalProgress::Init(IProgress *progress, bool inSizeIsMain) @@ -20,7 +20,7 @@ _inSizeIsMain = inSizeIsMain; } -STDMETHODIMP CLocalProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) +Z7_COM7F_IMF(CLocalProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize)) { UInt64 inSize2 = InSize; UInt64 outSize2 = OutSize; @@ -32,7 +32,7 @@ if (SendRatio && _ratioProgress) { - RINOK(_ratioProgress->SetRatioInfo(&inSize2, &outSize2)); + RINOK(_ratioProgress->SetRatioInfo(&inSize2, &outSize2)) } if (SendProgress) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/ProgressUtils.h 7zip-23.01+dfsg/CPP/7zip/Common/ProgressUtils.h --- 7zip-22.01+dfsg/CPP/7zip/Common/ProgressUtils.h 2015-02-13 07:34:41.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/ProgressUtils.h 2023-04-05 14:00:00.000000000 +0000 @@ -1,35 +1,33 @@ // ProgressUtils.h -#ifndef __PROGRESS_UTILS_H -#define __PROGRESS_UTILS_H +#ifndef ZIP7_INC_PROGRESS_UTILS_H +#define ZIP7_INC_PROGRESS_UTILS_H #include "../../Common/MyCom.h" #include "../ICoder.h" #include "../IProgress.h" -class CLocalProgress: - public ICompressProgressInfo, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CLocalProgress + , ICompressProgressInfo +) +public: + bool SendRatio; + bool SendProgress; +private: + bool _inSizeIsMain; CMyComPtr _progress; CMyComPtr _ratioProgress; - bool _inSizeIsMain; public: UInt64 ProgressOffset; UInt64 InSize; UInt64 OutSize; - bool SendRatio; - bool SendProgress; CLocalProgress(); void Init(IProgress *progress, bool inSizeIsMain); HRESULT SetCur(); - - MY_UNKNOWN_IMP1(ICompressProgressInfo) - - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/PropId.cpp 7zip-23.01+dfsg/CPP/7zip/Common/PropId.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/PropId.cpp 2022-05-03 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/PropId.cpp 2022-11-05 14:00:00.000000000 +0000 @@ -111,5 +111,7 @@ VT_UI4, VT_UI4, VT_UI4, - VT_UI4 // kpidDeviceMinor + VT_UI4, + VT_UI4, + VT_UI4 // kpidDevMinor }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/RegisterArc.h 7zip-23.01+dfsg/CPP/7zip/Common/RegisterArc.h --- 7zip-22.01+dfsg/CPP/7zip/Common/RegisterArc.h 2022-05-18 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/RegisterArc.h 2023-03-06 16:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // RegisterArc.h -#ifndef __REGISTER_ARC_H -#define __REGISTER_ARC_H +#ifndef ZIP7_INC_REGISTER_ARC_H +#define ZIP7_INC_REGISTER_ARC_H #include "../Archive/IArchive.h" @@ -34,7 +34,7 @@ #define IMP_CreateArcIn IMP_CreateArcIn_2(CHandler()) -#ifdef EXTRACT_ONLY +#ifdef Z7_EXTRACT_ONLY #define IMP_CreateArcOut #define CreateArcOut NULL #else @@ -52,7 +52,7 @@ #define REGISTER_ARC_I_CLS(cls, n, e, ae, id, sig, offs, flags, isArc) \ IMP_CreateArcIn_2(cls) \ - REGISTER_ARC_R(n, e, ae, id, ARRAY_SIZE(sig), sig, offs, flags, 0, CreateArc, NULL, isArc) + REGISTER_ARC_R(n, e, ae, id, Z7_ARRAY_SIZE(sig), sig, offs, flags, 0, CreateArc, NULL, isArc) #define REGISTER_ARC_I_CLS_NO_SIG(cls, n, e, ae, id, offs, flags, isArc) \ IMP_CreateArcIn_2(cls) \ @@ -68,12 +68,12 @@ #define REGISTER_ARC_IO(n, e, ae, id, sig, offs, flags, tf, isArc) \ IMP_CreateArcIn \ IMP_CreateArcOut \ - REGISTER_ARC_R(n, e, ae, id, ARRAY_SIZE(sig), sig, offs, flags, tf, CreateArc, CreateArcOut, isArc) + REGISTER_ARC_R(n, e, ae, id, Z7_ARRAY_SIZE(sig), sig, offs, flags, tf, CreateArc, CreateArcOut, isArc) #define REGISTER_ARC_IO_DECREMENT_SIG(n, e, ae, id, sig, offs, flags, tf, isArc) \ IMP_CreateArcIn \ IMP_CreateArcOut \ - REGISTER_ARC_V(n, e, ae, id, ARRAY_SIZE(sig), sig, offs, flags, tf, CreateArc, CreateArcOut, isArc) \ + REGISTER_ARC_V(n, e, ae, id, Z7_ARRAY_SIZE(sig), sig, offs, flags, tf, CreateArc, CreateArcOut, isArc) \ struct CRegisterArcDecSig { CRegisterArcDecSig() { sig[0]--; RegisterArc(&g_ArcInfo); }}; \ static CRegisterArcDecSig g_RegisterArc; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/RegisterCodec.h 7zip-23.01+dfsg/CPP/7zip/Common/RegisterCodec.h --- 7zip-22.01+dfsg/CPP/7zip/Common/RegisterCodec.h 2019-08-28 14:41:07.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/RegisterCodec.h 2023-03-06 16:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // RegisterCodec.h -#ifndef __REGISTER_CODEC_H -#define __REGISTER_CODEC_H +#ifndef ZIP7_INC_REGISTER_CODEC_H +#define ZIP7_INC_REGISTER_CODEC_H #include "../Common/MethodId.h" @@ -37,7 +37,7 @@ #define REGISTER_CODECS_VAR static const CCodecInfo g_CodecsInfo[] = #define REGISTER_CODECS(x) struct REGISTER_CODECS_NAME(x) { \ - REGISTER_CODECS_NAME(x)() { for (unsigned i = 0; i < ARRAY_SIZE(g_CodecsInfo); i++) \ + REGISTER_CODECS_NAME(x)() { for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_CodecsInfo); i++) \ RegisterCodec(&g_CodecsInfo[i]); }}; \ static REGISTER_CODECS_NAME(x) g_RegisterCodecs; @@ -48,7 +48,7 @@ REGISTER_CODEC(x) -#ifdef EXTRACT_ONLY +#ifdef Z7_EXTRACT_ONLY #define REGISTER_CODEC_E(x, clsDec, clsEnc, id, name) \ REGISTER_CODEC_CREATE(CreateDec, clsDec) \ REGISTER_CODEC_2(x, CreateDec, NULL, id, name) @@ -71,7 +71,7 @@ REGISTER_FILTER_ITEM(crDec, crEnc, id, name); \ REGISTER_CODEC(x) -#ifdef EXTRACT_ONLY +#ifdef Z7_EXTRACT_ONLY #define REGISTER_FILTER_E(x, clsDec, clsEnc, id, name) \ REGISTER_FILTER_CREATE(x ## _CreateDec, clsDec) \ REGISTER_FILTER(x, x ## _CreateDec, NULL, id, name) @@ -97,7 +97,7 @@ #define REGISTER_HASHER_NAME(x) CRegHasher_ ## x #define REGISTER_HASHER(cls, id, name, size) \ - STDMETHODIMP_(UInt32) cls::GetDigestSize() throw() { return size; } \ + Z7_COM7F_IMF2(UInt32, cls::GetDigestSize()) { return size; } \ static IHasher *CreateHasherSpec() { return new cls(); } \ static const CHasherInfo g_HasherInfo = { CreateHasherSpec, id, name, size }; \ struct REGISTER_HASHER_NAME(cls) { REGISTER_HASHER_NAME(cls)() { RegisterHasher(&g_HasherInfo); }}; \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Common/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Common/StdAfx.h 2013-11-24 12:55:03.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/StreamBinder.cpp 7zip-23.01+dfsg/CPP/7zip/Common/StreamBinder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/StreamBinder.cpp 2021-06-05 11:25:17.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/StreamBinder.cpp 2023-04-05 14:00:00.000000000 +0000 @@ -6,51 +6,44 @@ #include "StreamBinder.h" -class CBinderInStream: - public ISequentialInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CBinderInStream + , ISequentialInStream +) CStreamBinder *_binder; public: - MY_UNKNOWN_IMP1(ISequentialInStream) - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); ~CBinderInStream() { _binder->CloseRead_CallOnce(); } CBinderInStream(CStreamBinder *binder): _binder(binder) {} }; -STDMETHODIMP CBinderInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CBinderInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { return _binder->Read(data, size, processedSize); } -class CBinderOutStream: - public ISequentialOutStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_COM_1( + CBinderOutStream + , ISequentialOutStream +) CStreamBinder *_binder; public: - MY_UNKNOWN_IMP1(ISequentialOutStream) - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); ~CBinderOutStream() { _binder->CloseWrite(); } CBinderOutStream(CStreamBinder *binder): _binder(binder) {} }; -STDMETHODIMP CBinderOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CBinderOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { return _binder->Write(data, size, processedSize); } -static HRESULT Event__Create_or_Reset(NWindows::NSynchronization::CAutoResetEvent &event) +static HRESULT Event_Create_or_Reset(NWindows::NSynchronization::CAutoResetEvent &event) { - WRes wres; - if (event.IsCreated()) - wres = event.Reset(); - else - wres = event.Create(); + const WRes wres = event.CreateIfNotCreated_Reset(); return HRESULT_FROM_WIN32(wres); } HRESULT CStreamBinder::Create_ReInit() { - RINOK(Event__Create_or_Reset(_canRead_Event)); - // RINOK(Event__Create_or_Reset(_canWrite_Event)); + RINOK(Event_Create_or_Reset(_canRead_Event)) + // RINOK(Event_Create_or_Reset(_canWrite_Event)) // _canWrite_Semaphore.Close(); // we need at least 3 items of maxCount: 1 for normal unlock in Read(), 2 items for unlock in CloseRead_CallOnce() diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/StreamBinder.h 7zip-23.01+dfsg/CPP/7zip/Common/StreamBinder.h --- 7zip-22.01+dfsg/CPP/7zip/Common/StreamBinder.h 2020-11-27 11:36:31.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/StreamBinder.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // StreamBinder.h -#ifndef __STREAM_BINDER_H -#define __STREAM_BINDER_H +#ifndef ZIP7_INC_STREAM_BINDER_H +#define ZIP7_INC_STREAM_BINDER_H #include "../../Windows/Synchronization.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/StreamObjects.cpp 7zip-23.01+dfsg/CPP/7zip/Common/StreamObjects.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/StreamObjects.cpp 2021-01-24 16:05:28.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/StreamObjects.cpp 2023-04-05 14:00:00.000000000 +0000 @@ -2,13 +2,11 @@ #include "StdAfx.h" -#include - #include "../../../C/Alloc.h" #include "StreamObjects.h" -STDMETHODIMP CBufferInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CBufferInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -26,7 +24,7 @@ return S_OK; } -STDMETHODIMP CBufferInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CBufferInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { @@ -43,7 +41,7 @@ return S_OK; } -STDMETHODIMP CBufInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CBufInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -61,7 +59,7 @@ return S_OK; } -STDMETHODIMP CBufInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CBufInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { @@ -99,8 +97,8 @@ void CByteDynBuffer::Free() throw() { - free(_buf); - _buf = 0; + MyFree(_buf); + _buf = NULL; _capacity = 0; } @@ -108,11 +106,10 @@ { if (cap <= _capacity) return true; - size_t delta = _capacity / 4; - size_t cap2 = _capacity + delta; + const size_t cap2 = _capacity + _capacity / 4; if (cap < cap2) cap = cap2; - Byte *buf = (Byte *)realloc(_buf, cap); + Byte *buf = (Byte *)MyRealloc(_buf, cap); if (!buf) return false; _buf = buf; @@ -135,7 +132,7 @@ dest.CopyFrom((const Byte *)_buffer, _size); } -STDMETHODIMP CDynBufSeqOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CDynBufSeqOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -151,7 +148,7 @@ return S_OK; } -STDMETHODIMP CBufPtrSeqOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CBufPtrSeqOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { size_t rem = _size - _pos; if (rem > size) @@ -166,7 +163,7 @@ return (rem != 0 || size == 0) ? S_OK : E_FAIL; } -STDMETHODIMP CSequentialOutStreamSizeCount::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CSequentialOutStreamSizeCount::Write(const void *data, UInt32 size, UInt32 *processedSize)) { UInt32 realProcessedSize; HRESULT result = _stream->Write(data, size, &realProcessedSize); @@ -216,12 +213,12 @@ { _size = size; _pos = 0; - size_t numBlocks = (size_t)1 << _numBlocksLog; + const size_t numBlocks = (size_t)1 << _numBlocksLog; for (size_t i = 0; i < numBlocks; i++) _tags[i] = kEmptyTag; } -STDMETHODIMP CCachedInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CCachedInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -231,7 +228,7 @@ return S_OK; { - UInt64 rem = _size - _pos; + const UInt64 rem = _size - _pos; if (size > rem) size = (UInt32)rem; } @@ -245,12 +242,12 @@ if (_tags[cacheIndex] != cacheTag) { _tags[cacheIndex] = kEmptyTag; - UInt64 remInBlock = _size - (cacheTag << _blockSizeLog); + const UInt64 remInBlock = _size - (cacheTag << _blockSizeLog); size_t blockSize = (size_t)1 << _blockSizeLog; if (blockSize > remInBlock) blockSize = (size_t)remInBlock; - RINOK(ReadBlock(cacheTag, p, blockSize)); + RINOK(ReadBlock(cacheTag, p, blockSize)) _tags[cacheIndex] = cacheTag; } @@ -275,7 +272,7 @@ } -STDMETHODIMP CCachedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CCachedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/StreamObjects.h 7zip-23.01+dfsg/CPP/7zip/Common/StreamObjects.h --- 7zip-22.01+dfsg/CPP/7zip/Common/StreamObjects.h 2019-08-27 18:12:44.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/StreamObjects.h 2023-04-05 14:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // StreamObjects.h -#ifndef __STREAM_OBJECTS_H -#define __STREAM_OBJECTS_H +#ifndef ZIP7_INC_STREAM_OBJECTS_H +#define ZIP7_INC_STREAM_OBJECTS_H #include "../../Common/MyBuffer.h" #include "../../Common/MyCom.h" @@ -9,35 +9,27 @@ #include "../IStream.h" -class CBufferInStream: - public IInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_IInStream( + CBufferInStream +) UInt64 _pos; public: CByteBuffer Buf; void Init() { _pos = 0; } - - MY_UNKNOWN_IMP2(ISequentialInStream, IInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); }; -struct CReferenceBuf: - public IUnknown, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_0( + CReferenceBuf +) +public: CByteBuffer Buf; - MY_UNKNOWN_IMP }; -class CBufInStream: - public IInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_IInStream( + CBufInStream +) const Byte *_data; UInt64 _pos; size_t _size; @@ -52,9 +44,8 @@ } void Init(CReferenceBuf *ref) { Init(ref->Buf, ref->Buf.Size(), ref); } - MY_UNKNOWN_IMP2(ISequentialInStream, IInStream) - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); + // Seek() is allowed here. So reading order could be changed + bool WasFinished() const { return _pos == _size; } }; @@ -64,13 +55,13 @@ { Create_BufInStream_WithNewBuffer(buf, buf.Size(), stream); } -class CByteDynBuffer +class CByteDynBuffer Z7_final { size_t _capacity; Byte *_buf; - CLASS_NO_COPY(CByteDynBuffer); + Z7_CLASS_NO_COPY(CByteDynBuffer) public: - CByteDynBuffer(): _capacity(0), _buf(NULL) {}; + CByteDynBuffer(): _capacity(0), _buf(NULL) {} // there is no copy constructor. So don't copy this object. ~CByteDynBuffer() { Free(); } void Free() throw(); @@ -81,10 +72,10 @@ }; -class CDynBufSeqOutStream: - public ISequentialOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CDynBufSeqOutStream + , ISequentialOutStream +) CByteDynBuffer _buffer; size_t _size; public: @@ -95,16 +86,13 @@ void CopyToBuffer(CByteBuffer &dest) const; Byte *GetBufPtrForWriting(size_t addSize); void UpdateSize(size_t addSize) { _size += addSize; } - - MY_UNKNOWN_IMP1(ISequentialOutStream) - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); }; -class CBufPtrSeqOutStream: - public ISequentialOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CBufPtrSeqOutStream + , ISequentialOutStream +) Byte *_buffer; size_t _size; size_t _pos; @@ -116,25 +104,19 @@ _size = size; } size_t GetPos() const { return _pos; } - - MY_UNKNOWN_IMP1(ISequentialOutStream) - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); }; -class CSequentialOutStreamSizeCount: - public ISequentialOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CSequentialOutStreamSizeCount + , ISequentialOutStream +) CMyComPtr _stream; UInt64 _size; public: void SetStream(ISequentialOutStream *stream) { _stream = stream; } void Init() { _size = 0; } UInt64 GetSize() const { return _size; } - - MY_UNKNOWN_IMP1(ISequentialOutStream) - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); }; @@ -142,6 +124,8 @@ public IInStream, public CMyUnknownImp { + Z7_IFACES_IMP_UNK_2(ISequentialInStream, IInStream) + UInt64 *_tags; Byte *_data; size_t _dataSize; @@ -153,14 +137,10 @@ virtual HRESULT ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize) = 0; public: CCachedInStream(): _tags(NULL), _data(NULL) {} - virtual ~CCachedInStream() { Free(); } // the destructor must be virtual (release calls it) !!! + virtual ~CCachedInStream() { Free(); } // the destructor must be virtual (Release() calls it) !!! void Free() throw(); bool Alloc(unsigned blockSizeLog, unsigned numBlocksLog) throw(); void Init(UInt64 size) throw(); - - MY_UNKNOWN_IMP2(ISequentialInStream, IInStream) - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/StreamUtils.cpp 7zip-23.01+dfsg/CPP/7zip/Common/StreamUtils.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/StreamUtils.cpp 2014-08-08 11:40:36.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/StreamUtils.cpp 2023-03-26 18:00:00.000000000 +0000 @@ -2,10 +2,55 @@ #include "StdAfx.h" +#include "../../Common/MyCom.h" + #include "StreamUtils.h" static const UInt32 kBlockSize = ((UInt32)1 << 31); + +HRESULT InStream_SeekToBegin(IInStream *stream) throw() +{ + return InStream_SeekSet(stream, 0); +} + + +HRESULT InStream_AtBegin_GetSize(IInStream *stream, UInt64 &sizeRes) throw() +{ +#ifdef _WIN32 + { + Z7_DECL_CMyComPtr_QI_FROM( + IStreamGetSize, + streamGetSize, stream) + if (streamGetSize && streamGetSize->GetSize(&sizeRes) == S_OK) + return S_OK; + } +#endif + const HRESULT hres = InStream_GetSize_SeekToEnd(stream, sizeRes); + const HRESULT hres2 = InStream_SeekToBegin(stream); + return hres != S_OK ? hres : hres2; +} + + +HRESULT InStream_GetPos_GetSize(IInStream *stream, UInt64 &curPosRes, UInt64 &sizeRes) throw() +{ + RINOK(InStream_GetPos(stream, curPosRes)) +#ifdef _WIN32 + { + Z7_DECL_CMyComPtr_QI_FROM( + IStreamGetSize, + streamGetSize, stream) + if (streamGetSize && streamGetSize->GetSize(&sizeRes) == S_OK) + return S_OK; + } +#endif + const HRESULT hres = InStream_GetSize_SeekToEnd(stream, sizeRes); + const HRESULT hres2 = InStream_SeekSet(stream, curPosRes); + return hres != S_OK ? hres : hres2; +} + + + HRESULT ReadStream(ISequentialInStream *stream, void *data, size_t *processedSize) throw() { size_t size = *processedSize; @@ -18,7 +63,7 @@ *processedSize += processedSizeLoc; data = (void *)((Byte *)data + processedSizeLoc); size -= processedSizeLoc; - RINOK(res); + RINOK(res) if (processedSizeLoc == 0) return S_OK; } @@ -28,14 +73,14 @@ HRESULT ReadStream_FALSE(ISequentialInStream *stream, void *data, size_t size) throw() { size_t processedSize = size; - RINOK(ReadStream(stream, data, &processedSize)); + RINOK(ReadStream(stream, data, &processedSize)) return (size == processedSize) ? S_OK : S_FALSE; } HRESULT ReadStream_FAIL(ISequentialInStream *stream, void *data, size_t size) throw() { size_t processedSize = size; - RINOK(ReadStream(stream, data, &processedSize)); + RINOK(ReadStream(stream, data, &processedSize)) return (size == processedSize) ? S_OK : E_FAIL; } @@ -48,7 +93,7 @@ HRESULT res = stream->Write(data, curSize, &processedSizeLoc); data = (const void *)((const Byte *)data + processedSizeLoc); size -= processedSizeLoc; - RINOK(res); + RINOK(res) if (processedSizeLoc == 0) return E_FAIL; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/StreamUtils.h 7zip-23.01+dfsg/CPP/7zip/Common/StreamUtils.h --- 7zip-22.01+dfsg/CPP/7zip/Common/StreamUtils.h 2013-01-28 19:15:29.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/StreamUtils.h 2023-01-19 09:00:00.000000000 +0000 @@ -1,10 +1,28 @@ // StreamUtils.h -#ifndef __STREAM_UTILS_H -#define __STREAM_UTILS_H +#ifndef ZIP7_INC_STREAM_UTILS_H +#define ZIP7_INC_STREAM_UTILS_H #include "../IStream.h" +inline HRESULT InStream_SeekSet(IInStream *stream, UInt64 offset) throw() + { return stream->Seek((Int64)offset, STREAM_SEEK_SET, NULL); } +inline HRESULT InStream_GetPos(IInStream *stream, UInt64 &curPosRes) throw() + { return stream->Seek(0, STREAM_SEEK_CUR, &curPosRes); } +inline HRESULT InStream_GetSize_SeekToEnd(IInStream *stream, UInt64 &sizeRes) throw() + { return stream->Seek(0, STREAM_SEEK_END, &sizeRes); } + +HRESULT InStream_SeekToBegin(IInStream *stream) throw(); +HRESULT InStream_AtBegin_GetSize(IInStream *stream, UInt64 &size) throw(); +HRESULT InStream_GetPos_GetSize(IInStream *stream, UInt64 &curPosRes, UInt64 &sizeRes) throw(); + +inline HRESULT InStream_GetSize_SeekToBegin(IInStream *stream, UInt64 &sizeRes) throw() +{ + RINOK(InStream_SeekToBegin(stream)) + return InStream_AtBegin_GetSize(stream, sizeRes); +} + + HRESULT ReadStream(ISequentialInStream *stream, void *data, size_t *size) throw(); HRESULT ReadStream_FALSE(ISequentialInStream *stream, void *data, size_t size) throw(); HRESULT ReadStream_FAIL(ISequentialInStream *stream, void *data, size_t size) throw(); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/UniqBlocks.h 7zip-23.01+dfsg/CPP/7zip/Common/UniqBlocks.h --- 7zip-22.01+dfsg/CPP/7zip/Common/UniqBlocks.h 2022-04-02 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/UniqBlocks.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // UniqBlocks.h -#ifndef __UNIQ_BLOCKS_H -#define __UNIQ_BLOCKS_H +#ifndef ZIP7_INC_UNIQ_BLOCKS_H +#define ZIP7_INC_UNIQ_BLOCKS_H #include "../../Common/MyBuffer.h" #include "../../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/VirtThread.cpp 7zip-23.01+dfsg/CPP/7zip/Common/VirtThread.cpp --- 7zip-22.01+dfsg/CPP/7zip/Common/VirtThread.cpp 2021-01-24 16:07:22.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/VirtThread.cpp 2023-03-21 07:00:00.000000000 +0000 @@ -11,7 +11,7 @@ CVirtThread *t = (CVirtThread *)p; t->StartEvent.Lock(); if (t->Exit) - return 0; + return THREAD_FUNC_RET_ZERO; t->Execute(); t->FinishedEvent.Set(); } @@ -19,8 +19,8 @@ WRes CVirtThread::Create() { - RINOK_WRes(StartEvent.CreateIfNotCreated_Reset()); - RINOK_WRes(FinishedEvent.CreateIfNotCreated_Reset()); + RINOK_WRes(StartEvent.CreateIfNotCreated_Reset()) + RINOK_WRes(FinishedEvent.CreateIfNotCreated_Reset()) // StartEvent.Reset(); // FinishedEvent.Reset(); Exit = false; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Common/VirtThread.h 7zip-23.01+dfsg/CPP/7zip/Common/VirtThread.h --- 7zip-22.01+dfsg/CPP/7zip/Common/VirtThread.h 2020-11-27 13:09:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Common/VirtThread.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // VirtThread.h -#ifndef __VIRT_THREAD_H -#define __VIRT_THREAD_H +#ifndef ZIP7_INC_VIRT_THREAD_H +#define ZIP7_INC_VIRT_THREAD_H #include "../../Windows/Synchronization.h" #include "../../Windows/Thread.h" @@ -13,7 +13,7 @@ NWindows::CThread Thread; bool Exit; - ~CVirtThread() { WaitThreadFinish(); } + virtual ~CVirtThread() { WaitThreadFinish(); } void WaitThreadFinish(); // call it in destructor of child class ! WRes Create(); WRes Start(); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/Bcj2Coder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/Bcj2Coder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/Bcj2Coder.cpp 2021-01-25 11:14:40.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/Bcj2Coder.cpp 2023-03-24 10:00:00.000000000 +0000 @@ -2,6 +2,8 @@ #include "StdAfx.h" +// #include + #include "../../../C/Alloc.h" #include "../Common/StreamUtils.h" @@ -13,42 +15,47 @@ CBaseCoder::CBaseCoder() { - for (int i = 0; i < BCJ2_NUM_STREAMS + 1; i++) + for (unsigned i = 0; i < BCJ2_NUM_STREAMS + 1; i++) { _bufs[i] = NULL; - _bufsCurSizes[i] = 0; - _bufsNewSizes[i] = (1 << 18); + _bufsSizes[i] = 0; + _bufsSizes_New[i] = (1 << 18); } } CBaseCoder::~CBaseCoder() { - for (int i = 0; i < BCJ2_NUM_STREAMS + 1; i++) + for (unsigned i = 0; i < BCJ2_NUM_STREAMS + 1; i++) ::MidFree(_bufs[i]); } HRESULT CBaseCoder::Alloc(bool allocForOrig) { - unsigned num = allocForOrig ? BCJ2_NUM_STREAMS + 1 : BCJ2_NUM_STREAMS; + const unsigned num = allocForOrig ? BCJ2_NUM_STREAMS + 1 : BCJ2_NUM_STREAMS; for (unsigned i = 0; i < num; i++) { - UInt32 newSize = _bufsNewSizes[i]; - const UInt32 kMinBufSize = 1; - if (newSize < kMinBufSize) - newSize = kMinBufSize; - if (!_bufs[i] || newSize != _bufsCurSizes[i]) + UInt32 size = _bufsSizes_New[i]; + /* buffer sizes for BCJ2_STREAM_CALL and BCJ2_STREAM_JUMP streams + must be aligned for 4 */ + size &= ~(UInt32)3; + const UInt32 kMinBufSize = 4; + if (size < kMinBufSize) + size = kMinBufSize; + // size = 4 * 100; // for debug + // if (BCJ2_IS_32BIT_STREAM(i) == 1) size = 4 * 1; // for debug + if (!_bufs[i] || size != _bufsSizes[i]) { if (_bufs[i]) { ::MidFree(_bufs[i]); - _bufs[i] = 0; + _bufs[i] = NULL; } - _bufsCurSizes[i] = 0; - Byte *buf = (Byte *)::MidAlloc(newSize); - _bufs[i] = buf; + _bufsSizes[i] = 0; + Byte *buf = (Byte *)::MidAlloc(size); if (!buf) return E_OUTOFMEMORY; - _bufsCurSizes[i] = newSize; + _bufs[i] = buf; + _bufsSizes[i] = size; } } return S_OK; @@ -56,23 +63,30 @@ -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY -CEncoder::CEncoder(): _relatLim(BCJ2_RELAT_LIMIT) {} +CEncoder::CEncoder(): + _relatLim(BCJ2_ENC_RELAT_LIMIT_DEFAULT) + // , _excludeRangeBits(BCJ2_RELAT_EXCLUDE_NUM_BITS) + {} CEncoder::~CEncoder() {} -STDMETHODIMP CEncoder::SetInBufSize(UInt32, UInt32 size) { _bufsNewSizes[BCJ2_NUM_STREAMS] = size; return S_OK; } -STDMETHODIMP CEncoder::SetOutBufSize(UInt32 streamIndex, UInt32 size) { _bufsNewSizes[streamIndex] = size; return S_OK; } +Z7_COM7F_IMF(CEncoder::SetInBufSize(UInt32, UInt32 size)) + { _bufsSizes_New[BCJ2_NUM_STREAMS] = size; return S_OK; } +Z7_COM7F_IMF(CEncoder::SetOutBufSize(UInt32 streamIndex, UInt32 size)) + { _bufsSizes_New[streamIndex] = size; return S_OK; } -STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps) +Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps)) { - UInt32 relatLim = BCJ2_RELAT_LIMIT; - + UInt32 relatLim = BCJ2_ENC_RELAT_LIMIT_DEFAULT; + // UInt32 excludeRangeBits = BCJ2_RELAT_EXCLUDE_NUM_BITS; for (UInt32 i = 0; i < numProps; i++) { const PROPVARIANT &prop = props[i]; - PROPID propID = propIDs[i]; - if (propID >= NCoderPropID::kReduceSize) + const PROPID propID = propIDs[i]; + if (propID >= NCoderPropID::kReduceSize + // && propID != NCoderPropID::kHashBits + ) continue; switch (propID) { @@ -87,225 +101,310 @@ relatLim = (UInt32)1 << v; break; } + case NCoderPropID::kHashBits: + { + if (prop.vt != VT_UI4) + return E_INVALIDARG; + UInt32 v = prop.ulVal; + if (v > 31) + return E_INVALIDARG; + excludeRangeBits = v; + break; + } */ case NCoderPropID::kDictionarySize: { if (prop.vt != VT_UI4) return E_INVALIDARG; relatLim = prop.ulVal; - if (relatLim > ((UInt32)1 << 31)) + if (relatLim > BCJ2_ENC_RELAT_LIMIT_MAX) return E_INVALIDARG; break; } - case NCoderPropID::kNumThreads: - continue; case NCoderPropID::kLevel: continue; - default: return E_INVALIDARG; } } - _relatLim = relatLim; - + // _excludeRangeBits = excludeRangeBits; return S_OK; } -HRESULT CEncoder::CodeReal(ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams, +HRESULT CEncoder::CodeReal( + ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams, ISequentialOutStream * const *outStreams, const UInt64 * const * /* outSizes */, UInt32 numOutStreams, ICompressProgressInfo *progress) { if (numInStreams != 1 || numOutStreams != BCJ2_NUM_STREAMS) return E_INVALIDARG; - RINOK(Alloc()); + RINOK(Alloc()) - UInt32 fileSize_for_Conv = 0; + CBcj2Enc_ip_unsigned fileSize_minus1 = BCJ2_ENC_FileSizeField_UNLIMITED; if (inSizes && inSizes[0]) { - UInt64 inSize = *inSizes[0]; - if (inSize <= BCJ2_FileSize_MAX) - fileSize_for_Conv = (UInt32)inSize; + const UInt64 inSize = *inSizes[0]; + #ifdef BCJ2_ENC_FileSize_MAX + if (inSize <= BCJ2_ENC_FileSize_MAX) + #endif + fileSize_minus1 = BCJ2_ENC_GET_FileSizeField_VAL_FROM_FileSize(inSize); } - CMyComPtr getSubStreamSize; - inStreams[0]->QueryInterface(IID_ICompressGetSubStreamSize, (void **)&getSubStreamSize); + Z7_DECL_CMyComPtr_QI_FROM(ICompressGetSubStreamSize, getSubStreamSize, inStreams[0]) CBcj2Enc enc; - enc.src = _bufs[BCJ2_NUM_STREAMS]; enc.srcLim = enc.src; - { - for (int i = 0; i < BCJ2_NUM_STREAMS; i++) + for (unsigned i = 0; i < BCJ2_NUM_STREAMS; i++) { enc.bufs[i] = _bufs[i]; - enc.lims[i] = _bufs[i] + _bufsCurSizes[i]; + enc.lims[i] = _bufs[i] + _bufsSizes[i]; } } - - size_t numBytes_in_ReadBuf = 0; - UInt64 prevProgress = 0; - UInt64 totalStreamRead = 0; // size read from InputStream - UInt64 currentInPos = 0; // data that was processed, it doesn't include data in input buffer and data in enc.temp - UInt64 outSizeRc = 0; - Bcj2Enc_Init(&enc); - - enc.fileIp = 0; - enc.fileSize = fileSize_for_Conv; - + enc.fileIp64 = 0; + enc.fileSize64_minus1 = fileSize_minus1; enc.relatLimit = _relatLim; - + // enc.relatExcludeBits = _excludeRangeBits; enc.finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE; - bool needSubSize = false; - UInt64 subStreamIndex = 0; - UInt64 subStreamStartPos = 0; + // Varibales that correspond processed data in input stream: + UInt64 inPos_without_Temp = 0; // it doesn't include data in enc.temp[] + UInt64 inPos_with_Temp = 0; // it includes data in enc.temp[] + + UInt64 prevProgress = 0; + UInt64 totalRead = 0; // size read from input stream + UInt64 outSizeRc = 0; + UInt64 subStream_Index = 0; + UInt64 subStream_StartPos = 0; // global start offset of subStreams[subStream_Index] + UInt64 subStream_Size = 0; + const Byte *srcLim_Read = _bufs[BCJ2_NUM_STREAMS]; bool readWasFinished = false; + bool isAccurate = false; + bool wasUnknownSize = false; for (;;) { - if (needSubSize && getSubStreamSize) - { - enc.fileIp = 0; - enc.fileSize = fileSize_for_Conv; - enc.finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE; - - for (;;) - { - UInt64 subStreamSize = 0; - HRESULT result = getSubStreamSize->GetSubStreamSize(subStreamIndex, &subStreamSize); - needSubSize = false; - - if (result == S_OK) - { - UInt64 newEndPos = subStreamStartPos + subStreamSize; - - bool isAccurateEnd = (newEndPos < totalStreamRead || - (newEndPos <= totalStreamRead && readWasFinished)); - - if (newEndPos <= currentInPos && isAccurateEnd) - { - subStreamStartPos = newEndPos; - subStreamIndex++; - continue; - } - - enc.srcLim = _bufs[BCJ2_NUM_STREAMS] + numBytes_in_ReadBuf; - - if (isAccurateEnd) - { - // data in enc.temp is possible here - size_t rem = (size_t)(totalStreamRead - newEndPos); - - /* Pos_of(enc.src) <= old newEndPos <= newEndPos - in another case, it's fail in some code */ - if ((size_t)(enc.srcLim - enc.src) < rem) - return E_FAIL; - - enc.srcLim -= rem; - enc.finishMode = BCJ2_ENC_FINISH_MODE_END_BLOCK; - } - - if (subStreamSize <= BCJ2_FileSize_MAX) - { - enc.fileIp = enc.ip + (UInt32)(subStreamStartPos - currentInPos); - enc.fileSize = (UInt32)subStreamSize; - } - break; - } - - if (result == S_FALSE) - break; - if (result == E_NOTIMPL) - { - getSubStreamSize.Release(); - break; - } - return result; - } - } - - if (readWasFinished && totalStreamRead - currentInPos == Bcj2Enc_Get_InputData_Size(&enc)) + if (readWasFinished && enc.srcLim == srcLim_Read) enc.finishMode = BCJ2_ENC_FINISH_MODE_END_STREAM; + // for debug: + // for (int y=0;y<100;y++) { CBcj2Enc enc2 = enc; Bcj2Enc_Encode(&enc2); } + Bcj2Enc_Encode(&enc); - currentInPos = totalStreamRead - numBytes_in_ReadBuf + (size_t)(enc.src - _bufs[BCJ2_NUM_STREAMS]) - enc.tempPos; + inPos_with_Temp = totalRead - (size_t)(srcLim_Read - enc.src); + inPos_without_Temp = inPos_with_Temp - Bcj2Enc_Get_AvailInputSize_in_Temp(&enc); + // if (inPos_without_Temp != enc.ip64) return E_FAIL; + if (Bcj2Enc_IsFinished(&enc)) break; if (enc.state < BCJ2_NUM_STREAMS) { + if (enc.bufs[enc.state] != enc.lims[enc.state]) + return E_FAIL; const size_t curSize = (size_t)(enc.bufs[enc.state] - _bufs[enc.state]); // printf("Write stream = %2d %6d\n", enc.state, curSize); - RINOK(WriteStream(outStreams[enc.state], _bufs[enc.state], curSize)); + RINOK(WriteStream(outStreams[enc.state], _bufs[enc.state], curSize)) if (enc.state == BCJ2_STREAM_RC) outSizeRc += curSize; - enc.bufs[enc.state] = _bufs[enc.state]; - enc.lims[enc.state] = _bufs[enc.state] + _bufsCurSizes[enc.state]; + enc.lims[enc.state] = _bufs[enc.state] + _bufsSizes[enc.state]; } - else if (enc.state != BCJ2_ENC_STATE_ORIG) - return E_FAIL; else { - needSubSize = true; + if (enc.state != BCJ2_ENC_STATE_ORIG) + return E_FAIL; + // (enc.state == BCJ2_ENC_STATE_ORIG) + if (enc.src != enc.srcLim) + return E_FAIL; + if (enc.finishMode != BCJ2_ENC_FINISH_MODE_CONTINUE + && Bcj2Enc_Get_AvailInputSize_in_Temp(&enc) != 0) + return E_FAIL; + + if (enc.src == srcLim_Read) + { + if (readWasFinished) + return E_FAIL; + UInt32 curSize = _bufsSizes[BCJ2_NUM_STREAMS]; + RINOK(inStreams[0]->Read(_bufs[BCJ2_NUM_STREAMS], curSize, &curSize)) + // printf("Read %6u bytes\n", curSize); + if (curSize == 0) + readWasFinished = true; + totalRead += curSize; + enc.src = _bufs[BCJ2_NUM_STREAMS]; + srcLim_Read = _bufs[BCJ2_NUM_STREAMS] + curSize; + } + enc.srcLim = srcLim_Read; - if (numBytes_in_ReadBuf != (size_t)(enc.src - _bufs[BCJ2_NUM_STREAMS])) + if (getSubStreamSize) { - enc.srcLim = _bufs[BCJ2_NUM_STREAMS] + numBytes_in_ReadBuf; - continue; - } + /* we set base default conversions options that will be used, + if subStream related options will be not OK */ + enc.fileIp64 = 0; + enc.fileSize64_minus1 = fileSize_minus1; + for (;;) + { + UInt64 nextPos; + if (isAccurate) + nextPos = subStream_StartPos + subStream_Size; + else + { + const HRESULT hres = getSubStreamSize->GetSubStreamSize(subStream_Index, &subStream_Size); + if (hres != S_OK) + { + enc.finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE; + /* if sub-stream size is unknown, we use default settings. + We still can recover to normal mode for next sub-stream, + if GetSubStreamSize() will return S_OK, when current + sub-stream will be finished. + */ + if (hres == S_FALSE) + { + wasUnknownSize = true; + break; + } + if (hres == E_NOTIMPL) + { + getSubStreamSize.Release(); + break; + } + return hres; + } + // printf("GetSubStreamSize %6u : %6u \n", (unsigned)subStream_Index, (unsigned)subStream_Size); + nextPos = subStream_StartPos + subStream_Size; + if ((Int64)subStream_Size == -1) + { + /* it's not expected, but (-1) can mean unknown size. */ + enc.finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE; + wasUnknownSize = true; + break; + } + if (nextPos < subStream_StartPos) + return E_FAIL; + isAccurate = + (nextPos < totalRead + || (nextPos <= totalRead && readWasFinished)); + } + + /* (nextPos) is estimated end position of current sub_stream. + But only (totalRead) and (readWasFinished) values + can confirm that this estimated end position is accurate. + That end position is accurate, if it can't be changed in + further calls of GetSubStreamSize() */ + + /* (nextPos < inPos_with_Temp) is unexpected case here, that we + can get if from some incorrect ICompressGetSubStreamSize object, + where new GetSubStreamSize() call returns smaller size than + confirmed by Read() size from previous GetSubStreamSize() call. + */ + if (nextPos < inPos_with_Temp) + { + if (wasUnknownSize) + { + /* that case can be complicated for recovering. + so we disable sub-streams requesting. */ + enc.finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE; + getSubStreamSize.Release(); + break; + } + return E_FAIL; // to stop after failure + } - if (readWasFinished) - continue; - - numBytes_in_ReadBuf = 0; - enc.src = _bufs[BCJ2_NUM_STREAMS]; - enc.srcLim = _bufs[BCJ2_NUM_STREAMS]; - - UInt32 curSize = _bufsCurSizes[BCJ2_NUM_STREAMS]; - RINOK(inStreams[0]->Read(_bufs[BCJ2_NUM_STREAMS], curSize, &curSize)); + if (nextPos <= inPos_with_Temp) + { + // (nextPos == inPos_with_Temp) + /* CBcj2Enc encoder requires to finish each [non-empty] block (sub-stream) + with BCJ2_ENC_FINISH_MODE_END_BLOCK + or with BCJ2_ENC_FINISH_MODE_END_STREAM for last block: + And we send data of new block to CBcj2Enc, only if previous block was finished. + So we switch to next sub-stream if after Bcj2Enc_Encode() call we have + && (enc.finishMode != BCJ2_ENC_FINISH_MODE_CONTINUE) + && (nextPos == inPos_with_Temp) + && (enc.state == BCJ2_ENC_STATE_ORIG) + */ + if (enc.finishMode != BCJ2_ENC_FINISH_MODE_CONTINUE) + { + /* subStream_StartPos is increased only here. + (subStream_StartPos == inPos_with_Temp) : at start + (subStream_StartPos <= inPos_with_Temp) : will be later + */ + subStream_StartPos = nextPos; + subStream_Size = 0; + wasUnknownSize = false; + subStream_Index++; + isAccurate = false; + // we don't change finishMode here + continue; + } + } + + enc.finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE; + /* for (!isAccurate) case: + (totalRead <= real_end_of_subStream) + so we can use BCJ2_ENC_FINISH_MODE_CONTINUE up to (totalRead) + // we don't change settings at the end of substream, if settings were unknown, + */ + + /* if (wasUnknownSize) then we can't trust size of that sub-stream. + so we use default settings instead */ + if (!wasUnknownSize) + #ifdef BCJ2_ENC_FileSize_MAX + if (subStream_Size <= BCJ2_ENC_FileSize_MAX) + #endif + { + enc.fileIp64 = + (CBcj2Enc_ip_unsigned)( + (CBcj2Enc_ip_signed)enc.ip64 + + (CBcj2Enc_ip_signed)(subStream_StartPos - inPos_without_Temp)); + Bcj2Enc_SET_FileSize(&enc, subStream_Size) + } - // printf("Read %6d bytes\n", curSize); - if (curSize == 0) - { - readWasFinished = true; - continue; - } + if (isAccurate) + { + /* (real_end_of_subStream == nextPos <= totalRead) + So we can use BCJ2_ENC_FINISH_MODE_END_BLOCK up to (nextPos). */ + const size_t rem = (size_t)(totalRead - nextPos); + if ((size_t)(enc.srcLim - enc.src) < rem) + return E_FAIL; + enc.srcLim -= rem; + enc.finishMode = BCJ2_ENC_FINISH_MODE_END_BLOCK; + } - numBytes_in_ReadBuf = curSize; - totalStreamRead += numBytes_in_ReadBuf; - enc.srcLim = _bufs[BCJ2_NUM_STREAMS] + numBytes_in_ReadBuf; + break; + } // for() loop + } // getSubStreamSize } - if (progress && currentInPos - prevProgress >= (1 << 20)) + if (progress && inPos_without_Temp - prevProgress >= (1 << 22)) { - const UInt64 outSize2 = currentInPos + outSizeRc + (size_t)(enc.bufs[BCJ2_STREAM_RC] - enc.bufs[BCJ2_STREAM_RC]); - prevProgress = currentInPos; - // printf("progress %8d, %8d\n", (int)inSize2, (int)outSize2); - RINOK(progress->SetRatioInfo(¤tInPos, &outSize2)); + prevProgress = inPos_without_Temp; + const UInt64 outSize2 = inPos_without_Temp + outSizeRc + + (size_t)(enc.bufs[BCJ2_STREAM_RC] - _bufs[BCJ2_STREAM_RC]); + // printf("progress %8u, %8u\n", (unsigned)inSize2, (unsigned)outSize2); + RINOK(progress->SetRatioInfo(&inPos_without_Temp, &outSize2)) } } - for (int i = 0; i < BCJ2_NUM_STREAMS; i++) + for (unsigned i = 0; i < BCJ2_NUM_STREAMS; i++) { - RINOK(WriteStream(outStreams[i], _bufs[i], (size_t)(enc.bufs[i] - _bufs[i]))); + RINOK(WriteStream(outStreams[i], _bufs[i], (size_t)(enc.bufs[i] - _bufs[i]))) } - - // if (currentInPos != subStreamStartPos + subStreamSize) return E_FAIL; - + // if (inPos_without_Temp != subStream_StartPos + subStream_Size) return E_FAIL; return S_OK; } -STDMETHODIMP CEncoder::Code(ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams, + +Z7_COM7F_IMF(CEncoder::Code( + ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams, ISequentialOutStream * const *outStreams, const UInt64 * const *outSizes, UInt32 numOutStreams, - ICompressProgressInfo *progress) + ICompressProgressInfo *progress)) { try { @@ -321,141 +420,170 @@ -STDMETHODIMP CDecoder::SetInBufSize(UInt32 streamIndex, UInt32 size) { _bufsNewSizes[streamIndex] = size; return S_OK; } -STDMETHODIMP CDecoder::SetOutBufSize(UInt32 , UInt32 size) { _bufsNewSizes[BCJ2_NUM_STREAMS] = size; return S_OK; } - -CDecoder::CDecoder(): _finishMode(false), _outSizeDefined(false), _outSize(0) +CDecoder::CDecoder(): + _finishMode(false) +#ifndef Z7_NO_READ_FROM_CODER + , _outSizeDefined(false) + , _outSize(0) + , _outSize_Processed(0) +#endif {} -STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode) +Z7_COM7F_IMF(CDecoder::SetInBufSize(UInt32 streamIndex, UInt32 size)) + { _bufsSizes_New[streamIndex] = size; return S_OK; } +Z7_COM7F_IMF(CDecoder::SetOutBufSize(UInt32, UInt32 size)) + { _bufsSizes_New[BCJ2_NUM_STREAMS] = size; return S_OK; } + +Z7_COM7F_IMF(CDecoder::SetFinishMode(UInt32 finishMode)) { _finishMode = (finishMode != 0); return S_OK; } -void CDecoder::InitCommon() +void CBaseDecoder::InitCommon() { + for (unsigned i = 0; i < BCJ2_NUM_STREAMS; i++) { - for (int i = 0; i < BCJ2_NUM_STREAMS; i++) - dec.lims[i] = dec.bufs[i] = _bufs[i]; + dec.lims[i] = dec.bufs[i] = _bufs[i]; + _readRes[i] = S_OK; + _extraSizes[i] = 0; + _readSizes[i] = 0; } + Bcj2Dec_Init(&dec); +} + +/* call ReadInStream() only after Bcj2Dec_Decode(). + input requirement: + (dec.state < BCJ2_NUM_STREAMS) +*/ +void CBaseDecoder::ReadInStream(ISequentialInStream *inStream) +{ + const unsigned state = dec.state; + UInt32 total; + { + Byte *buf = _bufs[state]; + const Byte *cur = dec.bufs[state]; + // if (cur != dec.lims[state]) throw 1; // unexpected case + dec.lims[state] = + dec.bufs[state] = buf; + total = (UInt32)_extraSizes[state]; + for (UInt32 i = 0; i < total; i++) + buf[i] = cur[i]; + } + + if (_readRes[state] != S_OK) + return; + + do + { + UInt32 curSize = _bufsSizes[state] - total; + // if (state == 0) curSize = 0; // for debug + // curSize = 7; // for debug + /* even if we have reached provided inSizes[state] limit, + we call Read() with (curSize != 0), because + we want the called handler of stream->Read() could + execute required Init/Flushing code even for empty stream. + In another way we could call Read() with (curSize == 0) for + finished streams, but some Read() handlers can ignore Read(size=0) calls. + */ + const HRESULT hres = inStream->Read(_bufs[state] + total, curSize, &curSize); + _readRes[state] = hres; + if (curSize == 0) + break; + _readSizes[state] += curSize; + total += curSize; + if (hres != S_OK) + break; + } + while (total < 4 && BCJ2_IS_32BIT_STREAM(state)); + + /* we exit from decoding loop here, if we can't + provide new data for input stream. + Usually it's normal exit after full stream decoding. */ + if (total == 0) + return; + + if (BCJ2_IS_32BIT_STREAM(state)) { - for (int i = 0; i < BCJ2_NUM_STREAMS; i++) + const unsigned extra = ((unsigned)total & 3); + _extraSizes[state] = extra; + if (total < 4) { - _extraReadSizes[i] = 0; - _inStreamsProcessed[i] = 0; - _readRes[i] = S_OK; + if (_readRes[state] == S_OK) + _readRes[state] = S_FALSE; // actually it's stream error. So maybe we need another error code. + return; } + total -= extra; } - - Bcj2Dec_Init(&dec); + + dec.lims[state] += total; // = _bufs[state] + total; } -HRESULT CDecoder::Code(ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams, + +Z7_COM7F_IMF(CDecoder::Code( + ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams, ISequentialOutStream * const *outStreams, const UInt64 * const *outSizes, UInt32 numOutStreams, - ICompressProgressInfo *progress) + ICompressProgressInfo *progress)) { if (numInStreams != BCJ2_NUM_STREAMS || numOutStreams != 1) return E_INVALIDARG; - RINOK(Alloc()); - + RINOK(Alloc()) InitCommon(); dec.destLim = dec.dest = _bufs[BCJ2_NUM_STREAMS]; - UInt64 outSizeProcessed = 0; + UInt64 outSizeWritten = 0; UInt64 prevProgress = 0; - HRESULT res = S_OK; + HRESULT hres_Crit = S_OK; // critical hres status (mostly from input stream reading) + HRESULT hres_Weak = S_OK; // first non-critical error code from input stream reading for (;;) { if (Bcj2Dec_Decode(&dec) != SZ_OK) - return S_FALSE; - + { + /* it's possible only at start (first 5 bytes in RC stream) */ + hres_Crit = S_FALSE; + break; + } if (dec.state < BCJ2_NUM_STREAMS) { - size_t totalRead = _extraReadSizes[dec.state]; + ReadInStream(inStreams[dec.state]); + const unsigned state = dec.state; + const HRESULT hres = _readRes[state]; + if (dec.lims[state] == _bufs[state]) { - Byte *buf = _bufs[dec.state]; - for (size_t i = 0; i < totalRead; i++) - buf[i] = dec.bufs[dec.state][i]; - dec.lims[dec.state] = - dec.bufs[dec.state] = buf; - } - - if (_readRes[dec.state] != S_OK) - { - res = _readRes[dec.state]; + // we break decoding, if there are no new data in input stream + hres_Crit = hres; break; } - - do - { - UInt32 curSize = _bufsCurSizes[dec.state] - (UInt32)totalRead; - /* - we want to call Read even even if size is 0 - if (inSizes && inSizes[dec.state]) - { - UInt64 rem = *inSizes[dec.state] - _inStreamsProcessed[dec.state]; - if (curSize > rem) - curSize = (UInt32)rem; - } - */ - - HRESULT res2 = inStreams[dec.state]->Read(_bufs[dec.state] + totalRead, curSize, &curSize); - _readRes[dec.state] = res2; - if (curSize == 0) - break; - _inStreamsProcessed[dec.state] += curSize; - totalRead += curSize; - if (res2 != S_OK) - break; - } - while (totalRead < 4 && BCJ2_IS_32BIT_STREAM(dec.state)); - - if (_readRes[dec.state] != S_OK) - res = _readRes[dec.state]; - - if (totalRead == 0) - break; - - // res == S_OK; - - if (BCJ2_IS_32BIT_STREAM(dec.state)) - { - unsigned extraSize = ((unsigned)totalRead & 3); - _extraReadSizes[dec.state] = extraSize; - if (totalRead < 4) - { - res = (_readRes[dec.state] != S_OK) ? _readRes[dec.state] : S_FALSE; - break; - } - totalRead -= extraSize; - } - - dec.lims[dec.state] = _bufs[dec.state] + totalRead; + if (hres != S_OK && hres_Weak == S_OK) + hres_Weak = hres; } - else // if (dec.state <= BCJ2_STATE_ORIG) + else // (BCJ2_DEC_STATE_ORIG_0 <= state <= BCJ2_STATE_ORIG) { - const size_t curSize = (size_t)(dec.dest - _bufs[BCJ2_NUM_STREAMS]); - if (curSize != 0) { - outSizeProcessed += curSize; - RINOK(WriteStream(outStreams[0], _bufs[BCJ2_NUM_STREAMS], curSize)); + const size_t curSize = (size_t)(dec.dest - _bufs[BCJ2_NUM_STREAMS]); + if (curSize != 0) + { + outSizeWritten += curSize; + RINOK(WriteStream(outStreams[0], _bufs[BCJ2_NUM_STREAMS], curSize)) + } } - dec.dest = _bufs[BCJ2_NUM_STREAMS]; { - size_t rem = _bufsCurSizes[BCJ2_NUM_STREAMS]; + UInt32 rem = _bufsSizes[BCJ2_NUM_STREAMS]; if (outSizes && outSizes[0]) { - UInt64 outSize = *outSizes[0] - outSizeProcessed; + const UInt64 outSize = *outSizes[0] - outSizeWritten; if (rem > outSize) - rem = (size_t)outSize; + rem = (UInt32)outSize; } + dec.dest = _bufs[BCJ2_NUM_STREAMS]; dec.destLim = dec.dest + rem; + /* we exit from decoding loop here, + if (outSizes[0]) limit for output stream was reached */ if (rem == 0) break; } @@ -463,47 +591,67 @@ if (progress) { - const UInt64 outSize2 = outSizeProcessed + (size_t)(dec.dest - _bufs[BCJ2_NUM_STREAMS]); - if (outSize2 - prevProgress >= (1 << 22)) + // here we don't count additional data in dec.temp (up to 4 bytes for output stream) + const UInt64 processed = outSizeWritten + (size_t)(dec.dest - _bufs[BCJ2_NUM_STREAMS]); + if (processed - prevProgress >= (1 << 24)) { - const UInt64 inSize2 = outSize2 + _inStreamsProcessed[BCJ2_STREAM_RC] - (size_t)(dec.lims[BCJ2_STREAM_RC] - dec.bufs[BCJ2_STREAM_RC]); - RINOK(progress->SetRatioInfo(&inSize2, &outSize2)); - prevProgress = outSize2; + prevProgress = processed; + const UInt64 inSize = processed + + _readSizes[BCJ2_STREAM_RC] - (size_t)( + dec.lims[BCJ2_STREAM_RC] - + dec.bufs[BCJ2_STREAM_RC]); + RINOK(progress->SetRatioInfo(&inSize, &prevProgress)) } } } - const size_t curSize = (size_t)(dec.dest - _bufs[BCJ2_NUM_STREAMS]); - if (curSize != 0) { - outSizeProcessed += curSize; - RINOK(WriteStream(outStreams[0], _bufs[BCJ2_NUM_STREAMS], curSize)); + const size_t curSize = (size_t)(dec.dest - _bufs[BCJ2_NUM_STREAMS]); + if (curSize != 0) + { + outSizeWritten += curSize; + RINOK(WriteStream(outStreams[0], _bufs[BCJ2_NUM_STREAMS], curSize)) + } } - if (res != S_OK) - return res; + if (hres_Crit == S_OK) hres_Crit = hres_Weak; + if (hres_Crit != S_OK) return hres_Crit; if (_finishMode) { - if (!Bcj2Dec_IsFinished(&dec)) + if (!Bcj2Dec_IsMaybeFinished_code(&dec)) return S_FALSE; - // we still allow the cases when input streams are larger than required for decoding. - // so the case (dec.state == BCJ2_STATE_ORIG) is also allowed, if MAIN stream is larger than required. - if (dec.state != BCJ2_STREAM_MAIN && - dec.state != BCJ2_DEC_STATE_ORIG) + /* here we support two correct ways to finish full stream decoding + with one of the following conditions: + - the end of input stream MAIN was reached + - the end of output stream ORIG was reached + Currently 7-Zip/7z code ends with (state == BCJ2_STREAM_MAIN), + because the sizes of MAIN and ORIG streams are known and these + sizes are stored in 7z archive headers. + And Bcj2Dec_Decode() exits with (state == BCJ2_STREAM_MAIN), + if both MAIN and ORIG streams have reached buffers limits. + But if the size of MAIN stream is not known or if the + size of MAIN stream includes some padding after payload data, + then we still can correctly finish decoding with + (state == BCJ2_DEC_STATE_ORIG), if we know the exact size + of output ORIG stream. + */ + if (dec.state != BCJ2_STREAM_MAIN) + if (dec.state != BCJ2_DEC_STATE_ORIG) + return S_FALSE; + + /* the caller also will know written size. + So the following check is optional: */ + if (outSizes && outSizes[0] && *outSizes[0] != outSizeWritten) return S_FALSE; if (inSizes) { - for (int i = 0; i < BCJ2_NUM_STREAMS; i++) + for (unsigned i = 0; i < BCJ2_NUM_STREAMS; i++) { - const size_t rem = (size_t)(dec.lims[i] - dec.bufs[i]) + _extraReadSizes[i]; - /* - if (rem != 0) - return S_FALSE; - */ - if (inSizes[i] && *inSizes[i] != _inStreamsProcessed[i] - rem) + /* if (inSizes[i]) is defined, we do full check for processed stream size. */ + if (inSizes[i] && *inSizes[i] != GetProcessedSize_ForInStream(i)) return S_FALSE; } } @@ -512,49 +660,65 @@ return S_OK; } -STDMETHODIMP CDecoder::SetInStream2(UInt32 streamIndex, ISequentialInStream *inStream) + +Z7_COM7F_IMF(CDecoder::GetInStreamProcessedSize2(UInt32 streamIndex, UInt64 *value)) +{ + *value = GetProcessedSize_ForInStream(streamIndex); + return S_OK; +} + + +#ifndef Z7_NO_READ_FROM_CODER + +Z7_COM7F_IMF(CDecoder::SetInStream2(UInt32 streamIndex, ISequentialInStream *inStream)) { _inStreams[streamIndex] = inStream; return S_OK; } -STDMETHODIMP CDecoder::ReleaseInStream2(UInt32 streamIndex) +Z7_COM7F_IMF(CDecoder::ReleaseInStream2(UInt32 streamIndex)) { _inStreams[streamIndex].Release(); return S_OK; } -STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) +Z7_COM7F_IMF(CDecoder::SetOutStreamSize(const UInt64 *outSize)) { _outSizeDefined = (outSize != NULL); _outSize = 0; if (_outSizeDefined) _outSize = *outSize; - _outSize_Processed = 0; - HRESULT res = Alloc(false); - + const HRESULT res = Alloc(false); // allocForOrig InitCommon(); dec.destLim = dec.dest = NULL; - return res; } -STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; - if (size == 0) - return S_OK; + /* Note the case: + The output (ORIG) stream can be empty. + But BCJ2_STREAM_RC stream always is not empty. + And we want to support full data processing for all streams. + We disable check (size == 0) here. + So if the caller calls this CDecoder::Read() with (size == 0), + we execute required Init/Flushing code in this CDecoder object. + Also this CDecoder::Read() function will call Read() for input streams. + So the handlers of input streams objects also can do Init/Flushing. + */ + // if (size == 0) return S_OK; // disabled to allow (size == 0) processing UInt32 totalProcessed = 0; if (_outSizeDefined) { - UInt64 rem = _outSize - _outSize_Processed; + const UInt64 rem = _outSize - _outSize_Processed; if (size > rem) size = (UInt32)rem; } @@ -565,102 +729,125 @@ for (;;) { - SRes sres = Bcj2Dec_Decode(&dec); - if (sres != SZ_OK) - return S_FALSE; - + if (Bcj2Dec_Decode(&dec) != SZ_OK) + return S_FALSE; // this error can be only at start of stream { - UInt32 curSize = (UInt32)(dec.dest - (Byte *)data); + const UInt32 curSize = (UInt32)(size_t)(dec.dest - (Byte *)data); if (curSize != 0) { - totalProcessed += curSize; - if (processedSize) - *processedSize = totalProcessed; data = (void *)((Byte *)data + curSize); size -= curSize; _outSize_Processed += curSize; + totalProcessed += curSize; + if (processedSize) + *processedSize = totalProcessed; } } - if (dec.state >= BCJ2_NUM_STREAMS) break; - + ReadInStream(_inStreams[dec.state]); + if (dec.lims[dec.state] == _bufs[dec.state]) { - size_t totalRead = _extraReadSizes[dec.state]; - { - Byte *buf = _bufs[dec.state]; - for (size_t i = 0; i < totalRead; i++) - buf[i] = dec.bufs[dec.state][i]; - dec.lims[dec.state] = - dec.bufs[dec.state] = buf; - } - - if (_readRes[dec.state] != S_OK) - return _readRes[dec.state]; - - do - { - UInt32 curSize = _bufsCurSizes[dec.state] - (UInt32)totalRead; - HRESULT res2 = _inStreams[dec.state]->Read(_bufs[dec.state] + totalRead, curSize, &curSize); - _readRes[dec.state] = res2; - if (curSize == 0) - break; - _inStreamsProcessed[dec.state] += curSize; - totalRead += curSize; - if (res2 != S_OK) - break; - } - while (totalRead < 4 && BCJ2_IS_32BIT_STREAM(dec.state)); - - if (totalRead == 0) - { - if (totalProcessed == 0) - res = _readRes[dec.state]; - break; - } - - if (BCJ2_IS_32BIT_STREAM(dec.state)) - { - unsigned extraSize = ((unsigned)totalRead & 3); - _extraReadSizes[dec.state] = extraSize; - if (totalRead < 4) - { - if (totalProcessed != 0) - return S_OK; - return (_readRes[dec.state] != S_OK) ? _readRes[dec.state] : S_FALSE; - } - totalRead -= extraSize; - } - - dec.lims[dec.state] = _bufs[dec.state] + totalRead; + /* we break decoding, if there are no new data in input stream. + and we ignore error code, if some data were written to output buffer. */ + if (totalProcessed == 0) + res = _readRes[dec.state]; + break; } } + if (res == S_OK) if (_finishMode && _outSizeDefined && _outSize == _outSize_Processed) { - if (!Bcj2Dec_IsFinished(&dec)) + if (!Bcj2Dec_IsMaybeFinished_code(&dec)) return S_FALSE; - - if (dec.state != BCJ2_STREAM_MAIN && - dec.state != BCJ2_DEC_STATE_ORIG) + if (dec.state != BCJ2_STREAM_MAIN) + if (dec.state != BCJ2_DEC_STATE_ORIG) return S_FALSE; - - /* - for (int i = 0; i < BCJ2_NUM_STREAMS; i++) - if (dec.bufs[i] != dec.lims[i] || _extraReadSizes[i] != 0) - return S_FALSE; - */ } return res; } +#endif + +}} + -STDMETHODIMP CDecoder::GetInStreamProcessedSize2(UInt32 streamIndex, UInt64 *value) +/* +extern "C" { - const size_t rem = (size_t)(dec.lims[streamIndex] - dec.bufs[streamIndex]) + _extraReadSizes[streamIndex]; - *value = _inStreamsProcessed[streamIndex] - rem; - return S_OK; +extern UInt32 bcj2_stats[256 + 2][2]; } -}} +static class CBcj2Stat +{ +public: + ~CBcj2Stat() + { + printf("\nBCJ2 stat:"); + unsigned sums[2] = { 0, 0 }; + int i; + for (i = 2; i < 256 + 2; i++) + { + sums[0] += bcj2_stats[i][0]; + sums[1] += bcj2_stats[i][1]; + } + const unsigned sums2 = sums[0] + sums[1]; + for (int vi = 0; vi < 256 + 3; vi++) + { + printf("\n"); + UInt32 n0, n1; + if (vi < 4) + printf("\n"); + + if (vi < 2) + i = vi; + else if (vi == 2) + i = -1; + else + i = vi - 1; + + if (i < 0) + { + n0 = sums[0]; + n1 = sums[1]; + printf("calls :"); + } + else + { + if (i == 0) + printf("jcc :"); + else if (i == 1) + printf("jump :"); + else + printf("call %02x :", i - 2); + n0 = bcj2_stats[i][0]; + n1 = bcj2_stats[i][1]; + } + + const UInt32 sum = n0 + n1; + printf(" %10u", sum); + + #define PRINT_PERC(val, sum) \ + { UInt32 _sum = sum; if (_sum == 0) _sum = 1; \ + printf(" %7.3f %%", (double)((double)val * (double)100 / (double)_sum )); } + + if (i >= 2 || i < 0) + { + PRINT_PERC(sum, sums2); + } + else + printf("%10s", ""); + + printf(" :%10u", n0); + PRINT_PERC(n0, sum); + + printf(" :%10u", n1); + PRINT_PERC(n1, sum); + } + printf("\n\n"); + fflush(stdout); + } +} g_CBcjStat; +*/ diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/Bcj2Coder.h 7zip-23.01+dfsg/CPP/7zip/Compress/Bcj2Coder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/Bcj2Coder.h 2016-12-28 15:40:58.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/Bcj2Coder.h 2023-02-22 11:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Bcj2Coder.h -#ifndef __COMPRESS_BCJ2_CODER_H -#define __COMPRESS_BCJ2_CODER_H +#ifndef ZIP7_INC_COMPRESS_BCJ2_CODER_H +#define ZIP7_INC_COMPRESS_BCJ2_CODER_H #include "../../../C/Bcj2.h" @@ -16,8 +16,8 @@ { protected: Byte *_bufs[BCJ2_NUM_STREAMS + 1]; - UInt32 _bufsCurSizes[BCJ2_NUM_STREAMS + 1]; - UInt32 _bufsNewSizes[BCJ2_NUM_STREAMS + 1]; + UInt32 _bufsSizes[BCJ2_NUM_STREAMS + 1]; + UInt32 _bufsSizes_New[BCJ2_NUM_STREAMS + 1]; HRESULT Alloc(bool allocForOrig = true); public: @@ -26,92 +26,99 @@ }; -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY -class CEncoder: +class CEncoder Z7_final: public ICompressCoder2, public ICompressSetCoderProperties, public ICompressSetBufSize, public CMyUnknownImp, public CBaseCoder { + Z7_IFACES_IMP_UNK_3( + ICompressCoder2, + ICompressSetCoderProperties, + ICompressSetBufSize) + UInt32 _relatLim; + // UInt32 _excludeRangeBits; - HRESULT CodeReal(ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams, + HRESULT CodeReal( + ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams, ISequentialOutStream * const *outStreams, const UInt64 * const *outSizes, UInt32 numOutStreams, ICompressProgressInfo *progress); - public: - MY_UNKNOWN_IMP3(ICompressCoder2, ICompressSetCoderProperties, ICompressSetBufSize) - - STDMETHOD(Code)(ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams, - ISequentialOutStream * const *outStreams, const UInt64 * const *outSizes, UInt32 numOutStreams, - ICompressProgressInfo *progress); - - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); - - STDMETHOD(SetInBufSize)(UInt32 streamIndex, UInt32 size); - STDMETHOD(SetOutBufSize)(UInt32 streamIndex, UInt32 size); - CEncoder(); ~CEncoder(); }; #endif -class CDecoder: + + +class CBaseDecoder: public CBaseCoder +{ +protected: + HRESULT _readRes[BCJ2_NUM_STREAMS]; + unsigned _extraSizes[BCJ2_NUM_STREAMS]; + UInt64 _readSizes[BCJ2_NUM_STREAMS]; + + CBcj2Dec dec; + + UInt64 GetProcessedSize_ForInStream(unsigned i) const + { + return _readSizes[i] - ((size_t)(dec.lims[i] - dec.bufs[i]) + _extraSizes[i]); + } + void InitCommon(); + void ReadInStream(ISequentialInStream *inStream); +}; + + +class CDecoder Z7_final: public ICompressCoder2, public ICompressSetFinishMode, public ICompressGetInStreamProcessedSize2, + public ICompressSetBufSize, +#ifndef Z7_NO_READ_FROM_CODER public ICompressSetInStream2, - public ISequentialInStream, public ICompressSetOutStreamSize, - public ICompressSetBufSize, + public ISequentialInStream, +#endif public CMyUnknownImp, - public CBaseCoder + public CBaseDecoder { - unsigned _extraReadSizes[BCJ2_NUM_STREAMS]; - UInt64 _inStreamsProcessed[BCJ2_NUM_STREAMS]; - HRESULT _readRes[BCJ2_NUM_STREAMS]; - CMyComPtr _inStreams[BCJ2_NUM_STREAMS]; + Z7_COM_QI_BEGIN2(ICompressCoder2) + Z7_COM_QI_ENTRY(ICompressSetFinishMode) + Z7_COM_QI_ENTRY(ICompressGetInStreamProcessedSize2) + Z7_COM_QI_ENTRY(ICompressSetBufSize) + #ifndef Z7_NO_READ_FROM_CODER + Z7_COM_QI_ENTRY(ICompressSetInStream2) + Z7_COM_QI_ENTRY(ICompressSetOutStreamSize) + Z7_COM_QI_ENTRY(ISequentialInStream) + #endif + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(ICompressCoder2) + Z7_IFACE_COM7_IMP(ICompressSetFinishMode) + Z7_IFACE_COM7_IMP(ICompressGetInStreamProcessedSize2) + Z7_IFACE_COM7_IMP(ICompressSetBufSize) +#ifndef Z7_NO_READ_FROM_CODER + Z7_IFACE_COM7_IMP(ICompressSetInStream2) + Z7_IFACE_COM7_IMP(ICompressSetOutStreamSize) + Z7_IFACE_COM7_IMP(ISequentialInStream) +#endif bool _finishMode; + +#ifndef Z7_NO_READ_FROM_CODER bool _outSizeDefined; UInt64 _outSize; UInt64 _outSize_Processed; - CBcj2Dec dec; - - void InitCommon(); - // HRESULT ReadSpec(); - + CMyComPtr _inStreams[BCJ2_NUM_STREAMS]; +#endif + public: - MY_UNKNOWN_IMP7( - ICompressCoder2, - ICompressSetFinishMode, - ICompressGetInStreamProcessedSize2, - ICompressSetInStream2, - ISequentialInStream, - ICompressSetOutStreamSize, - ICompressSetBufSize - ); - - STDMETHOD(Code)(ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams, - ISequentialOutStream * const *outStreams, const UInt64 * const *outSizes, UInt32 numOutStreams, - ICompressProgressInfo *progress); - - STDMETHOD(SetFinishMode)(UInt32 finishMode); - STDMETHOD(GetInStreamProcessedSize2)(UInt32 streamIndex, UInt64 *value); - - STDMETHOD(SetInStream2)(UInt32 streamIndex, ISequentialInStream *inStream); - STDMETHOD(ReleaseInStream2)(UInt32 streamIndex); - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - - STDMETHOD(SetOutStreamSize)(const UInt64 *outSize); - - STDMETHOD(SetInBufSize)(UInt32 streamIndex, UInt32 size); - STDMETHOD(SetOutBufSize)(UInt32 streamIndex, UInt32 size); - CDecoder(); }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/Bcj2Register.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/Bcj2Register.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/Bcj2Register.cpp 2019-03-28 11:32:51.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/Bcj2Register.cpp 2023-01-29 16:00:00.000000000 +0000 @@ -10,7 +10,7 @@ namespace NBcj2 { REGISTER_CODEC_CREATE_2(CreateCodec, CDecoder(), ICompressCoder2) -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY REGISTER_CODEC_CREATE_2(CreateCodecOut, CEncoder(), ICompressCoder2) #else #define CreateCodecOut NULL diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/BcjCoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/BcjCoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/BcjCoder.cpp 2016-04-25 10:18:10.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/BcjCoder.cpp 2023-03-27 18:00:00.000000000 +0000 @@ -7,17 +7,17 @@ namespace NCompress { namespace NBcj { -STDMETHODIMP CCoder::Init() +Z7_COM7F_IMF(CCoder2::Init()) { - _bufferPos = 0; - x86_Convert_Init(_prevMask); + _pc = 0; + _state = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL; return S_OK; } -STDMETHODIMP_(UInt32) CCoder::Filter(Byte *data, UInt32 size) +Z7_COM7F_IMF2(UInt32, CCoder2::Filter(Byte *data, UInt32 size)) { - UInt32 processed = (UInt32)::x86_Convert(data, size, _bufferPos, &_prevMask, _encode); - _bufferPos += processed; + const UInt32 processed = (UInt32)(size_t)(_convFunc(data, size, _pc, &_state) - data); + _pc += processed; return processed; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/BcjCoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/BcjCoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/BcjCoder.h 2016-04-25 10:17:38.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/BcjCoder.h 2023-03-01 12:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // BcjCoder.h -#ifndef __COMPRESS_BCJ_CODER_H -#define __COMPRESS_BCJ_CODER_H +#ifndef ZIP7_INC_COMPRESS_BCJ_CODER_H +#define ZIP7_INC_COMPRESS_BCJ_CODER_H #include "../../../C/Bra.h" @@ -12,18 +12,24 @@ namespace NCompress { namespace NBcj { -class CCoder: - public ICompressFilter, - public CMyUnknownImp -{ - UInt32 _bufferPos; - UInt32 _prevMask; - int _encode; +/* CCoder in old versions used another constructor parameter CCoder(int encode). + And some code called it as CCoder(0). + We have changed constructor parameter type. + So we have changed the name of class also to CCoder2. */ + +Z7_CLASS_IMP_COM_1( + CCoder2 + , ICompressFilter +) + UInt32 _pc; + UInt32 _state; + z7_Func_BranchConvSt _convFunc; public: - MY_UNKNOWN_IMP1(ICompressFilter); - INTERFACE_ICompressFilter(;) - - CCoder(int encode): _bufferPos(0), _encode(encode) { x86_Convert_Init(_prevMask); } + CCoder2(z7_Func_BranchConvSt convFunc): + _pc(0), + _state(Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL), + _convFunc(convFunc) + {} }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/BcjRegister.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/BcjRegister.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/BcjRegister.cpp 2016-04-25 10:17:38.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/BcjRegister.cpp 2023-02-20 11:00:00.000000000 +0000 @@ -10,8 +10,8 @@ namespace NBcj { REGISTER_FILTER_E(BCJ, - CCoder(false), - CCoder(true), + CCoder2(z7_BranchConvSt_X86_Dec), + CCoder2(z7_BranchConvSt_X86_Enc), 0x3030103, "BCJ") }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/BitlDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/BitlDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/BitlDecoder.h 2022-01-28 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/BitlDecoder.h 2023-03-07 08:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // BitlDecoder.h -- the Least Significant Bit of byte is First -#ifndef __BITL_DECODER_H -#define __BITL_DECODER_H +#ifndef ZIP7_INC_BITL_DECODER_H +#define ZIP7_INC_BITL_DECODER_H #include "../IStream.h" @@ -54,14 +54,14 @@ bool ThereAreDataInBitsBuffer() const { return this->_bitPos != kNumBigValueBits; } - MY_FORCE_INLINE + Z7_FORCE_INLINE void Normalize() { for (; _bitPos >= 8; _bitPos -= 8) _value = ((UInt32)_stream.ReadByte() << (kNumBigValueBits - _bitPos)) | _value; } - MY_FORCE_INLINE + Z7_FORCE_INLINE UInt32 ReadBits(unsigned numBits) { Normalize(); @@ -102,7 +102,7 @@ _normalValue = 0; } - MY_FORCE_INLINE + Z7_FORCE_INLINE void Normalize() { for (; this->_bitPos >= 8; this->_bitPos -= 8) @@ -113,21 +113,21 @@ } } - MY_FORCE_INLINE + Z7_FORCE_INLINE UInt32 GetValue(unsigned numBits) { Normalize(); return ((this->_value >> (8 - this->_bitPos)) & kMask) >> (kNumValueBits - numBits); } - MY_FORCE_INLINE + Z7_FORCE_INLINE void MovePos(unsigned numBits) { this->_bitPos += numBits; _normalValue >>= numBits; } - MY_FORCE_INLINE + Z7_FORCE_INLINE UInt32 ReadBits(unsigned numBits) { Normalize(); @@ -138,10 +138,10 @@ void AlignToByte() { MovePos((32 - this->_bitPos) & 7); } - MY_FORCE_INLINE + Z7_FORCE_INLINE Byte ReadDirectByte() { return this->_stream.ReadByte(); } - MY_FORCE_INLINE + Z7_FORCE_INLINE Byte ReadAlignedByte() { if (this->_bitPos == kNumBigValueBits) @@ -152,7 +152,7 @@ } // call it only if the object is aligned for byte. - MY_FORCE_INLINE + Z7_FORCE_INLINE bool ReadAlignedByte_FromBuf(Byte &b) { if (this->_stream.NumExtraBytes != 0) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/BitlEncoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/BitlEncoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/BitlEncoder.h 2021-01-28 08:49:33.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/BitlEncoder.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // BitlEncoder.h -- the Least Significant Bit of byte is First -#ifndef __BITL_ENCODER_H -#define __BITL_ENCODER_H +#ifndef ZIP7_INC_BITL_ENCODER_H +#define ZIP7_INC_BITL_ENCODER_H #include "../Common/OutBuffer.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/BitmDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/BitmDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/BitmDecoder.h 2017-04-28 09:57:53.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/BitmDecoder.h 2023-03-07 08:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // BitmDecoder.h -- the Most Significant Bit of byte is First -#ifndef __BITM_DECODER_H -#define __BITM_DECODER_H +#ifndef ZIP7_INC_BITM_DECODER_H +#define ZIP7_INC_BITM_DECODER_H #include "../IStream.h" @@ -47,28 +47,28 @@ return (_stream.NumExtraBytes > 4); } - MY_FORCE_INLINE + Z7_FORCE_INLINE void Normalize() { for (; _bitPos >= 8; _bitPos -= 8) _value = (_value << 8) | _stream.ReadByte(); } - MY_FORCE_INLINE + Z7_FORCE_INLINE UInt32 GetValue(unsigned numBits) const { // return (_value << _bitPos) >> (kNumBigValueBits - numBits); return ((_value >> (8 - _bitPos)) & kMask) >> (kNumValueBits - numBits); } - MY_FORCE_INLINE + Z7_FORCE_INLINE void MovePos(unsigned numBits) { _bitPos += numBits; Normalize(); } - MY_FORCE_INLINE + Z7_FORCE_INLINE UInt32 ReadBits(unsigned numBits) { UInt32 res = GetValue(numBits); @@ -91,7 +91,7 @@ void AlignToByte() { MovePos((kNumBigValueBits - _bitPos) & 7); } - MY_FORCE_INLINE + Z7_FORCE_INLINE UInt32 ReadAlignBits() { return ReadBits((kNumBigValueBits - _bitPos) & 7); } }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/BitmEncoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/BitmEncoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/BitmEncoder.h 2021-04-01 09:36:46.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/BitmEncoder.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // BitmEncoder.h -- the Most Significant Bit of byte is First -#ifndef __BITM_ENCODER_H -#define __BITM_ENCODER_H +#ifndef ZIP7_INC_BITM_ENCODER_H +#define ZIP7_INC_BITM_ENCODER_H #include "../IStream.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/BranchMisc.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/BranchMisc.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/BranchMisc.cpp 2016-04-25 10:09:50.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/BranchMisc.cpp 2023-03-28 08:00:00.000000000 +0000 @@ -2,22 +2,109 @@ #include "StdAfx.h" +#include "../../../C/CpuArch.h" + +#include "../Common/StreamUtils.h" + #include "BranchMisc.h" namespace NCompress { namespace NBranch { -STDMETHODIMP CCoder::Init() +Z7_COM7F_IMF(CCoder::Init()) +{ + _pc = 0; + return S_OK; +} + + +Z7_COM7F_IMF2(UInt32, CCoder::Filter(Byte *data, UInt32 size)) +{ + const UInt32 processed = (UInt32)(size_t)(BraFunc(data, size, _pc) - data); + _pc += processed; + return processed; +} + + +namespace NArm64 { + +#ifndef Z7_EXTRACT_ONLY + +Z7_COM7F_IMF(CEncoder::Init()) +{ + _pc = _pc_Init; + return S_OK; +} + +Z7_COM7F_IMF2(UInt32, CEncoder::Filter(Byte *data, UInt32 size)) +{ + const UInt32 processed = (UInt32)(size_t)(Z7_BRANCH_CONV_ENC(ARM64)(data, size, _pc) - data); + _pc += processed; + return processed; +} + +Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps)) { - _bufferPos = 0; + UInt32 pc = 0; + for (UInt32 i = 0; i < numProps; i++) + { + const PROPID propID = propIDs[i]; + if (propID == NCoderPropID::kDefaultProp || + propID == NCoderPropID::kBranchOffset) + { + const PROPVARIANT &prop = props[i]; + if (prop.vt != VT_UI4) + return E_INVALIDARG; + pc = prop.ulVal; + if ((pc & 3) != 0) + return E_INVALIDARG; + } + } + _pc_Init = pc; return S_OK; } -STDMETHODIMP_(UInt32) CCoder::Filter(Byte *data, UInt32 size) + +Z7_COM7F_IMF(CEncoder::WriteCoderProperties(ISequentialOutStream *outStream)) +{ + if (_pc_Init == 0) + return S_OK; + Byte buf[4]; + SetUi32(buf, _pc_Init) + return WriteStream(outStream, buf, 4); +} + +#endif + + +Z7_COM7F_IMF(CDecoder::Init()) { - UInt32 processed = (UInt32)BraFunc(data, size, _bufferPos, _encode); - _bufferPos += processed; + _pc = _pc_Init; + return S_OK; +} + +Z7_COM7F_IMF2(UInt32, CDecoder::Filter(Byte *data, UInt32 size)) +{ + const UInt32 processed = (UInt32)(size_t)(Z7_BRANCH_CONV_DEC(ARM64)(data, size, _pc) - data); + _pc += processed; return processed; } +Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *props, UInt32 size)) +{ + UInt32 val = 0; + if (size != 0) + { + if (size != 4) + return E_NOTIMPL; + val = GetUi32(props); + if ((val & 3) != 0) + return E_NOTIMPL; + } + _pc_Init = val; + return S_OK; +} + +} + }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/BranchMisc.h 7zip-23.01+dfsg/CPP/7zip/Compress/BranchMisc.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/BranchMisc.h 2016-04-25 10:09:26.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/BranchMisc.h 2023-03-28 08:00:00.000000000 +0000 @@ -1,35 +1,57 @@ // BranchMisc.h -#ifndef __COMPRESS_BRANCH_MISC_H -#define __COMPRESS_BRANCH_MISC_H +#ifndef ZIP7_INC_COMPRESS_BRANCH_MISC_H +#define ZIP7_INC_COMPRESS_BRANCH_MISC_H +#include "../../../C/Bra.h" #include "../../Common/MyCom.h" #include "../ICoder.h" -EXTERN_C_BEGIN +namespace NCompress { +namespace NBranch { -typedef SizeT (*Func_Bra)(Byte *data, SizeT size, UInt32 ip, int encoding); +Z7_CLASS_IMP_COM_1( + CCoder + , ICompressFilter +) + UInt32 _pc; + z7_Func_BranchConv BraFunc; +public: + CCoder(z7_Func_BranchConv bra): _pc(0), BraFunc(bra) {} +}; -EXTERN_C_END +namespace NArm64 { -namespace NCompress { -namespace NBranch { +#ifndef Z7_EXTRACT_ONLY -class CCoder: - public ICompressFilter, - public CMyUnknownImp -{ - UInt32 _bufferPos; - int _encode; - Func_Bra BraFunc; +Z7_CLASS_IMP_COM_3( + CEncoder + , ICompressFilter + , ICompressSetCoderProperties + , ICompressWriteCoderProperties +) + UInt32 _pc; + UInt32 _pc_Init; public: - MY_UNKNOWN_IMP1(ICompressFilter); - INTERFACE_ICompressFilter(;) + CEncoder(): _pc(0), _pc_Init(0) {} +}; + +#endif - CCoder(Func_Bra bra, int encode): _bufferPos(0), _encode(encode), BraFunc(bra) {} +Z7_CLASS_IMP_COM_2( + CDecoder + , ICompressFilter + , ICompressSetDecoderProperties2 +) + UInt32 _pc; + UInt32 _pc_Init; +public: + CDecoder(): _pc(0), _pc_Init(0) {} }; +} + }} #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/BranchRegister.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/BranchRegister.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/BranchRegister.cpp 2016-04-25 10:10:55.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/BranchRegister.cpp 2023-03-28 08:00:00.000000000 +0000 @@ -2,8 +2,6 @@ #include "StdAfx.h" -#include "../../../C/Bra.h" - #include "../Common/RegisterCodec.h" #include "BranchMisc.h" @@ -11,9 +9,18 @@ namespace NCompress { namespace NBranch { +#ifdef Z7_EXTRACT_ONLY +#define GET_CREATE_FUNC(x) NULL +#define CREATE_BRA_E(n) +#else +#define GET_CREATE_FUNC(x) x +#define CREATE_BRA_E(n) \ + REGISTER_FILTER_CREATE(CreateBra_Encoder_ ## n, CCoder(Z7_BRANCH_CONV_ENC(n))) +#endif + #define CREATE_BRA(n) \ - REGISTER_FILTER_CREATE(CreateBra_Decoder_ ## n, CCoder(n ## _Convert, false)) \ - REGISTER_FILTER_CREATE(CreateBra_Encoder_ ## n, CCoder(n ## _Convert, true)) \ + REGISTER_FILTER_CREATE(CreateBra_Decoder_ ## n, CCoder(Z7_BRANCH_CONV_DEC(n))) \ + CREATE_BRA_E(n) CREATE_BRA(PPC) CREATE_BRA(IA64) @@ -23,8 +30,8 @@ #define METHOD_ITEM(n, id, name) \ REGISTER_FILTER_ITEM( \ - CreateBra_Decoder_ ## n, \ - CreateBra_Encoder_ ## n, \ + CreateBra_Decoder_ ## n, GET_CREATE_FUNC( \ + CreateBra_Encoder_ ## n), \ 0x3030000 + id, name) REGISTER_CODECS_VAR @@ -38,4 +45,11 @@ REGISTER_CODECS(Branch) +namespace NArm64 { +REGISTER_FILTER_E(ARM64, + CDecoder(), + CEncoder(), + 0xa, "ARM64") +} + }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/ByteSwap.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/ByteSwap.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/ByteSwap.cpp 2016-04-25 10:11:48.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/ByteSwap.cpp 2023-03-15 10:00:00.000000000 +0000 @@ -2,6 +2,8 @@ #include "StdAfx.h" +#include "../../../C/SwapBytes.h" + #include "../../Common/MyCom.h" #include "../ICoder.h" @@ -11,80 +13,77 @@ namespace NCompress { namespace NByteSwap { -class CByteSwap2: - public ICompressFilter, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP1(ICompressFilter); - INTERFACE_ICompressFilter(;) -}; - -class CByteSwap4: - public ICompressFilter, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP1(ICompressFilter); - INTERFACE_ICompressFilter(;) -}; +Z7_CLASS_IMP_COM_1(CByteSwap2, ICompressFilter) }; +Z7_CLASS_IMP_COM_1(CByteSwap4, ICompressFilter) }; -STDMETHODIMP CByteSwap2::Init() { return S_OK; } +Z7_COM7F_IMF(CByteSwap2::Init()) { return S_OK; } -STDMETHODIMP_(UInt32) CByteSwap2::Filter(Byte *data, UInt32 size) +Z7_COM7F_IMF2(UInt32, CByteSwap2::Filter(Byte *data, UInt32 size)) { - const UInt32 kStep = 2; - if (size < kStep) - return 0; - size &= ~(kStep - 1); - - const Byte *end = data + (size_t)size; - - do + const UInt32 kMask = 2 - 1; + size &= ~kMask; + /* + if ((unsigned)(ptrdiff_t)data & kMask) { - Byte b0 = data[0]; - data[0] = data[1]; - data[1] = b0; - data += kStep; + if (size == 0) + return 0; + const Byte *end = data + (size_t)size; + do + { + const Byte b0 = data[0]; + data[0] = data[1]; + data[1] = b0; + data += kStep; + } + while (data != end); } - while (data != end); - + else + */ + z7_SwapBytes2((UInt16 *)(void *)data, size >> 1); return size; } -STDMETHODIMP CByteSwap4::Init() { return S_OK; } -STDMETHODIMP_(UInt32) CByteSwap4::Filter(Byte *data, UInt32 size) +Z7_COM7F_IMF(CByteSwap4::Init()) { return S_OK; } + +Z7_COM7F_IMF2(UInt32, CByteSwap4::Filter(Byte *data, UInt32 size)) { - const UInt32 kStep = 4; - if (size < kStep) - return 0; - size &= ~(kStep - 1); - - const Byte *end = data + (size_t)size; - - do + const UInt32 kMask = 4 - 1; + size &= ~kMask; + /* + if ((unsigned)(ptrdiff_t)data & kMask) { - Byte b0 = data[0]; - Byte b1 = data[1]; - data[0] = data[3]; - data[1] = data[2]; - data[2] = b1; - data[3] = b0; - data += kStep; + if (size == 0) + return 0; + const Byte *end = data + (size_t)size; + do + { + const Byte b0 = data[0]; + const Byte b1 = data[1]; + data[0] = data[3]; + data[1] = data[2]; + data[2] = b1; + data[3] = b0; + data += kStep; + } + while (data != end); } - while (data != end); - + else + */ + z7_SwapBytes4((UInt32 *)(void *)data, size >> 2); return size; } +static struct C_SwapBytesPrepare { C_SwapBytesPrepare() { z7_SwapBytesPrepare(); } } g_SwapBytesPrepare; + + REGISTER_FILTER_CREATE(CreateFilter2, CByteSwap2()) REGISTER_FILTER_CREATE(CreateFilter4, CByteSwap4()) REGISTER_CODECS_VAR { REGISTER_FILTER_ITEM(CreateFilter2, CreateFilter2, 0x20302, "Swap2"), - REGISTER_FILTER_ITEM(CreateFilter4, CreateFilter4, 0x20304, "Swap4") + REGISTER_FILTER_ITEM(CreateFilter4, CreateFilter4, 0x20304, "Swap4"), }; REGISTER_CODECS(ByteSwap) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/BZip2Const.h 7zip-23.01+dfsg/CPP/7zip/Compress/BZip2Const.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/BZip2Const.h 2019-12-28 11:02:11.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/BZip2Const.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Compress/BZip2Const.h -#ifndef __COMPRESS_BZIP2_CONST_H -#define __COMPRESS_BZIP2_CONST_H +#ifndef ZIP7_INC_COMPRESS_BZIP2_CONST_H +#define ZIP7_INC_COMPRESS_BZIP2_CONST_H namespace NCompress { namespace NBZip2 { diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/BZip2Crc.h 7zip-23.01+dfsg/CPP/7zip/Compress/BZip2Crc.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/BZip2Crc.h 2021-09-13 18:28:28.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/BZip2Crc.h 2023-03-28 10:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // BZip2Crc.h -#ifndef __BZIP2_CRC_H -#define __BZIP2_CRC_H +#ifndef ZIP7_INC_BZIP2_CRC_H +#define ZIP7_INC_BZIP2_CRC_H #include "../../Common/MyTypes.h" @@ -11,10 +11,10 @@ static UInt32 Table[256]; public: static void InitTable(); - CBZip2Crc(UInt32 initVal = 0xFFFFFFFF): _value(initVal) {}; + CBZip2Crc(UInt32 initVal = 0xFFFFFFFF): _value(initVal) {} void Init(UInt32 initVal = 0xFFFFFFFF) { _value = initVal; } void UpdateByte(Byte b) { _value = Table[(_value >> 24) ^ b] ^ (_value << 8); } - void UpdateByte(unsigned int b) { _value = Table[(_value >> 24) ^ b] ^ (_value << 8); } + void UpdateByte(unsigned b) { _value = Table[(_value >> 24) ^ b] ^ (_value << 8); } UInt32 GetDigest() const { return _value ^ 0xFFFFFFFF; } }; @@ -22,7 +22,7 @@ { UInt32 _value; public: - CBZip2CombinedCrc(): _value(0){}; + CBZip2CombinedCrc(): _value(0) {} void Init() { _value = 0; } void Update(UInt32 v) { _value = ((_value << 1) | (_value >> 31)) ^ v; } UInt32 GetDigest() const { return _value ; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/BZip2Decoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/BZip2Decoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/BZip2Decoder.cpp 2021-02-27 08:45:39.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/BZip2Decoder.cpp 2023-03-28 13:00:00.000000000 +0000 @@ -32,7 +32,7 @@ namespace NBZip2 { // #undef NO_INLINE -#define NO_INLINE MY_NO_INLINE +#define NO_INLINE Z7_NO_INLINE #define BZIP2_BYTE_MODE @@ -169,7 +169,7 @@ SRes CBitDecoder::ReadByte(int &b) { b = -1; - READ_BITS_8(b, 8); + READ_BITS_8(b, 8) return SZ_OK; } @@ -180,7 +180,7 @@ for (;;) { unsigned b; - READ_BITS_8(b, 8); + READ_BITS_8(b, 8) if ( (state2 == 0 && b != kArSig0) || (state2 == 1 && b != kArSig1) @@ -230,7 +230,7 @@ while (state2 < 10) { unsigned b; - READ_BITS_8(b, 8); + READ_BITS_8(b, 8) temp[state2] = (Byte)b; state2++; } @@ -285,7 +285,7 @@ { if (Props.randMode) { - READ_BIT(Props.randMode); + READ_BIT(Props.randMode) } state = STATE_ORIG_BITS; // g_Tick = GetCpuTicks(); @@ -293,7 +293,7 @@ if (state == STATE_ORIG_BITS) { - READ_BITS(Props.origPtr, kNumOrigBits); + READ_BITS(Props.origPtr, kNumOrigBits) if (Props.origPtr >= blockSizeMax) return SZ_ERROR_DATA; state = STATE_IN_USE; @@ -303,7 +303,7 @@ if (state == STATE_IN_USE) { - READ_BITS(state2, 16); + READ_BITS(state2, 16) state = STATE_IN_USE2; state3 = 0; numInUse = 0; @@ -316,7 +316,7 @@ if (state2 & ((UInt32)0x8000 >> (state3 >> 4))) { unsigned b; - READ_BIT(b); + READ_BIT(b) if (b) mtf.Add(numInUse++, (Byte)state3); } @@ -328,7 +328,7 @@ if (state == STATE_NUM_TABLES) { - READ_BITS_8(numTables, kNumTablesBits); + READ_BITS_8(numTables, kNumTablesBits) state = STATE_NUM_SELECTORS; if (numTables < kNumTablesMin || numTables > kNumTablesMax) return SZ_ERROR_DATA; @@ -336,7 +336,7 @@ if (state == STATE_NUM_SELECTORS) { - READ_BITS(numSelectors, kNumSelectorsBits); + READ_BITS(numSelectors, kNumSelectorsBits) state = STATE_SELECTORS; state2 = 0x543210; state3 = 0; @@ -358,7 +358,7 @@ for (;;) { unsigned b; - READ_BIT(b); + READ_BIT(b) if (!b) break; if (++state4 >= numTables) @@ -392,7 +392,7 @@ { if (state3 == 0) { - READ_BITS_8(state3, kNumLevelsBits); + READ_BITS_8(state3, kNumLevelsBits) state4 = 0; state5 = 0; } @@ -407,14 +407,14 @@ if (state5 == 0) { unsigned b; - READ_BIT(b); + READ_BIT(b) if (!b) break; } state5 = 1; unsigned b; - READ_BIT(b); + READ_BIT(b) state5 = 0; state3++; @@ -573,8 +573,8 @@ // UInt32 b = (UInt32)mtf.GetAndMove((unsigned)sym); - const unsigned lim = sym >> MTF_MOVS; - const unsigned pos = (sym & MTF_MASK) << 3; + const unsigned lim = sym >> Z7_MTF_MOVS; + const unsigned pos = (sym & Z7_MTF_MASK) << 3; CMtfVar next = mtf.Buf[lim]; CMtfVar prev = (next >> pos) & 0xFF; @@ -593,7 +593,7 @@ { CMtfVar n0 = *m; *m = (n0 << 8) | prev; - prev = (n0 >> (MTF_MASK << 3)); + prev = (n0 >> (Z7_MTF_MASK << 3)); } while (++m != mLim); } @@ -879,7 +879,7 @@ if (processed >= size) { - RINOK(Flush()); + RINOK(Flush()) } if (block.Finished()) @@ -900,7 +900,7 @@ _inBuf(NULL), _inProcessed(0) { - #ifndef _7ZIP_ST + #ifndef Z7_ST MtMode = false; NeedWaitScout = false; // ScoutRes = S_OK; @@ -912,7 +912,7 @@ { PRIN("\n~CDecoder()"); - #ifndef _7ZIP_ST + #ifndef Z7_ST if (Thread.IsCreated()) { @@ -966,7 +966,7 @@ { for (;;) { - RINOK(ReadInput()); + RINOK(ReadInput()) SRes res = Base.ReadStreamSignature2(); if (res != SZ_OK) return S_FALSE; @@ -992,7 +992,7 @@ { for (;;) { - RINOK(ReadInput()); + RINOK(ReadInput()) SRes res = Base.ReadBlockSignature2(); @@ -1015,7 +1015,7 @@ { for (;;) { - RINOK(ReadInput()); + RINOK(ReadInput()) SRes res = Base.ReadBlock2(); @@ -1036,18 +1036,18 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress) { { - #ifndef _7ZIP_ST + #ifndef Z7_ST _block.StopScout = false; #endif } - RINOK(StartRead()); + RINOK(StartRead()) UInt64 inPrev = 0; UInt64 outPrev = 0; { - #ifndef _7ZIP_ST + #ifndef Z7_ST CWaitScout_Releaser waitScout_Releaser(this); bool useMt = false; @@ -1072,7 +1072,7 @@ const UInt64 outCur = GetOutProcessedSize(); if (packPos - inPrev >= kProgressStep || outCur - outPrev >= kProgressStep) { - RINOK(progress->SetRatioInfo(&packPos, &outCur)); + RINOK(progress->SetRatioInfo(&packPos, &outCur)) inPrev = packPos; outPrev = outCur; } @@ -1083,7 +1083,7 @@ return nextRes; if ( - #ifndef _7ZIP_ST + #ifndef Z7_ST !useMt && #endif !wasFinished && Base.state == STATE_BLOCK_SIGNATURE) @@ -1125,7 +1125,7 @@ wasFinished = false; - #ifndef _7ZIP_ST + #ifndef Z7_ST if (MtMode) if (props.blockSize != 0) { @@ -1136,7 +1136,7 @@ if (!Thread.IsCreated()) { PRIN("=== MT_MODE"); - RINOK(CreateThread()); + RINOK(CreateThread()) } useMt = true; } @@ -1148,7 +1148,7 @@ { crc = nextCrc; - #ifndef _7ZIP_ST + #ifndef Z7_ST if (useMt) { PRIN("DecoderEvent.Lock()"); @@ -1165,7 +1165,7 @@ crc = _block.Crc; packPos = _block.PackPos; wasFinished = _block.WasFinished; - RINOK(_block.Res); + RINOK(_block.Res) } else #endif @@ -1175,7 +1175,7 @@ TICKS_START Base.Props.randMode = 1; - RINOK(ReadBlock()); + RINOK(ReadBlock()) TICKS_UPDATE(0) props = Base.Props; @@ -1190,7 +1190,7 @@ TICKS_UPDATE(1) } - #ifndef _7ZIP_ST + #ifndef Z7_ST if (useMt && !wasFinished) { /* @@ -1216,7 +1216,7 @@ if (props.blockSize == 0) continue; - RINOK(DecodeBlock(props)); + RINOK(DecodeBlock(props)) if (!_blockFinished) return nextRes; @@ -1278,8 +1278,8 @@ } -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress)) { /* { @@ -1344,21 +1344,21 @@ } -STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode) +Z7_COM7F_IMF(CDecoder::SetFinishMode(UInt32 finishMode)) { FinishMode = (finishMode != 0); return S_OK; } -STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value) +Z7_COM7F_IMF(CDecoder::GetInStreamProcessedSize(UInt64 *value)) { *value = GetInStreamSize(); return S_OK; } -STDMETHODIMP CDecoder::ReadUnusedFromInBuf(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CDecoder::ReadUnusedFromInBuf(void *data, UInt32 size, UInt32 *processedSize)) { Base.AlignToByte(); UInt32 i; @@ -1376,7 +1376,7 @@ } -#ifndef _7ZIP_ST +#ifndef Z7_ST #define PRIN_MT(s) PRIN(" " s) @@ -1397,9 +1397,9 @@ for (;;) { { - PRIN_MT("ScoutEvent.Lock()"); + PRIN_MT("ScoutEvent.Lock()") WRes wres = ScoutEvent.Lock(); - PRIN_MT("-- ScoutEvent.Lock()"); + PRIN_MT("-- ScoutEvent.Lock()") if (wres != 0) { // ScoutRes = wres; @@ -1461,7 +1461,7 @@ res = ReadBlock(); - PRIN_MT("-- Base.ReadBlock"); + PRIN_MT("-- Base.ReadBlock") if (res != S_OK) break; block.Props = Base.Props; @@ -1505,13 +1505,13 @@ if (res != S_OK) { - PRIN_MT("error"); + PRIN_MT("error") block.Res = res; block.WasFinished = true; } block.PackPos = GetInputProcessedSize(); - PRIN_MT("DecoderEvent.Set()"); + PRIN_MT("DecoderEvent.Set()") WRes wres = DecoderEvent.Set(); if (wres != 0) { @@ -1522,7 +1522,7 @@ } -STDMETHODIMP CDecoder::SetNumberOfThreads(UInt32 numThreads) +Z7_COM7F_IMF(CDecoder::SetNumberOfThreads(UInt32 numThreads)) { MtMode = (numThreads > 1); @@ -1538,10 +1538,10 @@ -#ifndef NO_READ_FROM_CODER +#ifndef Z7_NO_READ_FROM_CODER -STDMETHODIMP CDecoder::SetInStream(ISequentialInStream *inStream) +Z7_COM7F_IMF(CDecoder::SetInStream(ISequentialInStream *inStream)) { Base.InStreamRef = inStream; Base.InStream = inStream; @@ -1549,7 +1549,7 @@ } -STDMETHODIMP CDecoder::ReleaseInStream() +Z7_COM7F_IMF(CDecoder::ReleaseInStream()) { Base.InStreamRef.Release(); Base.InStream = NULL; @@ -1558,7 +1558,7 @@ -STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) +Z7_COM7F_IMF(CDecoder::SetOutStreamSize(const UInt64 *outSize)) { InitOutSize(outSize); @@ -1583,7 +1583,7 @@ -STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize)) { *processedSize = 0; @@ -1689,7 +1689,7 @@ // ---------- NSIS ---------- -STDMETHODIMP CNsisDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CNsisDecoder::Read(void *data, UInt32 size, UInt32 *processedSize)) { *processedSize = 0; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/BZip2Decoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/BZip2Decoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/BZip2Decoder.h 2021-01-25 15:02:05.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/BZip2Decoder.h 2023-03-28 10:00:00.000000000 +0000 @@ -1,14 +1,14 @@ // Compress/BZip2Decoder.h -#ifndef __COMPRESS_BZIP2_DECODER_H -#define __COMPRESS_BZIP2_DECODER_H +#ifndef ZIP7_INC_COMPRESS_BZIP2_DECODER_H +#define ZIP7_INC_COMPRESS_BZIP2_DECODER_H #include "../../Common/MyCom.h" -// #define NO_READ_FROM_CODER -// #define _7ZIP_ST +// #define Z7_NO_READ_FROM_CODER +// #define Z7_ST -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "../../Windows/Synchronization.h" #include "../../Windows/Thread.h" #endif @@ -134,7 +134,7 @@ ISequentialInStream *InStream; - #ifndef NO_READ_FROM_CODER + #ifndef Z7_NO_READ_FROM_CODER CMyComPtr InStreamRef; #endif @@ -194,24 +194,51 @@ -class CDecoder : +class CDecoder: public ICompressCoder, public ICompressSetFinishMode, public ICompressGetInStreamProcessedSize, public ICompressReadUnusedFromInBuf, - - #ifndef NO_READ_FROM_CODER +#ifndef Z7_NO_READ_FROM_CODER public ICompressSetInStream, public ICompressSetOutStreamSize, public ISequentialInStream, - #endif - - #ifndef _7ZIP_ST +#endif +#ifndef Z7_ST public ICompressSetCoderMt, - #endif - +#endif public CMyUnknownImp { + Z7_COM_QI_BEGIN2(ICompressCoder) + Z7_COM_QI_ENTRY(ICompressSetFinishMode) + Z7_COM_QI_ENTRY(ICompressGetInStreamProcessedSize) + Z7_COM_QI_ENTRY(ICompressReadUnusedFromInBuf) +#ifndef Z7_NO_READ_FROM_CODER + Z7_COM_QI_ENTRY(ICompressSetInStream) + Z7_COM_QI_ENTRY(ICompressSetOutStreamSize) + Z7_COM_QI_ENTRY(ISequentialInStream) +#endif +#ifndef Z7_ST + Z7_COM_QI_ENTRY(ICompressSetCoderMt) +#endif + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(ICompressCoder) + Z7_IFACE_COM7_IMP(ICompressSetFinishMode) + Z7_IFACE_COM7_IMP(ICompressGetInStreamProcessedSize) + Z7_IFACE_COM7_IMP(ICompressReadUnusedFromInBuf) +#ifndef Z7_NO_READ_FROM_CODER + Z7_IFACE_COM7_IMP(ICompressSetInStream) + Z7_IFACE_COM7_IMP(ICompressSetOutStreamSize) + Z7_IFACE_COM7_IMP_NONFINAL(ISequentialInStream) +#endif +public: +#ifndef Z7_ST + Z7_IFACE_COM7_IMP(ICompressSetCoderMt) +#endif + +private: Byte *_outBuf; size_t _outPos; UInt64 _outWritten; @@ -235,7 +262,7 @@ CSpecState _spec; UInt32 *_counters; - #ifndef _7ZIP_ST + #ifndef Z7_ST struct CBlock { @@ -339,60 +366,20 @@ HRESULT DecodeBlock(const CBlockProps &props); HRESULT DecodeStreams(ICompressProgressInfo *progress); - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - MY_QUERYINTERFACE_ENTRY(ICompressSetFinishMode) - MY_QUERYINTERFACE_ENTRY(ICompressGetInStreamProcessedSize) - MY_QUERYINTERFACE_ENTRY(ICompressReadUnusedFromInBuf) - - #ifndef NO_READ_FROM_CODER - MY_QUERYINTERFACE_ENTRY(ICompressSetInStream) - MY_QUERYINTERFACE_ENTRY(ICompressSetOutStreamSize) - MY_QUERYINTERFACE_ENTRY(ISequentialInStream) - #endif - - #ifndef _7ZIP_ST - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt) - #endif - - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetFinishMode)(UInt32 finishMode); - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); - STDMETHOD(ReadUnusedFromInBuf)(void *data, UInt32 size, UInt32 *processedSize); - UInt64 GetNumStreams() const { return Base.NumStreams; } UInt64 GetNumBlocks() const { return Base.NumBlocks; } - #ifndef NO_READ_FROM_CODER - - STDMETHOD(SetInStream)(ISequentialInStream *inStream); - STDMETHOD(ReleaseInStream)(); - STDMETHOD(SetOutStreamSize)(const UInt64 *outSize); - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - - #endif - - #ifndef _7ZIP_ST - STDMETHOD(SetNumberOfThreads)(UInt32 numThreads); - #endif - CDecoder(); - ~CDecoder(); + virtual ~CDecoder(); }; -#ifndef NO_READ_FROM_CODER +#ifndef Z7_NO_READ_FROM_CODER -class CNsisDecoder : public CDecoder +class CNsisDecoder Z7_final: public CDecoder { -public: - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); + Z7_IFACE_COM7_IMP(ISequentialInStream) }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/BZip2Encoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/BZip2Encoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/BZip2Encoder.cpp 2022-02-07 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/BZip2Encoder.cpp 2023-01-30 18:00:00.000000000 +0000 @@ -46,7 +46,7 @@ m_Block = NULL; } -#ifndef _7ZIP_ST +#ifndef Z7_ST static THREAD_FUNC_DECL MFThread(void *threadCoderInfo) { @@ -146,14 +146,14 @@ { _props.Normalize(-1); - #ifndef _7ZIP_ST + #ifndef Z7_ST ThreadsInfo = NULL; m_NumThreadsPrev = 0; NumThreads = 1; #endif } -#ifndef _7ZIP_ST +#ifndef Z7_ST CEncoder::~CEncoder() { Free(); @@ -558,8 +558,8 @@ { UInt32 groupSize = 0; UInt32 groupIndex = 0; - const Byte *lens = 0; - const UInt32 *codes = 0; + const Byte *lens = NULL; + const UInt32 *codes = NULL; UInt32 mtfPos = 0; do { @@ -706,7 +706,7 @@ EncodeBlock2(m_Block, blockSize, Encoder->_props.NumPasses); - #ifndef _7ZIP_ST + #ifndef Z7_ST if (Encoder->MtMode) Encoder->ThreadsInfo[m_BlockIndex].CanWriteEvent.Lock(); #endif @@ -714,7 +714,7 @@ Encoder->CombinedCrc.Update(m_CRCs[i]); Encoder->WriteBytes(m_TempArray, outStreamTemp.GetPos(), outStreamTemp.GetCurByte()); HRESULT res = S_OK; - #ifndef _7ZIP_ST + #ifndef Z7_ST if (Encoder->MtMode) { UInt32 blockIndex = m_BlockIndex + 1; @@ -746,13 +746,13 @@ const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) { NumBlocks = 0; - #ifndef _7ZIP_ST + #ifndef Z7_ST Progress = progress; - RINOK(Create()); + RINOK(Create()) for (UInt32 t = 0; t < NumThreads; t++) #endif { - #ifndef _7ZIP_ST + #ifndef Z7_ST CThreadInfo &ti = ThreadsInfo[t]; if (MtMode) { @@ -787,7 +787,7 @@ m_OutStream.Init(); CombinedCrc.Init(); - #ifndef _7ZIP_ST + #ifndef Z7_ST NextBlockIndex = 0; StreamWasFinished = false; CloseThreads = false; @@ -799,7 +799,7 @@ WriteByte(kArSig2); WriteByte((Byte)(kArSig3 + _props.BlockSizeMult)); - #ifndef _7ZIP_ST + #ifndef Z7_ST if (MtMode) { @@ -814,7 +814,7 @@ for (t = 0; t < NumThreads; t++) ThreadsInfo[t].WaitingWasStartedEvent.Lock(); CanStartWaitingEvent.Reset(); - RINOK(Result); + RINOK(Result) } else #endif @@ -822,7 +822,7 @@ for (;;) { CThreadInfo &ti = - #ifndef _7ZIP_ST + #ifndef Z7_ST ThreadsInfo[0]; #else ThreadsInfo; @@ -830,12 +830,12 @@ UInt32 blockSize = ReadRleBlock(ti.m_Block); if (blockSize == 0) break; - RINOK(ti.EncodeBlock3(blockSize)); + RINOK(ti.EncodeBlock3(blockSize)) if (progress) { const UInt64 unpackSize = m_InStream.GetProcessedSize(); const UInt64 packSize = m_OutStream.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&unpackSize, &packSize)); + RINOK(progress->SetRatioInfo(&unpackSize, &packSize)) } } } @@ -847,14 +847,14 @@ WriteByte(kFinSig5); WriteCrc(CombinedCrc.GetDigest()); - RINOK(Flush()); + RINOK(Flush()) if (!m_InStream.WasFinished()) return E_FAIL; return S_OK; } -STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)) { try { return CodeReal(inStream, outStream, inSize, outSize, progress); } catch(const CInBufferException &e) { return e.ErrorCode; } @@ -862,7 +862,7 @@ catch(...) { return S_FALSE; } } -HRESULT CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps) +Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps)) { int level = -1; CEncProps props; @@ -892,7 +892,7 @@ case NCoderPropID::kLevel: level = (int)v; break; case NCoderPropID::kNumThreads: { - #ifndef _7ZIP_ST + #ifndef Z7_ST SetNumberOfThreads(v); #endif break; @@ -905,8 +905,8 @@ return S_OK; } -#ifndef _7ZIP_ST -STDMETHODIMP CEncoder::SetNumberOfThreads(UInt32 numThreads) +#ifndef Z7_ST +Z7_COM7F_IMF(CEncoder::SetNumberOfThreads(UInt32 numThreads)) { const UInt32 kNumThreadsMax = 64; if (numThreads < 1) numThreads = 1; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/BZip2Encoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/BZip2Encoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/BZip2Encoder.h 2022-02-07 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/BZip2Encoder.h 2023-03-28 10:00:00.000000000 +0000 @@ -1,12 +1,12 @@ // BZip2Encoder.h -#ifndef __COMPRESS_BZIP2_ENCODER_H -#define __COMPRESS_BZIP2_ENCODER_H +#ifndef ZIP7_INC_COMPRESS_BZIP2_ENCODER_H +#define ZIP7_INC_COMPRESS_BZIP2_ENCODER_H #include "../../Common/Defs.h" #include "../../Common/MyCom.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "../../Windows/Synchronization.h" #include "../../Windows/Thread.h" #endif @@ -107,8 +107,6 @@ UInt32 m_CRCs[1 << kNumPassesMax]; UInt32 m_NumCrcs; - UInt32 m_BlockIndex; - void WriteBits2(UInt32 value, unsigned numBits); void WriteByte2(Byte b); void WriteBit2(Byte v); @@ -120,7 +118,7 @@ public: bool m_OptimizeNumTables; CEncoder *Encoder; - #ifndef _7ZIP_ST + #ifndef Z7_ST NWindows::CThread Thread; NWindows::NSynchronization::CAutoResetEvent StreamWasFinishedEvent; @@ -129,13 +127,15 @@ // it's not member of this thread. We just need one event per thread NWindows::NSynchronization::CAutoResetEvent CanWriteEvent; +private: + UInt32 m_BlockIndex; UInt64 m_UnpackSize; - +public: Byte MtPad[1 << 8]; // It's pad for Multi-Threading. Must be >= Cache_Line_Size. HRESULT Create(); void FinishStream(bool needLeave); THREAD_FUNC_RET_TYPE ThreadFunc(); - #endif + #endif CThreadInfo(): m_Block(NULL), m_BlockSorterIndex(NULL) {} ~CThreadInfo() { Free(); } @@ -161,23 +161,41 @@ bool DoOptimizeNumTables() const { return NumPasses > 1; } }; -class CEncoder : +class CEncoder Z7_final: public ICompressCoder, public ICompressSetCoderProperties, - #ifndef _7ZIP_ST + #ifndef Z7_ST public ICompressSetCoderMt, - #endif + #endif public CMyUnknownImp { + Z7_COM_QI_BEGIN2(ICompressCoder) + Z7_COM_QI_ENTRY(ICompressSetCoderProperties) + #ifndef Z7_ST + Z7_COM_QI_ENTRY(ICompressSetCoderMt) + #endif + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(ICompressCoder) + Z7_IFACE_COM7_IMP(ICompressSetCoderProperties) + #ifndef Z7_ST + Z7_IFACE_COM7_IMP(ICompressSetCoderMt) + #endif + + #ifndef Z7_ST UInt32 m_NumThreadsPrev; + #endif public: CInBuffer m_InStream; + #ifndef Z7_ST Byte MtPad[1 << 8]; // It's pad for Multi-Threading. Must be >= Cache_Line_Size. + #endif CBitmEncoder m_OutStream; CEncProps _props; CBZip2CombinedCrc CombinedCrc; - #ifndef _7ZIP_ST + #ifndef Z7_ST CThreadInfo *ThreadsInfo; NWindows::NSynchronization::CManualResetEvent CanProcessEvent; NWindows::NSynchronization::CCriticalSection CS; @@ -191,9 +209,9 @@ HRESULT Result; ICompressProgressInfo *Progress; - #else + #else CThreadInfo ThreadsInfo; - #endif + #endif UInt64 NumBlocks; @@ -207,37 +225,21 @@ // void WriteBit(Byte v); void WriteCrc(UInt32 v); - #ifndef _7ZIP_ST + #ifndef Z7_ST HRESULT Create(); void Free(); - #endif + #endif public: CEncoder(); - #ifndef _7ZIP_ST + #ifndef Z7_ST ~CEncoder(); - #endif + #endif HRESULT Flush() { return m_OutStream.Flush(); } - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - #ifndef _7ZIP_ST - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt) - #endif - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderProperties) - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); - - #ifndef _7ZIP_ST - STDMETHOD(SetNumberOfThreads)(UInt32 numThreads); - #endif }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/BZip2Register.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/BZip2Register.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/BZip2Register.cpp 2016-04-25 10:02:03.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/BZip2Register.cpp 2023-03-28 10:00:00.000000000 +0000 @@ -5,7 +5,7 @@ #include "../Common/RegisterCodec.h" #include "BZip2Decoder.h" -#if !defined(EXTRACT_ONLY) && !defined(BZIP2_EXTRACT_ONLY) +#if !defined(Z7_EXTRACT_ONLY) && !defined(Z7_BZIP2_EXTRACT_ONLY) #include "BZip2Encoder.h" #endif @@ -14,7 +14,7 @@ REGISTER_CODEC_CREATE(CreateDec, CDecoder) -#if !defined(EXTRACT_ONLY) && !defined(BZIP2_EXTRACT_ONLY) +#if !defined(Z7_EXTRACT_ONLY) && !defined(Z7_BZIP2_EXTRACT_ONLY) REGISTER_CODEC_CREATE(CreateEnc, CEncoder) #else #define CreateEnc NULL diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/Codec.def 7zip-23.01+dfsg/CPP/7zip/Compress/Codec.def --- 7zip-22.01+dfsg/CPP/7zip/Compress/Codec.def 2015-06-21 02:15:02.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/Codec.def 2023-04-03 11:00:00.000000000 +0000 @@ -4,3 +4,4 @@ GetMethodProperty PRIVATE CreateDecoder PRIVATE CreateEncoder PRIVATE + GetModuleProp PRIVATE diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/CodecExports.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/CodecExports.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/CodecExports.cpp 2021-08-07 16:26:47.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/CodecExports.cpp 2023-04-08 11:00:00.000000000 +0000 @@ -3,11 +3,13 @@ #include "StdAfx.h" #include "../../../C/CpuArch.h" +#include "../../../C/7zVersion.h" #include "../../Common/ComTry.h" #include "../../Common/MyCom.h" #include "../../Windows/Defs.h" +#include "../../Windows/PropVariant.h" #include "../ICoder.h" @@ -21,7 +23,7 @@ static void SetPropFromAscii(const char *s, PROPVARIANT *prop) throw() { - UINT len = (UINT)strlen(s); + const UINT len = (UINT)strlen(s); BSTR dest = ::SysAllocStringLen(NULL, len); if (dest) { @@ -45,7 +47,7 @@ clsId.Data1 = k_7zip_GUID_Data1; clsId.Data2 = k_7zip_GUID_Data2; clsId.Data3 = typeId; - SetUi64(clsId.Data4, id); + SetUi64(clsId.Data4, id) return SetPropGUID(clsId, value); } @@ -61,7 +63,7 @@ if (clsid->Data3 == k_7zip_GUID_Data3_Decoder) encode = false; else if (clsid->Data3 != k_7zip_GUID_Data3_Encoder) return S_OK; - UInt64 id = GetUi64(clsid->Data4); + const UInt64 id = GetUi64(clsid->Data4); for (unsigned i = 0; i < g_NumCodecs; i++) { @@ -75,7 +77,7 @@ if (codec.NumStreams == 1 ? isCoder2 : !isCoder2) return E_NOINTERFACE; - index = i; + index = (int)i; return S_OK; } @@ -169,7 +171,7 @@ bool isFilter = false; bool isCoder2 = false; - bool isCoder = (*iid == IID_ICompressCoder) != 0; + const bool isCoder = (*iid == IID_ICompressCoder) != 0; if (!isCoder) { isFilter = (*iid == IID_ICompressFilter) != 0; @@ -183,13 +185,13 @@ bool encode; int codecIndex; - HRESULT res = FindCodecClassId(clsid, isCoder2, isFilter, encode, codecIndex); + const HRESULT res = FindCodecClassId(clsid, isCoder2, isFilter, encode, codecIndex); if (res != S_OK) return res; if (codecIndex < 0) return CLASS_E_CLASSNOTAVAILABLE; - return CreateCoderMain(codecIndex, encode, outObject); + return CreateCoderMain((unsigned)codecIndex, encode, outObject); } @@ -255,8 +257,8 @@ } -STDAPI GetNumberOfMethods(UINT32 *numCodecs); -STDAPI GetNumberOfMethods(UINT32 *numCodecs) +STDAPI GetNumberOfMethods(UInt32 *numCodecs); +STDAPI GetNumberOfMethods(UInt32 *numCodecs) { *numCodecs = g_NumCodecs; return S_OK; @@ -271,10 +273,10 @@ clsid->Data2 != k_7zip_GUID_Data2 || clsid->Data3 != k_7zip_GUID_Data3_Hasher) return -1; - UInt64 id = GetUi64(clsid->Data4); + const UInt64 id = GetUi64(clsid->Data4); for (unsigned i = 0; i < g_NumCodecs; i++) if (id == g_Hashers[i]->Id) - return i; + return (int)i; return -1; } @@ -292,11 +294,11 @@ STDAPI CreateHasher(const GUID *clsid, IHasher **outObject) { COM_TRY_BEGIN - *outObject = 0; - int index = FindHasherClassId(clsid); + *outObject = NULL; + const int index = FindHasherClassId(clsid); if (index < 0) return CLASS_E_CLASSNOTAVAILABLE; - return CreateHasher2(index, outObject); + return CreateHasher2((UInt32)(unsigned)index, outObject); COM_TRY_END } @@ -326,17 +328,7 @@ return S_OK; } -class CHashers: - public IHashers, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP1(IHashers) - - STDMETHOD_(UInt32, GetNumHashers)(); - STDMETHOD(GetHasherProp)(UInt32 index, PROPID propID, PROPVARIANT *value); - STDMETHOD(CreateHasher)(UInt32 index, IHasher **hasher); -}; +Z7_CLASS_IMP_COM_1(CHashers, IHashers) }; STDAPI GetHashers(IHashers **hashers); STDAPI GetHashers(IHashers **hashers) @@ -349,17 +341,38 @@ COM_TRY_END } -STDMETHODIMP_(UInt32) CHashers::GetNumHashers() +Z7_COM7F_IMF2(UInt32, CHashers::GetNumHashers()) { return g_NumHashers; } -STDMETHODIMP CHashers::GetHasherProp(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHashers::GetHasherProp(UInt32 index, PROPID propID, PROPVARIANT *value)) { return ::GetHasherProp(index, propID, value); } -STDMETHODIMP CHashers::CreateHasher(UInt32 index, IHasher **hasher) +Z7_COM7F_IMF(CHashers::CreateHasher(UInt32 index, IHasher **hasher)) { return ::CreateHasher2(index, hasher); } + + +STDAPI GetModuleProp(PROPID propID, PROPVARIANT *value); +STDAPI GetModuleProp(PROPID propID, PROPVARIANT *value) +{ + ::VariantClear((VARIANTARG *)value); + switch (propID) + { + case NModulePropID::kInterfaceType: + { + NWindows::NCOM::PropVarEm_Set_UInt32(value, NModuleInterfaceType::k_IUnknown_VirtDestructor_ThisModule); + break; + } + case NModulePropID::kVersion: + { + NWindows::NCOM::PropVarEm_Set_UInt32(value, (MY_VER_MAJOR << 16) | MY_VER_MINOR); + break; + } + } + return S_OK; +} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/CopyCoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/CopyCoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/CopyCoder.cpp 2021-12-13 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/CopyCoder.cpp 2023-02-01 10:00:00.000000000 +0000 @@ -15,15 +15,15 @@ ::MidFree(_buf); } -STDMETHODIMP CCopyCoder::SetFinishMode(UInt32 /* finishMode */) +Z7_COM7F_IMF(CCopyCoder::SetFinishMode(UInt32 /* finishMode */)) { return S_OK; } -STDMETHODIMP CCopyCoder::Code(ISequentialInStream *inStream, +Z7_COM7F_IMF(CCopyCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 * /* inSize */, const UInt64 *outSize, - ICompressProgressInfo *progress) + ICompressProgressInfo *progress)) { if (!_buf) { @@ -44,7 +44,12 @@ { size = (UInt32)rem; if (size == 0) + { + /* if we enable the following check, + we will make one call of Read(_buf, 0) for empty stream */ + // if (TotalSize != 0) return S_OK; + } } } @@ -81,7 +86,7 @@ return E_FAIL; // internal code failure pos += processed; TotalSize += processed; - RINOK(res); + RINOK(res) if (processed == 0) return E_FAIL; } @@ -90,32 +95,32 @@ else TotalSize += size; - RINOK(readRes); + RINOK(readRes) if (size != kBufSize) return S_OK; if (progress && (TotalSize & (((UInt32)1 << 22) - 1)) == 0) { - RINOK(progress->SetRatioInfo(&TotalSize, &TotalSize)); + RINOK(progress->SetRatioInfo(&TotalSize, &TotalSize)) } } } -STDMETHODIMP CCopyCoder::SetInStream(ISequentialInStream *inStream) +Z7_COM7F_IMF(CCopyCoder::SetInStream(ISequentialInStream *inStream)) { _inStream = inStream; TotalSize = 0; return S_OK; } -STDMETHODIMP CCopyCoder::ReleaseInStream() +Z7_COM7F_IMF(CCopyCoder::ReleaseInStream()) { _inStream.Release(); return S_OK; } -STDMETHODIMP CCopyCoder::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CCopyCoder::Read(void *data, UInt32 size, UInt32 *processedSize)) { UInt32 realProcessedSize = 0; HRESULT res = _inStream->Read(data, size, &realProcessedSize); @@ -125,7 +130,7 @@ return res; } -STDMETHODIMP CCopyCoder::GetInStreamProcessedSize(UInt64 *value) +Z7_COM7F_IMF(CCopyCoder::GetInStreamProcessedSize(UInt64 *value)) { *value = TotalSize; return S_OK; @@ -141,7 +146,7 @@ { NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder; CMyComPtr copyCoder = copyCoderSpec; - RINOK(copyCoder->Code(inStream, outStream, NULL, &size, progress)); + RINOK(copyCoder->Code(inStream, outStream, NULL, &size, progress)) return copyCoderSpec->TotalSize == size ? S_OK : E_FAIL; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/CopyCoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/CopyCoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/CopyCoder.h 2017-02-12 05:52:06.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/CopyCoder.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Compress/CopyCoder.h -#ifndef __COMPRESS_COPY_CODER_H -#define __COMPRESS_COPY_CODER_H +#ifndef ZIP7_INC_COMPRESS_COPY_CODER_H +#define ZIP7_INC_COMPRESS_COPY_CODER_H #include "../../Common/MyCom.h" @@ -9,36 +9,21 @@ namespace NCompress { -class CCopyCoder: - public ICompressCoder, - public ICompressSetInStream, - public ISequentialInStream, - public ICompressSetFinishMode, - public ICompressGetInStreamProcessedSize, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_5( + CCopyCoder + , ICompressCoder + , ICompressSetInStream + , ISequentialInStream + , ICompressSetFinishMode + , ICompressGetInStreamProcessedSize +) Byte *_buf; CMyComPtr _inStream; public: UInt64 TotalSize; - CCopyCoder(): _buf(0), TotalSize(0) {}; + CCopyCoder(): _buf(NULL), TotalSize(0) {} ~CCopyCoder(); - - MY_UNKNOWN_IMP5( - ICompressCoder, - ICompressSetInStream, - ISequentialInStream, - ICompressSetFinishMode, - ICompressGetInStreamProcessedSize) - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetInStream)(ISequentialInStream *inStream); - STDMETHOD(ReleaseInStream)(); - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(SetFinishMode)(UInt32 finishMode); - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); }; HRESULT CopyStream(ISequentialInStream *inStream, ISequentialOutStream *outStream, ICompressProgressInfo *progress); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/Deflate64Register.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/Deflate64Register.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/Deflate64Register.cpp 2016-04-25 10:19:43.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/Deflate64Register.cpp 2023-03-28 10:00:00.000000000 +0000 @@ -5,8 +5,7 @@ #include "../Common/RegisterCodec.h" #include "DeflateDecoder.h" - -#if !defined(EXTRACT_ONLY) && !defined(DEFLATE_EXTRACT_ONLY) +#if !defined(Z7_EXTRACT_ONLY) && !defined(Z7_DEFLATE_EXTRACT_ONLY) #include "DeflateEncoder.h" #endif @@ -15,7 +14,7 @@ REGISTER_CODEC_CREATE(CreateDec, NDecoder::CCOMCoder64()) -#if !defined(EXTRACT_ONLY) && !defined(DEFLATE_EXTRACT_ONLY) +#if !defined(Z7_EXTRACT_ONLY) && !defined(Z7_DEFLATE_EXTRACT_ONLY) REGISTER_CODEC_CREATE(CreateEnc, NEncoder::CCOMCoder64()) #else #define CreateEnc NULL diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/DeflateConst.h 7zip-23.01+dfsg/CPP/7zip/Compress/DeflateConst.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/DeflateConst.h 2015-05-09 09:52:29.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/DeflateConst.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // DeflateConst.h -#ifndef __DEFLATE_CONST_H -#define __DEFLATE_CONST_H +#ifndef ZIP7_INC_DEFLATE_CONST_H +#define ZIP7_INC_DEFLATE_CONST_H namespace NCompress { namespace NDeflate { diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/DeflateDecoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/DeflateDecoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/DeflateDecoder.cpp 2022-01-26 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/DeflateDecoder.cpp 2023-03-28 11:00:00.000000000 +0000 @@ -83,7 +83,7 @@ m_FinalBlock = (ReadBits(kFinalBlockFieldSize) == NFinalBlockField::kFinalBlock); if (m_InBitStream.ExtraBitsWereRead()) return false; - UInt32 blockType = ReadBits(kBlockTypeFieldSize); + const UInt32 blockType = ReadBits(kBlockTypeFieldSize); if (blockType > NBlockType::kDynamicHuffman) return false; if (m_InBitStream.ExtraBitsWereRead()) @@ -109,9 +109,9 @@ } else { - unsigned numLitLenLevels = ReadBits(kNumLenCodesFieldSize) + kNumLitLenCodesMin; + const unsigned numLitLenLevels = ReadBits(kNumLenCodesFieldSize) + kNumLitLenCodesMin; _numDistLevels = ReadBits(kNumDistCodesFieldSize) + kNumDistCodesMin; - unsigned numLevelCodes = ReadBits(kNumLevelCodesFieldSize) + kNumLevelCodesMin; + const unsigned numLevelCodes = ReadBits(kNumLevelCodesFieldSize) + kNumLevelCodesMin; if (!_deflate64Mode) if (_numDistLevels > kDistTableSize32) @@ -120,7 +120,7 @@ Byte levelLevels[kLevelTableSize]; for (unsigned i = 0; i < kLevelTableSize; i++) { - unsigned position = kCodeLengthAlphabetOrder[i]; + const unsigned position = kCodeLengthAlphabetOrder[i]; if (i < numLevelCodes) levelLevels[position] = (Byte)ReadBits(kLevelFieldSize); else @@ -130,7 +130,7 @@ if (m_InBitStream.ExtraBitsWereRead()) return false; - RIF(m_LevelDecoder.Build(levelLevels)); + RIF(m_LevelDecoder.Build(levelLevels)) Byte tmpLevels[kFixedMainTableSize + kFixedDistTableSize]; if (!DecodeLevels(tmpLevels, numLitLenLevels + _numDistLevels)) @@ -143,7 +143,7 @@ memcpy(levels.litLenLevels, tmpLevels, numLitLenLevels); memcpy(levels.distLevels, tmpLevels + numLitLenLevels, _numDistLevels); } - RIF(m_MainDecoder.Build(levels.litLenLevels)); + RIF(m_MainDecoder.Build(levels.litLenLevels)) return m_DistDecoder.Build(levels.distLevels); } @@ -174,7 +174,7 @@ if (!_keepHistory) if (!m_OutWindowStream.Create(_deflate64Mode ? kHistorySize64: kHistorySize32)) return E_OUTOFMEMORY; - RINOK(InitInStream(_needInitInStream)); + RINOK(InitInStream(_needInitInStream)) m_OutWindowStream.Init(_keepHistory); m_FinalBlock = false; @@ -185,7 +185,7 @@ while (_remainLen > 0 && curSize > 0) { _remainLen--; - Byte b = m_OutWindowStream.GetByte(_rep0); + const Byte b = m_OutWindowStream.GetByte(_rep0); m_OutWindowStream.PutByte(b); curSize--; } @@ -314,7 +314,7 @@ } -#ifdef _NO_EXCEPTIONS +#ifdef Z7_NO_EXCEPTIONS #define DEFLATE_TRY_BEGIN #define DEFLATE_TRY_END(res) @@ -361,7 +361,7 @@ if (!finishInputStream && curSize == 0) break; - RINOK(CodeSpec(curSize, finishInputStream, progress ? kInputProgressLimit : 0)); + RINOK(CodeSpec(curSize, finishInputStream, progress ? kInputProgressLimit : 0)) if (_remainLen == kLenIdFinished) break; @@ -370,7 +370,7 @@ { const UInt64 inSize = m_InBitStream.GetProcessedSize() - inStart; const UInt64 nowPos64 = GetOutProcessedCur(); - RINOK(progress->SetRatioInfo(&inSize, &nowPos64)); + RINOK(progress->SetRatioInfo(&inSize, &nowPos64)) } } @@ -392,12 +392,12 @@ } -HRESULT CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress)) { SetInStream(inStream); SetOutStreamSize(outSize); - HRESULT res = CodeReal(outStream, progress); + const HRESULT res = CodeReal(outStream, progress); ReleaseInStream(); /* if (res == S_OK) @@ -408,21 +408,21 @@ } -STDMETHODIMP CCoder::SetFinishMode(UInt32 finishMode) +Z7_COM7F_IMF(CCoder::SetFinishMode(UInt32 finishMode)) { Set_NeedFinishInput(finishMode != 0); return S_OK; } -STDMETHODIMP CCoder::GetInStreamProcessedSize(UInt64 *value) +Z7_COM7F_IMF(CCoder::GetInStreamProcessedSize(UInt64 *value)) { *value = m_InBitStream.GetStreamSize(); return S_OK; } -STDMETHODIMP CCoder::ReadUnusedFromInBuf(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CCoder::ReadUnusedFromInBuf(void *data, UInt32 size, UInt32 *processedSize)) { AlignToByte(); UInt32 i = 0; @@ -439,7 +439,7 @@ } -STDMETHODIMP CCoder::SetInStream(ISequentialInStream *inStream) +Z7_COM7F_IMF(CCoder::SetInStream(ISequentialInStream *inStream)) { m_InStreamRef = inStream; m_InBitStream.SetStream(inStream); @@ -447,7 +447,7 @@ } -STDMETHODIMP CCoder::ReleaseInStream() +Z7_COM7F_IMF(CCoder::ReleaseInStream()) { m_InStreamRef.Release(); return S_OK; @@ -468,7 +468,7 @@ } -STDMETHODIMP CCoder::SetOutStreamSize(const UInt64 *outSize) +Z7_COM7F_IMF(CCoder::SetOutStreamSize(const UInt64 *outSize)) { /* 18.06: @@ -484,9 +484,9 @@ } -#ifndef NO_READ_FROM_CODER +#ifndef Z7_NO_READ_FROM_CODER -STDMETHODIMP CCoder::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CCoder::Read(void *data, UInt32 size, UInt32 *processedSize)) { HRESULT res; @@ -517,7 +517,7 @@ DEFLATE_TRY_END(res) { - HRESULT res2 = Flush(); + const HRESULT res2 = Flush(); if (res2 != S_OK) res = res2; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/DeflateDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/DeflateDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/DeflateDecoder.h 2019-09-09 17:14:08.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/DeflateDecoder.h 2023-03-28 11:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // DeflateDecoder.h -#ifndef __DEFLATE_DECODER_H -#define __DEFLATE_DECODER_H +#ifndef ZIP7_INC_DEFLATE_DECODER_H +#define ZIP7_INC_DEFLATE_DECODER_H #include "../../Common/MyCom.h" @@ -26,13 +26,37 @@ public ICompressSetFinishMode, public ICompressGetInStreamProcessedSize, public ICompressReadUnusedFromInBuf, - #ifndef NO_READ_FROM_CODER public ICompressSetInStream, public ICompressSetOutStreamSize, + #ifndef Z7_NO_READ_FROM_CODER public ISequentialInStream, - #endif + #endif public CMyUnknownImp { + Z7_COM_QI_BEGIN2(ICompressCoder) + Z7_COM_QI_ENTRY(ICompressSetFinishMode) + Z7_COM_QI_ENTRY(ICompressGetInStreamProcessedSize) + Z7_COM_QI_ENTRY(ICompressReadUnusedFromInBuf) + Z7_COM_QI_ENTRY(ICompressSetInStream) + Z7_COM_QI_ENTRY(ICompressSetOutStreamSize) + #ifndef Z7_NO_READ_FROM_CODER + Z7_COM_QI_ENTRY(ISequentialInStream) + #endif + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(ICompressCoder) + Z7_IFACE_COM7_IMP(ICompressSetFinishMode) + Z7_IFACE_COM7_IMP(ICompressGetInStreamProcessedSize) + Z7_IFACE_COM7_IMP(ICompressReadUnusedFromInBuf) +public: + Z7_IFACE_COM7_IMP(ICompressSetInStream) +private: + Z7_IFACE_COM7_IMP(ICompressSetOutStreamSize) + #ifndef Z7_NO_READ_FROM_CODER + Z7_IFACE_COM7_IMP(ISequentialInStream) + #endif + CLzOutWindow m_OutWindowStream; CMyComPtr m_InStreamRef; NBitl::CDecoder m_InBitStream; @@ -89,50 +113,20 @@ Byte ZlibFooter[4]; CCoder(bool deflate64Mode); - virtual ~CCoder() {}; + virtual ~CCoder() {} void SetNsisMode(bool nsisMode) { _deflateNSIS = nsisMode; } void Set_KeepHistory(bool keepHistory) { _keepHistory = keepHistory; } void Set_NeedFinishInput(bool needFinishInput) { _needFinishInput = needFinishInput; } - bool IsFinished() const { return _remainLen == kLenIdFinished;; } + bool IsFinished() const { return _remainLen == kLenIdFinished; } bool IsFinalBlock() const { return m_FinalBlock; } HRESULT CodeReal(ISequentialOutStream *outStream, ICompressProgressInfo *progress); - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - MY_QUERYINTERFACE_ENTRY(ICompressSetFinishMode) - MY_QUERYINTERFACE_ENTRY(ICompressGetInStreamProcessedSize) - MY_QUERYINTERFACE_ENTRY(ICompressReadUnusedFromInBuf) - - #ifndef NO_READ_FROM_CODER - MY_QUERYINTERFACE_ENTRY(ICompressSetInStream) - MY_QUERYINTERFACE_ENTRY(ICompressSetOutStreamSize) - MY_QUERYINTERFACE_ENTRY(ISequentialInStream) - #endif - - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetFinishMode)(UInt32 finishMode); - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); - STDMETHOD(ReadUnusedFromInBuf)(void *data, UInt32 size, UInt32 *processedSize); - - STDMETHOD(SetInStream)(ISequentialInStream *inStream); - STDMETHOD(ReleaseInStream)(); - STDMETHOD(SetOutStreamSize)(const UInt64 *outSize); - - #ifndef NO_READ_FROM_CODER - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - #endif - +public: HRESULT CodeResume(ISequentialOutStream *outStream, const UInt64 *outSize, ICompressProgressInfo *progress); - HRESULT InitInStream(bool needInit); void AlignToByte() { m_InBitStream.AlignToByte(); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/DeflateEncoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/DeflateEncoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/DeflateEncoder.cpp 2021-07-13 12:51:14.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/DeflateEncoder.cpp 2023-03-07 07:00:00.000000000 +0000 @@ -14,7 +14,7 @@ #undef NO_INLINE #ifdef _MSC_VER -#define NO_INLINE MY_NO_INLINE +#define NO_INLINE Z7_NO_INLINE #else #define NO_INLINE #endif @@ -158,34 +158,34 @@ HRESULT CCoder::Create() { // COM_TRY_BEGIN - if (m_Values == 0) + if (!m_Values) { m_Values = (CCodeValue *)MyAlloc((kMaxUncompressedBlockSize) * sizeof(CCodeValue)); - if (m_Values == 0) + if (!m_Values) return E_OUTOFMEMORY; } - if (m_Tables == 0) + if (!m_Tables) { m_Tables = (CTables *)MyAlloc((kNumTables) * sizeof(CTables)); - if (m_Tables == 0) + if (!m_Tables) return E_OUTOFMEMORY; } if (m_IsMultiPass) { - if (m_OnePosMatchesMemory == 0) + if (!m_OnePosMatchesMemory) { m_OnePosMatchesMemory = (UInt16 *)::MidAlloc(kMatchArraySize * sizeof(UInt16)); - if (m_OnePosMatchesMemory == 0) + if (!m_OnePosMatchesMemory) return E_OUTOFMEMORY; } } else { - if (m_DistanceMemory == 0) + if (!m_DistanceMemory) { m_DistanceMemory = (UInt16 *)MyAlloc((kMatchMaxLen + 2) * 2 * sizeof(UInt16)); - if (m_DistanceMemory == 0) + if (!m_DistanceMemory) return E_OUTOFMEMORY; m_MatchDistances = m_DistanceMemory; } @@ -195,10 +195,11 @@ { _lzInWindow.btMode = (Byte)(_btMode ? 1 : 0); _lzInWindow.numHashBytes = 3; + _lzInWindow.numHashBytes_Min = 3; if (!MatchFinder_Create(&_lzInWindow, m_Deflate64Mode ? kHistorySize64 : kHistorySize32, kNumOpts + kMaxUncompressedBlockSize, - m_NumFastBytes, m_MatchMaxLen - m_NumFastBytes, &g_Alloc)) + m_NumFastBytes, m_MatchMaxLen - m_NumFastBytes, &g_AlignedAlloc)) return E_OUTOFMEMORY; if (!m_OutStream.Create(1 << 20)) return E_OUTOFMEMORY; @@ -239,16 +240,16 @@ void CCoder::Free() { - ::MidFree(m_OnePosMatchesMemory); m_OnePosMatchesMemory = 0; - ::MyFree(m_DistanceMemory); m_DistanceMemory = 0; - ::MyFree(m_Values); m_Values = 0; - ::MyFree(m_Tables); m_Tables = 0; + ::MidFree(m_OnePosMatchesMemory); m_OnePosMatchesMemory = NULL; + ::MyFree(m_DistanceMemory); m_DistanceMemory = NULL; + ::MyFree(m_Values); m_Values = NULL; + ::MyFree(m_Tables); m_Tables = NULL; } CCoder::~CCoder() { Free(); - MatchFinder_Free(&_lzInWindow, &g_Alloc); + MatchFinder_Free(&_lzInWindow, &g_AlignedAlloc); } NO_INLINE void CCoder::GetMatches() @@ -945,17 +946,19 @@ m_CheckStatic = (m_NumPasses != 1 || m_NumDivPasses != 1); m_IsMultiPass = (m_CheckStatic || (m_NumPasses != 1 || m_NumDivPasses != 1)); - RINOK(Create()); - - m_ValueBlockSize = (7 << 10) + (1 << 12) * m_NumDivPasses; - - UInt64 nowPos = 0; + /* we can set stream mode before MatchFinder_Create + if default MatchFinder mode was not STREAM_MODE) */ + // MatchFinder_SET_STREAM_MODE(&_lzInWindow); CSeqInStreamWrap _seqInStream; - _seqInStream.Init(inStream); + MatchFinder_SET_STREAM(&_lzInWindow, &_seqInStream.vt) - _lzInWindow.stream = &_seqInStream.vt; + RINOK(Create()) + + m_ValueBlockSize = (7 << 10) + (1 << 12) * m_NumDivPasses; + + UInt64 nowPos = 0; MatchFinder_Init(&_lzInWindow); m_OutStream.SetStream(outStream); @@ -978,7 +981,7 @@ if (progress != NULL) { UInt64 packSize = m_OutStream.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&nowPos, &packSize)); + RINOK(progress->SetRatioInfo(&nowPos, &packSize)) } } while (Inline_MatchFinder_GetNumAvailableBytes(&_lzInWindow) != 0); @@ -999,18 +1002,18 @@ catch(...) { return E_FAIL; } } -STDMETHODIMP CCOMCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CCOMCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)) { return BaseCode(inStream, outStream, inSize, outSize, progress); } -STDMETHODIMP CCOMCoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps) +Z7_COM7F_IMF(CCOMCoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps)) { return BaseSetEncoderProperties2(propIDs, props, numProps); } -STDMETHODIMP CCOMCoder64::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CCOMCoder64::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)) { return BaseCode(inStream, outStream, inSize, outSize, progress); } -STDMETHODIMP CCOMCoder64::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps) +Z7_COM7F_IMF(CCOMCoder64::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps)) { return BaseSetEncoderProperties2(propIDs, props, numProps); } }}} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/DeflateEncoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/DeflateEncoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/DeflateEncoder.h 2017-04-05 12:49:10.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/DeflateEncoder.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // DeflateEncoder.h -#ifndef __DEFLATE_ENCODER_H -#define __DEFLATE_ENCODER_H +#ifndef ZIP7_INC_DEFLATE_ENCODER_H +#define ZIP7_INC_DEFLATE_ENCODER_H #include "../../../C/LzFind.h" @@ -176,32 +176,26 @@ }; -class CCOMCoder : +class CCOMCoder Z7_final: public ICompressCoder, public ICompressSetCoderProperties, public CMyUnknownImp, public CCoder { + Z7_IFACES_IMP_UNK_2(ICompressCoder, ICompressSetCoderProperties) public: - MY_UNKNOWN_IMP2(ICompressCoder, ICompressSetCoderProperties) - CCOMCoder(): CCoder(false) {}; - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); + CCOMCoder(): CCoder(false) {} }; -class CCOMCoder64 : +class CCOMCoder64 Z7_final: public ICompressCoder, public ICompressSetCoderProperties, public CMyUnknownImp, public CCoder { + Z7_IFACES_IMP_UNK_2(ICompressCoder, ICompressSetCoderProperties) public: - MY_UNKNOWN_IMP2(ICompressCoder, ICompressSetCoderProperties) - CCOMCoder64(): CCoder(true) {}; - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); + CCOMCoder64(): CCoder(true) {} }; }}} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/DeflateRegister.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/DeflateRegister.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/DeflateRegister.cpp 2016-04-25 10:01:16.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/DeflateRegister.cpp 2023-03-28 10:00:00.000000000 +0000 @@ -5,7 +5,7 @@ #include "../Common/RegisterCodec.h" #include "DeflateDecoder.h" -#if !defined(EXTRACT_ONLY) && !defined(DEFLATE_EXTRACT_ONLY) +#if !defined(Z7_EXTRACT_ONLY) && !defined(Z7_DEFLATE_EXTRACT_ONLY) #include "DeflateEncoder.h" #endif @@ -14,7 +14,7 @@ REGISTER_CODEC_CREATE(CreateDec, NDecoder::CCOMCoder) -#if !defined(EXTRACT_ONLY) && !defined(DEFLATE_EXTRACT_ONLY) +#if !defined(Z7_EXTRACT_ONLY) && !defined(Z7_DEFLATE_EXTRACT_ONLY) REGISTER_CODEC_CREATE(CreateEnc, NEncoder::CCOMCoder) #else #define CreateEnc NULL diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/DeltaFilter.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/DeltaFilter.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/DeltaFilter.cpp 2016-04-26 11:24:13.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/DeltaFilter.cpp 2023-03-28 11:00:00.000000000 +0000 @@ -23,41 +23,40 @@ }; -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY -class CEncoder: +class CEncoder Z7_final: public ICompressFilter, public ICompressSetCoderProperties, public ICompressWriteCoderProperties, - CDelta, - public CMyUnknownImp + public CMyUnknownImp, + CDelta { -public: - MY_UNKNOWN_IMP3(ICompressFilter, ICompressSetCoderProperties, ICompressWriteCoderProperties) - INTERFACE_ICompressFilter(;) - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); - STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream); + Z7_IFACES_IMP_UNK_3( + ICompressFilter, + ICompressSetCoderProperties, + ICompressWriteCoderProperties) }; -STDMETHODIMP CEncoder::Init() +Z7_COM7F_IMF(CEncoder::Init()) { DeltaInit(); return S_OK; } -STDMETHODIMP_(UInt32) CEncoder::Filter(Byte *data, UInt32 size) +Z7_COM7F_IMF2(UInt32, CEncoder::Filter(Byte *data, UInt32 size)) { Delta_Encode(_state, _delta, data, size); return size; } -STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps) +Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps)) { UInt32 delta = _delta; for (UInt32 i = 0; i < numProps; i++) { const PROPVARIANT &prop = props[i]; - PROPID propID = propIDs[i]; + const PROPID propID = propIDs[i]; if (propID >= NCoderPropID::kReduceSize) continue; if (prop.vt != VT_UI4) @@ -78,40 +77,39 @@ return S_OK; } -STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream) +Z7_COM7F_IMF(CEncoder::WriteCoderProperties(ISequentialOutStream *outStream)) { - Byte prop = (Byte)(_delta - 1); + const Byte prop = (Byte)(_delta - 1); return outStream->Write(&prop, 1, NULL); } #endif -class CDecoder: +class CDecoder Z7_final: public ICompressFilter, public ICompressSetDecoderProperties2, - CDelta, - public CMyUnknownImp + public CMyUnknownImp, + CDelta { -public: - MY_UNKNOWN_IMP2(ICompressFilter, ICompressSetDecoderProperties2) - INTERFACE_ICompressFilter(;) - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); + Z7_IFACES_IMP_UNK_2( + ICompressFilter, + ICompressSetDecoderProperties2) }; -STDMETHODIMP CDecoder::Init() +Z7_COM7F_IMF(CDecoder::Init()) { DeltaInit(); return S_OK; } -STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) +Z7_COM7F_IMF2(UInt32, CDecoder::Filter(Byte *data, UInt32 size)) { Delta_Decode(_state, _delta, data, size); return size; } -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *props, UInt32 size) +Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *props, UInt32 size)) { if (size != 1) return E_INVALIDARG; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/HuffmanDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/HuffmanDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/HuffmanDecoder.h 2017-04-10 10:00:18.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/HuffmanDecoder.h 2023-03-07 08:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Compress/HuffmanDecoder.h -#ifndef __COMPRESS_HUFFMAN_DECODER_H -#define __COMPRESS_HUFFMAN_DECODER_H +#ifndef ZIP7_INC_COMPRESS_HUFFMAN_DECODER_H +#define ZIP7_INC_COMPRESS_HUFFMAN_DECODER_H #include "../../Common/MyTypes.h" @@ -141,7 +141,7 @@ template - MY_FORCE_INLINE + Z7_FORCE_INLINE UInt32 Decode(TBitDecoder *bitStream) const { UInt32 val = bitStream->GetValue(kNumBitsMax); @@ -166,7 +166,7 @@ template - MY_FORCE_INLINE + Z7_FORCE_INLINE UInt32 DecodeFull(TBitDecoder *bitStream) const { UInt32 val = bitStream->GetValue(kNumBitsMax); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/ImplodeDecoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/ImplodeDecoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/ImplodeDecoder.cpp 2020-09-28 07:37:45.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/ImplodeDecoder.cpp 2023-03-28 11:00:00.000000000 +0000 @@ -49,7 +49,7 @@ for (sym = 0; sym < numSymbols; sym++) { - unsigned len = lens[sym]; + const unsigned len = lens[sym]; if (len != 0) _symbols[--counts[len]] = (Byte)sym; } @@ -60,10 +60,10 @@ UInt32 CHuffmanDecoder::Decode(CInBit *inStream) const throw() { - UInt32 val = inStream->GetValue(kNumHuffmanBits); + const UInt32 val = inStream->GetValue(kNumHuffmanBits); unsigned numBits; for (numBits = 1; val < _limits[numBits]; numBits++); - UInt32 sym = _symbols[_poses[numBits] + ((val - _limits[numBits]) >> (kNumHuffmanBits - numBits))]; + const UInt32 sym = _symbols[_poses[numBits] + ((val - _limits[numBits]) >> (kNumHuffmanBits - numBits))]; inStream->MovePos(numBits); return sym; } @@ -95,9 +95,9 @@ unsigned index = 0; do { - unsigned b = (unsigned)_inBitStream.ReadAlignedByte(); - Byte level = (Byte)((b & 0xF) + 1); - unsigned rep = ((unsigned)b >> 4) + 1; + const unsigned b = (unsigned)_inBitStream.ReadAlignedByte(); + const Byte level = (Byte)((b & 0xF) + 1); + const unsigned rep = ((unsigned)b >> 4) + 1; if (index + rep > numSymbols) return false; for (unsigned j = 0; j < rep; j++) @@ -149,7 +149,7 @@ if (progress && (pos - prevProgress) >= (1 << 18)) { const UInt64 packSize = _inBitStream.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &pos)); + RINOK(progress->SetRatioInfo(&packSize, &pos)) prevProgress = pos; } @@ -158,7 +158,7 @@ Byte b; if (literalsOn) { - UInt32 sym = _litDecoder.Decode(&_inBitStream); + const UInt32 sym = _litDecoder.Decode(&_inBitStream); // if (sym >= kLitTableSize) break; b = (Byte)sym; } @@ -169,7 +169,7 @@ } else { - UInt32 lowDistBits = _inBitStream.ReadBits(numDistDirectBits); + const UInt32 lowDistBits = _inBitStream.ReadBits(numDistDirectBits); UInt32 dist = _distDecoder.Decode(&_inBitStream); // if (dist >= kDistTableSize) break; dist = (dist << numDistDirectBits) + lowDistBits; @@ -222,8 +222,8 @@ } -STDMETHODIMP CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)) { try { return CodeReal(inStream, outStream, inSize, outSize, progress); } // catch(const CInBufferException &e) { return e.ErrorCode; } @@ -233,7 +233,7 @@ } -STDMETHODIMP CCoder::SetDecoderProperties2(const Byte *data, UInt32 size) +Z7_COM7F_IMF(CCoder::SetDecoderProperties2(const Byte *data, UInt32 size)) { if (size == 0) return E_NOTIMPL; @@ -242,14 +242,14 @@ } -STDMETHODIMP CCoder::SetFinishMode(UInt32 finishMode) +Z7_COM7F_IMF(CCoder::SetFinishMode(UInt32 finishMode)) { _fullStreamMode = (finishMode != 0); return S_OK; } -STDMETHODIMP CCoder::GetInStreamProcessedSize(UInt64 *value) +Z7_COM7F_IMF(CCoder::GetInStreamProcessedSize(UInt64 *value)) { *value = _inBitStream.GetProcessedSize(); return S_OK; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/ImplodeDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/ImplodeDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/ImplodeDecoder.h 2017-01-06 09:57:34.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/ImplodeDecoder.h 2023-03-28 11:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ImplodeDecoder.h -#ifndef __COMPRESS_IMPLODE_DECODER_H -#define __COMPRESS_IMPLODE_DECODER_H +#ifndef ZIP7_INC_COMPRESS_IMPLODE_DECODER_H +#define ZIP7_INC_COMPRESS_IMPLODE_DECODER_H #include "../../Common/MyCom.h" @@ -32,13 +32,13 @@ }; -class CCoder: - public ICompressCoder, - public ICompressSetDecoderProperties2, - public ICompressSetFinishMode, - public ICompressGetInStreamProcessedSize, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_4( + CCoder + , ICompressCoder + , ICompressSetDecoderProperties2 + , ICompressSetFinishMode + , ICompressGetInStreamProcessedSize +) CLzOutWindow _outWindowStream; CInBit _inBitStream; @@ -52,19 +52,7 @@ bool BuildHuff(CHuffmanDecoder &table, unsigned numSymbols); HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - public: - MY_UNKNOWN_IMP3( - ICompressSetDecoderProperties2, - ICompressSetFinishMode, - ICompressGetInStreamProcessedSize) - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - STDMETHOD(SetFinishMode)(UInt32 finishMode); - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); - CCoder(); }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/ImplodeHuffmanDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/ImplodeHuffmanDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/ImplodeHuffmanDecoder.h 2017-04-25 10:46:49.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/ImplodeHuffmanDecoder.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,6 +1,6 @@ // ImplodeHuffmanDecoder.h -#ifndef __IMPLODE_HUFFMAN_DECODER_H -#define __IMPLODE_HUFFMAN_DECODER_H +#ifndef ZIP7_INC_IMPLODE_HUFFMAN_DECODER_H +#define ZIP7_INC_IMPLODE_HUFFMAN_DECODER_H #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/LzfseDecoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/LzfseDecoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/LzfseDecoder.cpp 2022-07-07 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/LzfseDecoder.cpp 2023-03-07 08:00:00.000000000 +0000 @@ -293,7 +293,7 @@ } -static MY_FORCE_INLINE unsigned CountZeroBits(UInt32 val, UInt32 mask) +static Z7_FORCE_INLINE unsigned CountZeroBits(UInt32 val, UInt32 mask) { for (unsigned i = 0;;) { @@ -305,7 +305,7 @@ } -static MY_FORCE_INLINE void InitLitTable(const UInt16 *freqs, UInt32 *table) +static Z7_FORCE_INLINE void InitLitTable(const UInt16 *freqs, UInt32 *table) { for (unsigned i = 0; i < NUM_LIT_SYMBOLS; i++) { @@ -440,7 +440,7 @@ } CBitStream; -static MY_FORCE_INLINE int FseInStream_Init(CBitStream *s, +static Z7_FORCE_INLINE int FseInStream_Init(CBitStream *s, int n, // [-7, 0], (-n == number_of_unused_bits) in last byte const Byte **pbuf) { @@ -448,7 +448,7 @@ s->accum = GetUi32(*pbuf); if (n) { - s->numBits = n + 32; + s->numBits = (unsigned)(n + 32); if ((s->accum >> s->numBits) != 0) return -1; // ERROR, encoder should have zeroed the upper bits } @@ -466,7 +466,7 @@ #define mask31(x, numBits) ((x) & (((UInt32)1 << (numBits)) - 1)) #define FseInStream_FLUSH \ - { unsigned nbits = (31 - in.numBits) & -8; \ + { const unsigned nbits = (31 - in.numBits) & (unsigned)-8; \ if (nbits) { \ buf -= (nbits >> 3); \ if (buf < buf_check) return S_FALSE; \ @@ -476,7 +476,7 @@ -static MY_FORCE_INLINE UInt32 BitStream_Pull(CBitStream *s, unsigned numBits) +static Z7_FORCE_INLINE UInt32 BitStream_Pull(CBitStream *s, unsigned numBits) { s->numBits -= numBits; UInt32 v = s->accum >> s->numBits; @@ -491,7 +491,7 @@ dest = (Byte)(e >> 8); } -static MY_FORCE_INLINE UInt32 FseDecodeExtra(CFseState *pstate, +static Z7_FORCE_INLINE UInt32 FseDecodeExtra(CFseState *pstate, const CExtraEntry *table, CBitStream *s) { @@ -509,6 +509,7 @@ #define freqs_LIT (freqs_D + NUM_D_SYMBOLS) #define GET_BITS_64(v, offset, num, dest) dest = (UInt32) ((v >> (offset)) & ((1 << (num)) - 1)); +#define GET_BITS_64_Int32(v, offset, num, dest) dest = (Int32)((v >> (offset)) & ((1 << (num)) - 1)); #define GET_BITS_32(v, offset, num, dest) dest = (CFseState)((v >> (offset)) & ((1 << (num)) - 1)); @@ -592,22 +593,22 @@ UInt64 v; v = GetUi64(temp); - GET_BITS_64(v, 0, 20, numLiterals); - GET_BITS_64(v, 20, 20, litPayloadSize); - GET_BITS_64(v, 40, 20, numMatches); - GET_BITS_64(v, 60, 3 + 1, literal_bits); // (NumberOfUsedBits - 1) + GET_BITS_64(v, 0, 20, numLiterals) + GET_BITS_64(v, 20, 20, litPayloadSize) + GET_BITS_64(v, 40, 20, numMatches) + GET_BITS_64_Int32(v, 60, 3 + 1, literal_bits) // (NumberOfUsedBits - 1) literal_bits -= 7; // (-NumberOfUnusedBits) if (literal_bits > 0) return S_FALSE; // GET_BITS_64(v, 63, 1, unused); v = GetUi64(temp + 8); - GET_BITS_64(v, 0, 10, lit_state_0); - GET_BITS_64(v, 10, 10, lit_state_1); - GET_BITS_64(v, 20, 10, lit_state_2); - GET_BITS_64(v, 30, 10, lit_state_3); - GET_BITS_64(v, 40, 20, lmdPayloadSize); - GET_BITS_64(v, 60, 3 + 1, lmd_bits); + GET_BITS_64(v, 0, 10, lit_state_0) + GET_BITS_64(v, 10, 10, lit_state_1) + GET_BITS_64(v, 20, 10, lit_state_2) + GET_BITS_64(v, 30, 10, lit_state_3) + GET_BITS_64(v, 40, 20, lmdPayloadSize) + GET_BITS_64_Int32(v, 60, 3 + 1, lmd_bits) lmd_bits -= 7; if (lmd_bits > 0) return S_FALSE; @@ -618,10 +619,10 @@ // correspond to a field in the uncompressed header version, // but is required; we wouldn't know the size of the // compresssed header otherwise. - GET_BITS_32(v32, 0, 10, l_state); - GET_BITS_32(v32, 10, 10, m_state); - GET_BITS_32(v32, 20, 10 + 2, d_state); - // GET_BITS_64(v, 62, 2, unused); + GET_BITS_32(v32, 0, 10, l_state) + GET_BITS_32(v32, 10, 10, m_state) + GET_BITS_32(v32, 20, 10 + 2, d_state) + // GET_BITS_64(v, 62, 2, unused) headerSize = GetUi32(temp + 16); if (headerSize <= kPreHeaderSize + kHeaderSize) @@ -726,11 +727,11 @@ for (; lit < lit_limit; lit += 4) { FseInStream_FLUSH - DECODE_LIT (lit[0], lit_state_0); - DECODE_LIT (lit[1], lit_state_1); + DECODE_LIT (lit[0], lit_state_0) + DECODE_LIT (lit[1], lit_state_1) FseInStream_FLUSH - DECODE_LIT (lit[2], lit_state_2); - DECODE_LIT (lit[3], lit_state_3); + DECODE_LIT (lit[2], lit_state_2) + DECODE_LIT (lit[3], lit_state_3) } if ((buf_start - buf) * 8 != (int)in.numBits) @@ -821,7 +822,7 @@ // LZFSE encoder writes 8 additional zero bytes before LMD payload // We test it: - if ((buf - buf_start) * 8 + in.numBits != 64) + if ((size_t)(buf - buf_start) * 8 + in.numBits != 64) return S_FALSE; if (GetUi64(buf_start) != 0) return S_FALSE; @@ -830,7 +831,7 @@ } -STDMETHODIMP CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, +HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) { PRF(printf("\n\nLzfseDecoder %7u %7u\n", (unsigned)*outSize, (unsigned)*inSize)); @@ -853,12 +854,14 @@ if (LzvnMode) { + if (!outSize || !inSize) + return E_NOTIMPL; const UInt64 unpackSize = *outSize; const UInt64 packSize = *inSize; if (unpackSize > (UInt32)(Int32)-1 || packSize > (UInt32)(Int32)-1) return S_FALSE; - RINOK(DecodeLzvn((UInt32)unpackSize, (UInt32)packSize)); + RINOK(DecodeLzvn((UInt32)unpackSize, (UInt32)packSize)) } else for (;;) @@ -868,12 +871,11 @@ if (progress && ((pos - prevOut) >= (1 << 22) || (packPos - prevIn) >= (1 << 22))) { - RINOK(progress->SetRatioInfo(&packPos, &pos)); + RINOK(progress->SetRatioInfo(&packPos, &pos)) prevIn = packPos; prevOut = pos; } - const UInt64 rem = *outSize - pos; UInt32 v; RINOK(GetUInt32(v)) if ((v & 0xFFFFFF) != 0x787662) // bvx @@ -884,12 +886,15 @@ break; UInt32 unpackSize; - RINOK(GetUInt32(unpackSize)); - + RINOK(GetUInt32(unpackSize)) + UInt32 cur = unpackSize; - if (cur > rem) - cur = (UInt32)rem; - + if (outSize) + { + const UInt64 rem = *outSize - pos; + if (cur > rem) + cur = (UInt32)rem; + } unpackSize -= cur; HRESULT res; @@ -917,15 +922,15 @@ coderReleaser.NeedFlush = false; HRESULT res = m_OutWindowStream.Flush(); if (res == S_OK) - if (*inSize != m_InStream.GetProcessedSize() - || *outSize != m_OutWindowStream.GetProcessedSize()) + if ((inSize && *inSize != m_InStream.GetProcessedSize()) + || (outSize && *outSize != m_OutWindowStream.GetProcessedSize())) res = S_FALSE; return res; } -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)) { try { return CodeReal(inStream, outStream, inSize, outSize, progress); } catch(const CInBufferException &e) { return e.ErrorCode; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/LzfseDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/LzfseDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/LzfseDecoder.h 2022-07-07 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/LzfseDecoder.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // LzfseDecoder.h -#ifndef __LZFSE_DECODER_H -#define __LZFSE_DECODER_H +#ifndef ZIP7_INC_LZFSE_DECODER_H +#define ZIP7_INC_LZFSE_DECODER_H #include "../../Common/MyBuffer.h" #include "../../Common/MyCom.h" @@ -15,10 +15,10 @@ namespace NCompress { namespace NLzfse { -class CDecoder: - public ICompressCoder, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + CDecoder + , ICompressCoder +) CLzOutWindow m_OutWindowStream; CInBuffer m_InStream; CByteBuffer _literals; @@ -44,11 +44,10 @@ HRESULT DecodeLzvn(UInt32 unpackSize, UInt32 packSize); HRESULT DecodeLzfse(UInt32 unpackSize, Byte version); - STDMETHOD(CodeReal)(ISequentialInStream *inStream, ISequentialOutStream *outStream, + HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); public: bool LzvnMode; - MY_UNKNOWN_IMP CDecoder(): LzvnMode(false) @@ -57,9 +56,6 @@ // sizes are checked in Code() // UInt64 GetInputProcessedSize() const { return m_InStream.GetProcessedSize(); } // UInt64 GetOutputProcessedSize() const { return m_OutWindowStream.GetProcessedSize(); } - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize, - const UInt64 *outSize, ICompressProgressInfo *progress); }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/LzhDecoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/LzhDecoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/LzhDecoder.cpp 2015-09-03 12:04:03.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/LzhDecoder.cpp 2023-03-28 11:00:00.000000000 +0000 @@ -15,7 +15,7 @@ UInt32 sum = 0; for (unsigned i = 0; i < num; i++) { - unsigned len = lens[i]; + const unsigned len = lens[i]; if (len != 0) sum += ((UInt32)1 << (NUM_CODE_BITS - len)); } @@ -26,11 +26,12 @@ { _symbolT = -1; - UInt32 n = _inBitStream.ReadBits(numBits); + const UInt32 n = _inBitStream.ReadBits(numBits); if (n == 0) { - _symbolT = _inBitStream.ReadBits(numBits); - return ((unsigned)_symbolT < num); + const unsigned s = _inBitStream.ReadBits(numBits); + _symbolT = (int)s; + return (s < num); } if (n > num) @@ -46,7 +47,7 @@ do { - UInt32 val = _inBitStream.GetValue(16); + const UInt32 val = _inBitStream.GetValue(16); unsigned c = val >> 13; if (c == 7) @@ -85,8 +86,9 @@ if (n == 0) { - _symbolC = _inBitStream.ReadBits(NUM_C_BITS); - return ((unsigned)_symbolC < NC); + const unsigned s = _inBitStream.ReadBits(NUM_C_BITS); + _symbolC = (int)s; + return (s < NC); } if (n > NC) @@ -135,7 +137,7 @@ HRESULT CCoder::CodeReal(UInt64 rem, ICompressProgressInfo *progress) { - unsigned pbit = (DictSize <= (1 << 14) ? 4 : 5); + const unsigned pbit = (DictSize <= (1 << 14) ? 4 : 5); UInt32 blockSize = 0; @@ -148,9 +150,9 @@ if (progress) { - UInt64 packSize = _inBitStream.GetProcessedSize(); - UInt64 pos = _outWindow.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &pos)); + const UInt64 packSize = _inBitStream.GetProcessedSize(); + const UInt64 pos = _outWindow.GetProcessedSize(); + RINOK(progress->SetRatioInfo(&packSize, &pos)) } blockSize = _inBitStream.ReadBits(16); @@ -217,8 +219,8 @@ } -STDMETHODIMP CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress)) { try { @@ -237,7 +239,7 @@ CCoderReleaser coderReleaser(this); - RINOK(CodeReal(*outSize, progress)); + RINOK(CodeReal(*outSize, progress)) coderReleaser.Disable(); return _outWindow.Flush(); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/LzhDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/LzhDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/LzhDecoder.h 2015-05-11 09:36:03.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/LzhDecoder.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // LzhDecoder.h -#ifndef __COMPRESS_LZH_DECODER_H -#define __COMPRESS_LZH_DECODER_H +#ifndef ZIP7_INC_COMPRESS_LZH_DECODER_H +#define ZIP7_INC_COMPRESS_LZH_DECODER_H #include "../../Common/MyCom.h" @@ -26,10 +26,10 @@ const unsigned NP = (NUM_DIC_BITS_MAX + 1); const unsigned NPT = NP; // Max(NT, NP) -class CCoder: - public ICompressCoder, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + CCoder + , ICompressCoder +) CLzOutWindow _outWindow; NBitm::CDecoder _inBitStream; @@ -54,14 +54,9 @@ HRESULT CodeReal(UInt64 outSize, ICompressProgressInfo *progress); public: - MY_UNKNOWN_IMP - UInt32 DictSize; bool FinishMode; - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - void SetDictSize(unsigned dictSize) { DictSize = dictSize; } CCoder(): DictSize(1 << 16), FinishMode(false) {} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/Lzma2Decoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/Lzma2Decoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/Lzma2Decoder.cpp 2018-02-17 15:53:51.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/Lzma2Decoder.cpp 2023-03-28 11:00:00.000000000 +0000 @@ -21,7 +21,7 @@ , _finishMode(false) , _inBufSize(1 << 20) , _outStep(1 << 20) - #ifndef _7ZIP_ST + #ifndef Z7_ST , _tryMt(1) , _numThreads(1) , _memUsage((UInt64)(sizeof(size_t)) << 28) @@ -34,10 +34,10 @@ Lzma2DecMt_Destroy(_dec); } -STDMETHODIMP CDecoder::SetInBufSize(UInt32 , UInt32 size) { _inBufSize = size; return S_OK; } -STDMETHODIMP CDecoder::SetOutBufSize(UInt32 , UInt32 size) { _outStep = size; return S_OK; } +Z7_COM7F_IMF(CDecoder::SetInBufSize(UInt32 , UInt32 size)) { _inBufSize = size; return S_OK; } +Z7_COM7F_IMF(CDecoder::SetOutBufSize(UInt32 , UInt32 size)) { _outStep = size; return S_OK; } -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *prop, UInt32 size) +Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *prop, UInt32 size)) { if (size != 1) return E_NOTIMPL; @@ -48,7 +48,7 @@ } -STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode) +Z7_COM7F_IMF(CDecoder::SetFinishMode(UInt32 finishMode)) { _finishMode = (finishMode != 0); return S_OK; @@ -56,7 +56,7 @@ -#ifndef _7ZIP_ST +#ifndef Z7_ST static UInt64 Get_ExpectedBlockSize_From_Dict(UInt32 dictSize) { @@ -81,8 +81,8 @@ #define RET_IF_WRAP_ERROR(wrapRes, sRes, sResErrorCode) \ if (wrapRes != S_OK /* && (sRes == SZ_OK || sRes == sResErrorCode) */) return wrapRes; -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)) { _inProcessed = 0; @@ -102,24 +102,24 @@ props.inBufSize_ST = _inBufSize; props.outStep_ST = _outStep; - #ifndef _7ZIP_ST + #ifndef Z7_ST { props.numThreads = 1; UInt32 numThreads = _numThreads; if (_tryMt && numThreads >= 1) { - UInt64 useLimit = _memUsage; - UInt32 dictSize = LZMA2_DIC_SIZE_FROM_PROP_FULL(_prop); - UInt64 expectedBlockSize64 = Get_ExpectedBlockSize_From_Dict(dictSize); - size_t expectedBlockSize = (size_t)expectedBlockSize64; - size_t inBlockMax = expectedBlockSize + expectedBlockSize / 16; + const UInt64 useLimit = _memUsage; + const UInt32 dictSize = LZMA2_DIC_SIZE_FROM_PROP_FULL(_prop); + const UInt64 expectedBlockSize64 = Get_ExpectedBlockSize_From_Dict(dictSize); + const size_t expectedBlockSize = (size_t)expectedBlockSize64; + const size_t inBlockMax = expectedBlockSize + expectedBlockSize / 16; if (expectedBlockSize == expectedBlockSize64 && inBlockMax >= expectedBlockSize) { props.outBlockMax = expectedBlockSize; props.inBlockMax = inBlockMax; const size_t kOverheadSize = props.inBufSize_MT + (1 << 16); - UInt64 okThreads = useLimit / (props.outBlockMax + props.inBlockMax + kOverheadSize); + const UInt64 okThreads = useLimit / (props.outBlockMax + props.inBlockMax + kOverheadSize); if (numThreads > okThreads) numThreads = (UInt32)okThreads; if (numThreads == 0) @@ -143,7 +143,7 @@ UInt64 inProcessed = 0; int isMT = False; - #ifndef _7ZIP_ST + #ifndef Z7_ST isMT = _tryMt; #endif @@ -162,7 +162,7 @@ */ - #ifndef _7ZIP_ST + #ifndef Z7_ST /* we reset _tryMt, only if p->props.numThreads was changed */ if (props.numThreads > 1) _tryMt = isMT; @@ -186,22 +186,22 @@ } -STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value) +Z7_COM7F_IMF(CDecoder::GetInStreamProcessedSize(UInt64 *value)) { *value = _inProcessed; return S_OK; } -#ifndef _7ZIP_ST +#ifndef Z7_ST -STDMETHODIMP CDecoder::SetNumberOfThreads(UInt32 numThreads) +Z7_COM7F_IMF(CDecoder::SetNumberOfThreads(UInt32 numThreads)) { _numThreads = numThreads; return S_OK; } -STDMETHODIMP CDecoder::SetMemLimit(UInt64 memUsage) +Z7_COM7F_IMF(CDecoder::SetMemLimit(UInt64 memUsage)) { _memUsage = memUsage; return S_OK; @@ -210,9 +210,9 @@ #endif -#ifndef NO_READ_FROM_CODER +#ifndef Z7_NO_READ_FROM_CODER -STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) +Z7_COM7F_IMF(CDecoder::SetOutStreamSize(const UInt64 *outSize)) { CLzma2DecMtProps props; Lzma2DecMtProps_Init(&props); @@ -230,7 +230,7 @@ _inWrap.Init(_inStream); - SRes res = Lzma2DecMt_Init(_dec, _prop, &props, outSize, _finishMode, &_inWrap.vt); + const SRes res = Lzma2DecMt_Init(_dec, _prop, &props, outSize, _finishMode, &_inWrap.vt); if (res != SZ_OK) return SResToHRESULT(res); @@ -238,11 +238,13 @@ } -STDMETHODIMP CDecoder::SetInStream(ISequentialInStream *inStream) { _inStream = inStream; return S_OK; } -STDMETHODIMP CDecoder::ReleaseInStream() { _inStream.Release(); return S_OK; } +Z7_COM7F_IMF(CDecoder::SetInStream(ISequentialInStream *inStream)) + { _inStream = inStream; return S_OK; } +Z7_COM7F_IMF(CDecoder::ReleaseInStream()) + { _inStream.Release(); return S_OK; } -STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -250,7 +252,7 @@ size_t size2 = size; UInt64 inProcessed = 0; - SRes res = Lzma2DecMt_Read(_dec, (Byte *)data, &size2, &inProcessed); + const SRes res = Lzma2DecMt_Read(_dec, (Byte *)data, &size2, &inProcessed); _inProcessed += inProcessed; if (processedSize) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/Lzma2Decoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/Lzma2Decoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/Lzma2Decoder.h 2018-02-08 16:33:37.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/Lzma2Decoder.h 2023-02-01 10:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Lzma2Decoder.h -#ifndef __LZMA2_DECODER_H -#define __LZMA2_DECODER_H +#ifndef ZIP7_INC_LZMA2_DECODER_H +#define ZIP7_INC_LZMA2_DECODER_H #include "../../../C/Lzma2DecMt.h" @@ -10,26 +10,55 @@ namespace NCompress { namespace NLzma2 { -class CDecoder: +class CDecoder Z7_final: public ICompressCoder, public ICompressSetDecoderProperties2, public ICompressSetFinishMode, public ICompressGetInStreamProcessedSize, public ICompressSetBufSize, - - #ifndef NO_READ_FROM_CODER + #ifndef Z7_NO_READ_FROM_CODER public ICompressSetInStream, public ICompressSetOutStreamSize, public ISequentialInStream, - #endif - - #ifndef _7ZIP_ST + #endif + #ifndef Z7_ST public ICompressSetCoderMt, public ICompressSetMemLimit, - #endif - + #endif public CMyUnknownImp { + Z7_COM_QI_BEGIN2(ICompressCoder) + Z7_COM_QI_ENTRY(ICompressSetDecoderProperties2) + Z7_COM_QI_ENTRY(ICompressSetFinishMode) + Z7_COM_QI_ENTRY(ICompressGetInStreamProcessedSize) + Z7_COM_QI_ENTRY(ICompressSetBufSize) + #ifndef Z7_NO_READ_FROM_CODER + Z7_COM_QI_ENTRY(ICompressSetInStream) + Z7_COM_QI_ENTRY(ICompressSetOutStreamSize) + Z7_COM_QI_ENTRY(ISequentialInStream) + #endif + #ifndef Z7_ST + Z7_COM_QI_ENTRY(ICompressSetCoderMt) + Z7_COM_QI_ENTRY(ICompressSetMemLimit) + #endif + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(ICompressCoder) + Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2) + Z7_IFACE_COM7_IMP(ICompressSetFinishMode) + Z7_IFACE_COM7_IMP(ICompressGetInStreamProcessedSize) + Z7_IFACE_COM7_IMP(ICompressSetBufSize) + #ifndef Z7_NO_READ_FROM_CODER + Z7_IFACE_COM7_IMP(ICompressSetOutStreamSize) + Z7_IFACE_COM7_IMP(ICompressSetInStream) + Z7_IFACE_COM7_IMP(ISequentialInStream) + #endif + #ifndef Z7_ST + Z7_IFACE_COM7_IMP(ICompressSetCoderMt) + Z7_IFACE_COM7_IMP(ICompressSetMemLimit) + #endif + CLzma2DecMtHandle _dec; UInt64 _inProcessed; Byte _prop; @@ -37,58 +66,20 @@ UInt32 _inBufSize; UInt32 _outStep; -public: - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - MY_QUERYINTERFACE_ENTRY(ICompressSetDecoderProperties2) - MY_QUERYINTERFACE_ENTRY(ICompressSetFinishMode) - MY_QUERYINTERFACE_ENTRY(ICompressGetInStreamProcessedSize) - MY_QUERYINTERFACE_ENTRY(ICompressSetBufSize) - - #ifndef NO_READ_FROM_CODER - MY_QUERYINTERFACE_ENTRY(ICompressSetInStream) - MY_QUERYINTERFACE_ENTRY(ICompressSetOutStreamSize) - MY_QUERYINTERFACE_ENTRY(ISequentialInStream) - #endif - - #ifndef _7ZIP_ST - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt) - MY_QUERYINTERFACE_ENTRY(ICompressSetMemLimit) - #endif - - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - STDMETHOD(SetFinishMode)(UInt32 finishMode); - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); - STDMETHOD(SetInBufSize)(UInt32 streamIndex, UInt32 size); - STDMETHOD(SetOutBufSize)(UInt32 streamIndex, UInt32 size); - - #ifndef _7ZIP_ST -private: + #ifndef Z7_ST int _tryMt; UInt32 _numThreads; UInt64 _memUsage; -public: - STDMETHOD(SetNumberOfThreads)(UInt32 numThreads); - STDMETHOD(SetMemLimit)(UInt64 memUsage); - #endif + #endif - #ifndef NO_READ_FROM_CODER -private: + #ifndef Z7_NO_READ_FROM_CODER CMyComPtr _inStream; CSeqInStreamWrap _inWrap; -public: - STDMETHOD(SetOutStreamSize)(const UInt64 *outSize); - STDMETHOD(SetInStream)(ISequentialInStream *inStream); - STDMETHOD(ReleaseInStream)(); - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - #endif + #endif +public: CDecoder(); - virtual ~CDecoder(); + ~CDecoder(); }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/Lzma2Encoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/Lzma2Encoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/Lzma2Encoder.cpp 2021-01-22 17:28:59.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/Lzma2Encoder.cpp 2023-03-28 11:00:00.000000000 +0000 @@ -55,33 +55,33 @@ lzma2Props.numTotalThreads = (int)(prop.ulVal); break; default: - RINOK(NLzma::SetLzmaProp(propID, prop, lzma2Props.lzmaProps)); + RINOK(NLzma::SetLzmaProp(propID, prop, lzma2Props.lzmaProps)) } return S_OK; } -STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, - const PROPVARIANT *coderProps, UInt32 numProps) +Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs, + const PROPVARIANT *coderProps, UInt32 numProps)) { CLzma2EncProps lzma2Props; Lzma2EncProps_Init(&lzma2Props); for (UInt32 i = 0; i < numProps; i++) { - RINOK(SetLzma2Prop(propIDs[i], coderProps[i], lzma2Props)); + RINOK(SetLzma2Prop(propIDs[i], coderProps[i], lzma2Props)) } return SResToHRESULT(Lzma2Enc_SetProps(_encoder, &lzma2Props)); } -STDMETHODIMP CEncoder::SetCoderPropertiesOpt(const PROPID *propIDs, - const PROPVARIANT *coderProps, UInt32 numProps) +Z7_COM7F_IMF(CEncoder::SetCoderPropertiesOpt(const PROPID *propIDs, + const PROPVARIANT *coderProps, UInt32 numProps)) { for (UInt32 i = 0; i < numProps; i++) { const PROPVARIANT &prop = coderProps[i]; - PROPID propID = propIDs[i]; + const PROPID propID = propIDs[i]; if (propID == NCoderPropID::kExpectedDataSize) if (prop.vt == VT_UI8) Lzma2Enc_SetDataSize(_encoder, prop.uhVal.QuadPart); @@ -90,9 +90,9 @@ } -STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream) +Z7_COM7F_IMF(CEncoder::WriteCoderProperties(ISequentialOutStream *outStream)) { - Byte prop = Lzma2Enc_WriteProperties(_encoder); + const Byte prop = Lzma2Enc_WriteProperties(_encoder); return WriteStream(outStream, &prop, 1); } @@ -100,8 +100,8 @@ #define RET_IF_WRAP_ERROR(wrapRes, sRes, sResErrorCode) \ if (wrapRes != S_OK /* && (sRes == SZ_OK || sRes == sResErrorCode) */) return wrapRes; -STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress)) { CSeqInStreamWrap inWrap; CSeqOutStreamWrap outWrap; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/Lzma2Encoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/Lzma2Encoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/Lzma2Encoder.h 2017-06-08 09:29:08.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/Lzma2Encoder.h 2023-03-28 11:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Lzma2Encoder.h -#ifndef __LZMA2_ENCODER_H -#define __LZMA2_ENCODER_H +#ifndef ZIP7_INC_LZMA2_ENCODER_H +#define ZIP7_INC_LZMA2_ENCODER_H #include "../../../C/Lzma2Enc.h" @@ -12,29 +12,17 @@ namespace NCompress { namespace NLzma2 { -class CEncoder: - public ICompressCoder, - public ICompressSetCoderProperties, - public ICompressWriteCoderProperties, - public ICompressSetCoderPropertiesOpt, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_4( + CEncoder + , ICompressCoder + , ICompressSetCoderProperties + , ICompressWriteCoderProperties + , ICompressSetCoderPropertiesOpt +) CLzma2EncHandle _encoder; public: - MY_UNKNOWN_IMP4( - ICompressCoder, - ICompressSetCoderProperties, - ICompressWriteCoderProperties, - ICompressSetCoderPropertiesOpt) - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); - STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream); - STDMETHOD(SetCoderPropertiesOpt)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); - CEncoder(); - virtual ~CEncoder(); + ~CEncoder(); }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/Lzma2Register.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/Lzma2Register.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/Lzma2Register.cpp 2016-04-25 10:06:03.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/Lzma2Register.cpp 2023-01-29 16:00:00.000000000 +0000 @@ -6,7 +6,7 @@ #include "Lzma2Decoder.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY #include "Lzma2Encoder.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/LzmaDecoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/LzmaDecoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/LzmaDecoder.cpp 2020-03-19 12:16:21.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/LzmaDecoder.cpp 2023-03-28 12:00:00.000000000 +0000 @@ -25,14 +25,14 @@ namespace NLzma { CDecoder::CDecoder(): - _inBuf(NULL), - _lzmaStatus(LZMA_STATUS_NOT_SPECIFIED), FinishStream(false), _propsWereSet(false), _outSizeDefined(false), _outStep(1 << 20), _inBufSize(0), - _inBufSizeNew(1 << 20) + _inBufSizeNew(1 << 20), + _lzmaStatus(LZMA_STATUS_NOT_SPECIFIED), + _inBuf(NULL) { _inProcessed = 0; _inPos = _inLim = 0; @@ -42,7 +42,7 @@ _alloc.numAlignBits = 7; _alloc.offset = 0; */ - LzmaDec_Construct(&_state); + LzmaDec_CONSTRUCT(&_state) } CDecoder::~CDecoder() @@ -51,8 +51,10 @@ MyFree(_inBuf); } -STDMETHODIMP CDecoder::SetInBufSize(UInt32 , UInt32 size) { _inBufSizeNew = size; return S_OK; } -STDMETHODIMP CDecoder::SetOutBufSize(UInt32 , UInt32 size) { _outStep = size; return S_OK; } +Z7_COM7F_IMF(CDecoder::SetInBufSize(UInt32 , UInt32 size)) + { _inBufSizeNew = size; return S_OK; } +Z7_COM7F_IMF(CDecoder::SetOutBufSize(UInt32 , UInt32 size)) + { _outStep = size; return S_OK; } HRESULT CDecoder::CreateInputBuffer() { @@ -69,7 +71,7 @@ } -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *prop, UInt32 size) +Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *prop, UInt32 size)) { RINOK(SResToHRESULT(LzmaDec_Allocate(&_state, prop, size, &g_AlignedAlloc))) // &_alloc.vt _propsWereSet = true; @@ -90,7 +92,7 @@ } -STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) +Z7_COM7F_IMF(CDecoder::SetOutStreamSize(const UInt64 *outSize)) { _inProcessed = 0; _inPos = _inLim = 0; @@ -99,14 +101,14 @@ } -STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode) +Z7_COM7F_IMF(CDecoder::SetFinishMode(UInt32 finishMode)) { FinishStream = (finishMode != 0); return S_OK; } -STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value) +Z7_COM7F_IMF(CDecoder::GetInStreamProcessedSize(UInt64 *value)) { *value = _inProcessed; return S_OK; @@ -154,7 +156,7 @@ SizeT inProcessed = _inLim - _inPos; ELzmaStatus status; - SRes res = LzmaDec_DecodeToDic(&_state, dicPos + size, _inBuf + _inPos, &inProcessed, finishMode, &status); + const SRes res = LzmaDec_DecodeToDic(&_state, dicPos + size, _inBuf + _inPos, &inProcessed, finishMode, &status); _lzmaStatus = status; _inPos += (UInt32)inProcessed; @@ -163,22 +165,22 @@ _outProcessed += outProcessed; // we check for LZMA_STATUS_NEEDS_MORE_INPUT to allow RangeCoder initialization, if (_outSizeDefined && _outSize == 0) - bool outFinished = (_outSizeDefined && _outProcessed >= _outSize); + const bool outFinished = (_outSizeDefined && _outProcessed >= _outSize); - bool needStop = (res != 0 + const bool needStop = (res != 0 || (inProcessed == 0 && outProcessed == 0) || status == LZMA_STATUS_FINISHED_WITH_MARK || (outFinished && status != LZMA_STATUS_NEEDS_MORE_INPUT)); if (needStop || outProcessed >= size) { - HRESULT res2 = WriteStream(outStream, _state.dic + wrPos, _state.dicPos - wrPos); + const HRESULT res2 = WriteStream(outStream, _state.dic + wrPos, _state.dicPos - wrPos); if (_state.dicPos == _state.dicBufSize) _state.dicPos = 0; wrPos = _state.dicPos; - RINOK(res2); + RINOK(res2) if (needStop) { @@ -207,14 +209,14 @@ if (progress) { const UInt64 inSize = _inProcessed - startInProgress; - RINOK(progress->SetRatioInfo(&inSize, &_outProcessed)); + RINOK(progress->SetRatioInfo(&inSize, &_outProcessed)) } } } -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)) { if (!_inBuf) return E_INVALIDARG; @@ -227,13 +229,14 @@ } -#ifndef NO_READ_FROM_CODER - -STDMETHODIMP CDecoder::SetInStream(ISequentialInStream *inStream) { _inStream = inStream; return S_OK; } -STDMETHODIMP CDecoder::ReleaseInStream() { _inStream.Release(); return S_OK; } +#ifndef Z7_NO_READ_FROM_CODER +Z7_COM7F_IMF(CDecoder::SetInStream(ISequentialInStream *inStream)) + { _inStream = inStream; return S_OK; } +Z7_COM7F_IMF(CDecoder::ReleaseInStream()) + { _inStream.Release(); return S_OK; } -STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -264,7 +267,7 @@ SizeT outProcessed = size; ELzmaStatus status; - SRes res = LzmaDec_DecodeToBuf(&_state, (Byte *)data, &outProcessed, + const SRes res = LzmaDec_DecodeToBuf(&_state, (Byte *)data, &outProcessed, _inBuf + _inPos, &inProcessed, finishMode, &status); _lzmaStatus = status; @@ -308,7 +311,7 @@ HRESULT CDecoder::ReadFromInputStream(void *data, UInt32 size, UInt32 *processedSize) { - RINOK(CreateInputBuffer()); + RINOK(CreateInputBuffer()) if (processedSize) *processedSize = 0; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/LzmaDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/LzmaDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/LzmaDecoder.h 2018-02-07 16:37:19.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/LzmaDecoder.h 2023-03-28 12:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // LzmaDecoder.h -#ifndef __LZMA_DECODER_H -#define __LZMA_DECODER_H +#ifndef ZIP7_INC_LZMA_DECODER_H +#define ZIP7_INC_LZMA_DECODER_H // #include "../../../C/Alloc.h" #include "../../../C/LzmaDec.h" @@ -12,39 +12,71 @@ namespace NCompress { namespace NLzma { -class CDecoder: +class CDecoder Z7_final: public ICompressCoder, public ICompressSetDecoderProperties2, public ICompressSetFinishMode, public ICompressGetInStreamProcessedSize, public ICompressSetBufSize, - #ifndef NO_READ_FROM_CODER + #ifndef Z7_NO_READ_FROM_CODER public ICompressSetInStream, public ICompressSetOutStreamSize, public ISequentialInStream, - #endif + #endif public CMyUnknownImp { - Byte *_inBuf; - UInt32 _inPos; - UInt32 _inLim; - - ELzmaStatus _lzmaStatus; + Z7_COM_QI_BEGIN2(ICompressCoder) + Z7_COM_QI_ENTRY(ICompressSetDecoderProperties2) + Z7_COM_QI_ENTRY(ICompressSetFinishMode) + Z7_COM_QI_ENTRY(ICompressGetInStreamProcessedSize) + Z7_COM_QI_ENTRY(ICompressSetBufSize) + #ifndef Z7_NO_READ_FROM_CODER + Z7_COM_QI_ENTRY(ICompressSetInStream) + Z7_COM_QI_ENTRY(ICompressSetOutStreamSize) + Z7_COM_QI_ENTRY(ISequentialInStream) + #endif + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + Z7_IFACE_COM7_IMP(ICompressCoder) public: - bool FinishStream; // set it before decoding, if you need to decode full LZMA stream + Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2) +private: + Z7_IFACE_COM7_IMP(ICompressSetFinishMode) + Z7_IFACE_COM7_IMP(ICompressGetInStreamProcessedSize) + // Z7_IFACE_COM7_IMP(ICompressSetOutStreamSize) + + Z7_IFACE_COM7_IMP(ICompressSetBufSize) + + #ifndef Z7_NO_READ_FROM_CODER +public: + Z7_IFACE_COM7_IMP(ICompressSetInStream) +private: + Z7_IFACE_COM7_IMP(ISequentialInStream) + Z7_IFACE_COM7_IMP(ICompressSetOutStreamSize) + #else + Z7_COM7F_IMF(SetOutStreamSize(const UInt64 *outSize)); + #endif +public: + bool FinishStream; // set it before decoding, if you need to decode full LZMA stream private: bool _propsWereSet; bool _outSizeDefined; - UInt64 _outSize; - UInt64 _inProcessed; - UInt64 _outProcessed; UInt32 _outStep; UInt32 _inBufSize; UInt32 _inBufSizeNew; + ELzmaStatus _lzmaStatus; + UInt32 _inPos; + UInt32 _inLim; + Byte *_inBuf; + + UInt64 _outSize; + UInt64 _inProcessed; + UInt64 _outProcessed; + // CAlignOffsetAlloc _alloc; CLzmaDec _state; @@ -53,53 +85,21 @@ HRESULT CodeSpec(ISequentialInStream *inStream, ISequentialOutStream *outStream, ICompressProgressInfo *progress); void SetOutStreamSizeResume(const UInt64 *outSize); -public: - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - MY_QUERYINTERFACE_ENTRY(ICompressSetDecoderProperties2) - MY_QUERYINTERFACE_ENTRY(ICompressSetFinishMode) - MY_QUERYINTERFACE_ENTRY(ICompressGetInStreamProcessedSize) - MY_QUERYINTERFACE_ENTRY(ICompressSetBufSize) - #ifndef NO_READ_FROM_CODER - MY_QUERYINTERFACE_ENTRY(ICompressSetInStream) - MY_QUERYINTERFACE_ENTRY(ICompressSetOutStreamSize) - MY_QUERYINTERFACE_ENTRY(ISequentialInStream) - #endif - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - STDMETHOD(SetFinishMode)(UInt32 finishMode); - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); - STDMETHOD(SetOutStreamSize)(const UInt64 *outSize); - STDMETHOD(SetInBufSize)(UInt32 streamIndex, UInt32 size); - STDMETHOD(SetOutBufSize)(UInt32 streamIndex, UInt32 size); - - #ifndef NO_READ_FROM_CODER - + #ifndef Z7_NO_READ_FROM_CODER private: CMyComPtr _inStream; public: - - STDMETHOD(SetInStream)(ISequentialInStream *inStream); - STDMETHOD(ReleaseInStream)(); - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - HRESULT CodeResume(ISequentialOutStream *outStream, const UInt64 *outSize, ICompressProgressInfo *progress); HRESULT ReadFromInputStream(void *data, UInt32 size, UInt32 *processedSize); - - #endif - - UInt64 GetInputProcessedSize() const { return _inProcessed; } + #endif +public: CDecoder(); - virtual ~CDecoder(); + ~CDecoder(); + UInt64 GetInputProcessedSize() const { return _inProcessed; } UInt64 GetOutputProcessedSize() const { return _outProcessed; } - bool NeedsMoreInput() const { return _lzmaStatus == LZMA_STATUS_NEEDS_MORE_INPUT; } - bool CheckFinishStatus(bool withEndMark) const { return _lzmaStatus == (withEndMark ? diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/LzmaEncoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/LzmaEncoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/LzmaEncoder.cpp 2022-02-09 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/LzmaEncoder.cpp 2023-03-28 13:00:00.000000000 +0000 @@ -48,12 +48,12 @@ static int ParseMatchFinder(const wchar_t *s, int *btMode, int *numHashBytes) { - wchar_t c = GetLowCharFast(*s++); + const wchar_t c = GetLowCharFast(*s++); if (c == 'h') { if (GetLowCharFast(*s++) != 'c') return 0; - int num = (int)(*s++ - L'0'); + const int num = (int)(*s++ - L'0'); if (num < 4 || num > 5) return 0; if (*s != 0) @@ -68,7 +68,7 @@ { if (GetLowCharFast(*s++) != 't') return 0; - int num = (int)(*s++ - L'0'); + const int num = (int)(*s++ - L'0'); if (num < 2 || num > 5) return 0; if (*s != 0) @@ -101,6 +101,15 @@ return S_OK; } + if (propID == NCoderPropID::kHashBits) + { + if (prop.vt == VT_UI4) + ep.numHashOutBits = prop.ulVal; + else + return E_INVALIDARG; + return S_OK; + } + if (propID > NCoderPropID::kReduceSize) return S_OK; @@ -133,7 +142,7 @@ if (prop.vt != VT_UI4) return E_INVALIDARG; - UInt32 v = prop.ulVal; + const UInt32 v = prop.ulVal; switch (propID) { case NCoderPropID::kDefaultProp: @@ -155,8 +164,8 @@ return S_OK; } -STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, - const PROPVARIANT *coderProps, UInt32 numProps) +Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs, + const PROPVARIANT *coderProps, UInt32 numProps)) { CLzmaEncProps props; LzmaEncProps_Init(&props); @@ -164,7 +173,7 @@ for (UInt32 i = 0; i < numProps; i++) { const PROPVARIANT &prop = coderProps[i]; - PROPID propID = propIDs[i]; + const PROPID propID = propIDs[i]; switch (propID) { case NCoderPropID::kEndMarker: @@ -173,20 +182,20 @@ props.writeEndMark = (prop.boolVal != VARIANT_FALSE); break; default: - RINOK(SetLzmaProp(propID, prop, props)); + RINOK(SetLzmaProp(propID, prop, props)) } } return SResToHRESULT(LzmaEnc_SetProps(_encoder, &props)); } -STDMETHODIMP CEncoder::SetCoderPropertiesOpt(const PROPID *propIDs, - const PROPVARIANT *coderProps, UInt32 numProps) +Z7_COM7F_IMF(CEncoder::SetCoderPropertiesOpt(const PROPID *propIDs, + const PROPVARIANT *coderProps, UInt32 numProps)) { for (UInt32 i = 0; i < numProps; i++) { const PROPVARIANT &prop = coderProps[i]; - PROPID propID = propIDs[i]; + const PROPID propID = propIDs[i]; if (propID == NCoderPropID::kExpectedDataSize) if (prop.vt == VT_UI8) LzmaEnc_SetDataSize(_encoder, prop.uhVal.QuadPart); @@ -195,11 +204,11 @@ } -STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream) +Z7_COM7F_IMF(CEncoder::WriteCoderProperties(ISequentialOutStream *outStream)) { Byte props[LZMA_PROPS_SIZE]; - size_t size = LZMA_PROPS_SIZE; - RINOK(LzmaEnc_WriteProperties(_encoder, props, &size)); + SizeT size = LZMA_PROPS_SIZE; + RINOK(LzmaEnc_WriteProperties(_encoder, props, &size)) return WriteStream(outStream, props, size); } @@ -293,8 +302,8 @@ -STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress)) { CSeqInStreamWrap inWrap; CSeqOutStreamWrap outWrap; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/LzmaEncoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/LzmaEncoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/LzmaEncoder.h 2017-06-07 18:36:49.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/LzmaEncoder.h 2023-03-28 13:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // LzmaEncoder.h -#ifndef __LZMA_ENCODER_H -#define __LZMA_ENCODER_H +#ifndef ZIP7_INC_LZMA_ENCODER_H +#define ZIP7_INC_LZMA_ENCODER_H #include "../../../C/LzmaEnc.h" @@ -12,30 +12,29 @@ namespace NCompress { namespace NLzma { -class CEncoder: +class CEncoder Z7_final: public ICompressCoder, public ICompressSetCoderProperties, public ICompressWriteCoderProperties, public ICompressSetCoderPropertiesOpt, public CMyUnknownImp { - CLzmaEncHandle _encoder; - UInt64 _inputProcessed; -public: - MY_UNKNOWN_IMP4( + Z7_COM_UNKNOWN_IMP_4( ICompressCoder, ICompressSetCoderProperties, ICompressWriteCoderProperties, ICompressSetCoderPropertiesOpt) - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); - STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream); - STDMETHOD(SetCoderPropertiesOpt)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); + Z7_IFACE_COM7_IMP(ICompressCoder) +public: + Z7_IFACE_COM7_IMP(ICompressSetCoderProperties) + Z7_IFACE_COM7_IMP(ICompressWriteCoderProperties) + Z7_IFACE_COM7_IMP(ICompressSetCoderPropertiesOpt) + + CLzmaEncHandle _encoder; + UInt64 _inputProcessed; CEncoder(); - virtual ~CEncoder(); + ~CEncoder(); UInt64 GetInputProcessedSize() const { return _inputProcessed; } bool IsWriteEndMark() const { return LzmaEnc_IsWriteEndMark(_encoder) != 0; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/LzmaRegister.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/LzmaRegister.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/LzmaRegister.cpp 2016-04-25 10:06:03.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/LzmaRegister.cpp 2023-01-29 16:00:00.000000000 +0000 @@ -6,7 +6,7 @@ #include "LzmaDecoder.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY #include "LzmaEncoder.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/LzmsDecoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/LzmsDecoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/LzmsDecoder.cpp 2021-04-01 11:00:17.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/LzmsDecoder.cpp 2023-03-28 13:00:00.000000000 +0000 @@ -77,7 +77,7 @@ unsigned right = k_NumPosSyms; for (;;) { - unsigned m = (left + right) / 2; + const unsigned m = (left + right) / 2; if (left == m) return m + 1; if (size >= g_PosBases[m]) @@ -139,7 +139,7 @@ Int32 maxTransOffset = k_x86_TransOffset; - Byte b = p[0]; + const Byte b = p[0]; if (b == 0x48) { @@ -202,8 +202,8 @@ UInt32 n = GetUi32(p2); if (i - last_x86_pos <= maxTransOffset) { - n -= i; - SetUi32(p2, n); + n = (UInt32)((Int32)n - i); + SetUi32(p2, n) } target = history + (((UInt32)i + n) & 0xFFFF); } @@ -319,7 +319,7 @@ if (_rc.Decode(&mainState, k_NumMainProbs, mainProbs) == 0) { UInt32 number; - HUFF_DEC(number, m_LitDecoder); + HUFF_DEC(number, m_LitDecoder) LIMIT_CHECK _win[_pos++] = (Byte)number; prevType = 0; @@ -331,12 +331,12 @@ if (_rc.Decode(&lzRepStates[0], k_NumRepProbs, lzRepProbs[0]) == 0) { UInt32 number; - HUFF_DEC(number, m_PosDecoder); + HUFF_DEC(number, m_PosDecoder) LIMIT_CHECK - unsigned numDirectBits = g_PosDirectBits[number]; + const unsigned numDirectBits = g_PosDirectBits[number]; distance = g_PosBases[number]; - READ_BITS_CHECK(numDirectBits); + READ_BITS_CHECK(numDirectBits) distance += _bs.ReadBits32(numDirectBits); // LIMIT_CHECK _reps[3] = _reps[2]; @@ -394,13 +394,13 @@ } UInt32 lenSlot; - HUFF_DEC(lenSlot, m_LenDecoder); + HUFF_DEC(lenSlot, m_LenDecoder) LIMIT_CHECK UInt32 len = g_LenBases[lenSlot]; { - unsigned numDirectBits = k_LenDirectBits[lenSlot]; - READ_BITS_CHECK(numDirectBits); + const unsigned numDirectBits = k_LenDirectBits[lenSlot]; + READ_BITS_CHECK(numDirectBits) len += _bs.ReadBits32(numDirectBits); } // LIMIT_CHECK @@ -429,16 +429,16 @@ if (_rc.Decode(&deltaRepStates[0], k_NumRepProbs, deltaRepProbs[0]) == 0) { - HUFF_DEC(power, m_PowerDecoder); + HUFF_DEC(power, m_PowerDecoder) LIMIT_CHECK UInt32 number; - HUFF_DEC(number, m_DeltaDecoder); + HUFF_DEC(number, m_DeltaDecoder) LIMIT_CHECK - unsigned numDirectBits = g_PosDirectBits[number]; + const unsigned numDirectBits = g_PosDirectBits[number]; distance32 = g_PosBases[number]; - READ_BITS_CHECK(numDirectBits); + READ_BITS_CHECK(numDirectBits) distance32 += _bs.ReadBits32(numDirectBits); // LIMIT_CHECK @@ -500,16 +500,16 @@ power = (UInt32)(_deltaReps[0] >> 32); } - UInt32 dist = (distance32 << power); + const UInt32 dist = (distance32 << power); UInt32 lenSlot; - HUFF_DEC(lenSlot, m_LenDecoder); + HUFF_DEC(lenSlot, m_LenDecoder) LIMIT_CHECK UInt32 len = g_LenBases[lenSlot]; { unsigned numDirectBits = k_LenDirectBits[lenSlot]; - READ_BITS_CHECK(numDirectBits); + READ_BITS_CHECK(numDirectBits) len += _bs.ReadBits32(numDirectBits); } // LIMIT_CHECK diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/LzmsDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/LzmsDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/LzmsDecoder.h 2020-09-29 16:00:05.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/LzmsDecoder.h 2023-01-17 13:00:00.000000000 +0000 @@ -1,8 +1,8 @@ // LzmsDecoder.h // The code is based on LZMS description from wimlib code -#ifndef __LZMS_DECODER_H -#define __LZMS_DECODER_H +#ifndef ZIP7_INC_LZMS_DECODER_H +#define ZIP7_INC_LZMS_DECODER_H // #define SHOW_DEBUG_INFO @@ -158,7 +158,7 @@ void Update(unsigned bit) throw() { - Prob += (Int32)(Hist >> (k_ProbLimit - 1)) - (Int32)bit; + Prob += (UInt32)((Int32)(Hist >> (k_ProbLimit - 1)) - (Int32)bit); Hist = (Hist << 1) | bit; } }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/LzOutWindow.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/LzOutWindow.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/LzOutWindow.cpp 2014-12-30 09:59:53.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/LzOutWindow.cpp 2023-03-28 11:00:00.000000000 +0000 @@ -8,7 +8,7 @@ { if (!solid) COutBuffer::Init(); - #ifdef _NO_EXCEPTIONS + #ifdef Z7_NO_EXCEPTIONS ErrorCode = S_OK; #endif } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/LzOutWindow.h 7zip-23.01+dfsg/CPP/7zip/Compress/LzOutWindow.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/LzOutWindow.h 2018-01-24 16:04:57.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/LzOutWindow.h 2023-03-28 11:00:00.000000000 +0000 @@ -1,11 +1,11 @@ // LzOutWindow.h -#ifndef __LZ_OUT_WINDOW_H -#define __LZ_OUT_WINDOW_H +#ifndef ZIP7_INC_LZ_OUT_WINDOW_H +#define ZIP7_INC_LZ_OUT_WINDOW_H #include "../Common/OutBuffer.h" -#ifndef _NO_EXCEPTIONS +#ifndef Z7_NO_EXCEPTIONS typedef COutBufferException CLzOutWindowException; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/LzxDecoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/LzxDecoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/LzxDecoder.cpp 2021-01-25 18:43:01.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/LzxDecoder.cpp 2023-03-28 13:00:00.000000000 +0000 @@ -27,7 +27,7 @@ return; size -= kResidue; - Byte save = data[(size_t)size + 4]; + const Byte save = data[(size_t)size + 4]; data[(size_t)size + 4] = 0xE8; for (UInt32 i = 0;;) @@ -52,7 +52,7 @@ if (v >= pos && v < (Int32)translationSize) { v += (v >= 0 ? pos : (Int32)translationSize); - SetUi32(p, (UInt32)v); + SetUi32(p, (UInt32)v) } } } @@ -88,7 +88,7 @@ if (_x86_translationSize != 0) { Byte *destData = _win + _writePos; - UInt32 curSize = _pos - _writePos; + const UInt32 curSize = _pos - _writePos; if (KeepHistoryForNext) { if (!_x86_buf) @@ -125,7 +125,7 @@ Byte levels2[kLevelTableSize]; for (unsigned i = 0; i < kLevelTableSize; i++) levels2[i] = (Byte)ReadBits(kNumLevelBits); - RIF(_levelDecoder.Build(levels2)); + RIF(_levelDecoder.Build(levels2)) } unsigned i = 0; @@ -163,7 +163,7 @@ else return false; - unsigned limit = i + num; + const unsigned limit = i + num; if (limit > numSymbols) return false; @@ -188,7 +188,7 @@ _bitStream.NormalizeBig(); - unsigned blockType = (unsigned)ReadBits(kBlockType_NumBits); + const unsigned blockType = (unsigned)ReadBits(kBlockType_NumBits); if (blockType > kBlockType_Uncompressed) return false; @@ -227,7 +227,7 @@ for (unsigned i = 0; i < kNumReps; i++) { - UInt32 rep = _bitStream.ReadUInt32(); + const UInt32 rep = _bitStream.ReadUInt32(); if (rep > _winSize) return false; _reps[i] = rep; @@ -244,16 +244,16 @@ _numAlignBits = kNumAlignBits; for (unsigned i = 0; i < kAlignTableSize; i++) levels[i] = (Byte)ReadBits(kNumAlignLevelBits); - RIF(_alignDecoder.Build(levels)); + RIF(_alignDecoder.Build(levels)) } } - RIF(ReadTable(_mainLevels, 256)); - RIF(ReadTable(_mainLevels + 256, _numPosLenSlots)); + RIF(ReadTable(_mainLevels, 256)) + RIF(ReadTable(_mainLevels + 256, _numPosLenSlots)) unsigned end = 256 + _numPosLenSlots; memset(_mainLevels + end, 0, kMainTableSize - end); - RIF(_mainDecoder.Build(_mainLevels)); - RIF(ReadTable(_lenLevels, kNumLenSymbols)); + RIF(_mainDecoder.Build(_mainLevels)) + RIF(ReadTable(_lenLevels, kNumLenSymbols)) return _lenDecoder.Build(_lenLevels); } @@ -310,7 +310,7 @@ if (_isUncompressedBlock) { - size_t rem = _bitStream.GetRem(); + const size_t rem = _bitStream.GetRem(); if (rem == 0) return S_FALSE; if (next > rem) @@ -359,8 +359,8 @@ sym -= 256; if (sym >= _numPosLenSlots) return S_FALSE; - UInt32 posSlot = sym / kNumLenSlots; - UInt32 lenSlot = sym % kNumLenSlots; + const UInt32 posSlot = sym / kNumLenSlots; + const UInt32 lenSlot = sym % kNumLenSlots; UInt32 len = kMatchMinLen + lenSlot; if (lenSlot == kNumLenSlots - 1) @@ -397,7 +397,7 @@ if (numDirectBits >= _numAlignBits) { dist += (_bitStream.ReadBitsSmall(numDirectBits - kNumAlignBits) << kNumAlignBits); - UInt32 alignTemp = _alignDecoder.Decode(&_bitStream); + const UInt32 alignTemp = _alignDecoder.Decode(&_bitStream); if (alignTemp >= kAlignTableSize) return S_FALSE; dist += alignTemp; @@ -435,7 +435,7 @@ } else { - ptrdiff_t src = (ptrdiff_t)srcPos - (ptrdiff_t)_pos; + const ptrdiff_t src = (ptrdiff_t)srcPos - (ptrdiff_t)_pos; _pos += len; const Byte *lim = dest + len; *(dest) = *(dest + src); @@ -485,8 +485,8 @@ _bitStream.Init(inData, inSize); - HRESULT res = CodeSpec(outSize); - HRESULT res2 = Flush(); + const HRESULT res = CodeSpec(outSize); + const HRESULT res2 = Flush(); return (res == S_OK ? res2 : res); } @@ -496,7 +496,7 @@ _numDictBits = numDictBits; if (numDictBits < kNumDictBits_Min || numDictBits > kNumDictBits_Max) return E_INVALIDARG; - unsigned numPosSlots = (numDictBits < 20) ? + const unsigned numPosSlots = (numDictBits < 20) ? numDictBits * 2 : 34 + ((unsigned)1 << (numDictBits - 17)); _numPosLenSlots = numPosSlots * kNumLenSlots; @@ -506,9 +506,9 @@ HRESULT CDecoder::SetParams_and_Alloc(unsigned numDictBits) { - RINOK(SetParams2(numDictBits)); + RINOK(SetParams2(numDictBits)) - UInt32 newWinSize = (UInt32)1 << numDictBits; + const UInt32 newWinSize = (UInt32)1 << numDictBits; if (NeedAlloc) { diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/LzxDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/LzxDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/LzxDecoder.h 2021-01-25 15:08:13.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/LzxDecoder.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // LzxDecoder.h -#ifndef __LZX_DECODER_H -#define __LZX_DECODER_H +#ifndef ZIP7_INC_LZX_DECODER_H +#define ZIP7_INC_LZX_DECODER_H #include "../../../C/CpuArch.h" @@ -167,10 +167,9 @@ }; -class CDecoder: - public IUnknown, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_0( + CDecoder +) CBitDecoder _bitStream; Byte *_win; UInt32 _pos; @@ -220,8 +219,6 @@ CDecoder(bool wimMode = false); ~CDecoder(); - MY_UNKNOWN_IMP - HRESULT SetExternalWindow(Byte *win, unsigned numDictBits) { NeedAlloc = false; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/Lzx.h 7zip-23.01+dfsg/CPP/7zip/Compress/Lzx.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/Lzx.h 2015-08-30 06:08:36.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/Lzx.h 2023-03-28 13:00:00.000000000 +0000 @@ -1,7 +1,9 @@ // Lzx.h -#ifndef __COMPRESS_LZX_H -#define __COMPRESS_LZX_H +#ifndef ZIP7_INC_COMPRESS_LZX_H +#define ZIP7_INC_COMPRESS_LZX_H + +#include "../../Common/MyTypes.h" namespace NCompress { namespace NLzx { diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/Mtf8.h 7zip-23.01+dfsg/CPP/7zip/Compress/Mtf8.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/Mtf8.h 2017-04-10 13:16:54.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/Mtf8.h 2023-03-28 13:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Mtf8.h -#ifndef __COMPRESS_MTF8_H -#define __COMPRESS_MTF8_H +#ifndef ZIP7_INC_COMPRESS_MTF8_H +#define ZIP7_INC_COMPRESS_MTF8_H #include "../../../C/CpuArch.h" @@ -15,7 +15,7 @@ { size_t pos; for (pos = 0; Buf[pos] != v; pos++); - unsigned resPos = (unsigned)pos; + const unsigned resPos = (unsigned)pos; for (; pos >= 8; pos -= 8) { Buf[pos] = Buf[pos - 1]; @@ -66,28 +66,28 @@ #ifdef MY_CPU_64BIT typedef UInt64 CMtfVar; - #define MTF_MOVS 3 + #define Z7_MTF_MOVS 3 #else typedef UInt32 CMtfVar; - #define MTF_MOVS 2 + #define Z7_MTF_MOVS 2 #endif -#define MTF_MASK ((1 << MTF_MOVS) - 1) +#define Z7_MTF_MASK ((1 << Z7_MTF_MOVS) - 1) struct CMtf8Decoder { - CMtfVar Buf[256 >> MTF_MOVS]; + CMtfVar Buf[256 >> Z7_MTF_MOVS]; void StartInit() { memset(Buf, 0, sizeof(Buf)); } - void Add(unsigned pos, Byte val) { Buf[pos >> MTF_MOVS] |= ((CMtfVar)val << ((pos & MTF_MASK) << 3)); } + void Add(unsigned pos, Byte val) { Buf[pos >> Z7_MTF_MOVS] |= ((CMtfVar)val << ((pos & Z7_MTF_MASK) << 3)); } Byte GetHead() const { return (Byte)Buf[0]; } - MY_FORCE_INLINE + Z7_FORCE_INLINE Byte GetAndMove(unsigned pos) throw() { - UInt32 lim = ((UInt32)pos >> MTF_MOVS); - pos = (pos & MTF_MASK) << 3; + const UInt32 lim = ((UInt32)pos >> Z7_MTF_MOVS); + pos = (pos & Z7_MTF_MASK) << 3; CMtfVar prev = (Buf[lim] >> pos) & 0xFF; UInt32 i = 0; @@ -98,7 +98,7 @@ { CMtfVar next = Buf[0]; Buf[0] = (next << 8) | prev; - prev = (next >> (MTF_MASK << 3)); + prev = (next >> (Z7_MTF_MASK << 3)); i = 1; lim -= 1; } @@ -107,21 +107,21 @@ CMtfVar n0 = Buf[i]; CMtfVar n1 = Buf[i + 1]; Buf[i ] = (n0 << 8) | prev; - Buf[i + 1] = (n1 << 8) | (n0 >> (MTF_MASK << 3)); - prev = (n1 >> (MTF_MASK << 3)); + Buf[i + 1] = (n1 << 8) | (n0 >> (Z7_MTF_MASK << 3)); + prev = (n1 >> (Z7_MTF_MASK << 3)); } */ for (; i < lim; i++) { - CMtfVar n0 = Buf[i]; + const CMtfVar n0 = Buf[i]; Buf[i ] = (n0 << 8) | prev; - prev = (n0 >> (MTF_MASK << 3)); + prev = (n0 >> (Z7_MTF_MASK << 3)); } - CMtfVar next = Buf[i]; - CMtfVar mask = (((CMtfVar)0x100 << pos) - 1); + const CMtfVar next = Buf[i]; + const CMtfVar mask = (((CMtfVar)0x100 << pos) - 1); Buf[i] = (next & ~mask) | (((next << 8) | prev) & mask); return (Byte)Buf[0]; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/PpmdDecoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/PpmdDecoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/PpmdDecoder.cpp 2021-01-25 18:44:41.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/PpmdDecoder.cpp 2023-03-28 13:53:00.000000000 +0000 @@ -1,5 +1,4 @@ // PpmdDecoder.cpp -// 2020-07-03 : Igor Pavlov : Public domain #include "StdAfx.h" @@ -29,14 +28,13 @@ Ppmd7_Free(&_ppmd, &g_BigAlloc); } -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *props, UInt32 size) +Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *props, UInt32 size)) { if (size < 5) return E_INVALIDARG; _order = props[0]; - UInt32 memSize = GetUi32(props + 1); - if ( - // _order < PPMD7_MIN_ORDER || + const UInt32 memSize = GetUi32(props + 1); + if (_order < PPMD7_MIN_ORDER || _order > PPMD7_MAX_ORDER || memSize < PPMD7_MIN_MEM_SIZE || memSize > PPMD7_MAX_MEM_SIZE) @@ -48,7 +46,7 @@ return S_OK; } -#define _rangeDec _ppmd.rc.dec +#define MY_rangeDec _ppmd.rc.dec #define CHECK_EXTRA_ERROR \ if (_inStream.Extra) { \ @@ -67,7 +65,7 @@ case kStatus_Error: return S_FALSE; case kStatus_NeedInit: _inStream.Init(); - if (!Ppmd7z_RangeDec_Init(&_rangeDec)) + if (!Ppmd7z_RangeDec_Init(&MY_rangeDec)) { _status = kStatus_Error; return (_res = S_FALSE); @@ -110,7 +108,7 @@ if (!FinishStream || !_outSizeDefined || _outSize != _processedSize - || _rangeDec.Code == 0) + || MY_rangeDec.Code == 0) return S_OK; /* // We can decode additional End Marker here: @@ -119,7 +117,7 @@ */ } - if (sym != PPMD7_SYM_END || _rangeDec.Code != 0) + if (sym != PPMD7_SYM_END || MY_rangeDec.Code != 0) { _status = kStatus_Error; return (_res = S_FALSE); @@ -131,8 +129,8 @@ -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)) { if (!_outBuf) { @@ -147,16 +145,16 @@ do { const UInt64 startPos = _processedSize; - HRESULT res = CodeSpec(_outBuf, kBufSize); - size_t processed = (size_t)(_processedSize - startPos); - RINOK(WriteStream(outStream, _outBuf, processed)); - RINOK(res); + const HRESULT res = CodeSpec(_outBuf, kBufSize); + const size_t processed = (size_t)(_processedSize - startPos); + RINOK(WriteStream(outStream, _outBuf, processed)) + RINOK(res) if (_status == kStatus_Finished_With_Mark) break; if (progress) { const UInt64 inProcessed = _inStream.GetProcessed(); - RINOK(progress->SetRatioInfo(&inProcessed, &_processedSize)); + RINOK(progress->SetRatioInfo(&inProcessed, &_processedSize)) } } while (!_outSizeDefined || _processedSize < _outSize); @@ -168,7 +166,7 @@ } -STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) +Z7_COM7F_IMF(CDecoder::SetOutStreamSize(const UInt64 *outSize)) { _outSizeDefined = (outSize != NULL); if (_outSizeDefined) @@ -179,37 +177,37 @@ return S_OK; } -STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode) +Z7_COM7F_IMF(CDecoder::SetFinishMode(UInt32 finishMode)) { FinishStream = (finishMode != 0); return S_OK; } -STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value) +Z7_COM7F_IMF(CDecoder::GetInStreamProcessedSize(UInt64 *value)) { *value = _inStream.GetProcessed(); return S_OK; } -#ifndef NO_READ_FROM_CODER +#ifndef Z7_NO_READ_FROM_CODER -STDMETHODIMP CDecoder::SetInStream(ISequentialInStream *inStream) +Z7_COM7F_IMF(CDecoder::SetInStream(ISequentialInStream *inStream)) { InSeqStream = inStream; _inStream.Stream = inStream; return S_OK; } -STDMETHODIMP CDecoder::ReleaseInStream() +Z7_COM7F_IMF(CDecoder::ReleaseInStream()) { InSeqStream.Release(); return S_OK; } -STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize)) { const UInt64 startPos = _processedSize; - HRESULT res = CodeSpec((Byte *)data, size); + const HRESULT res = CodeSpec((Byte *)data, size); if (processedSize) *processedSize = (UInt32)(_processedSize - startPos); return res; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/PpmdDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/PpmdDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/PpmdDecoder.h 2020-07-03 09:56:31.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/PpmdDecoder.h 2023-03-28 13:00:00.000000000 +0000 @@ -1,8 +1,7 @@ // PpmdDecoder.h -// 2020-07-03 : Igor Pavlov : Public domain -#ifndef __COMPRESS_PPMD_DECODER_H -#define __COMPRESS_PPMD_DECODER_H +#ifndef ZIP7_INC_COMPRESS_PPMD_DECODER_H +#define ZIP7_INC_COMPRESS_PPMD_DECODER_H #include "../../../C/Ppmd7.h" @@ -15,18 +14,42 @@ namespace NCompress { namespace NPpmd { -class CDecoder : +class CDecoder Z7_final: public ICompressCoder, public ICompressSetDecoderProperties2, public ICompressSetFinishMode, public ICompressGetInStreamProcessedSize, - #ifndef NO_READ_FROM_CODER + #ifndef Z7_NO_READ_FROM_CODER public ICompressSetInStream, public ICompressSetOutStreamSize, public ISequentialInStream, - #endif + #endif public CMyUnknownImp { + Z7_COM_QI_BEGIN2(ICompressCoder) + Z7_COM_QI_ENTRY(ICompressSetDecoderProperties2) + Z7_COM_QI_ENTRY(ICompressSetFinishMode) + Z7_COM_QI_ENTRY(ICompressGetInStreamProcessedSize) + #ifndef Z7_NO_READ_FROM_CODER + Z7_COM_QI_ENTRY(ICompressSetInStream) + Z7_COM_QI_ENTRY(ICompressSetOutStreamSize) + Z7_COM_QI_ENTRY(ISequentialInStream) + #endif + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(ICompressCoder) + Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2) + Z7_IFACE_COM7_IMP(ICompressSetFinishMode) + Z7_IFACE_COM7_IMP(ICompressGetInStreamProcessedSize) + #ifndef Z7_NO_READ_FROM_CODER + Z7_IFACE_COM7_IMP(ICompressSetOutStreamSize) + Z7_IFACE_COM7_IMP(ICompressSetInStream) + Z7_IFACE_COM7_IMP(ISequentialInStream) + #else + Z7_COM7F_IMF(SetOutStreamSize(const UInt64 *outSize)); + #endif + Byte *_outBuf; CByteInBufWrap _inStream; CPpmd7 _ppmd; @@ -43,36 +66,9 @@ public: - #ifndef NO_READ_FROM_CODER + #ifndef Z7_NO_READ_FROM_CODER CMyComPtr InSeqStream; - #endif - - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - MY_QUERYINTERFACE_ENTRY(ICompressSetDecoderProperties2) - MY_QUERYINTERFACE_ENTRY(ICompressSetFinishMode) - MY_QUERYINTERFACE_ENTRY(ICompressGetInStreamProcessedSize) - #ifndef NO_READ_FROM_CODER - MY_QUERYINTERFACE_ENTRY(ICompressSetInStream) - MY_QUERYINTERFACE_ENTRY(ICompressSetOutStreamSize) - MY_QUERYINTERFACE_ENTRY(ISequentialInStream) - #endif - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - STDMETHOD(SetFinishMode)(UInt32 finishMode); - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); - - STDMETHOD(SetOutStreamSize)(const UInt64 *outSize); - - #ifndef NO_READ_FROM_CODER - STDMETHOD(SetInStream)(ISequentialInStream *inStream); - STDMETHOD(ReleaseInStream)(); - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - #endif + #endif CDecoder(): _outBuf(NULL), diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/PpmdEncoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/PpmdEncoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/PpmdEncoder.cpp 2021-05-29 06:49:08.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/PpmdEncoder.cpp 2023-03-28 13:00:00.000000000 +0000 @@ -24,7 +24,7 @@ const unsigned kMult = 16; if (MemSize / kMult > ReduceSize) { - for (unsigned i = 16; i <= 31; i++) + for (unsigned i = 16; i < 32; i++) { UInt32 m = (UInt32)1 << i; if (ReduceSize <= m / kMult) @@ -52,7 +52,7 @@ Ppmd7_Free(&_ppmd, &g_BigAlloc); } -STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps) +Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps)) { int level = -1; CEncProps props; @@ -109,7 +109,7 @@ if (prop.vt != VT_UI4) return E_INVALIDARG; - UInt32 v = (UInt32)prop.ulVal; + const UInt32 v = (UInt32)prop.ulVal; switch (propID) { case NCoderPropID::kOrder: @@ -127,17 +127,17 @@ return S_OK; } -STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream) +Z7_COM7F_IMF(CEncoder::WriteCoderProperties(ISequentialOutStream *outStream)) { const UInt32 kPropSize = 5; Byte props[kPropSize]; props[0] = (Byte)_props.Order; - SetUi32(props + 1, _props.MemSize); + SetUi32(props + 1, _props.MemSize) return WriteStream(outStream, props, kPropSize); } -HRESULT CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress)) { if (!_inBuf) { @@ -160,7 +160,7 @@ for (;;) { UInt32 size; - RINOK(inStream->Read(_inBuf, kBufSize, &size)); + RINOK(inStream->Read(_inBuf, kBufSize, &size)) if (size == 0) { // We don't write EndMark in PPMD-7z. @@ -179,13 +179,13 @@ */ Ppmd7z_EncodeSymbols(&_ppmd, buf, lim); - RINOK(_outStream.Res); + RINOK(_outStream.Res) processed += size; if (progress) { const UInt64 outSize = _outStream.GetProcessed(); - RINOK(progress->SetRatioInfo(&processed, &outSize)); + RINOK(progress->SetRatioInfo(&processed, &outSize)) } } } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/PpmdEncoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/PpmdEncoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/PpmdEncoder.h 2020-04-14 11:33:48.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/PpmdEncoder.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // PpmdEncoder.h -#ifndef __COMPRESS_PPMD_ENCODER_H -#define __COMPRESS_PPMD_ENCODER_H +#ifndef ZIP7_INC_COMPRESS_PPMD_ENCODER_H +#define ZIP7_INC_COMPRESS_PPMD_ENCODER_H #include "../../../C/Ppmd7.h" @@ -29,25 +29,17 @@ void Normalize(int level); }; -class CEncoder : - public ICompressCoder, - public ICompressSetCoderProperties, - public ICompressWriteCoderProperties, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_3( + CEncoder + , ICompressCoder + , ICompressSetCoderProperties + , ICompressWriteCoderProperties +) Byte *_inBuf; CByteOutBufWrap _outStream; CPpmd7 _ppmd; CEncProps _props; public: - MY_UNKNOWN_IMP3( - ICompressCoder, - ICompressSetCoderProperties, - ICompressWriteCoderProperties) - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); - STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream); CEncoder(); ~CEncoder(); }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/PpmdRegister.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/PpmdRegister.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/PpmdRegister.cpp 2016-04-25 10:06:03.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/PpmdRegister.cpp 2023-01-29 16:00:00.000000000 +0000 @@ -6,7 +6,7 @@ #include "PpmdDecoder.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY #include "PpmdEncoder.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/PpmdZip.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/PpmdZip.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/PpmdZip.cpp 2021-01-25 18:47:29.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/PpmdZip.cpp 2023-03-28 14:00:00.000000000 +0000 @@ -24,8 +24,8 @@ Ppmd8_Free(&_ppmd, &g_BigAlloc); } -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)) { // try { @@ -44,10 +44,10 @@ if (_inStream.Extra) return S_FALSE; - UInt32 val = GetUi16(buf); - unsigned order = (val & 0xF) + 1; - UInt32 mem = ((val >> 4) & 0xFF) + 1; - unsigned restor = (val >> 12); + const UInt32 val = GetUi16(buf); + const unsigned order = (val & 0xF) + 1; + const UInt32 mem = ((val >> 4) & 0xFF) + 1; + const unsigned restor = (val >> 12); if (order < 2 || restor > 2) return S_FALSE; @@ -94,12 +94,12 @@ } while (buf != lim); - size_t cur = (size_t)(buf - _outStream.Buf); + const size_t cur = (size_t)(buf - _outStream.Buf); processedSize += cur; - RINOK(WriteStream(outStream, _outStream.Buf, cur)); + RINOK(WriteStream(outStream, _outStream.Buf, cur)) - RINOK(_inStream.Res); + RINOK(_inStream.Res) if (_inStream.Extra) return S_FALSE; @@ -114,18 +114,18 @@ if (progress) { const UInt64 inProccessed = _inStream.GetProcessed(); - RINOK(progress->SetRatioInfo(&inProccessed, &processedSize)); + RINOK(progress->SetRatioInfo(&inProccessed, &processedSize)) } } - RINOK(_inStream.Res); + RINOK(_inStream.Res) if (_fullFileMode) { if (!wasFinished) { - int res = Ppmd8_DecodeSymbol(&_ppmd); - RINOK(_inStream.Res); + const int res = Ppmd8_DecodeSymbol(&_ppmd); + RINOK(_inStream.Res) if (_inStream.Extra || res != -1) return S_FALSE; } @@ -142,13 +142,13 @@ } -STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode) +Z7_COM7F_IMF(CDecoder::SetFinishMode(UInt32 finishMode)) { _fullFileMode = (finishMode != 0); return S_OK; } -STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value) +Z7_COM7F_IMF(CDecoder::GetInStreamProcessedSize(UInt64 *value)) { *value = _inStream.GetProcessed(); return S_OK; @@ -184,14 +184,14 @@ Ppmd8_Free(&_ppmd, &g_BigAlloc); } -STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps) +Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps)) { int level = -1; CEncProps props; for (UInt32 i = 0; i < numProps; i++) { const PROPVARIANT &prop = coderProps[i]; - PROPID propID = propIDs[i]; + const PROPID propID = propIDs[i]; if (propID > NCoderPropID::kReduceSize) continue; if (propID == NCoderPropID::kReduceSize) @@ -203,7 +203,7 @@ } if (prop.vt != VT_UI4) return E_INVALIDARG; - UInt32 v = (UInt32)prop.ulVal; + const UInt32 v = (UInt32)prop.ulVal; switch (propID) { case NCoderPropID::kUsedMemorySize: @@ -238,8 +238,8 @@ Ppmd8_Construct(&_ppmd); } -STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress)) { if (!_inStream.Alloc()) return E_OUTOFMEMORY; @@ -251,21 +251,21 @@ _outStream.Stream = outStream; _outStream.Init(); - Ppmd8_Init_RangeEnc(&_ppmd); + Ppmd8_Init_RangeEnc(&_ppmd) Ppmd8_Init(&_ppmd, (unsigned)_props.Order, (unsigned)_props.Restor); { - UInt32 val = (UInt32)(((unsigned)_props.Order - 1) + ((_props.MemSizeMB - 1) << 4) + ((unsigned)_props.Restor << 12)); + const UInt32 val = (UInt32)(((unsigned)_props.Order - 1) + ((_props.MemSizeMB - 1) << 4) + ((unsigned)_props.Restor << 12)); _outStream.WriteByte((Byte)(val & 0xFF)); _outStream.WriteByte((Byte)(val >> 8)); } - RINOK(_outStream.Res); + RINOK(_outStream.Res) UInt64 processed = 0; for (;;) { UInt32 size; - RINOK(inStream->Read(_inStream.Buf, kBufSize, &size)); + RINOK(inStream->Read(_inStream.Buf, kBufSize, &size)) if (size == 0) { Ppmd8_EncodeSymbol(&_ppmd, -1); @@ -284,12 +284,12 @@ } while (++buf != lim); - RINOK(_outStream.Res); + RINOK(_outStream.Res) if (progress) { const UInt64 outProccessed = _outStream.GetProcessed(); - RINOK(progress->SetRatioInfo(&processed, &outProccessed)); + RINOK(progress->SetRatioInfo(&processed, &outProccessed)) } } } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/PpmdZip.h 7zip-23.01+dfsg/CPP/7zip/Compress/PpmdZip.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/PpmdZip.h 2020-04-13 14:02:23.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/PpmdZip.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // PpmdZip.h -#ifndef __COMPRESS_PPMD_ZIP_H -#define __COMPRESS_PPMD_ZIP_H +#ifndef ZIP7_INC_COMPRESS_PPMD_ZIP_H +#define ZIP7_INC_COMPRESS_PPMD_ZIP_H #include "../../../C/Alloc.h" #include "../../../C/Ppmd8.h" @@ -27,31 +27,22 @@ { if (!Buf) Buf = (Byte *)::MidAlloc(kBufSize); - return (Buf != 0); + return (Buf != NULL); } }; -class CDecoder : - public ICompressCoder, - public ICompressSetFinishMode, - public ICompressGetInStreamProcessedSize, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_3( + CDecoder + , ICompressCoder + , ICompressSetFinishMode + , ICompressGetInStreamProcessedSize +) CByteInBufWrap _inStream; CBuf _outStream; CPpmd8 _ppmd; bool _fullFileMode; public: - MY_UNKNOWN_IMP2( - ICompressSetFinishMode, - ICompressGetInStreamProcessedSize) - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetFinishMode)(UInt32 finishMode); - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); - CDecoder(bool fullFileMode = true); ~CDecoder(); }; @@ -74,20 +65,17 @@ void Normalize(int level); }; -class CEncoder : - public ICompressCoder, - public ICompressSetCoderProperties, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_NOQIB_2( + CEncoder + , ICompressCoder + , ICompressSetCoderProperties +) CByteOutBufWrap _outStream; CBuf _inStream; CPpmd8 _ppmd; CEncProps _props; public: - MY_UNKNOWN_IMP1(ICompressSetCoderProperties) - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); CEncoder(); ~CEncoder(); }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/QuantumDecoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/QuantumDecoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/QuantumDecoder.cpp 2021-04-01 09:50:22.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/QuantumDecoder.cpp 2023-03-28 14:00:00.000000000 +0000 @@ -33,12 +33,12 @@ unsigned CModelDecoder::Decode(CRangeDecoder *rc) { - UInt32 threshold = rc->GetThreshold(Freqs[0]); + const UInt32 threshold = rc->GetThreshold(Freqs[0]); unsigned i; for (i = 1; Freqs[i] > threshold; i++); rc->Decode(Freqs[i], Freqs[(size_t)i - 1], Freqs[0]); - unsigned res = Vals[--i]; + const unsigned res = Vals[--i]; do Freqs[i] = (UInt16)(Freqs[i] + kUpdateStep); @@ -55,8 +55,8 @@ for (unsigned j = i + 1; j < NumItems; j++) if (Freqs[i] < Freqs[j]) { - UInt16 tmpFreq = Freqs[i]; - Byte tmpVal = Vals[i]; + const UInt16 tmpFreq = Freqs[i]; + const Byte tmpVal = Vals[i]; Freqs[i] = Freqs[j]; Vals[i] = Vals[j]; Freqs[j] = tmpFreq; @@ -90,7 +90,7 @@ unsigned i; for (i = 0; i < kNumLitSelectors; i++) m_Literals[i].Init(kNumLitSymbols); - unsigned numItems = (_numDictBits == 0 ? 1 : (_numDictBits << 1)); + const unsigned numItems = (_numDictBits == 0 ? 1 : (_numDictBits << 1)); const unsigned kNumPosSymbolsMax[kNumMatchSelectors] = { 24, 36, 42 }; for (i = 0; i < kNumMatchSelectors; i++) m_PosSlot[i].Init(MyMin(numItems, kNumPosSymbolsMax[i])); @@ -116,7 +116,7 @@ if (selector < kNumLitSelectors) { - Byte b = (Byte)((selector << (8 - kNumLitSelectorBits)) + m_Literals[selector].Decode(&rc)); + const Byte b = (Byte)((selector << (8 - kNumLitSelectorBits)) + m_Literals[selector].Decode(&rc)); _outWindow.PutByte(b); outSize--; } @@ -131,7 +131,7 @@ if (lenSlot >= kNumSimpleLenSlots) { lenSlot -= 2; - unsigned numDirectBits = (unsigned)(lenSlot >> 2); + const unsigned numDirectBits = (unsigned)(lenSlot >> 2); len += ((4 | (lenSlot & 3)) << numDirectBits) - 2; if (numDirectBits < 6) len += rc.Stream.ReadBits(numDirectBits); @@ -174,8 +174,8 @@ if (!keepHistory) Init(); - HRESULT res = CodeSpec(inData, inSize, outSize); - HRESULT res2 = _outWindow.Flush(); + const HRESULT res = CodeSpec(inData, inSize, outSize); + const HRESULT res2 = _outWindow.Flush(); return res != S_OK ? res : res2; } catch(const CLzOutWindowException &e) { return e.ErrorCode; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/QuantumDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/QuantumDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/QuantumDecoder.h 2015-08-29 10:53:14.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/QuantumDecoder.h 2023-03-28 11:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // QuantumDecoder.h -#ifndef __COMPRESS_QUANTUM_DECODER_H -#define __COMPRESS_QUANTUM_DECODER_H +#ifndef ZIP7_INC_COMPRESS_QUANTUM_DECODER_H +#define ZIP7_INC_COMPRESS_QUANTUM_DECODER_H #include "../../Common/MyCom.h" @@ -142,10 +142,9 @@ }; -class CDecoder: - public IUnknown, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_0( + CDecoder +) CLzOutWindow _outWindow; unsigned _numDictBits; @@ -157,17 +156,12 @@ void Init(); HRESULT CodeSpec(const Byte *inData, size_t inSize, UInt32 outSize); public: - - MY_UNKNOWN_IMP - HRESULT Code(const Byte *inData, size_t inSize, ISequentialOutStream *outStream, UInt32 outSize, bool keepHistory); - HRESULT SetParams(unsigned numDictBits); - + CDecoder(): _numDictBits(0) {} - virtual ~CDecoder() {} }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/ShrinkDecoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/ShrinkDecoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/ShrinkDecoder.cpp 2021-01-25 18:48:21.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/ShrinkDecoder.cpp 2023-01-28 17:00:00.000000000 +0000 @@ -198,7 +198,7 @@ while (i); } - RINOK(outBuffer.Flush()); + RINOK(outBuffer.Flush()) if (res == S_OK) if (_fullStreamMode) @@ -216,8 +216,8 @@ } -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)) { try { return CodeReal(inStream, outStream, inSize, outSize, progress); } // catch(const CInBufferException &e) { return e.ErrorCode; } @@ -227,14 +227,14 @@ } -STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode) +Z7_COM7F_IMF(CDecoder::SetFinishMode(UInt32 finishMode)) { _fullStreamMode = (finishMode != 0); return S_OK; } -STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value) +Z7_COM7F_IMF(CDecoder::GetInStreamProcessedSize(UInt64 *value)) { *value = _inProcessed; return S_OK; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/ShrinkDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/ShrinkDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/ShrinkDecoder.h 2017-12-29 16:06:30.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/ShrinkDecoder.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ShrinkDecoder.h -#ifndef __COMPRESS_SHRINK_DECODER_H -#define __COMPRESS_SHRINK_DECODER_H +#ifndef ZIP7_INC_COMPRESS_SHRINK_DECODER_H +#define ZIP7_INC_COMPRESS_SHRINK_DECODER_H #include "../../Common/MyCom.h" @@ -13,12 +13,12 @@ const unsigned kNumMaxBits = 13; const unsigned kNumItems = 1 << kNumMaxBits; -class CDecoder : - public ICompressCoder, - public ICompressSetFinishMode, - public ICompressGetInStreamProcessedSize, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_3( + CDecoder + , ICompressCoder + , ICompressSetFinishMode + , ICompressGetInStreamProcessedSize +) bool _fullStreamMode; UInt64 _inProcessed; @@ -28,16 +28,6 @@ HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - -public: - MY_UNKNOWN_IMP2( - ICompressSetFinishMode, - ICompressGetInStreamProcessedSize) - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetFinishMode)(UInt32 finishMode); - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Compress/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/StdAfx.h 2013-11-13 06:35:49.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/XpressDecoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/XpressDecoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/XpressDecoder.cpp 2021-01-22 20:15:57.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/XpressDecoder.cpp 2023-03-28 18:00:00.000000000 +0000 @@ -50,7 +50,7 @@ Byte levels[kNumSyms]; for (unsigned i = 0; i < kNumSyms / 2; i++) { - Byte b = in[i]; + const Byte b = in[i]; levels[(size_t)i * 2] = (Byte)(b & 0xF); levels[(size_t)i * 2 + 1] = (Byte)(b >> 4); } @@ -64,7 +64,7 @@ const Byte *lim = in + inSize - 1; in += kNumSyms / 2; - bs.Value = (GetUi16(in) << 16) | GetUi16(in + 2); + bs.Value = ((UInt32)GetUi16(in) << 16) | GetUi16(in + 2); in += 4; bs.BitPos = 32; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/XpressDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/XpressDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/XpressDecoder.h 2015-08-26 11:24:39.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/XpressDecoder.h 2023-03-28 18:00:00.000000000 +0000 @@ -1,7 +1,9 @@ // XpressDecoder.h -#ifndef __XPRESS_DECODER_H -#define __XPRESS_DECODER_H +#ifndef ZIP7_INC_XPRESS_DECODER_H +#define ZIP7_INC_XPRESS_DECODER_H + +#include "../../Common/MyWindows.h" namespace NCompress { namespace NXpress { diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/XzDecoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/XzDecoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/XzDecoder.cpp 2020-03-07 17:59:40.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/XzDecoder.cpp 2023-03-28 18:00:00.000000000 +0000 @@ -50,10 +50,10 @@ int isMT = False; - #ifndef _7ZIP_ST + #ifndef Z7_ST { props.numThreads = 1; - UInt32 numThreads = _numThreads; + const UInt32 numThreads = _numThreads; if (_tryMt && numThreads > 1) { @@ -87,7 +87,7 @@ MainDecodeSRes = res; - #ifndef _7ZIP_ST + #ifndef Z7_ST // _tryMt = isMT; #endif @@ -113,33 +113,33 @@ } -HRESULT CComDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CComDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress)) { return Decode(inStream, outStream, outSize, _finishStream, progress); } -STDMETHODIMP CComDecoder::SetFinishMode(UInt32 finishMode) +Z7_COM7F_IMF(CComDecoder::SetFinishMode(UInt32 finishMode)) { _finishStream = (finishMode != 0); return S_OK; } -STDMETHODIMP CComDecoder::GetInStreamProcessedSize(UInt64 *value) +Z7_COM7F_IMF(CComDecoder::GetInStreamProcessedSize(UInt64 *value)) { *value = Stat.InSize; return S_OK; } -#ifndef _7ZIP_ST +#ifndef Z7_ST -STDMETHODIMP CComDecoder::SetNumberOfThreads(UInt32 numThreads) +Z7_COM7F_IMF(CComDecoder::SetNumberOfThreads(UInt32 numThreads)) { _numThreads = numThreads; return S_OK; } -STDMETHODIMP CComDecoder::SetMemLimit(UInt64 memUsage) +Z7_COM7F_IMF(CComDecoder::SetMemLimit(UInt64 memUsage)) { _memUsage = memUsage; return S_OK; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/XzDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/XzDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/XzDecoder.h 2020-03-04 13:44:14.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/XzDecoder.h 2023-02-01 10:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // XzDecoder.h -#ifndef __XZ_DECODER_H -#define __XZ_DECODER_H +#ifndef ZIP7_INC_XZ_DECODER_H +#define ZIP7_INC_XZ_DECODER_H #include "../../../C/Xz.h" @@ -46,45 +46,38 @@ }; -class CComDecoder: +class CComDecoder Z7_final: public ICompressCoder, public ICompressSetFinishMode, public ICompressGetInStreamProcessedSize, - - #ifndef _7ZIP_ST + #ifndef Z7_ST public ICompressSetCoderMt, public ICompressSetMemLimit, - #endif - + #endif public CMyUnknownImp, public CDecoder { + Z7_COM_QI_BEGIN2(ICompressCoder) + Z7_COM_QI_ENTRY(ICompressSetFinishMode) + Z7_COM_QI_ENTRY(ICompressGetInStreamProcessedSize) + #ifndef Z7_ST + Z7_COM_QI_ENTRY(ICompressSetCoderMt) + Z7_COM_QI_ENTRY(ICompressSetMemLimit) + #endif + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(ICompressCoder) + Z7_IFACE_COM7_IMP(ICompressSetFinishMode) + Z7_IFACE_COM7_IMP(ICompressGetInStreamProcessedSize) + #ifndef Z7_ST + Z7_IFACE_COM7_IMP(ICompressSetCoderMt) + Z7_IFACE_COM7_IMP(ICompressSetMemLimit) + #endif + bool _finishStream; public: - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - - MY_QUERYINTERFACE_ENTRY(ICompressSetFinishMode) - MY_QUERYINTERFACE_ENTRY(ICompressGetInStreamProcessedSize) - - #ifndef _7ZIP_ST - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt) - MY_QUERYINTERFACE_ENTRY(ICompressSetMemLimit) - #endif - - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetFinishMode)(UInt32 finishMode); - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); - - #ifndef _7ZIP_ST - STDMETHOD(SetNumberOfThreads)(UInt32 numThreads); - STDMETHOD(SetMemLimit)(UInt64 memUsage); - #endif - CComDecoder(): _finishStream(false) {} }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/XzEncoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/XzEncoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/XzEncoder.cpp 2021-01-25 11:20:01.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/XzEncoder.cpp 2023-03-28 18:00:00.000000000 +0000 @@ -15,9 +15,7 @@ namespace NCompress { namespace NLzma2 { - HRESULT SetLzma2Prop(PROPID propID, const PROPVARIANT &prop, CLzma2EncProps &lzma2Props); - } namespace NXz { @@ -63,7 +61,7 @@ static int FilterIdFromName(const wchar_t *name) { - for (unsigned i = 0; i < ARRAY_SIZE(g_NamePairs); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_NamePairs); i++) { const CMethodNamePair &pair = g_NamePairs[i]; if (StringsAreEqualNoCase_Ascii(name, pair.Name)) @@ -130,7 +128,7 @@ { if (prop.vt == VT_UI4) { - UInt32 id32 = prop.ulVal; + const UInt32 id32 = prop.ulVal; if (id32 == XZ_ID_Delta) return E_INVALIDARG; xzProps.filterProps.id = prop.ulVal; @@ -156,7 +154,7 @@ } else { - int filterId = FilterIdFromName(prop.bstrVal); + const int filterId = FilterIdFromName(prop.bstrVal); if (filterId < 0 /* || filterId == XZ_ID_LZMA2 */) return E_INVALIDARG; id32 = (unsigned)filterId; @@ -165,11 +163,11 @@ if (id32 == XZ_ID_Delta) { - wchar_t c = *name; + const wchar_t c = *name; if (c != '-' && c != ':') return E_INVALIDARG; name++; - UInt32 delta = ConvertStringToUInt32(name, &end); + const UInt32 delta = ConvertStringToUInt32(name, &end); if (end == name || *end != 0 || delta == 0 || delta > 256) return E_INVALIDARG; xzProps.filterProps.delta = delta; @@ -185,14 +183,14 @@ } -STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, - const PROPVARIANT *coderProps, UInt32 numProps) +Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs, + const PROPVARIANT *coderProps, UInt32 numProps)) { XzProps_Init(&xzProps); for (UInt32 i = 0; i < numProps; i++) { - RINOK(SetCoderProp(propIDs[i], coderProps[i])); + RINOK(SetCoderProp(propIDs[i], coderProps[i])) } return S_OK; @@ -200,13 +198,13 @@ } -STDMETHODIMP CEncoder::SetCoderPropertiesOpt(const PROPID *propIDs, - const PROPVARIANT *coderProps, UInt32 numProps) +Z7_COM7F_IMF(CEncoder::SetCoderPropertiesOpt(const PROPID *propIDs, + const PROPVARIANT *coderProps, UInt32 numProps)) { for (UInt32 i = 0; i < numProps; i++) { const PROPVARIANT &prop = coderProps[i]; - PROPID propID = propIDs[i]; + const PROPID propID = propIDs[i]; if (propID == NCoderPropID::kExpectedDataSize) if (prop.vt == VT_UI8) XzEnc_SetDataSize(_encoder, prop.uhVal.QuadPart); @@ -218,8 +216,8 @@ #define RET_IF_WRAP_ERROR(wrapRes, sRes, sResErrorCode) \ if (wrapRes != S_OK /* && (sRes == SZ_OK || sRes == sResErrorCode) */) return wrapRes; -STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress)) { CSeqInStreamWrap inWrap; CSeqOutStreamWrap outWrap; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/XzEncoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/XzEncoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/XzEncoder.h 2017-07-27 08:34:57.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/XzEncoder.h 2023-03-28 18:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // XzEncoder.h -#ifndef __XZ_ENCODER_H -#define __XZ_ENCODER_H +#ifndef ZIP7_INC_XZ_ENCODER_H +#define ZIP7_INC_XZ_ENCODER_H #include "../../../C/XzEnc.h" @@ -12,33 +12,22 @@ namespace NCompress { namespace NXz { - -class CEncoder: - public ICompressCoder, - public ICompressSetCoderProperties, - public ICompressSetCoderPropertiesOpt, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_3( + CEncoder + , ICompressCoder + , ICompressSetCoderProperties + , ICompressSetCoderPropertiesOpt +) CXzEncHandle _encoder; public: CXzProps xzProps; - MY_UNKNOWN_IMP3( - ICompressCoder, - ICompressSetCoderProperties, - ICompressSetCoderPropertiesOpt) - void InitCoderProps(); HRESULT SetCheckSize(UInt32 checkSizeInBytes); HRESULT SetCoderProp(PROPID propID, const PROPVARIANT &prop); - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); - STDMETHOD(SetCoderPropertiesOpt)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); CEncoder(); - virtual ~CEncoder(); + ~CEncoder(); }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/ZDecoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/ZDecoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/ZDecoder.cpp 2017-01-24 09:17:49.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/ZDecoder.cpp 2023-03-28 19:00:00.000000000 +0000 @@ -22,9 +22,9 @@ void CDecoder::Free() { - MyFree(_parents); _parents = 0; - MyFree(_suffixes); _suffixes = 0; - MyFree(_stack); _stack = 0; + MyFree(_parents); _parents = NULL; + MyFree(_suffixes); _suffixes = NULL; + MyFree(_stack); _stack = NULL; } CDecoder::~CDecoder() { Free(); } @@ -52,29 +52,29 @@ if (inBuffer.ReadBytes(buf, 3) < 3) return S_FALSE; if (buf[0] != 0x1F || buf[1] != 0x9D) - return S_FALSE;; + return S_FALSE; } Byte prop = buf[2]; if ((prop & 0x60) != 0) return S_FALSE; - unsigned maxbits = prop & kNumBitsMask; + const unsigned maxbits = prop & kNumBitsMask; if (maxbits < kNumMinBits || maxbits > kNumMaxBits) return S_FALSE; - UInt32 numItems = 1 << maxbits; + const UInt32 numItems = 1 << maxbits; // Speed optimization: blockSymbol can contain unused velue. - if (maxbits != _numMaxBits || _parents == 0 || _suffixes == 0 || _stack == 0) + if (maxbits != _numMaxBits || !_parents || !_suffixes || !_stack) { Free(); - _parents = (UInt16 *)MyAlloc(numItems * sizeof(UInt16)); if (_parents == 0) return E_OUTOFMEMORY; - _suffixes = (Byte *)MyAlloc(numItems * sizeof(Byte)); if (_suffixes == 0) return E_OUTOFMEMORY; - _stack = (Byte *)MyAlloc(numItems * sizeof(Byte)); if (_stack == 0) return E_OUTOFMEMORY; + _parents = (UInt16 *)MyAlloc(numItems * sizeof(UInt16)); if (!_parents) return E_OUTOFMEMORY; + _suffixes = (Byte *)MyAlloc(numItems * sizeof(Byte)); if (!_suffixes) return E_OUTOFMEMORY; + _stack = (Byte *)MyAlloc(numItems * sizeof(Byte)); if (!_stack) return E_OUTOFMEMORY; _numMaxBits = maxbits; } UInt64 prevPos = 0; - UInt32 blockSymbol = ((prop & kBlockModeMask) != 0) ? 256 : ((UInt32)1 << kNumMaxBits); + const UInt32 blockSymbol = ((prop & kBlockModeMask) != 0) ? 256 : ((UInt32)1 << kNumMaxBits); unsigned numBits = kNumMinBits; UInt32 head = (blockSymbol == 256) ? 257 : 256; bool needPrev = false; @@ -91,15 +91,15 @@ { numBufBits = (unsigned)inBuffer.ReadBytes(buf, numBits) * 8; bitPos = 0; - UInt64 nowPos = outBuffer.GetProcessedSize(); + const UInt64 nowPos = outBuffer.GetProcessedSize(); if (progress && nowPos - prevPos >= (1 << 13)) { prevPos = nowPos; - UInt64 packSize = inBuffer.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &nowPos)); + const UInt64 packSize = inBuffer.GetProcessedSize(); + RINOK(progress->SetRatioInfo(&packSize, &nowPos)) } } - unsigned bytePos = bitPos >> 3; + const unsigned bytePos = bitPos >> 3; UInt32 symbol = buf[bytePos] | ((UInt32)buf[(size_t)bytePos + 1] << 8) | ((UInt32)buf[(size_t)bytePos + 2] << 16); symbol >>= (bitPos & 7); symbol &= (1 << numBits) - 1; @@ -153,12 +153,12 @@ needPrev = false; } PackSize = inBuffer.GetProcessedSize(); - HRESULT res2 = outBuffer.Flush(); + const HRESULT res2 = outBuffer.Flush(); return (res == S_OK) ? res2 : res; } -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)) { try { return CodeReal(inStream, outStream, inSize, outSize, progress); } catch(const CInBufferException &e) { return e.ErrorCode; } @@ -172,14 +172,14 @@ return false; if (data[0] != 0x1F || data[1] != 0x9D) return false; - Byte prop = data[2]; + const Byte prop = data[2]; if ((prop & 0x60) != 0) return false; - unsigned maxbits = prop & kNumBitsMask; + const unsigned maxbits = prop & kNumBitsMask; if (maxbits < kNumMinBits || maxbits > kNumMaxBits) return false; - UInt32 numItems = 1 << maxbits; - UInt32 blockSymbol = ((prop & kBlockModeMask) != 0) ? 256 : ((UInt32)1 << kNumMaxBits); + const UInt32 numItems = 1 << maxbits; + const UInt32 blockSymbol = ((prop & kBlockModeMask) != 0) ? 256 : ((UInt32)1 << kNumMaxBits); unsigned numBits = kNumMinBits; UInt32 head = (blockSymbol == 256) ? 257 : 256; unsigned bitPos = 0; @@ -192,14 +192,14 @@ { if (numBufBits == bitPos) { - unsigned num = (numBits < size) ? numBits : (unsigned)size; + const unsigned num = (numBits < size) ? numBits : (unsigned)size; memcpy(buf, data, num); data += num; size -= num; numBufBits = num * 8; bitPos = 0; } - unsigned bytePos = bitPos >> 3; + const unsigned bytePos = bitPos >> 3; UInt32 symbol = buf[bytePos] | ((UInt32)buf[bytePos + 1] << 8) | ((UInt32)buf[bytePos + 2] << 16); symbol >>= (bitPos & 7); symbol &= (1 << numBits) - 1; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/ZDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/ZDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/ZDecoder.h 2013-04-08 03:24:39.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/ZDecoder.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ZDecoder.h -#ifndef __COMPRESS_Z_DECODER_H -#define __COMPRESS_Z_DECODER_H +#ifndef ZIP7_INC_COMPRESS_Z_DECODER_H +#define ZIP7_INC_COMPRESS_Z_DECODER_H #include "../../Common/MyCom.h" @@ -12,28 +12,23 @@ // Z decoder decodes Z data stream, including 3 bytes of header. -class CDecoder: - public ICompressCoder, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CDecoder + , ICompressCoder +) UInt16 *_parents; Byte *_suffixes; Byte *_stack; unsigned _numMaxBits; public: - CDecoder(): _parents(0), _suffixes(0), _stack(0), /* _prop(0), */ _numMaxBits(0) {}; + CDecoder(): _parents(NULL), _suffixes(NULL), _stack(NULL), /* _prop(0), */ _numMaxBits(0) {} ~CDecoder(); void Free(); UInt64 PackSize; - MY_UNKNOWN_IMP1(ICompressCoder) - HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); }; /* diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/ZlibDecoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/ZlibDecoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/ZlibDecoder.cpp 2021-01-22 20:23:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/ZlibDecoder.cpp 2023-03-28 19:00:00.000000000 +0000 @@ -2,6 +2,8 @@ #include "StdAfx.h" +#include "../../../C/CpuArch.h" + #include "../Common/StreamUtils.h" #include "ZlibDecoder.h" @@ -22,7 +24,7 @@ UInt32 b = (adler >> 16) & 0xFFFF; while (size > 0) { - unsigned curSize = (size > ADLER_LOOP_MAX) ? ADLER_LOOP_MAX : (unsigned )size; + const unsigned curSize = (size > ADLER_LOOP_MAX) ? ADLER_LOOP_MAX : (unsigned )size; unsigned i; for (i = 0; i < curSize; i++) { @@ -37,7 +39,7 @@ return (b << 16) + a; } -STDMETHODIMP COutStreamWithAdler::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(COutStreamWithAdler::Write(const void *data, UInt32 size, UInt32 *processedSize)) { HRESULT result = S_OK; if (_stream) @@ -49,8 +51,8 @@ return result; } -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)) { DEFLATE_TRY_BEGIN if (!AdlerStream) @@ -65,7 +67,7 @@ if (inSize && *inSize < 2) return S_FALSE; Byte buf[2]; - RINOK(ReadStream_FALSE(inStream, buf, 2)); + RINOK(ReadStream_FALSE(inStream, buf, 2)) if (!IsZlib(buf)) return S_FALSE; @@ -76,13 +78,13 @@ if (inSize) inSize2 = *inSize - 2; - HRESULT res = DeflateDecoder->Code(inStream, AdlerStream, inSize ? &inSize2 : NULL, outSize, progress); + const HRESULT res = DeflateDecoder->Code(inStream, AdlerStream, inSize ? &inSize2 : NULL, outSize, progress); AdlerSpec->ReleaseStream(); if (res == S_OK) { const Byte *p = DeflateDecoderSpec->ZlibFooter; - UInt32 adler = ((UInt32)p[0] << 24) | ((UInt32)p[1] << 16) | ((UInt32)p[2] << 8) | p[3]; + const UInt32 adler = GetBe32(p); if (adler != AdlerSpec->GetAdler()) return S_FALSE; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/ZlibDecoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/ZlibDecoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/ZlibDecoder.h 2013-09-17 05:50:48.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/ZlibDecoder.h 2023-03-28 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ZlibDecoder.h -#ifndef __ZLIB_DECODER_H -#define __ZLIB_DECODER_H +#ifndef ZIP7_INC_ZLIB_DECODER_H +#define ZIP7_INC_ZLIB_DECODER_H #include "DeflateDecoder.h" @@ -10,16 +10,14 @@ const UInt32 ADLER_INIT_VAL = 1; -class COutStreamWithAdler: - public ISequentialOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + COutStreamWithAdler + , ISequentialOutStream +) CMyComPtr _stream; UInt32 _adler; UInt64 _size; public: - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); void SetStream(ISequentialOutStream *stream) { _stream = stream; } void ReleaseStream() { _stream.Release(); } void Init() { _adler = ADLER_INIT_VAL; _size = 0; } @@ -27,23 +25,17 @@ UInt64 GetSize() const { return _size; } }; -class CDecoder: - public ICompressCoder, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + CDecoder + , ICompressCoder +) COutStreamWithAdler *AdlerSpec; CMyComPtr AdlerStream; - NCompress::NDeflate::NDecoder::CCOMCoder *DeflateDecoderSpec; CMyComPtr DeflateDecoder; public: - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - UInt64 GetInputProcessedSize() const { return DeflateDecoderSpec->GetInputProcessedSize() + 2; } UInt64 GetOutputProcessedSize() const { return AdlerSpec->GetSize(); } - - MY_UNKNOWN_IMP }; static bool inline IsZlib(const Byte *p) @@ -65,8 +57,8 @@ { if (!IsZlib(p)) return false; - unsigned val = p[2]; - unsigned blockType = (val >> 1) & 0x3; + const unsigned val = p[2]; + const unsigned blockType = (val >> 1) & 0x3; if (blockType == 3) // unsupported block type for deflate return false; if (blockType == NCompress::NDeflate::NBlockType::kStored && (val >> 3) != 0) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/ZlibEncoder.cpp 7zip-23.01+dfsg/CPP/7zip/Compress/ZlibEncoder.cpp --- 7zip-22.01+dfsg/CPP/7zip/Compress/ZlibEncoder.cpp 2009-06-21 13:30:02.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/ZlibEncoder.cpp 2023-03-28 19:00:00.000000000 +0000 @@ -14,12 +14,12 @@ UInt32 Adler32_Update(UInt32 adler, const Byte *buf, size_t size); -STDMETHODIMP CInStreamWithAdler::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CInStreamWithAdler::Read(void *data, UInt32 size, UInt32 *processedSize)) { - HRESULT result = _stream->Read(data, size, &size); + const HRESULT result = _stream->Read(data, size, &size); _adler = Adler32_Update(_adler, (const Byte *)data, size); _size += size; - if (processedSize != NULL) + if (processedSize) *processedSize = size; return result; } @@ -30,8 +30,8 @@ DeflateEncoder = DeflateEncoderSpec = new NDeflate::NEncoder::CCOMCoder; } -STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 * /* outSize */, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 *inSize, const UInt64 * /* outSize */, ICompressProgressInfo *progress)) { DEFLATE_TRY_BEGIN if (!AdlerStream) @@ -40,19 +40,19 @@ { Byte buf[2] = { 0x78, 0xDA }; - RINOK(WriteStream(outStream, buf, 2)); + RINOK(WriteStream(outStream, buf, 2)) } AdlerSpec->SetStream(inStream); AdlerSpec->Init(); - HRESULT res = DeflateEncoder->Code(AdlerStream, outStream, inSize, NULL, progress); + const HRESULT res = DeflateEncoder->Code(AdlerStream, outStream, inSize, NULL, progress); AdlerSpec->ReleaseStream(); - RINOK(res); + RINOK(res) { - UInt32 a = AdlerSpec->GetAdler(); - Byte buf[4] = { (Byte)(a >> 24), (Byte)(a >> 16), (Byte)(a >> 8), (Byte)(a) }; + const UInt32 a = AdlerSpec->GetAdler(); + const Byte buf[4] = { (Byte)(a >> 24), (Byte)(a >> 16), (Byte)(a >> 8), (Byte)(a) }; return WriteStream(outStream, buf, 4); } DEFLATE_TRY_END diff -Nru 7zip-22.01+dfsg/CPP/7zip/Compress/ZlibEncoder.h 7zip-23.01+dfsg/CPP/7zip/Compress/ZlibEncoder.h --- 7zip-22.01+dfsg/CPP/7zip/Compress/ZlibEncoder.h 2009-06-21 13:32:37.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Compress/ZlibEncoder.h 2023-01-31 17:00:00.000000000 +0000 @@ -1,23 +1,21 @@ // ZlibEncoder.h -#ifndef __ZLIB_ENCODER_H -#define __ZLIB_ENCODER_H +#ifndef ZIP7_INC_ZLIB_ENCODER_H +#define ZIP7_INC_ZLIB_ENCODER_H #include "DeflateEncoder.h" namespace NCompress { namespace NZlib { -class CInStreamWithAdler: - public ISequentialInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + CInStreamWithAdler + , ISequentialInStream +) CMyComPtr _stream; UInt32 _adler; UInt64 _size; public: - MY_UNKNOWN_IMP - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); void SetStream(ISequentialInStream *stream) { _stream = stream; } void ReleaseStream() { _stream.Release(); } void Init() { _adler = 1; _size = 0; } // ADLER_INIT_VAL @@ -25,10 +23,10 @@ UInt64 GetSize() const { return _size; } }; -class CEncoder: - public ICompressCoder, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + CEncoder + , ICompressCoder +) CInStreamWithAdler *AdlerSpec; CMyComPtr AdlerStream; CMyComPtr DeflateEncoder; @@ -36,11 +34,7 @@ NCompress::NDeflate::NEncoder::CCOMCoder *DeflateEncoderSpec; void Create(); - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); UInt64 GetInputProcessedSize() const { return AdlerSpec->GetSize(); } - - MY_UNKNOWN_IMP }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/7zAes.cpp 7zip-23.01+dfsg/CPP/7zip/Crypto/7zAes.cpp --- 7zip-22.01+dfsg/CPP/7zip/Crypto/7zAes.cpp 2021-01-26 11:28:41.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/7zAes.cpp 2023-04-02 09:00:00.000000000 +0000 @@ -8,7 +8,7 @@ #include "../../Common/ComTry.h" #include "../../Common/MyBuffer2.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "../../Windows/Synchronization.h" #endif @@ -17,7 +17,7 @@ #include "7zAes.h" #include "MyAes.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY #include "RandGen.h" #endif @@ -86,8 +86,8 @@ r += numUnroll; do { - SetUi32(dest, i); i++; dest += bufSize; - // SetUi32(dest, i); i++; dest += bufSize; + SetUi32(dest, i) i++; dest += bufSize; + // SetUi32(dest, i) i++; dest += bufSize; } while (i < r); Sha256_Update((CSha256 *)(void *)(Byte *)sha, buf, unrollSize); @@ -153,7 +153,7 @@ static CKeyInfoCache g_GlobalKeyCache(32); -#ifndef _7ZIP_ST +#ifndef Z7_ST static NWindows::NSynchronization::CCriticalSection g_GlobalKeyCacheCriticalSection; #define MT_LOCK NWindows::NSynchronization::CCriticalSectionLock lock(g_GlobalKeyCacheCriticalSection); #else @@ -185,10 +185,10 @@ g_GlobalKeyCache.FindAndAdd(_key); } -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY /* -STDMETHODIMP CEncoder::ResetSalt() +Z7_COM7F_IMF(CEncoder::ResetSalt()) { _key.SaltSize = 4; g_RandomGenerator.Generate(_key.Salt, _key.SaltSize); @@ -196,7 +196,7 @@ } */ -STDMETHODIMP CEncoder::ResetInitVector() +Z7_COM7F_IMF(CEncoder::ResetInitVector()) { for (unsigned i = 0; i < sizeof(_iv); i++) _iv[i] = 0; @@ -205,7 +205,7 @@ return S_OK; } -STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream) +Z7_COM7F_IMF(CEncoder::WriteCoderProperties(ISequentialOutStream *outStream)) { Byte props[2 + sizeof(_key.Salt) + sizeof(_iv)]; unsigned propsSize = 1; @@ -243,7 +243,7 @@ _aesFilter = new CAesCbcDecoder(kKeySize); } -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) +Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size)) { _key.ClearProps(); @@ -282,7 +282,7 @@ } -STDMETHODIMP CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size) +Z7_COM7F_IMF(CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size)) { COM_TRY_BEGIN @@ -293,23 +293,23 @@ COM_TRY_END } -STDMETHODIMP CBaseCoder::Init() +Z7_COM7F_IMF(CBaseCoder::Init()) { COM_TRY_BEGIN PrepareKey(); CMyComPtr cp; - RINOK(_aesFilter.QueryInterface(IID_ICryptoProperties, &cp)); + RINOK(_aesFilter.QueryInterface(IID_ICryptoProperties, &cp)) if (!cp) return E_FAIL; - RINOK(cp->SetKey(_key.Key, kKeySize)); - RINOK(cp->SetInitVector(_iv, sizeof(_iv))); + RINOK(cp->SetKey(_key.Key, kKeySize)) + RINOK(cp->SetInitVector(_iv, sizeof(_iv))) return _aesFilter->Init(); COM_TRY_END } -STDMETHODIMP_(UInt32) CBaseCoder::Filter(Byte *data, UInt32 size) +Z7_COM7F_IMF2(UInt32, CBaseCoder::Filter(Byte *data, UInt32 size)) { return _aesFilter->Filter(data, size); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/7zAes.h 7zip-23.01+dfsg/CPP/7zip/Crypto/7zAes.h --- 7zip-22.01+dfsg/CPP/7zip/Crypto/7zAes.h 2019-10-11 10:50:54.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/7zAes.h 2023-05-04 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // 7zAes.h -#ifndef __CRYPTO_7Z_AES_H -#define __CRYPTO_7Z_AES_H +#ifndef ZIP7_INC_CRYPTO_7Z_AES_H +#define ZIP7_INC_CRYPTO_7Z_AES_H #include "../../Common/MyBuffer.h" #include "../../Common/MyCom.h" @@ -43,10 +43,13 @@ Password.Wipe(); NumCyclesPower = 0; SaltSize = 0; - MY_memset_0_ARRAY(Salt); - MY_memset_0_ARRAY(Key); + Z7_memset_0_ARRAY(Salt); + Z7_memset_0_ARRAY(Key); } +#ifdef Z7_CPP_IS_SUPPORTED_default + CKeyInfo(const CKeyInfo &) = default; +#endif ~CKeyInfo() { Wipe(); } }; @@ -79,48 +82,46 @@ public CMyUnknownImp, public CBase { + Z7_IFACE_COM7_IMP(ICompressFilter) + Z7_IFACE_COM7_IMP(ICryptoSetPassword) protected: + virtual ~CBaseCoder() {} CMyComPtr _aesFilter; - -public: - INTERFACE_ICompressFilter(;) - - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); }; -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY -class CEncoder: +class CEncoder Z7_final: public CBaseCoder, public ICompressWriteCoderProperties, // public ICryptoResetSalt, public ICryptoResetInitVector { -public: - MY_UNKNOWN_IMP4( + Z7_COM_UNKNOWN_IMP_4( ICompressFilter, ICryptoSetPassword, ICompressWriteCoderProperties, // ICryptoResetSalt, ICryptoResetInitVector) - STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream); - // STDMETHOD(ResetSalt)(); - STDMETHOD(ResetInitVector)(); + Z7_IFACE_COM7_IMP(ICompressWriteCoderProperties) + // Z7_IFACE_COM7_IMP(ICryptoResetSalt) + Z7_IFACE_COM7_IMP(ICryptoResetInitVector) +public: CEncoder(); }; #endif -class CDecoder: +class CDecoder Z7_final: public CBaseCoder, public ICompressSetDecoderProperties2 { -public: - MY_UNKNOWN_IMP3( + Z7_COM_UNKNOWN_IMP_3( ICompressFilter, ICryptoSetPassword, ICompressSetDecoderProperties2) - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); + Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2) +public: CDecoder(); }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/7zAesRegister.cpp 7zip-23.01+dfsg/CPP/7zip/Crypto/7zAesRegister.cpp --- 7zip-22.01+dfsg/CPP/7zip/Crypto/7zAesRegister.cpp 2019-03-28 11:33:30.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/7zAesRegister.cpp 2022-12-19 22:00:00.000000000 +0000 @@ -9,7 +9,7 @@ namespace NCrypto { namespace N7z { -REGISTER_FILTER_E(_7zAES, +REGISTER_FILTER_E(SzAES, CDecoder, CEncoder, 0x6F10701, "7zAES") diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/HmacSha1.cpp 7zip-23.01+dfsg/CPP/7zip/Crypto/HmacSha1.cpp --- 7zip-22.01+dfsg/CPP/7zip/Crypto/HmacSha1.cpp 2019-08-29 11:23:35.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/HmacSha1.cpp 2023-03-22 19:00:00.000000000 +0000 @@ -2,6 +2,8 @@ #include "StdAfx.h" +#include + #include "../../../C/CpuArch.h" #include "HmacSha1.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/HmacSha1.h 7zip-23.01+dfsg/CPP/7zip/Crypto/HmacSha1.h --- 7zip-22.01+dfsg/CPP/7zip/Crypto/HmacSha1.h 2019-08-29 12:24:05.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/HmacSha1.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,8 +1,8 @@ // HmacSha1.h // Implements HMAC-SHA-1 (RFC2104, FIPS-198) -#ifndef __CRYPTO_HMAC_SHA1_H -#define __CRYPTO_HMAC_SHA1_H +#ifndef ZIP7_INC_CRYPTO_HMAC_SHA1_H +#define ZIP7_INC_CRYPTO_HMAC_SHA1_H #include "Sha1Cls.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/HmacSha256.cpp 7zip-23.01+dfsg/CPP/7zip/Crypto/HmacSha256.cpp --- 7zip-22.01+dfsg/CPP/7zip/Crypto/HmacSha256.cpp 2019-08-29 11:32:26.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/HmacSha256.cpp 2023-03-22 19:00:00.000000000 +0000 @@ -2,6 +2,8 @@ #include "StdAfx.h" +#include + #include "../../../C/CpuArch.h" #include "HmacSha256.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/HmacSha256.h 7zip-23.01+dfsg/CPP/7zip/Crypto/HmacSha256.h --- 7zip-22.01+dfsg/CPP/7zip/Crypto/HmacSha256.h 2019-08-29 11:32:38.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/HmacSha256.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,8 +1,8 @@ // HmacSha256.h // Implements HMAC-SHA-256 (RFC2104, FIPS-198) -#ifndef __CRYPTO_HMAC_SHA256_H -#define __CRYPTO_HMAC_SHA256_H +#ifndef ZIP7_INC_CRYPTO_HMAC_SHA256_H +#define ZIP7_INC_CRYPTO_HMAC_SHA256_H #include "../../../C/Sha256.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/MyAes.cpp 7zip-23.01+dfsg/CPP/7zip/Crypto/MyAes.cpp --- 7zip-22.01+dfsg/CPP/7zip/Crypto/MyAes.cpp 2021-03-29 17:56:26.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/MyAes.cpp 2023-04-02 10:00:00.000000000 +0000 @@ -10,11 +10,16 @@ static struct CAesTabInit { CAesTabInit() { AesGenTables();} } g_AesTabInit; -CAesCoder::CAesCoder(bool encodeMode, unsigned keySize, bool ctrMode): - _keySize(keySize), +CAesCoder::CAesCoder( + // bool encodeMode, + unsigned keySize + // , bool ctrMode + ): _keyIsSet(false), - _encodeMode(encodeMode), - _ctrMode(ctrMode), + // _encodeMode(encodeMode), + // _ctrMode(ctrMode), + _keySize(keySize), + // _ctrPos(0), // _ctrPos =0 will be set in Init() _aes(AES_NUM_IVMRK_WORDS * 4 + AES_BLOCK_SIZE * 2) { // _offset = ((0 - (unsigned)(ptrdiff_t)_aes) & 0xF) / sizeof(UInt32); @@ -24,64 +29,128 @@ for (unsigned i = 0; i < 16; i++) _iv[i] = (Byte)(i + 1); _iv[0] = 0xFE; _iv[1] = _iv[2] = _iv[3] = 0xFF; */ - SetFunctions(0); } -STDMETHODIMP CAesCoder::Init() +Z7_COM7F_IMF(CAesCoder::Init()) { + _ctrPos = 0; AesCbc_Init(Aes(), _iv); return _keyIsSet ? S_OK : E_NOTIMPL; // E_FAIL } -STDMETHODIMP_(UInt32) CAesCoder::Filter(Byte *data, UInt32 size) +Z7_COM7F_IMF2(UInt32, CAesCoder::Filter(Byte *data, UInt32 size)) { if (!_keyIsSet) return 0; - if (size == 0) - return 0; if (size < AES_BLOCK_SIZE) { - #ifndef _SFX - if (_ctrMode) - { - // use that code only for last block !!! - Byte *ctr = (Byte *)(Aes() + AES_NUM_IVMRK_WORDS); - memset(ctr, 0, AES_BLOCK_SIZE); - memcpy(ctr, data, size); - _codeFunc(Aes(), ctr, 1); - memcpy(data, ctr, size); - return size; - } - #endif + if (size == 0) + return 0; return AES_BLOCK_SIZE; } size >>= 4; + // (data) must be aligned for 16-bytes here _codeFunc(Aes(), data, size); return size << 4; } -STDMETHODIMP CAesCoder::SetKey(const Byte *data, UInt32 size) + +Z7_COM7F_IMF(CAesCoder::SetKey(const Byte *data, UInt32 size)) { if ((size & 0x7) != 0 || size < 16 || size > 32) return E_INVALIDARG; if (_keySize != 0 && size != _keySize) return E_INVALIDARG; - AES_SET_KEY_FUNC setKeyFunc = (_ctrMode | _encodeMode) ? Aes_SetKey_Enc : Aes_SetKey_Dec; - setKeyFunc(Aes() + 4, data, size); + _setKeyFunc(Aes() + 4, data, size); _keyIsSet = true; return S_OK; } -STDMETHODIMP CAesCoder::SetInitVector(const Byte *data, UInt32 size) +Z7_COM7F_IMF(CAesCoder::SetInitVector(const Byte *data, UInt32 size)) { if (size != AES_BLOCK_SIZE) return E_INVALIDARG; memcpy(_iv, data, size); + /* we allow SetInitVector() call before SetKey() call. + so we ignore possible error in Init() here */ CAesCoder::Init(); // don't call virtual function here !!! return S_OK; } -#ifndef _SFX + +#ifndef Z7_SFX + +/* +Z7_COM7F_IMF(CAesCtrCoder::Init()) +{ + _ctrPos = 0; + return CAesCoder::Init(); +} +*/ + +Z7_COM7F_IMF2(UInt32, CAesCtrCoder::Filter(Byte *data, UInt32 size)) +{ + if (!_keyIsSet) + return 0; + if (size == 0) + return 0; + + if (_ctrPos != 0) + { + /* Optimized caller will not call here */ + const Byte *ctr = (Byte *)(Aes() + AES_NUM_IVMRK_WORDS); + unsigned num = 0; + for (unsigned i = _ctrPos; i != AES_BLOCK_SIZE; i++) + { + if (num == size) + { + _ctrPos = i; + return num; + } + data[num++] ^= ctr[i]; + } + _ctrPos = 0; + /* if (num < size) { + we can filter more data with _codeFunc(). + But it's supposed that the caller can work correctly, + even if we do only partial filtering here. + So we filter data only for current 16-byte block. } + */ + /* + size -= num; + size >>= 4; + // (data) must be aligned for 16-bytes here + _codeFunc(Aes(), data + num, size); + return num + (size << 4); + */ + return num; + } + + if (size < AES_BLOCK_SIZE) + { + /* The good optimized caller can call here only in last Filter() call. + But we support also non-optimized callers, + where another Filter() calls are allowed after this call. + */ + Byte *ctr = (Byte *)(Aes() + AES_NUM_IVMRK_WORDS); + memset(ctr, 0, AES_BLOCK_SIZE); + memcpy(ctr, data, size); + _codeFunc(Aes(), ctr, 1); + memcpy(data, ctr, size); + _ctrPos = size; + return size; + } + + size >>= 4; + // (data) must be aligned for 16-bytes here + _codeFunc(Aes(), data, size); + return size << 4; +} + +#endif // Z7_SFX + + +#ifndef Z7_EXTRACT_ONLY #ifdef MY_CPU_X86_OR_AMD64 #define USE_HW_AES @@ -101,93 +170,65 @@ #endif #endif -#endif - - -bool CAesCoder::SetFunctions(UInt32 - #ifndef _SFX - algo - #endif - ) -{ - _codeFunc = g_AesCbc_Decode; - - #ifdef _SFX - - return true; - - #else - - if (_ctrMode) - _codeFunc = g_AesCtr_Code; - else if (_encodeMode) - _codeFunc = g_AesCbc_Encode; - - if (algo < 1) - return true; - - if (algo == 1) - { - _codeFunc = AesCbc_Decode; - - #ifndef _SFX - if (_ctrMode) - _codeFunc = AesCtr_Code; - else if (_encodeMode) - _codeFunc = AesCbc_Encode; - #endif - return true; - } - - #ifdef USE_HW_AES - // if (CPU_IsSupported_AES()) - { - if (algo == 2) - if (g_Aes_SupportedFunctions_Flags & k_Aes_SupportedFunctions_HW) - { - _codeFunc = AesCbc_Decode_HW; - #ifndef _SFX - if (_ctrMode) - _codeFunc = AesCtr_Code_HW; - else if (_encodeMode) - _codeFunc = AesCbc_Encode_HW; - #endif - return true; - } - - #if defined(MY_CPU_X86_OR_AMD64) - if (algo == 3) - if (g_Aes_SupportedFunctions_Flags & k_Aes_SupportedFunctions_HW_256) - { - _codeFunc = AesCbc_Decode_HW_256; - #ifndef _SFX - if (_ctrMode) - _codeFunc = AesCtr_Code_HW_256; - else if (_encodeMode) - _codeFunc = AesCbc_Encode_HW; - #endif - return true; - } - #endif - } - #endif +#ifdef USE_HW_AES + #define SET_AES_FUNC_2(f2) \ + if (algo == 2) if (g_Aes_SupportedFunctions_Flags & k_Aes_SupportedFunctions_HW) \ + { f = f2; } + #ifdef MY_CPU_X86_OR_AMD64 + #define SET_AES_FUNC_23(f2, f3) \ + SET_AES_FUNC_2(f2) \ + if (algo == 3) if (g_Aes_SupportedFunctions_Flags & k_Aes_SupportedFunctions_HW_256) \ + { f = f3; } + #else // MY_CPU_X86_OR_AMD64 + #define SET_AES_FUNC_23(f2, f3) \ + SET_AES_FUNC_2(f2) + #endif // MY_CPU_X86_OR_AMD64 +#else // USE_HW_AES + #define SET_AES_FUNC_23(f2, f3) +#endif // USE_HW_AES + +#define SET_AES_FUNCS(c, f0, f1, f2, f3) \ + bool c::SetFunctions(UInt32 algo) { \ + _codeFunc = f0; if (algo < 1) return true; \ + AES_CODE_FUNC f = NULL; \ + if (algo == 1) { f = f1; } \ + SET_AES_FUNC_23(f2, f3) \ + if (f) { _codeFunc = f; return true; } \ + return false; } - return false; - #endif -} +#ifndef Z7_SFX +SET_AES_FUNCS( + CAesCtrCoder, + g_AesCtr_Code, + AesCtr_Code, + AesCtr_Code_HW, + AesCtr_Code_HW_256) +#endif -#ifndef _SFX +SET_AES_FUNCS( + CAesCbcEncoder, + g_AesCbc_Encode, + AesCbc_Encode, + AesCbc_Encode_HW, + AesCbc_Encode_HW) + +SET_AES_FUNCS( + CAesCbcDecoder, + g_AesCbc_Decode, + AesCbc_Decode, + AesCbc_Decode_HW, + AesCbc_Decode_HW_256) -STDMETHODIMP CAesCoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps) +Z7_COM7F_IMF(CAesCoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps)) { UInt32 algo = 0; for (UInt32 i = 0; i < numProps; i++) { - const PROPVARIANT &prop = coderProps[i]; if (propIDs[i] == NCoderPropID::kDefaultProp) { + const PROPVARIANT &prop = coderProps[i]; if (prop.vt != VT_UI4) return E_INVALIDARG; if (prop.ulVal > 3) @@ -200,6 +241,6 @@ return S_OK; } -#endif +#endif // Z7_EXTRACT_ONLY } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/MyAes.h 7zip-23.01+dfsg/CPP/7zip/Crypto/MyAes.h --- 7zip-22.01+dfsg/CPP/7zip/Crypto/MyAes.h 2021-01-26 11:24:50.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/MyAes.h 2023-04-02 10:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Crypto/MyAes.h -#ifndef __CRYPTO_MY_AES_H -#define __CRYPTO_MY_AES_H +#ifndef ZIP7_INC_CRYPTO_MY_AES_H +#define ZIP7_INC_CRYPTO_MY_AES_H #include "../../../C/Aes.h" @@ -12,68 +12,111 @@ namespace NCrypto { +#ifdef Z7_EXTRACT_ONLY +#define Z7_IFACEN_IAesCoderSetFunctions(x) +#else +#define Z7_IFACEN_IAesCoderSetFunctions(x) \ + virtual bool SetFunctions(UInt32 algo) x +#endif + + class CAesCoder: public ICompressFilter, public ICryptoProperties, - #ifndef _SFX + #ifndef Z7_EXTRACT_ONLY public ICompressSetCoderProperties, - #endif + #endif public CMyUnknownImp { - AES_CODE_FUNC _codeFunc; + Z7_COM_QI_BEGIN2(ICompressFilter) + Z7_COM_QI_ENTRY(ICryptoProperties) + #ifndef Z7_EXTRACT_ONLY + Z7_COM_QI_ENTRY(ICompressSetCoderProperties) + #endif + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + +public: + Z7_IFACE_COM7_IMP_NONFINAL(ICompressFilter) + Z7_IFACE_COM7_IMP(ICryptoProperties) +private: + #ifndef Z7_EXTRACT_ONLY + Z7_IFACE_COM7_IMP(ICompressSetCoderProperties) + #endif + +protected: + bool _keyIsSet; + // bool _encodeMode; + // bool _ctrMode; // unsigned _offset; unsigned _keySize; - bool _keyIsSet; - bool _encodeMode; - bool _ctrMode; - + unsigned _ctrPos; // we need _ctrPos here for Init() / SetInitVector() + AES_CODE_FUNC _codeFunc; + AES_SET_KEY_FUNC _setKeyFunc; +private: // UInt32 _aes[AES_NUM_IVMRK_WORDS + 3]; - CAlignedBuffer _aes; + CAlignedBuffer1 _aes; Byte _iv[AES_BLOCK_SIZE]; // UInt32 *Aes() { return _aes + _offset; } +protected: UInt32 *Aes() { return (UInt32 *)(void *)(Byte *)_aes; } - bool SetFunctions(UInt32 algo); + Z7_IFACE_PURE(IAesCoderSetFunctions) public: - CAesCoder(bool encodeMode, unsigned keySize, bool ctrMode); - - virtual ~CAesCoder() {}; // we need virtual destructor for derived classes - - MY_QUERYINTERFACE_BEGIN2(ICompressFilter) - MY_QUERYINTERFACE_ENTRY(ICryptoProperties) - #ifndef _SFX - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderProperties) - #endif - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_ICompressFilter(;) - + CAesCoder( + // bool encodeMode, + unsigned keySize + // , bool ctrMode + ); + virtual ~CAesCoder() {} // we need virtual destructor for derived classes void SetKeySize(unsigned size) { _keySize = size; } - - STDMETHOD(SetKey)(const Byte *data, UInt32 size); - STDMETHOD(SetInitVector)(const Byte *data, UInt32 size); - - #ifndef _SFX - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); - #endif }; -#ifndef _SFX + +#ifndef Z7_EXTRACT_ONLY struct CAesCbcEncoder: public CAesCoder { - CAesCbcEncoder(unsigned keySize = 0): CAesCoder(true, keySize, false) {} + CAesCbcEncoder(unsigned keySize = 0): CAesCoder(keySize) + { + _setKeyFunc = Aes_SetKey_Enc; + _codeFunc = g_AesCbc_Encode; + } + Z7_IFACE_IMP(IAesCoderSetFunctions) }; #endif struct CAesCbcDecoder: public CAesCoder { - CAesCbcDecoder(unsigned keySize = 0): CAesCoder(false, keySize, false) {} + CAesCbcDecoder(unsigned keySize = 0): CAesCoder(keySize) + { + _setKeyFunc = Aes_SetKey_Dec; + _codeFunc = g_AesCbc_Decode; + } + Z7_IFACE_IMP(IAesCoderSetFunctions) }; +#ifndef Z7_SFX +struct CAesCtrCoder: public CAesCoder +{ +private: + // unsigned _ctrPos; + // Z7_IFACE_COM7_IMP(ICompressFilter) + // Z7_COM7F_IMP(Init()) + Z7_COM7F_IMP2(UInt32, Filter(Byte *data, UInt32 size)) +public: + CAesCtrCoder(unsigned keySize = 0): CAesCoder(keySize) + { + _ctrPos = 0; + _setKeyFunc = Aes_SetKey_Enc; + _codeFunc = g_AesCtr_Code; + } + Z7_IFACE_IMP(IAesCoderSetFunctions) +}; +#endif + } #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/MyAesReg.cpp 7zip-23.01+dfsg/CPP/7zip/Crypto/MyAesReg.cpp --- 7zip-22.01+dfsg/CPP/7zip/Crypto/MyAesReg.cpp 2019-09-02 11:11:35.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/MyAesReg.cpp 2023-04-02 10:00:00.000000000 +0000 @@ -8,22 +8,21 @@ namespace NCrypto { -#ifndef _SFX +#ifndef Z7_SFX -#define REGISTER_AES_2(name, nameString, keySize, isCtr) \ +#define REGISTER_AES_2(name, nameString, keySize) \ REGISTER_FILTER_E(name, \ - CAesCoder(false, keySize, isCtr), \ - CAesCoder(true , keySize, isCtr), \ - 0x6F00100 | ((keySize - 16) * 8) | (isCtr ? 4 : 1), \ + CAesCbcDecoder(keySize), \ + CAesCbcEncoder(keySize), \ + 0x6F00100 | ((keySize - 16) * 8) | (/* isCtr */ 0 ? 4 : 1), \ nameString) \ -#define REGISTER_AES(name, nameString, isCtr) \ - /* REGISTER_AES_2(AES128 ## name, "AES128" nameString, 16, isCtr) */ \ - /* REGISTER_AES_2(AES192 ## name, "AES192" nameString, 24, isCtr) */ \ - REGISTER_AES_2(AES256 ## name, "AES256" nameString, 32, isCtr) \ +#define REGISTER_AES(name, nameString) \ + /* REGISTER_AES_2(AES128 ## name, "AES128" nameString, 16) */ \ + /* REGISTER_AES_2(AES192 ## name, "AES192" nameString, 24) */ \ + REGISTER_AES_2(AES256 ## name, "AES256" nameString, 32) \ -REGISTER_AES(CBC, "CBC", false) -// REGISTER_AES(CTR, "CTR", true) +REGISTER_AES(CBC, "CBC") #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp 7zip-23.01+dfsg/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp --- 7zip-22.01+dfsg/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp 2021-01-22 20:17:36.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp 2023-03-22 19:00:00.000000000 +0000 @@ -2,6 +2,8 @@ #include "StdAfx.h" +#include + #include "../../../C/CpuArch.h" #include "HmacSha1.h" @@ -28,7 +30,7 @@ MY_ALIGN (16) UInt32 u[kNumDigestWords]; - SetBe32(u, i); + SetBe32(u, i) ctx.Update((const Byte *)u, 4); ctx.Final((Byte *)u); @@ -36,7 +38,7 @@ ctx = baseCtx; ctx.GetLoopXorDigest1((void *)u, numIterations - 1); - const unsigned curSize = (keySize < kDigestSize) ? (unsigned)keySize : kDigestSize;; + const unsigned curSize = (keySize < kDigestSize) ? (unsigned)keySize : kDigestSize; memcpy(key, (const Byte *)u, curSize); key += curSize; keySize -= curSize; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/Pbkdf2HmacSha1.h 7zip-23.01+dfsg/CPP/7zip/Crypto/Pbkdf2HmacSha1.h --- 7zip-22.01+dfsg/CPP/7zip/Crypto/Pbkdf2HmacSha1.h 2019-03-13 17:35:22.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/Pbkdf2HmacSha1.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,8 +1,8 @@ // Pbkdf2HmacSha1.h // Password-Based Key Derivation Function (RFC 2898, PKCS #5) based on HMAC-SHA-1 -#ifndef __CRYPTO_PBKDF2_HMAC_SHA1_H -#define __CRYPTO_PBKDF2_HMAC_SHA1_H +#ifndef ZIP7_INC_CRYPTO_PBKDF2_HMAC_SHA1_H +#define ZIP7_INC_CRYPTO_PBKDF2_HMAC_SHA1_H #include diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/RandGen.cpp 7zip-23.01+dfsg/CPP/7zip/Crypto/RandGen.cpp --- 7zip-22.01+dfsg/CPP/7zip/Crypto/RandGen.cpp 2021-04-01 11:43:29.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/RandGen.cpp 2023-03-24 20:10:00.000000000 +0000 @@ -6,7 +6,7 @@ #ifndef USE_STATIC_SYSTEM_RAND -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "../../Windows/Synchronization.h" #endif @@ -76,9 +76,9 @@ #ifdef _WIN32 DWORD w = ::GetCurrentProcessId(); - HASH_UPD(w); + HASH_UPD(w) w = ::GetCurrentThreadId(); - HASH_UPD(w); + HASH_UPD(w) #ifdef UNDER_CE /* @@ -96,11 +96,14 @@ } #else { - HMODULE hModule = ::LoadLibrary(TEXT("Advapi32.dll")); + const HMODULE hModule = ::LoadLibrary(TEXT("advapi32.dll")); if (hModule) { // SystemFunction036() is real name of RtlGenRandom() function - Func_RtlGenRandom my_RtlGenRandom = (Func_RtlGenRandom)(void *)GetProcAddress(hModule, "SystemFunction036"); + const + Func_RtlGenRandom + my_RtlGenRandom = Z7_GET_PROC_ADDRESS( + Func_RtlGenRandom, hModule, "SystemFunction036"); if (my_RtlGenRandom) { if (my_RtlGenRandom(buf, kBufSize)) @@ -117,9 +120,9 @@ #else pid_t pid = getpid(); - HASH_UPD(pid); + HASH_UPD(pid) pid = getppid(); - HASH_UPD(pid); + HASH_UPD(pid) { int f = open("/dev/urandom", O_RDONLY); @@ -164,25 +167,25 @@ #ifdef _WIN32 LARGE_INTEGER v; if (::QueryPerformanceCounter(&v)) - HASH_UPD(v.QuadPart); + HASH_UPD(v.QuadPart) #endif #ifdef USE_POSIX_TIME #ifdef USE_POSIX_TIME2 timeval v; - if (gettimeofday(&v, 0) == 0) + if (gettimeofday(&v, NULL) == 0) { - HASH_UPD(v.tv_sec); - HASH_UPD(v.tv_usec); + HASH_UPD(v.tv_sec) + HASH_UPD(v.tv_usec) } #endif - time_t v2 = time(NULL); - HASH_UPD(v2); + const time_t v2 = time(NULL); + HASH_UPD(v2) #endif #ifdef _WIN32 - DWORD tickCount = ::GetTickCount(); - HASH_UPD(tickCount); + const DWORD tickCount = ::GetTickCount(); + HASH_UPD(tickCount) #endif for (unsigned j = 0; j < 100; j++) @@ -198,7 +201,7 @@ _needInit = false; } -#ifndef _7ZIP_ST +#ifndef Z7_ST static NWindows::NSynchronization::CCriticalSection g_CriticalSection; #define MT_LOCK NWindows::NSynchronization::CCriticalSectionLock lock(g_CriticalSection); #else @@ -222,7 +225,7 @@ Sha256_Init(&hash); UInt32 salt = 0xF672ABD1; - HASH_UPD(salt); + HASH_UPD(salt) Sha256_Update(&hash, _buff, SHA256_DIGEST_SIZE); MY_ALIGN (16) Byte buff[SHA256_DIGEST_SIZE]; @@ -232,6 +235,7 @@ } } +MY_ALIGN (16) CRandomGenerator g_RandomGenerator; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/RandGen.h 7zip-23.01+dfsg/CPP/7zip/Crypto/RandGen.h --- 7zip-22.01+dfsg/CPP/7zip/Crypto/RandGen.h 2019-02-20 08:52:48.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/RandGen.h 2023-04-11 18:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // RandGen.h -#ifndef __CRYPTO_RAND_GEN_H -#define __CRYPTO_RAND_GEN_H +#ifndef ZIP7_INC_CRYPTO_RAND_GEN_H +#define ZIP7_INC_CRYPTO_RAND_GEN_H #include "../../../C/Sha256.h" @@ -27,10 +27,11 @@ void Init(); public: - CRandomGenerator(): _needInit(true) {}; + CRandomGenerator(): _needInit(true) {} void Generate(Byte *data, unsigned size); }; +MY_ALIGN (16) extern CRandomGenerator g_RandomGenerator; #define MY_RAND_GEN(data, size) g_RandomGenerator.Generate(data, size) diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/Rar20Crypto.cpp 7zip-23.01+dfsg/CPP/7zip/Crypto/Rar20Crypto.cpp --- 7zip-22.01+dfsg/CPP/7zip/Crypto/Rar20Crypto.cpp 2019-10-10 15:10:58.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/Rar20Crypto.cpp 2023-03-07 07:00:00.000000000 +0000 @@ -54,7 +54,7 @@ Keys[3] = 0xA4E7F123L; Byte psw[128]; - MY_memset_0_ARRAY(psw); + Z7_memset_0_ARRAY(psw); if (size != 0) { if (size >= sizeof(psw)) @@ -99,22 +99,22 @@ B = D; D = TB; } - SetUi32(buf + 0, C ^ Keys[0]); - SetUi32(buf + 4, D ^ Keys[1]); - SetUi32(buf + 8, A ^ Keys[2]); - SetUi32(buf + 12, B ^ Keys[3]); + SetUi32(buf + 0, C ^ Keys[0]) + SetUi32(buf + 4, D ^ Keys[1]) + SetUi32(buf + 8, A ^ Keys[2]) + SetUi32(buf + 12, B ^ Keys[3]) UpdateKeys(encrypt ? buf : inBuf); } -STDMETHODIMP CDecoder::Init() +Z7_COM7F_IMF(CDecoder::Init()) { return S_OK; } static const UInt32 kBlockSize = 16; -STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) +Z7_COM7F_IMF2(UInt32, CDecoder::Filter(Byte *data, UInt32 size)) { if (size == 0) return 0; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/Rar20Crypto.h 7zip-23.01+dfsg/CPP/7zip/Crypto/Rar20Crypto.h --- 7zip-22.01+dfsg/CPP/7zip/Crypto/Rar20Crypto.h 2019-10-11 10:48:43.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/Rar20Crypto.h 2023-03-07 07:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Crypto/Rar20Crypto.h -#ifndef __CRYPTO_RAR20_CRYPTO_H -#define __CRYPTO_RAR20_CRYPTO_H +#ifndef ZIP7_INC_CRYPTO_RAR20_CRYPTO_H +#define ZIP7_INC_CRYPTO_RAR20_CRYPTO_H #include "../../Common/MyCom.h" @@ -31,8 +31,8 @@ ~CData() { Wipe(); } void Wipe() { - MY_memset_0_ARRAY(SubstTable); - MY_memset_0_ARRAY(Keys); + Z7_memset_0_ARRAY(SubstTable); + Z7_memset_0_ARRAY(Keys); } void EncryptBlock(Byte *buf) { CryptBlock(buf, true); } @@ -40,14 +40,13 @@ void SetPassword(const Byte *password, unsigned passwordLen); }; -class CDecoder: +class CDecoder Z7_final: public ICompressFilter, public CMyUnknownImp, public CData { -public: - MY_UNKNOWN_IMP - INTERFACE_ICompressFilter(;) + Z7_COM_UNKNOWN_IMP_0 + Z7_IFACE_COM7_IMP(ICompressFilter) }; }} diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/Rar5Aes.cpp 7zip-23.01+dfsg/CPP/7zip/Crypto/Rar5Aes.cpp --- 7zip-22.01+dfsg/CPP/7zip/Crypto/Rar5Aes.cpp 2019-10-10 15:07:49.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/Rar5Aes.cpp 2023-01-30 18:00:00.000000000 +0000 @@ -4,7 +4,7 @@ #include "../../../C/CpuArch.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "../../Windows/Synchronization.h" #endif @@ -129,11 +129,11 @@ } -STDMETHODIMP CDecoder::Init() +Z7_COM7F_IMF(CDecoder::Init()) { CalcKey_and_CheckPassword(); - RINOK(SetKey(_key, kAesKeySize)); - RINOK(SetInitVector(_iv, AES_BLOCK_SIZE)); + RINOK(SetKey(_key, kAesKeySize)) + RINOK(SetInitVector(_iv, AES_BLOCK_SIZE)) return CAesCoder::Init(); } @@ -144,7 +144,7 @@ NSha256::CHmac ctx; ctx.SetKey(_hashKey, NSha256::kDigestSize); UInt32 v; - SetUi32(&v, crc); + SetUi32(&v, crc) ctx.Update((const Byte *)&v, 4); MY_ALIGN (16) UInt32 h[SHA256_NUM_DIGEST_WORDS]; @@ -153,7 +153,7 @@ for (unsigned i = 0; i < SHA256_NUM_DIGEST_WORDS; i++) crc ^= (UInt32)GetUi32(h + i); return crc; -}; +} void CDecoder::Hmac_Convert_32Bytes(Byte *data) const @@ -163,12 +163,12 @@ ctx.SetKey(_hashKey, NSha256::kDigestSize); ctx.Update(data, NSha256::kDigestSize); ctx.Final(data); -}; +} static CKey g_Key; -#ifndef _7ZIP_ST +#ifndef Z7_ST static NWindows::NSynchronization::CCriticalSection g_GlobalKeyCacheCriticalSection; #define MT_LOCK NWindows::NSynchronization::CCriticalSectionLock lock(g_GlobalKeyCacheCriticalSection); #else diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/Rar5Aes.h 7zip-23.01+dfsg/CPP/7zip/Crypto/Rar5Aes.h --- 7zip-22.01+dfsg/CPP/7zip/Crypto/Rar5Aes.h 2019-10-11 10:52:36.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/Rar5Aes.h 2023-05-04 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Crypto/Rar5Aes.h -#ifndef __CRYPTO_RAR5_AES_H -#define __CRYPTO_RAR5_AES_H +#ifndef ZIP7_INC_CRYPTO_RAR5_AES_H +#define ZIP7_INC_CRYPTO_RAR5_AES_H #include "../../../C/Sha256.h" @@ -53,17 +53,21 @@ void Wipe() { _password.Wipe(); - MY_memset_0_ARRAY(_salt); - MY_memset_0_ARRAY(_key); - MY_memset_0_ARRAY(_check_Calced); - MY_memset_0_ARRAY(_hashKey); + Z7_memset_0_ARRAY(_salt); + Z7_memset_0_ARRAY(_key); + Z7_memset_0_ARRAY(_check_Calced); + Z7_memset_0_ARRAY(_hashKey); } +#ifdef Z7_CPP_IS_SUPPORTED_default + // CKey(const CKey &) = default; + CKey& operator =(const CKey &) = default; +#endif ~CKey() { Wipe(); } }; -class CDecoder: +class CDecoder Z7_final: public CAesCbcDecoder, public CKey { @@ -77,7 +81,7 @@ CDecoder(); - STDMETHOD(Init)(); + Z7_COM7F_IMP(Init()) void SetPassword(const Byte *data, size_t size); HRESULT SetDecoderProps(const Byte *data, unsigned size, bool includeIV, bool isService); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/RarAes.cpp 7zip-23.01+dfsg/CPP/7zip/Crypto/RarAes.cpp --- 7zip-22.01+dfsg/CPP/7zip/Crypto/RarAes.cpp 2019-10-10 11:37:52.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/RarAes.cpp 2023-01-28 17:00:00.000000000 +0000 @@ -78,11 +78,11 @@ _password.CopyFrom(data, (size_t)size); } -STDMETHODIMP CDecoder::Init() +Z7_COM7F_IMF(CDecoder::Init()) { CalcKey(); - RINOK(SetKey(_key, kAesKeySize)); - RINOK(SetInitVector(_iv, AES_BLOCK_SIZE)); + RINOK(SetKey(_key, kAesKeySize)) + RINOK(SetInitVector(_iv, AES_BLOCK_SIZE)) return CAesCoder::Init(); } @@ -116,7 +116,7 @@ for (i = 0; i < SHA1_NUM_BLOCK_WORDS; i++) { - SetUi32(data + i * 4, W[kNumW - SHA1_NUM_BLOCK_WORDS + i]); + SetUi32(data + i * 4, W[kNumW - SHA1_NUM_BLOCK_WORDS + i]) } } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/RarAes.h 7zip-23.01+dfsg/CPP/7zip/Crypto/RarAes.h --- 7zip-22.01+dfsg/CPP/7zip/Crypto/RarAes.h 2019-10-10 15:09:27.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/RarAes.h 2023-04-02 10:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Crypto/RarAes.h -#ifndef __CRYPTO_RAR_AES_H -#define __CRYPTO_RAR_AES_H +#ifndef ZIP7_INC_CRYPTO_RAR_AES_H +#define ZIP7_INC_CRYPTO_RAR_AES_H #include "../../../C/Aes.h" @@ -16,10 +16,8 @@ const unsigned kAesKeySize = 16; -class CDecoder: +class CDecoder Z7_final: public CAesCbcDecoder - // public ICompressSetDecoderProperties2, - // public ICryptoSetPassword { Byte _salt[8]; bool _thereIsSalt; @@ -33,25 +31,20 @@ void CalcKey(); public: - /* - MY_UNKNOWN_IMP1( - ICryptoSetPassword - // ICompressSetDecoderProperties2 - */ - STDMETHOD(Init)(); + Z7_COM7F_IMP(Init()) void SetPassword(const Byte *data, unsigned size); HRESULT SetDecoderProperties2(const Byte *data, UInt32 size); CDecoder(); - ~CDecoder() { Wipe(); } + ~CDecoder() Z7_DESTRUCTOR_override { Wipe(); } void Wipe() { _password.Wipe(); - MY_memset_0_ARRAY(_salt); - MY_memset_0_ARRAY(_key); - MY_memset_0_ARRAY(_iv); + Z7_memset_0_ARRAY(_salt); + Z7_memset_0_ARRAY(_key); + Z7_memset_0_ARRAY(_iv); } // void SetRar350Mode(bool rar350Mode) { _rar350Mode = rar350Mode; } }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/Sha1Cls.h 7zip-23.01+dfsg/CPP/7zip/Crypto/Sha1Cls.h --- 7zip-22.01+dfsg/CPP/7zip/Crypto/Sha1Cls.h 2020-10-02 10:23:23.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/Sha1Cls.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Crypto/Sha1Cls.h -#ifndef __CRYPTO_SHA1_CLS_H -#define __CRYPTO_SHA1_CLS_H +#ifndef ZIP7_INC_CRYPTO_SHA1_CLS_H +#define ZIP7_INC_CRYPTO_SHA1_CLS_H #include "../../../C/Sha1.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/Crypto/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/Crypto/StdAfx.h 2013-11-27 10:12:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/WzAes.cpp 7zip-23.01+dfsg/CPP/7zip/Crypto/WzAes.cpp --- 7zip-22.01+dfsg/CPP/7zip/Crypto/WzAes.cpp 2021-01-25 18:49:19.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/WzAes.cpp 2023-04-02 10:00:00.000000000 +0000 @@ -23,7 +23,7 @@ static const UInt32 kNumKeyGenIterations = 1000; -STDMETHODIMP CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size) +Z7_COM7F_IMF(CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size)) { if (size > kPasswordSizeMax) return E_INVALIDARG; @@ -34,6 +34,7 @@ void CBaseCoder::Init2() { + _hmacOverCalc = 0; const unsigned dkSizeMax32 = (2 * kAesKeySizeMax + kPwdVerifSize + 3) / 4; Byte dk[dkSizeMax32 * 4]; @@ -59,7 +60,7 @@ if (_aesCoderSpec->Init() != S_OK) throw 3; } -STDMETHODIMP CBaseCoder::Init() +Z7_COM7F_IMF(CBaseCoder::Init()) { return S_OK; } @@ -69,7 +70,7 @@ unsigned saltSize = _key.GetSaltSize(); MY_RAND_GEN(_key.Salt, saltSize); Init2(); - RINOK(WriteStream(outStream, _key.Salt, saltSize)); + RINOK(WriteStream(outStream, _key.Salt, saltSize)) return WriteStream(outStream, _key.PwdVerifComputed, kPwdVerifSize); } @@ -82,7 +83,7 @@ } /* -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) +Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size)) { if (size != 1) return E_INVALIDARG; @@ -93,10 +94,10 @@ HRESULT CDecoder::ReadHeader(ISequentialInStream *inStream) { - unsigned saltSize = _key.GetSaltSize(); - unsigned extraSize = saltSize + kPwdVerifSize; + const unsigned saltSize = _key.GetSaltSize(); + const unsigned extraSize = saltSize + kPwdVerifSize; Byte temp[kSaltSizeMax + kPwdVerifSize]; - RINOK(ReadStream_FAIL(inStream, temp, extraSize)); + RINOK(ReadStream_FAIL(inStream, temp, extraSize)) unsigned i; for (i = 0; i < saltSize; i++) _key.Salt[i] = temp[i]; @@ -124,11 +125,13 @@ isOK = false; MY_ALIGN (16) Byte mac1[kMacSize]; - RINOK(ReadStream_FAIL(inStream, mac1, kMacSize)); + RINOK(ReadStream_FAIL(inStream, mac1, kMacSize)) MY_ALIGN (16) UInt32 mac2[NSha1::kNumDigestWords]; Hmac()->Final((Byte *)mac2); isOK = CompareArrays(mac1, (const Byte *)mac2, kMacSize); + if (_hmacOverCalc) + isOK = false; return S_OK; } @@ -202,7 +205,7 @@ /* (size != 16 * N) is allowed only for last Filter() call */ -STDMETHODIMP_(UInt32) CEncoder::Filter(Byte *data, UInt32 size) +Z7_COM7F_IMF2(UInt32, CEncoder::Filter(Byte *data, UInt32 size)) { // AesCtr2_Code(&_aes, data, size); size = _aesCoder->Filter(data, size); @@ -210,14 +213,18 @@ return size; } -STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) +Z7_COM7F_IMF2(UInt32, CDecoder::Filter(Byte *data, UInt32 size)) { if (size >= 16) size &= ~(UInt32)15; - - Hmac()->Update(data, size); + if (_hmacOverCalc < size) + { + Hmac()->Update(data + _hmacOverCalc, size - _hmacOverCalc); + _hmacOverCalc = size; + } // AesCtr2_Code(&_aes, data, size); size = _aesCoder->Filter(data, size); + _hmacOverCalc -= size; return size; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/WzAes.h 7zip-23.01+dfsg/CPP/7zip/Crypto/WzAes.h --- 7zip-22.01+dfsg/CPP/7zip/Crypto/WzAes.h 2021-01-26 11:35:46.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/WzAes.h 2023-04-02 10:00:00.000000000 +0000 @@ -9,8 +9,8 @@ - 2 bytes contain Password Verifier's Code */ -#ifndef __CRYPTO_WZ_AES_H -#define __CRYPTO_WZ_AES_H +#ifndef ZIP7_INC_CRYPTO_WZ_AES_H +#define ZIP7_INC_CRYPTO_WZ_AES_H #include "../../Common/MyBuffer.h" @@ -65,8 +65,8 @@ void Wipe() { Password.Wipe(); - MY_memset_0_ARRAY(Salt); - MY_memset_0_ARRAY(PwdVerifComputed); + Z7_memset_0_ARRAY(Salt); + Z7_memset_0_ARRAY(PwdVerifComputed); } ~CKeyInfo() { Wipe(); } @@ -94,12 +94,18 @@ public ICryptoSetPassword, public CMyUnknownImp { + Z7_COM_UNKNOWN_IMP_1(ICryptoSetPassword) + Z7_COM7F_IMP(Init()) +public: + Z7_IFACE_COM7_IMP(ICryptoSetPassword) protected: CKeyInfo _key; // NSha1::CHmac _hmac; // NSha1::CHmac *Hmac() { return &_hmac; } - CAlignedBuffer _hmacBuf; + CAlignedBuffer1 _hmacBuf; + UInt32 _hmacOverCalc; + NSha1::CHmac *Hmac() { return (NSha1::CHmac *)(void *)(Byte *)_hmacBuf; } // CAesCtr2 _aes; @@ -108,18 +114,12 @@ CBaseCoder(): _hmacBuf(sizeof(NSha1::CHmac)) { - _aesCoderSpec = new CAesCoder(true, 32, true); - _aesCoder = _aesCoderSpec; + _aesCoderSpec = new CAesCtrCoder(32); + _aesCoder = _aesCoderSpec; } void Init2(); public: - MY_UNKNOWN_IMP1(ICryptoSetPassword) - - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); - - STDMETHOD(Init)(); - unsigned GetHeaderSize() const { return _key.GetSaltSize() + kPwdVerifSize; } unsigned GetAddPackSize() const { return GetHeaderSize() + kMacSize; } @@ -134,24 +134,23 @@ virtual ~CBaseCoder() {} }; -class CEncoder: +class CEncoder Z7_final: public CBaseCoder { + Z7_COM7F_IMP2(UInt32, Filter(Byte *data, UInt32 size)) public: - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); HRESULT WriteHeader(ISequentialOutStream *outStream); HRESULT WriteFooter(ISequentialOutStream *outStream); }; -class CDecoder: +class CDecoder Z7_final: public CBaseCoder // public ICompressSetDecoderProperties2 { Byte _pwdVerifFromArchive[kPwdVerifSize]; + Z7_COM7F_IMP2(UInt32, Filter(Byte *data, UInt32 size)) public: - // ICompressSetDecoderProperties2 - // STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); + // Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2) HRESULT ReadHeader(ISequentialInStream *inStream); bool Init_and_CheckPassword(); HRESULT CheckMac(ISequentialInStream *inStream, bool &isOK); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/ZipCrypto.cpp 7zip-23.01+dfsg/CPP/7zip/Crypto/ZipCrypto.cpp --- 7zip-22.01+dfsg/CPP/7zip/Crypto/ZipCrypto.cpp 2019-02-10 10:41:44.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/ZipCrypto.cpp 2023-02-01 09:00:00.000000000 +0000 @@ -20,14 +20,14 @@ #define DECRYPT_BYTE_1 UInt32 temp = key2 | 2; #define DECRYPT_BYTE_2 ((Byte)((temp * (temp ^ 1)) >> 8)) -STDMETHODIMP CCipher::CryptoSetPassword(const Byte *data, UInt32 size) +Z7_COM7F_IMF(CCipher::CryptoSetPassword(const Byte *data, UInt32 size)) { UInt32 key0 = 0x12345678; UInt32 key1 = 0x23456789; UInt32 key2 = 0x34567890; for (UInt32 i = 0; i < size; i++) - UPDATE_KEYS(data[i]); + UPDATE_KEYS(data[i]) KeyMem0 = key0; KeyMem1 = key1; @@ -36,7 +36,7 @@ return S_OK; } -STDMETHODIMP CCipher::Init() +Z7_COM7F_IMF(CCipher::Init()) { return S_OK; } @@ -58,7 +58,7 @@ return WriteStream(outStream, h, kHeaderSize); } -STDMETHODIMP_(UInt32) CEncoder::Filter(Byte *data, UInt32 size) +Z7_COM7F_IMF2(UInt32, CEncoder::Filter(Byte *data, UInt32 size)) { UInt32 key0 = this->Key0; UInt32 key1 = this->Key1; @@ -69,7 +69,7 @@ Byte b = data[i]; DECRYPT_BYTE_1 data[i] = (Byte)(b ^ DECRYPT_BYTE_2); - UPDATE_KEYS(b); + UPDATE_KEYS(b) } this->Key0 = key0; @@ -90,7 +90,7 @@ Filter(_header, kHeaderSize); } -STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) +Z7_COM7F_IMF2(UInt32, CDecoder::Filter(Byte *data, UInt32 size)) { UInt32 key0 = this->Key0; UInt32 key1 = this->Key1; @@ -100,7 +100,7 @@ { DECRYPT_BYTE_1 Byte b = (Byte)(data[i] ^ DECRYPT_BYTE_2); - UPDATE_KEYS(b); + UPDATE_KEYS(b) data[i] = b; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/ZipCrypto.h 7zip-23.01+dfsg/CPP/7zip/Crypto/ZipCrypto.h --- 7zip-22.01+dfsg/CPP/7zip/Crypto/ZipCrypto.h 2019-10-03 17:50:31.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/ZipCrypto.h 2023-02-01 15:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Crypto/ZipCrypto.h -#ifndef __CRYPTO_ZIP_CRYPTO_H -#define __CRYPTO_ZIP_CRYPTO_H +#ifndef ZIP7_INC_CRYPTO_ZIP_CRYPTO_H +#define ZIP7_INC_CRYPTO_ZIP_CRYPTO_H #include "../../Common/MyCom.h" @@ -30,6 +30,10 @@ public ICryptoSetPassword, public CMyUnknownImp { + Z7_COM_UNKNOWN_IMP_1(ICryptoSetPassword) + Z7_COM7F_IMP(Init()) +public: + Z7_IFACE_COM7_IMP(ICryptoSetPassword) protected: UInt32 Key0; UInt32 Key1; @@ -47,10 +51,6 @@ } public: - MY_UNKNOWN_IMP1(ICryptoSetPassword) - STDMETHOD(Init)(); - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); - virtual ~CCipher() { Key0 = KeyMem0 = @@ -59,18 +59,18 @@ } }; -class CEncoder: public CCipher +class CEncoder Z7_final: public CCipher { + Z7_COM7F_IMP2(UInt32, Filter(Byte *data, UInt32 size)) public: - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); HRESULT WriteHeader_Check16(ISequentialOutStream *outStream, UInt16 crc); }; -class CDecoder: public CCipher +class CDecoder Z7_final: public CCipher { + Z7_COM7F_IMP2(UInt32, Filter(Byte *data, UInt32 size)) public: Byte _header[kHeaderSize]; - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); HRESULT ReadHeader(ISequentialInStream *inStream); void Init_BeforeDecode(); }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/ZipStrong.cpp 7zip-23.01+dfsg/CPP/7zip/Crypto/ZipStrong.cpp --- 7zip-22.01+dfsg/CPP/7zip/Crypto/ZipStrong.cpp 2021-04-01 10:01:30.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/ZipStrong.cpp 2023-02-01 09:00:00.000000000 +0000 @@ -59,36 +59,51 @@ DeriveKey(sha, MasterKey); } -STDMETHODIMP CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size) + + +CDecoder::CDecoder() +{ + CAesCbcDecoder *d = new CAesCbcDecoder(); + _cbcDecoder = d; + _aesFilter = d; +} + +Z7_COM7F_IMF(CDecoder::CryptoSetPassword(const Byte *data, UInt32 size)) { _key.SetPassword(data, size); return S_OK; } -STDMETHODIMP CBaseCoder::Init() +Z7_COM7F_IMF(CDecoder::Init()) { return S_OK; } +Z7_COM7F_IMF2(UInt32, CDecoder::Filter(Byte *data, UInt32 size)) +{ + return _aesFilter->Filter(data, size); +} + + HRESULT CDecoder::ReadHeader(ISequentialInStream *inStream, UInt32 crc, UInt64 unpackSize) { Byte temp[4]; - RINOK(ReadStream_FALSE(inStream, temp, 2)); + RINOK(ReadStream_FALSE(inStream, temp, 2)) _ivSize = GetUi16(temp); if (_ivSize == 0) { memset(_iv, 0, 16); - SetUi32(_iv + 0, crc); - SetUi64(_iv + 4, unpackSize); + SetUi32(_iv + 0, crc) + SetUi64(_iv + 4, unpackSize) _ivSize = 12; } else if (_ivSize == 16) { - RINOK(ReadStream_FALSE(inStream, _iv, _ivSize)); + RINOK(ReadStream_FALSE(inStream, _iv, _ivSize)) } else return E_NOTIMPL; - RINOK(ReadStream_FALSE(inStream, temp, 4)); + RINOK(ReadStream_FALSE(inStream, temp, 4)) _remSize = GetUi32(temp); // const UInt32 kAlign = 16; if (_remSize < 16 || _remSize > (1 << 18)) @@ -208,9 +223,10 @@ return E_NOTIMPL; { - RINOK(SetKey(_key.MasterKey, _key.KeySize)); - RINOK(SetInitVector(_iv, 16)); - RINOK(Init()); + RINOK(_cbcDecoder->SetKey(_key.MasterKey, _key.KeySize)) + RINOK(_cbcDecoder->SetInitVector(_iv, 16)) + // SetInitVector() calls also Init() + RINOK(_cbcDecoder->Init()) // it's optional Filter(p, rdSize); rdSize -= kPadSize; @@ -228,9 +244,10 @@ sha.Update(p, rdSize); DeriveKey(sha, fileKey); - RINOK(SetKey(fileKey, _key.KeySize)); - RINOK(SetInitVector(_iv, 16)); - Init(); + RINOK(_cbcDecoder->SetKey(fileKey, _key.KeySize)) + RINOK(_cbcDecoder->SetInitVector(_iv, 16)) + // SetInitVector() calls also Init() + RINOK(_cbcDecoder->Init()) // it's optional memmove(p, p + validOffset, validSize); Filter(p, validSize); diff -Nru 7zip-22.01+dfsg/CPP/7zip/Crypto/ZipStrong.h 7zip-23.01+dfsg/CPP/7zip/Crypto/ZipStrong.h --- 7zip-22.01+dfsg/CPP/7zip/Crypto/ZipStrong.h 2019-10-11 10:49:27.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Crypto/ZipStrong.h 2023-04-02 11:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Crypto/ZipStrong.h -#ifndef __CRYPTO_ZIP_STRONG_H -#define __CRYPTO_ZIP_STRONG_H +#ifndef ZIP7_INC_CRYPTO_ZIP_STRONG_H +#define ZIP7_INC_CRYPTO_ZIP_STRONG_H #include "../../Common/MyBuffer2.h" @@ -28,34 +28,29 @@ void SetPassword(const Byte *data, UInt32 size); - ~CKeyInfo() { Wipe(); } void Wipe() { - MY_memset_0_ARRAY(MasterKey); + Z7_memset_0_ARRAY(MasterKey); } }; -class CBaseCoder: - public CAesCbcDecoder, - public ICryptoSetPassword -{ -protected: - CKeyInfo _key; - CAlignedBuffer _bufAligned; -public: - STDMETHOD(Init)(); - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); -}; const unsigned kAesPadAllign = AES_BLOCK_SIZE; -class CDecoder: public CBaseCoder -{ +Z7_CLASS_IMP_COM_2( + CDecoder + , ICompressFilter + , ICryptoSetPassword +) + CAesCbcDecoder *_cbcDecoder; + CMyComPtr _aesFilter; + CKeyInfo _key; + CAlignedBuffer _bufAligned; + UInt32 _ivSize; Byte _iv[16]; UInt32 _remSize; public: - MY_UNKNOWN_IMP1(ICryptoSetPassword) HRESULT ReadHeader(ISequentialInStream *inStream, UInt32 crc, UInt64 unpackSize); HRESULT Init_and_CheckPassword(bool &passwOK); UInt32 GetPadSize(UInt32 packSize32) const @@ -64,11 +59,12 @@ // Change it, if is not AES return kAesPadAllign - (packSize32 & (kAesPadAllign - 1)); } - + CDecoder(); ~CDecoder() { Wipe(); } void Wipe() { - MY_memset_0_ARRAY(_iv); + Z7_memset_0_ARRAY(_iv); + _key.Wipe(); } }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/Guid.txt 7zip-23.01+dfsg/CPP/7zip/Guid.txt --- 7zip-22.01+dfsg/CPP/7zip/Guid.txt 2022-06-06 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/Guid.txt 2023-03-24 19:00:00.000000000 +0000 @@ -31,12 +31,15 @@ 02 ISequentialOutStream 03 IInStream 04 IOutStream + 06 IStreamGetSize 07 IOutStreamFinish 08 IStreamGetProps 09 IStreamGetProps2 0A IStreamGetProp + 10 IStreamSetRestriction + 04 ICoder.h @@ -94,7 +97,8 @@ 10 IArchiveOpenCallback 20 IArchiveExtractCallback - 21 IArchiveExtractCallbackMessage + 21 IArchiveExtractCallbackMessage (deprecated in v23) + 22 IArchiveExtractCallbackMessage2 (new in v23) 30 IArchiveOpenVolumeCallback 40 IInArchiveGetStream diff -Nru 7zip-22.01+dfsg/CPP/7zip/ICoder.h 7zip-23.01+dfsg/CPP/7zip/ICoder.h --- 7zip-22.01+dfsg/CPP/7zip/ICoder.h 2021-08-05 07:18:38.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/ICoder.h 2023-04-06 10:00:00.000000000 +0000 @@ -1,39 +1,40 @@ // ICoder.h -#ifndef __ICODER_H -#define __ICODER_H +#ifndef ZIP7_INC_ICODER_H +#define ZIP7_INC_ICODER_H #include "IStream.h" -#define CODER_INTERFACE(i, x) DECL_INTERFACE(i, 4, x) +Z7_PURE_INTERFACES_BEGIN -CODER_INTERFACE(ICompressProgressInfo, 0x04) -{ - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize) PURE; - - /* (inSize) can be NULL, if unknown +#define Z7_IFACE_CONSTR_CODER(i, n) \ + Z7_DECL_IFACE_7ZIP(i, 4, n) \ + { Z7_IFACE_COM7_PURE(i) }; + +#define Z7_IFACEM_ICompressProgressInfo(x) \ + x(SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize)) +Z7_IFACE_CONSTR_CODER(ICompressProgressInfo, 0x04) + /* + SetRatioInfo() + (inSize) can be NULL, if unknown (outSize) can be NULL, if unknown - returns: S_OK E_ABORT : Break by user another error codes */ -}; -CODER_INTERFACE(ICompressCoder, 0x05) -{ - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, - ICompressProgressInfo *progress) PURE; -}; - -CODER_INTERFACE(ICompressCoder2, 0x18) -{ - STDMETHOD(Code)(ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams, - ISequentialOutStream * const *outStreams, const UInt64 * const *outSizes, UInt32 numOutStreams, - ICompressProgressInfo *progress) PURE; -}; +#define Z7_IFACEM_ICompressCoder(x) \ + x(Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, \ + const UInt64 *inSize, const UInt64 *outSize, \ + ICompressProgressInfo *progress)) +Z7_IFACE_CONSTR_CODER(ICompressCoder, 0x05) + +#define Z7_IFACEM_ICompressCoder2(x) \ + x(Code(ISequentialInStream * const *inStreams, const UInt64 *const *inSizes, UInt32 numInStreams, \ + ISequentialOutStream *const *outStreams, const UInt64 *const *outSizes, UInt32 numOutStreams, \ + ICompressProgressInfo *progress)) +Z7_IFACE_CONSTR_CODER(ICompressCoder2, 0x18) /* ICompressCoder::Code @@ -54,7 +55,7 @@ { Encoders in 7-Zip ignore (inSize). Decoder can use (*inSize) to check that stream was decoded correctly. - Some decoder in 7-Zip check it, if (full_decoding mode was set via ICompressSetFinishMode) + Some decoders in 7-Zip check it, if (full_decoding mode was set via ICompressSetFinishMode) } If it's required to limit the reading from input stream (inStream), it can @@ -132,71 +133,91 @@ kCheckSize, // VT_UI4 : size of digest in bytes kFilter, // VT_BSTR kMemUse, // VT_UI8 - kAffinity // VT_UI8 + kAffinity, // VT_UI8 + kBranchOffset, // VT_UI4 + kHashBits, // VT_UI4 + /* + // kHash3Bits, // VT_UI4 + // kHash2Bits, // VT_UI4 + // kChainBits, // VT_UI4 + kChainSize, // VT_UI4 + kNativeLevel, // VT_UI4 + kFast, // VT_UI4 + kMinMatch, // VT_UI4 The minimum slen is 3 and the maximum is 7. + kOverlapLog, // VT_UI4 The minimum ovlog is 0 and the maximum is 9. (default: 6) + kRowMatchFinder, // VT_BOOL + kLdmEnable, // VT_BOOL + // kLdmWindowSizeLog, // VT_UI4 + kLdmWindowSize, // VT_UI4 + kLdmHashLog, // VT_UI4 The minimum ldmhlog is 6 and the maximum is 26 (default: 20). + kLdmMinMatchLength, // VT_UI4 The minimum ldmslen is 4 and the maximum is 4096 (default: 64). + kLdmBucketSizeLog, // VT_UI4 The minimum ldmblog is 0 and the maximum is 8 (default: 3). + kLdmHashRateLog, // VT_UI4 The default value is wlog - ldmhlog. + kWriteUnpackSizeFlag, // VT_BOOL + kUsePledged, // VT_BOOL + kUseSizeHintPledgedForSmall, // VT_BOOL + kUseSizeHintForEach, // VT_BOOL + kUseSizeHintGlobal, // VT_BOOL + kParamSelectMode, // VT_UI4 + // kSearchLog, // VT_UI4 The minimum slog is 1 and the maximum is 26 + // kTargetLen, // VT_UI4 The minimum tlen is 0 and the maximum is 999. + */ + k_NUM_DEFINED }; } -CODER_INTERFACE(ICompressSetCoderPropertiesOpt, 0x1F) -{ - STDMETHOD(SetCoderPropertiesOpt)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps) PURE; -}; +#define Z7_IFACEM_ICompressSetCoderPropertiesOpt(x) \ + x(SetCoderPropertiesOpt(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps)) +Z7_IFACE_CONSTR_CODER(ICompressSetCoderPropertiesOpt, 0x1F) -CODER_INTERFACE(ICompressSetCoderProperties, 0x20) -{ - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps) PURE; -}; + +#define Z7_IFACEM_ICompressSetCoderProperties(x) \ + x(SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps)) +Z7_IFACE_CONSTR_CODER(ICompressSetCoderProperties, 0x20) /* -CODER_INTERFACE(ICompressSetCoderProperties, 0x21) -{ - STDMETHOD(SetDecoderProperties)(ISequentialInStream *inStream) PURE; -}; +#define Z7_IFACEM_ICompressSetDecoderProperties(x) \ + x(SetDecoderProperties(ISequentialInStream *inStream)) +Z7_IFACE_CONSTR_CODER(ICompressSetDecoderProperties, 0x21) */ -CODER_INTERFACE(ICompressSetDecoderProperties2, 0x22) -{ +#define Z7_IFACEM_ICompressSetDecoderProperties2(x) \ + x(SetDecoderProperties2(const Byte *data, UInt32 size)) +Z7_IFACE_CONSTR_CODER(ICompressSetDecoderProperties2, 0x22) /* returns: S_OK E_NOTIMP : unsupported properties E_INVALIDARG : incorrect (or unsupported) properties E_OUTOFMEMORY : memory allocation error */ - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size) PURE; -}; - -CODER_INTERFACE(ICompressWriteCoderProperties, 0x23) -{ - STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream) PURE; -}; - -CODER_INTERFACE(ICompressGetInStreamProcessedSize, 0x24) -{ - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value) PURE; -}; - -CODER_INTERFACE(ICompressSetCoderMt, 0x25) -{ - STDMETHOD(SetNumberOfThreads)(UInt32 numThreads) PURE; -}; -CODER_INTERFACE(ICompressSetFinishMode, 0x26) -{ - STDMETHOD(SetFinishMode)(UInt32 finishMode) PURE; +#define Z7_IFACEM_ICompressWriteCoderProperties(x) \ + x(WriteCoderProperties(ISequentialOutStream *outStream)) +Z7_IFACE_CONSTR_CODER(ICompressWriteCoderProperties, 0x23) + +#define Z7_IFACEM_ICompressGetInStreamProcessedSize(x) \ + x(GetInStreamProcessedSize(UInt64 *value)) +Z7_IFACE_CONSTR_CODER(ICompressGetInStreamProcessedSize, 0x24) + +#define Z7_IFACEM_ICompressSetCoderMt(x) \ + x(SetNumberOfThreads(UInt32 numThreads)) +Z7_IFACE_CONSTR_CODER(ICompressSetCoderMt, 0x25) + +#define Z7_IFACEM_ICompressSetFinishMode(x) \ + x(SetFinishMode(UInt32 finishMode)) +Z7_IFACE_CONSTR_CODER(ICompressSetFinishMode, 0x26) /* finishMode: 0 : partial decoding is allowed. It's default mode for ICompressCoder::Code(), if (outSize) is defined. 1 : full decoding. The stream must be finished at the end of decoding. */ -}; -CODER_INTERFACE(ICompressGetInStreamProcessedSize2, 0x27) -{ - STDMETHOD(GetInStreamProcessedSize2)(UInt32 streamIndex, UInt64 *value) PURE; -}; - -CODER_INTERFACE(ICompressSetMemLimit, 0x28) -{ - STDMETHOD(SetMemLimit)(UInt64 memUsage) PURE; -}; +#define Z7_IFACEM_ICompressGetInStreamProcessedSize2(x) \ + x(GetInStreamProcessedSize2(UInt32 streamIndex, UInt64 *value)) +Z7_IFACE_CONSTR_CODER(ICompressGetInStreamProcessedSize2, 0x27) + +#define Z7_IFACEM_ICompressSetMemLimit(x) \ + x(SetMemLimit(UInt64 memUsage)) +Z7_IFACE_CONSTR_CODER(ICompressSetMemLimit, 0x28) /* @@ -208,23 +229,18 @@ data from the internal buffer. in ReadUnusedFromInBuf(): the Coder is not allowed to use (ISequentialInStream *inStream) object, that was sent to ICoder::Code(). */ +#define Z7_IFACEM_ICompressReadUnusedFromInBuf(x) \ + x(ReadUnusedFromInBuf(void *data, UInt32 size, UInt32 *processedSize)) +Z7_IFACE_CONSTR_CODER(ICompressReadUnusedFromInBuf, 0x29) -CODER_INTERFACE(ICompressReadUnusedFromInBuf, 0x29) -{ - STDMETHOD(ReadUnusedFromInBuf)(void *data, UInt32 size, UInt32 *processedSize) PURE; -}; - - - -CODER_INTERFACE(ICompressGetSubStreamSize, 0x30) -{ - STDMETHOD(GetSubStreamSize)(UInt64 subStream, UInt64 *value) PURE; +#define Z7_IFACEM_ICompressGetSubStreamSize(x) \ + x(GetSubStreamSize(UInt64 subStream, UInt64 *value)) +Z7_IFACE_CONSTR_CODER(ICompressGetSubStreamSize, 0x30) /* returns: S_OK : (*value) contains the size or estimated size (can be incorrect size) S_FALSE : size is undefined E_NOTIMP : the feature is not implemented - Let's (read_size) is size of data that was already read by ISequentialInStream::Read(). The caller should call GetSubStreamSize() after each Read() and check sizes: if (start_of_subStream + *value < read_size) @@ -234,74 +250,74 @@ subStream++; } */ -}; - -CODER_INTERFACE(ICompressSetInStream, 0x31) -{ - STDMETHOD(SetInStream)(ISequentialInStream *inStream) PURE; - STDMETHOD(ReleaseInStream)() PURE; -}; -CODER_INTERFACE(ICompressSetOutStream, 0x32) -{ - STDMETHOD(SetOutStream)(ISequentialOutStream *outStream) PURE; - STDMETHOD(ReleaseOutStream)() PURE; -}; +#define Z7_IFACEM_ICompressSetInStream(x) \ + x(SetInStream(ISequentialInStream *inStream)) \ + x(ReleaseInStream()) +Z7_IFACE_CONSTR_CODER(ICompressSetInStream, 0x31) + +#define Z7_IFACEM_ICompressSetOutStream(x) \ + x(SetOutStream(ISequentialOutStream *outStream)) \ + x(ReleaseOutStream()) +Z7_IFACE_CONSTR_CODER(ICompressSetOutStream, 0x32) /* -CODER_INTERFACE(ICompressSetInStreamSize, 0x33) -{ - STDMETHOD(SetInStreamSize)(const UInt64 *inSize) PURE; -}; +#define Z7_IFACEM_ICompressSetInStreamSize(x) \ + x(SetInStreamSize(const UInt64 *inSize)) \ +Z7_IFACE_CONSTR_CODER(ICompressSetInStreamSize, 0x33) */ -CODER_INTERFACE(ICompressSetOutStreamSize, 0x34) -{ - STDMETHOD(SetOutStreamSize)(const UInt64 *outSize) PURE; - +#define Z7_IFACEM_ICompressSetOutStreamSize(x) \ + x(SetOutStreamSize(const UInt64 *outSize)) +Z7_IFACE_CONSTR_CODER(ICompressSetOutStreamSize, 0x34) /* That function initializes decoder structures. Call this function only for stream version of decoder. if (outSize == NULL), then output size is unknown if (outSize != NULL), then the decoder must stop decoding after (*outSize) bytes. */ -}; - -CODER_INTERFACE(ICompressSetBufSize, 0x35) -{ - STDMETHOD(SetInBufSize)(UInt32 streamIndex, UInt32 size) PURE; - STDMETHOD(SetOutBufSize)(UInt32 streamIndex, UInt32 size) PURE; -}; - -CODER_INTERFACE(ICompressInitEncoder, 0x36) -{ - STDMETHOD(InitEncoder)() PURE; +#define Z7_IFACEM_ICompressSetBufSize(x) \ + x(SetInBufSize(UInt32 streamIndex, UInt32 size)) \ + x(SetOutBufSize(UInt32 streamIndex, UInt32 size)) + +Z7_IFACE_CONSTR_CODER(ICompressSetBufSize, 0x35) + +#define Z7_IFACEM_ICompressInitEncoder(x) \ + x(InitEncoder()) +Z7_IFACE_CONSTR_CODER(ICompressInitEncoder, 0x36) /* That function initializes encoder structures. Call this function only for stream version of encoder. */ -}; -CODER_INTERFACE(ICompressSetInStream2, 0x37) -{ - STDMETHOD(SetInStream2)(UInt32 streamIndex, ISequentialInStream *inStream) PURE; - STDMETHOD(ReleaseInStream2)(UInt32 streamIndex) PURE; -}; +#define Z7_IFACEM_ICompressSetInStream2(x) \ + x(SetInStream2(UInt32 streamIndex, ISequentialInStream *inStream)) \ + x(ReleaseInStream2(UInt32 streamIndex)) +Z7_IFACE_CONSTR_CODER(ICompressSetInStream2, 0x37) /* -CODER_INTERFACE(ICompressSetOutStream2, 0x38) -{ - STDMETHOD(SetOutStream2)(UInt32 streamIndex, ISequentialOutStream *outStream) PURE; - STDMETHOD(ReleaseOutStream2)(UInt32 streamIndex) PURE; -}; - -CODER_INTERFACE(ICompressSetInStreamSize2, 0x39) -{ - STDMETHOD(SetInStreamSize2)(UInt32 streamIndex, const UInt64 *inSize) PURE; -}; +#define Z7_IFACEM_ICompressSetOutStream2(x) \ + x(SetOutStream2(UInt32 streamIndex, ISequentialOutStream *outStream)) + x(ReleaseOutStream2(UInt32 streamIndex)) +Z7_IFACE_CONSTR_CODER(ICompressSetOutStream2, 0x38) + +#define Z7_IFACEM_ICompressSetInStreamSize2(x) \ + x(SetInStreamSize2(UInt32 streamIndex, const UInt64 *inSize)) +Z7_IFACE_CONSTR_CODER(ICompressSetInStreamSize2, 0x39) */ +/* +#define Z7_IFACEM_ICompressInSubStreams(x) \ + x(GetNextInSubStream(UInt64 *streamIndexRes, ISequentialInStream **stream)) +Z7_IFACE_CONSTR_CODER(ICompressInSubStreams, 0x3A) + +#define Z7_IFACEM_ICompressOutSubStreams(x) \ + x(GetNextOutSubStream(UInt64 *streamIndexRes, ISequentialOutStream **stream)) +Z7_IFACE_CONSTR_CODER(ICompressOutSubStreams, 0x3B) +*/ /* ICompressFilter - Filter() converts as most as possible bytes required for fast processing. + Filter(Byte *data, UInt32 size) + (size) + converts as most as possible bytes required for fast processing. Some filters have (smallest_fast_block). For example, (smallest_fast_block == 16) for AES CBC/CTR filters. If data stream is not finished, caller must call Filter() for larger block: @@ -310,13 +326,28 @@ { The filter can leave some bytes at the end of data without conversion: if there are data alignment reasons or speed reasons. - The caller must read additional data from stream and call Filter() again. + The caller can read additional data from stream and call Filter() again. } If data stream was finished, caller can call Filter() for (size < smallest_fast_block) - data : must be aligned for at least 16 bytes for some filters (AES) + (data) parameter: + Some filters require alignment for any Filter() call: + 1) (stream_offset % alignment_size) == (data % alignment_size) + 2) (alignment_size == 2^N) + where (stream_offset) - is the number of bytes that were already filtered before. + The callers of Filter() are required to meet these requirements. + (alignment_size) can be different: + 16 : for AES filters + 4 or 2 : for some branch convert filters + 1 : for another filters + (alignment_size >= 16) is enough for all current filters of 7-Zip. + But the caller can use larger (alignment_size). + Recommended alignment for (data) of Filter() call is (alignment_size == 64). + Also it's recommended to use aligned value for (size): + (size % alignment_size == 0), + if it's not last call of Filter() for current stream. - returns: (outSize): + returns: (outSize): if (outSize == 0) : Filter have not converted anything. So the caller can stop processing, if data stream was finished. if (outSize <= size) : Filter have converted outSize bytes @@ -325,60 +356,47 @@ (it's for crypto block algorithms). */ -#define INTERFACE_ICompressFilter(x) \ - STDMETHOD(Init)() x; \ - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size) x; \ - -CODER_INTERFACE(ICompressFilter, 0x40) -{ - INTERFACE_ICompressFilter(PURE); -}; - - -CODER_INTERFACE(ICompressCodecsInfo, 0x60) -{ - STDMETHOD(GetNumMethods)(UInt32 *numMethods) PURE; - STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) PURE; - STDMETHOD(CreateDecoder)(UInt32 index, const GUID *iid, void **coder) PURE; - STDMETHOD(CreateEncoder)(UInt32 index, const GUID *iid, void **coder) PURE; -}; - -CODER_INTERFACE(ISetCompressCodecsInfo, 0x61) -{ - STDMETHOD(SetCompressCodecsInfo)(ICompressCodecsInfo *compressCodecsInfo) PURE; -}; - -CODER_INTERFACE(ICryptoProperties, 0x80) -{ - STDMETHOD(SetKey)(const Byte *data, UInt32 size) PURE; - STDMETHOD(SetInitVector)(const Byte *data, UInt32 size) PURE; -}; +#define Z7_IFACEM_ICompressFilter(x) \ + x(Init()) \ + x##2(UInt32, Filter(Byte *data, UInt32 size)) +Z7_IFACE_CONSTR_CODER(ICompressFilter, 0x40) + + +#define Z7_IFACEM_ICompressCodecsInfo(x) \ + x(GetNumMethods(UInt32 *numMethods)) \ + x(GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) \ + x(CreateDecoder(UInt32 index, const GUID *iid, void* *coder)) \ + x(CreateEncoder(UInt32 index, const GUID *iid, void* *coder)) +Z7_IFACE_CONSTR_CODER(ICompressCodecsInfo, 0x60) + +#define Z7_IFACEM_ISetCompressCodecsInfo(x) \ + x(SetCompressCodecsInfo(ICompressCodecsInfo *compressCodecsInfo)) +Z7_IFACE_CONSTR_CODER(ISetCompressCodecsInfo, 0x61) + +#define Z7_IFACEM_ICryptoProperties(x) \ + x(SetKey(const Byte *data, UInt32 size)) \ + x(SetInitVector(const Byte *data, UInt32 size)) +Z7_IFACE_CONSTR_CODER(ICryptoProperties, 0x80) /* -CODER_INTERFACE(ICryptoResetSalt, 0x88) -{ - STDMETHOD(ResetSalt)() PURE; -}; + x(ResetSalt()) +Z7_IFACE_CONSTR_CODER(ICryptoResetSalt, 0x88) */ -CODER_INTERFACE(ICryptoResetInitVector, 0x8C) -{ - STDMETHOD(ResetInitVector)() PURE; - +#define Z7_IFACEM_ICryptoResetInitVector(x) \ + x(ResetInitVector()) +Z7_IFACE_CONSTR_CODER(ICryptoResetInitVector, 0x8C) /* Call ResetInitVector() only for encoding. Call ResetInitVector() before encoding and before WriteCoderProperties(). Crypto encoder can create random IV in that function. */ -}; -CODER_INTERFACE(ICryptoSetPassword, 0x90) -{ - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size) PURE; -}; - -CODER_INTERFACE(ICryptoSetCRC, 0xA0) -{ - STDMETHOD(CryptoSetCRC)(UInt32 crc) PURE; -}; +#define Z7_IFACEM_ICryptoSetPassword(x) \ + x(CryptoSetPassword(const Byte *data, UInt32 size)) +Z7_IFACE_CONSTR_CODER(ICryptoSetPassword, 0x90) + +#define Z7_IFACEM_ICryptoSetCRC(x) \ + x(CryptoSetCRC(UInt32 crc)) +Z7_IFACE_CONSTR_CODER(ICryptoSetCRC, 0xA0) namespace NMethodPropID @@ -399,24 +417,48 @@ }; } - -#define INTERFACE_IHasher(x) \ - STDMETHOD_(void, Init)() throw() x; \ - STDMETHOD_(void, Update)(const void *data, UInt32 size) throw() x; \ - STDMETHOD_(void, Final)(Byte *digest) throw() x; \ - STDMETHOD_(UInt32, GetDigestSize)() throw() x; \ - -CODER_INTERFACE(IHasher, 0xC0) +namespace NModuleInterfaceType { - INTERFACE_IHasher(PURE) -}; + /* + virtual destructor in IUnknown: + - no : 7-Zip (Windows) + - no : 7-Zip (Linux) (v23) in default mode + - yes : p7zip + - yes : 7-Zip (Linux) before v23 + - yes : 7-Zip (Linux) (v23), if Z7_USE_VIRTUAL_DESTRUCTOR_IN_IUNKNOWN is defined + */ + const UInt32 k_IUnknown_VirtDestructor_No = 0; + const UInt32 k_IUnknown_VirtDestructor_Yes = 1; + const UInt32 k_IUnknown_VirtDestructor_ThisModule = + #if !defined(_WIN32) && defined(Z7_USE_VIRTUAL_DESTRUCTOR_IN_IUNKNOWN) + k_IUnknown_VirtDestructor_Yes; + #else + k_IUnknown_VirtDestructor_No; + #endif +} -CODER_INTERFACE(IHashers, 0xC1) +namespace NModulePropID { - STDMETHOD_(UInt32, GetNumHashers)() PURE; - STDMETHOD(GetHasherProp)(UInt32 index, PROPID propID, PROPVARIANT *value) PURE; - STDMETHOD(CreateHasher)(UInt32 index, IHasher **hasher) PURE; -}; + enum EEnum + { + kInterfaceType, // VT_UI4 + kVersion // VT_UI4 + }; +} + + +#define Z7_IFACEM_IHasher(x) \ + x##2(void, Init()) \ + x##2(void, Update(const void *data, UInt32 size)) \ + x##2(void, Final(Byte *digest)) \ + x##2(UInt32, GetDigestSize()) +Z7_IFACE_CONSTR_CODER(IHasher, 0xC0) + +#define Z7_IFACEM_IHashers(x) \ + x##2(UInt32, GetNumHashers()) \ + x(GetHasherProp(UInt32 index, PROPID propID, PROPVARIANT *value)) \ + x(CreateHasher(UInt32 index, IHasher **hasher)) +Z7_IFACE_CONSTR_CODER(IHashers, 0xC1) extern "C" { @@ -428,6 +470,8 @@ typedef HRESULT (WINAPI *Func_GetHashers)(IHashers **hashers); typedef HRESULT (WINAPI *Func_SetCodecs)(ICompressCodecsInfo *compressCodecsInfo); + typedef HRESULT (WINAPI *Func_GetModuleProp)(PROPID propID, PROPVARIANT *value); } +Z7_PURE_INTERFACES_END #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/IDecl.h 7zip-23.01+dfsg/CPP/7zip/IDecl.h --- 7zip-22.01+dfsg/CPP/7zip/IDecl.h 2015-03-06 11:13:36.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/IDecl.h 2023-03-24 11:00:00.000000000 +0000 @@ -1,8 +1,9 @@ // IDecl.h -#ifndef __IDECL_H -#define __IDECL_H +#ifndef ZIP7_INC_IDECL_H +#define ZIP7_INC_IDECL_H +#include "../Common/Common.h" #include "../Common/MyUnknown.h" #define k_7zip_GUID_Data1 0x23170F69 @@ -14,15 +15,62 @@ #define k_7zip_GUID_Data3_Encoder 0x2791 #define k_7zip_GUID_Data3_Hasher 0x2792 - -#define DECL_INTERFACE_SUB(i, base, groupId, subId) \ - DEFINE_GUID(IID_ ## i, \ +#define Z7_DECL_IFACE_7ZIP_SUB(i, _base, groupId, subId) \ + Z7_DEFINE_GUID(IID_ ## i, \ k_7zip_GUID_Data1, \ k_7zip_GUID_Data2, \ k_7zip_GUID_Data3_Common, \ 0, 0, 0, (groupId), 0, (subId), 0, 0); \ - struct i: public base + struct Z7_DECLSPEC_NOVTABLE i: public _base + +#define Z7_DECL_IFACE_7ZIP(i, groupId, subId) \ + Z7_DECL_IFACE_7ZIP_SUB(i, IUnknown, groupId, subId) + + +#ifdef COM_DECLSPEC_NOTHROW +#define Z7_COMWF_B COM_DECLSPEC_NOTHROW STDMETHODIMP +#define Z7_COMWF_B_(t) COM_DECLSPEC_NOTHROW STDMETHODIMP_(t) +#else +#define Z7_COMWF_B STDMETHODIMP +#define Z7_COMWF_B_(t) STDMETHODIMP_(t) +#endif + +#if defined(_MSC_VER) && !defined(COM_DECLSPEC_NOTHROW) +#define Z7_COM7F_B __declspec(nothrow) STDMETHODIMP +#define Z7_COM7F_B_(t) __declspec(nothrow) STDMETHODIMP_(t) +#else +#define Z7_COM7F_B Z7_COMWF_B +#define Z7_COM7F_B_(t) Z7_COMWF_B_(t) +#endif -#define DECL_INTERFACE(i, groupId, subId) DECL_INTERFACE_SUB(i, IUnknown, groupId, subId) +// #define Z7_COM7F_E Z7_noexcept +#define Z7_COM7F_E throw() +#define Z7_COM7F_EO Z7_COM7F_E Z7_override +#define Z7_COM7F_EOF Z7_COM7F_EO Z7_final +#define Z7_COM7F_IMF(f) Z7_COM7F_B f Z7_COM7F_E +#define Z7_COM7F_IMF2(t, f) Z7_COM7F_B_(t) f Z7_COM7F_E + +#define Z7_COM7F_PURE(f) virtual Z7_COM7F_IMF(f) =0; +#define Z7_COM7F_PURE2(t, f) virtual Z7_COM7F_IMF2(t, f) =0; +#define Z7_COM7F_IMP(f) Z7_COM7F_IMF(f) Z7_override Z7_final; +#define Z7_COM7F_IMP2(t, f) Z7_COM7F_IMF2(t, f) Z7_override Z7_final; +#define Z7_COM7F_IMP_NONFINAL(f) Z7_COM7F_IMF(f) Z7_override; +#define Z7_COM7F_IMP_NONFINAL2(t, f) Z7_COM7F_IMF2(t, f) Z7_override; + +#define Z7_IFACE_PURE(name) Z7_IFACEN_ ## name(=0;) +#define Z7_IFACE_IMP(name) Z7_IFACEN_ ## name(Z7_override Z7_final;) + +#define Z7_IFACE_COM7_PURE(name) Z7_IFACEM_ ## name(Z7_COM7F_PURE) +#define Z7_IFACE_COM7_IMP(name) Z7_IFACEM_ ## name(Z7_COM7F_IMP) +#define Z7_IFACE_COM7_IMP_NONFINAL(name) Z7_IFACEM_ ## name(Z7_COM7F_IMP_NONFINAL) + + +#define Z7_IFACE_DECL_PURE(name) \ + DECLARE_INTERFACE(name) \ + { Z7_IFACE_PURE(name) }; + +#define Z7_IFACE_DECL_PURE_(name, baseiface) \ + DECLARE_INTERFACE_(name, baseiface) \ + { Z7_IFACE_PURE(name) }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/IPassword.h 7zip-23.01+dfsg/CPP/7zip/IPassword.h --- 7zip-22.01+dfsg/CPP/7zip/IPassword.h 2019-08-07 13:52:47.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/IPassword.h 2023-03-24 11:00:00.000000000 +0000 @@ -1,14 +1,17 @@ // IPassword.h -#ifndef __IPASSWORD_H -#define __IPASSWORD_H +#ifndef ZIP7_INC_IPASSWORD_H +#define ZIP7_INC_IPASSWORD_H #include "../Common/MyTypes.h" -#include "../Common/MyUnknown.h" #include "IDecl.h" -#define PASSWORD_INTERFACE(i, x) DECL_INTERFACE(i, 5, x) +Z7_PURE_INTERFACES_BEGIN + +#define Z7_IFACE_CONSTR_PASSWORD(i, n) \ + Z7_DECL_IFACE_7ZIP(i, 5, n) \ + { Z7_IFACE_COM7_PURE(i) }; /* How to use output parameter (BSTR *password): @@ -20,10 +23,9 @@ The caller must free BSTR string with function SysFreeString(); */ -PASSWORD_INTERFACE(ICryptoGetTextPassword, 0x10) -{ - STDMETHOD(CryptoGetTextPassword)(BSTR *password) PURE; -}; +#define Z7_IFACEM_ICryptoGetTextPassword(x) \ + x(CryptoGetTextPassword(BSTR *password)) +Z7_IFACE_CONSTR_PASSWORD(ICryptoGetTextPassword, 0x10) /* @@ -44,10 +46,9 @@ The caller must free BSTR string with function SysFreeString() */ +#define Z7_IFACEM_ICryptoGetTextPassword2(x) \ + x(CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password)) +Z7_IFACE_CONSTR_PASSWORD(ICryptoGetTextPassword2, 0x11) -PASSWORD_INTERFACE(ICryptoGetTextPassword2, 0x11) -{ - STDMETHOD(CryptoGetTextPassword2)(Int32 *passwordIsDefined, BSTR *password) PURE; -}; - +Z7_PURE_INTERFACES_END #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/IProgress.h 7zip-23.01+dfsg/CPP/7zip/IProgress.h --- 7zip-22.01+dfsg/CPP/7zip/IProgress.h 2015-08-01 14:40:47.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/IProgress.h 2023-02-01 18:00:00.000000000 +0000 @@ -1,19 +1,20 @@ // IProgress.h -#ifndef __IPROGRESS_H -#define __IPROGRESS_H +#ifndef ZIP7_INC_IPROGRESS_H +#define ZIP7_INC_IPROGRESS_H #include "../Common/MyTypes.h" #include "IDecl.h" -#define INTERFACE_IProgress(x) \ - STDMETHOD(SetTotal)(UInt64 total) x; \ - STDMETHOD(SetCompleted)(const UInt64 *completeValue) x; \ - -DECL_INTERFACE(IProgress, 0, 5) -{ - INTERFACE_IProgress(PURE) -}; +Z7_PURE_INTERFACES_BEGIN +#define Z7_IFACEM_IProgress(x) \ + x(SetTotal(UInt64 total)) \ + x(SetCompleted(const UInt64 *completeValue)) \ + +Z7_DECL_IFACE_7ZIP(IProgress, 0, 5) + { Z7_IFACE_COM7_PURE(IProgress) }; + +Z7_PURE_INTERFACES_END #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/IStream.h 7zip-23.01+dfsg/CPP/7zip/IStream.h --- 7zip-22.01+dfsg/CPP/7zip/IStream.h 2022-02-15 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/IStream.h 2023-03-24 11:00:00.000000000 +0000 @@ -1,24 +1,28 @@ // IStream.h -#ifndef __ISTREAM_H -#define __ISTREAM_H +#ifndef ZIP7_INC_ISTREAM_H +#define ZIP7_INC_ISTREAM_H #include "../Common/MyTypes.h" #include "../Common/MyWindows.h" #include "IDecl.h" -#define STREAM_INTERFACE_SUB(i, base, x) DECL_INTERFACE_SUB(i, base, 3, x) -#define STREAM_INTERFACE(i, x) STREAM_INTERFACE_SUB(i, IUnknown, x) +Z7_PURE_INTERFACES_BEGIN -STREAM_INTERFACE(ISequentialInStream, 0x01) -{ - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize) PURE; - - /* +#define Z7_IFACE_CONSTR_STREAM_SUB(i, base, n) \ + Z7_DECL_IFACE_7ZIP_SUB(i, base, 3, n) \ + { Z7_IFACE_COM7_PURE(i) }; + +#define Z7_IFACE_CONSTR_STREAM(i, n) \ + Z7_IFACE_CONSTR_STREAM_SUB(i, IUnknown, n) + + +/* +ISequentialInStream::Read() The requirement for caller: (processedSize != NULL). The callee can allow (processedSize == NULL) for compatibility reasons. - + if (size == 0), this function returns S_OK and (*processedSize) is set to 0. if (size != 0) @@ -31,21 +35,21 @@ If seek pointer before Read() call was changed to position past the end of stream: if (seek_pointer >= stream_size), this function returns S_OK and (*processedSize) is set to 0. - + ERROR CASES: If the function returns error code, then (*processedSize) is size of data written to (data) buffer (it can be data before error or data with errors). The recommended way for callee to work with reading errors: 1) write part of data before error to (data) buffer and return S_OK. 2) return error code for further calls of Read(). - */ -}; +*/ +#define Z7_IFACEM_ISequentialInStream(x) \ + x(Read(void *data, UInt32 size, UInt32 *processedSize)) +Z7_IFACE_CONSTR_STREAM(ISequentialInStream, 0x01) -STREAM_INTERFACE(ISequentialOutStream, 0x02) -{ - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize) PURE; - - /* + +/* +ISequentialOutStream::Write() The requirement for caller: (processedSize != NULL). The callee can allow (processedSize == NULL) for compatibility reasons. @@ -59,8 +63,11 @@ ERROR CASES: If the function returns error code, then (*processedSize) is size of data written from (data) buffer. - */ -}; +*/ +#define Z7_IFACEM_ISequentialOutStream(x) \ + x(Write(const void *data, UInt32 size, UInt32 *processedSize)) +Z7_IFACE_CONSTR_STREAM(ISequentialOutStream, 0x02) + #ifdef _WIN32 @@ -72,48 +79,42 @@ #else -#define HRESULT_WIN32_ERROR_NEGATIVE_SEEK MY__E_ERROR_NEGATIVE_SEEK +#define HRESULT_WIN32_ERROR_NEGATIVE_SEEK MY_E_ERROR_NEGATIVE_SEEK #endif -/* Seek() Function - If you seek before the beginning of the stream, Seek() function returns error code: +/* +IInStream::Seek() / IOutStream::Seek() + If you seek to position before the beginning of the stream, + Seek() function returns error code: Recommended error code is __HRESULT_FROM_WIN32(ERROR_NEGATIVE_SEEK). or STG_E_INVALIDFUNCTION - It is allowed to seek past the end of the stream. - - if Seek() returns error, then the value of *newPosition is undefined. */ -STREAM_INTERFACE_SUB(IInStream, ISequentialInStream, 0x03) -{ - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) PURE; -}; - -STREAM_INTERFACE_SUB(IOutStream, ISequentialOutStream, 0x04) -{ - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) PURE; - STDMETHOD(SetSize)(UInt64 newSize) PURE; -}; - -STREAM_INTERFACE(IStreamGetSize, 0x06) -{ - STDMETHOD(GetSize)(UInt64 *size) PURE; -}; - -STREAM_INTERFACE(IOutStreamFinish, 0x07) -{ - STDMETHOD(OutStreamFinish)() PURE; -}; - +#define Z7_IFACEM_IInStream(x) \ + x(Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) +Z7_IFACE_CONSTR_STREAM_SUB(IInStream, ISequentialInStream, 0x03) + +#define Z7_IFACEM_IOutStream(x) \ + x(Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) \ + x(SetSize(UInt64 newSize)) +Z7_IFACE_CONSTR_STREAM_SUB(IOutStream, ISequentialOutStream, 0x04) + +#define Z7_IFACEM_IStreamGetSize(x) \ + x(GetSize(UInt64 *size)) +Z7_IFACE_CONSTR_STREAM(IStreamGetSize, 0x06) + +#define Z7_IFACEM_IOutStreamFinish(x) \ + x(OutStreamFinish()) +Z7_IFACE_CONSTR_STREAM(IOutStreamFinish, 0x07) + +#define Z7_IFACEM_IStreamGetProps(x) \ + x(GetProps(UInt64 *size, FILETIME *cTime, FILETIME *aTime, FILETIME *mTime, UInt32 *attrib)) +Z7_IFACE_CONSTR_STREAM(IStreamGetProps, 0x08) -STREAM_INTERFACE(IStreamGetProps, 0x08) -{ - STDMETHOD(GetProps)(UInt64 *size, FILETIME *cTime, FILETIME *aTime, FILETIME *mTime, UInt32 *attrib) PURE; -}; struct CStreamFileProps { @@ -128,16 +129,79 @@ FILETIME MTime; }; -STREAM_INTERFACE(IStreamGetProps2, 0x09) -{ - STDMETHOD(GetProps2)(CStreamFileProps *props) PURE; -}; +#define Z7_IFACEM_IStreamGetProps2(x) \ + x(GetProps2(CStreamFileProps *props)) +Z7_IFACE_CONSTR_STREAM(IStreamGetProps2, 0x09) + +#define Z7_IFACEM_IStreamGetProp(x) \ + x(GetProperty(PROPID propID, PROPVARIANT *value)) \ + x(ReloadProps()) +Z7_IFACE_CONSTR_STREAM(IStreamGetProp, 0x0a) -STREAM_INTERFACE(IStreamGetProp, 0x0a) -{ - STDMETHOD(GetProperty)(PROPID propID, PROPVARIANT *value) PURE; - STDMETHOD(ReloadProps)() PURE; -}; +/* +IStreamSetRestriction::SetRestriction(UInt64 begin, UInt64 end) + + It sets region of data in output stream that is restricted. + For restricted region it's expected (or allowed) + to change data with different calls of Write()/SetSize(). + Another regions of output stream will be supposed as non-restricted: + - The callee usually doesn't flush the data in restricted region. + - The callee usually can flush data from non-restricted region. + +inputs: + + (begin > end) is not allowed, and returns E_FAIL; + + if (begin == end) + { + it means that there is no region restriction for flushing. + The callee is allowed to flush already written data and + is allowed to flush all data in future calls of + ISequentialOutStream::Write(), but before next call of SetRestriction(). + The pair of values (begin == 0 && end == 0) is recommended to + remove all restrictions. + } + + if (begin < end) + { + it means that callee must NOT to flush any data in region [begin, end). + The caller is allowed to Seek() to that region and rewrite the + data in that restriction region. + if (end == (UInt64(Int64)-1) + { + there is no upper bound for restricted region. + So non-restricted region will be [0, begin) in that case + } + + Note: it's not expected that some already written region was marked as + non-restricted by old call SetRestriction() and later the part of + that region was marked as restricted with new call SetRestriction(). + For example, for different calls with non-empty restricted regions: + (begin_new >= begin_old) is expected : + { + SetRestriction(begin_old, ...) + ... + SetRestriction(begin_new, ...) + } + } + + returns: + - if (begin > end) it return ERROR code (E_FAIL) + - S_OK : if no errors. + - Also the call of SetRestriction() can initiate the flushing of already written data. + So it can return the result of that flushing. + + Note: IOutStream::SetSize() also can change the data. + So it's not expected the call + IOutStream::SetSize() to unrestricted already written region. +*/ + +#define Z7_IFACEM_IStreamSetRestriction(x) \ + x(SetRestriction(UInt64 begin, UInt64 end)) \ + +Z7_IFACE_CONSTR_STREAM(IStreamSetRestriction, 0x10) + +Z7_PURE_INTERFACES_END #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/LzmaDec.mak 7zip-23.01+dfsg/CPP/7zip/LzmaDec.mak --- 7zip-22.01+dfsg/CPP/7zip/LzmaDec.mak 2020-03-16 12:48:53.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/LzmaDec.mak 2023-04-07 18:00:00.000000000 +0000 @@ -1,6 +1,6 @@ !IF "$(PLATFORM)" == "x64" !IFNDEF NO_ASM -CFLAGS_C_SPEC = -D_LZMA_DEC_OPT +CFLAGS_C_SPEC = -DZ7_LZMA_DEC_OPT ASM_OBJS = $(ASM_OBJS) \ $O\LzmaDecOpt.obj !ENDIF diff -Nru 7zip-22.01+dfsg/CPP/7zip/MyVersionInfo.rc 7zip-23.01+dfsg/CPP/7zip/MyVersionInfo.rc --- 7zip-22.01+dfsg/CPP/7zip/MyVersionInfo.rc 2011-04-18 11:38:38.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/MyVersionInfo.rc 2023-02-21 13:00:00.000000000 +0000 @@ -1,2 +1,2 @@ #include "MyVersion.h" -#include "..\..\C\7zVersion.rc" +#include "../../C/7zVersion.rc" diff -Nru 7zip-22.01+dfsg/CPP/7zip/PropID.h 7zip-23.01+dfsg/CPP/7zip/PropID.h --- 7zip-22.01+dfsg/CPP/7zip/PropID.h 2022-05-03 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/PropID.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // PropID.h -#ifndef __7ZIP_PROP_ID_H -#define __7ZIP_PROP_ID_H +#ifndef ZIP7_INC_7ZIP_PROP_ID_H +#define ZIP7_INC_7ZIP_PROP_ID_H #include "../Common/MyTypes.h" @@ -110,6 +110,8 @@ kpidGroupId, kpidDeviceMajor, kpidDeviceMinor, + kpidDevMajor, + kpidDevMinor, kpid_NUM_DEFINED, diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Agent/Agent.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Agent/Agent.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Agent/Agent.cpp 2022-06-03 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Agent/Agent.cpp 2023-04-24 18:00:00.000000000 +0000 @@ -12,7 +12,7 @@ #include "../../../Windows/FileName.h" #include "../../../Windows/PropVariantConv.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "../../../Windows/Synchronization.h" #endif @@ -29,8 +29,12 @@ false; // 22.00 // true; // 21.07 -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS + extern + CExternalCodecs g_ExternalCodecs; CExternalCodecs g_ExternalCodecs; + extern + const CExternalCodecs *g_ExternalCodecs_Ptr; const CExternalCodecs *g_ExternalCodecs_Ptr; static CCodecs::CReleaser g_CodecsReleaser; #else @@ -39,7 +43,7 @@ CMyComPtr g_CodecsRef; #endif -#ifndef _7ZIP_ST +#ifndef Z7_ST static NSynchronization::CCriticalSection g_CriticalSection; #define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection); #else @@ -50,7 +54,7 @@ { MT_LOCK - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS if (g_CodecsObj) { g_CodecsObj->CloseLibs(); @@ -73,7 +77,7 @@ g_CodecsObj = new CCodecs; - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS g_ExternalCodecs.GetCodecs = g_CodecsObj; g_ExternalCodecs.GetHashers = g_CodecsObj; g_CodecsReleaser.Set(g_CodecsObj); @@ -82,7 +86,7 @@ g_CodecsRef = g_CodecsObj; #endif - RINOK(g_CodecsObj->Load()); + RINOK(g_CodecsObj->Load()) if (g_CodecsObj->Formats.IsEmpty()) { FreeGlobalCodecs(); @@ -91,15 +95,15 @@ Codecs_AddHashArcHandler(g_CodecsObj); - #ifdef EXTERNAL_CODECS - RINOK(g_ExternalCodecs.Load()); + #ifdef Z7_EXTERNAL_CODECS + RINOK(g_ExternalCodecs.Load()) g_ExternalCodecs_Ptr = &g_ExternalCodecs; #endif return S_OK; } -STDMETHODIMP CAgentFolder::GetAgentFolder(CAgentFolder **agentFolder) +Z7_COM7F_IMF(CAgentFolder::GetAgentFolder(CAgentFolder **agentFolder)) { *agentFolder = this; return S_OK; @@ -119,9 +123,9 @@ _items.Add(item); const CProxyFile2 &file = _proxy2->Files[dir.Items[i]]; if (file.DirIndex != -1) - LoadFolder(file.DirIndex); + LoadFolder((unsigned)file.DirIndex); if (_loadAltStreams && file.AltDirIndex != -1) - LoadFolder(file.AltDirIndex); + LoadFolder((unsigned)file.AltDirIndex); } return; } @@ -143,7 +147,7 @@ } } -STDMETHODIMP CAgentFolder::LoadItems() +Z7_COM7F_IMF(CAgentFolder::LoadItems()) { if (!_agentSpec->_archiveLink.IsOpen) return E_FAIL; @@ -160,7 +164,7 @@ return S_OK; } -STDMETHODIMP CAgentFolder::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CAgentFolder::GetNumberOfItems(UInt32 *numItems)) { if (_flatMode) *numItems = _items.Size(); @@ -217,7 +221,7 @@ { const CProxyFile2 &file = _proxy2->Files[(unsigned)_proxy2->Dirs[proxyIndex].ArcIndex]; len += file.NameLen + 1; - proxyIndex = (file.Parent == -1) ? 0 : _proxy2->Files[(unsigned)file.Parent].GetDirIndex(file.IsAltStream); + proxyIndex = (file.Parent == -1) ? 0 : (unsigned)_proxy2->Files[(unsigned)file.Parent].GetDirIndex(file.IsAltStream); } wchar_t *p = prefix.GetBuf_SetEnd(len) + len; @@ -229,7 +233,7 @@ *p = WCHAR_PATH_SEPARATOR; p -= file.NameLen; wmemcpy(p, file.Name, file.NameLen); - proxyIndex = (file.Parent == -1) ? 0 : _proxy2->Files[(unsigned)file.Parent].GetDirIndex(file.IsAltStream); + proxyIndex = (file.Parent == -1) ? 0 : (unsigned)_proxy2->Files[(unsigned)file.Parent].GetDirIndex(file.IsAltStream); } } else @@ -239,7 +243,7 @@ { const CProxyDir *dir = &_proxy->Dirs[proxyIndex]; len += dir->NameLen + 1; - proxyIndex = dir->ParentDir; + proxyIndex = (unsigned)dir->ParentDir; } wchar_t *p = prefix.GetBuf_SetEnd(len) + len; @@ -251,14 +255,14 @@ *p = WCHAR_PATH_SEPARATOR; p -= dir->NameLen; wmemcpy(p, dir->Name, dir->NameLen); - proxyIndex = dir->ParentDir; + proxyIndex = (unsigned)dir->ParentDir; } } } UString CAgentFolder::GetFullPrefix(UInt32 index) const { - int foldIndex = _proxyDirIndex; + unsigned foldIndex = _proxyDirIndex; if (_flatMode) foldIndex = _items[index].DirIndex; @@ -269,7 +273,7 @@ return _proxy->GetDirPath_as_Prefix(foldIndex); } -STDMETHODIMP_(UInt64) CAgentFolder::GetItemSize(UInt32 index) +Z7_COM7F_IMF2(UInt64, CAgentFolder::GetItemSize(UInt32 index)) { unsigned arcIndex; if (_proxy2) @@ -294,7 +298,7 @@ return item.Size; if (!item.IsLeaf()) return 0; - arcIndex = item.ArcIndex; + arcIndex = (unsigned)item.ArcIndex; } else { @@ -309,7 +313,7 @@ return 0; } -STDMETHODIMP CAgentFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CAgentFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -363,7 +367,7 @@ // if (itemFolder.IsLeaf) if (!item.Ignore) { - RINOK(_agentSpec->GetArchive()->GetProperty(arcIndex, propID, value)); + RINOK(_agentSpec->GetArchive()->GetProperty(arcIndex, propID, value)) } if (itemFolder.CrcIsDefined && value->vt == VT_EMPTY) prop = itemFolder.Crc; @@ -397,7 +401,7 @@ { if (item.IsLeaf()) { - RINOK(_agentSpec->GetArchive()->GetProperty(item.ArcIndex, propID, value)); + RINOK(_agentSpec->GetArchive()->GetProperty((unsigned)item.ArcIndex, propID, value)) } if (item.CrcIsDefined && value->vt == VT_EMPTY) prop = item.Crc; @@ -405,7 +409,7 @@ } default: if (item.IsLeaf()) - return _agentSpec->GetArchive()->GetProperty(item.ArcIndex, propID, value); + return _agentSpec->GetArchive()->GetProperty((unsigned)item.ArcIndex, propID, value); } } else @@ -436,7 +440,7 @@ return 0; } -STDMETHODIMP CAgentFolder::GetItemName(UInt32 index, const wchar_t **name, unsigned *len) +Z7_COM7F_IMF(CAgentFolder::GetItemName(UInt32 index, const wchar_t **name, unsigned *len)) { if (_proxy2) { @@ -467,9 +471,9 @@ } } -STDMETHODIMP CAgentFolder::GetItemPrefix(UInt32 index, const wchar_t **name, unsigned *len) +Z7_COM7F_IMF(CAgentFolder::GetItemPrefix(UInt32 index, const wchar_t **name, unsigned *len)) { - *name = 0; + *name = NULL; *len = 0; if (!_flatMode) return S_OK; @@ -493,7 +497,7 @@ return S_OK; } -static int CompareRawProps(IArchiveGetRawProps *rawProps, int arcIndex1, int arcIndex2, PROPID propID) +static int CompareRawProps(IArchiveGetRawProps *rawProps, unsigned arcIndex1, unsigned arcIndex2, PROPID propID) { // if (propID == kpidSha1) if (rawProps) @@ -501,14 +505,14 @@ const void *p1, *p2; UInt32 size1, size2; UInt32 propType1, propType2; - HRESULT res1 = rawProps->GetRawProp(arcIndex1, propID, &p1, &size1, &propType1); - HRESULT res2 = rawProps->GetRawProp(arcIndex2, propID, &p2, &size2, &propType2); + const HRESULT res1 = rawProps->GetRawProp(arcIndex1, propID, &p1, &size1, &propType1); + const HRESULT res2 = rawProps->GetRawProp(arcIndex2, propID, &p2, &size2, &propType2); if (res1 == S_OK && res2 == S_OK) { for (UInt32 i = 0; i < size1 && i < size2; i++) { - Byte b1 = ((const Byte *)p1)[i]; - Byte b2 = ((const Byte *)p2)[i]; + const Byte b1 = ((const Byte *)p1)[i]; + const Byte b2 = ((const Byte *)p2)[i]; if (b1 < b2) return -1; if (b1 > b2) return 1; } @@ -681,7 +685,7 @@ } -STDMETHODIMP_(Int32) CAgentFolder::CompareItems(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw) +Z7_COM7F_IMF2(Int32, CAgentFolder::CompareItems(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw)) { try { if (_proxy2) @@ -725,7 +729,7 @@ if (realIndex1 < dir1->SubDirs.Size()) { proxFolder1 = &_proxy->Dirs[dir1->SubDirs[realIndex1]]; - arcIndex1 = proxFolder1->ArcIndex; + arcIndex1 = (unsigned)proxFolder1->ArcIndex; } else arcIndex1 = dir1->SubFiles[realIndex1 - dir1->SubDirs.Size()]; @@ -733,7 +737,7 @@ if (realIndex2 < dir2->SubDirs.Size()) { proxFolder2 = &_proxy->Dirs[dir2->SubDirs[realIndex2]]; - arcIndex2 = proxFolder2->ArcIndex; + arcIndex2 = (unsigned)proxFolder2->ArcIndex; } else arcIndex2 = dir2->SubFiles[realIndex2 - dir2->SubDirs.Size()]; @@ -866,17 +870,17 @@ return S_OK; } -STDMETHODIMP CAgentFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder) +Z7_COM7F_IMF(CAgentFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder)) { COM_TRY_BEGIN if (_proxy2) { SET_realIndex_AND_dir_2 - unsigned arcIndex = dir->Items[realIndex]; + const unsigned arcIndex = dir->Items[realIndex]; const CProxyFile2 &item = _proxy2->Files[arcIndex]; if (!item.IsDir()) return E_INVALIDARG; - return BindToFolder_Internal(item.DirIndex, resultFolder); + return BindToFolder_Internal((unsigned)item.DirIndex, resultFolder); } SET_realIndex_AND_dir if (realIndex >= (UInt32)dir->SubDirs.Size()) @@ -885,20 +889,20 @@ COM_TRY_END } -STDMETHODIMP CAgentFolder::BindToFolder(const wchar_t *name, IFolderFolder **resultFolder) +Z7_COM7F_IMF(CAgentFolder::BindToFolder(const wchar_t *name, IFolderFolder **resultFolder)) { COM_TRY_BEGIN if (_proxy2) { - int index = _proxy2->FindItem(_proxyDirIndex, name, true); + const int index = _proxy2->FindItem(_proxyDirIndex, name, true); if (index == -1) return E_INVALIDARG; - return BindToFolder_Internal(_proxy2->Files[_proxy2->Dirs[_proxyDirIndex].Items[index]].DirIndex, resultFolder); + return BindToFolder_Internal((unsigned)_proxy2->Files[_proxy2->Dirs[_proxyDirIndex].Items[index]].DirIndex, resultFolder); } - int index = _proxy->FindSubDir(_proxyDirIndex, name); + const int index = _proxy->FindSubDir(_proxyDirIndex, name); if (index == -1) return E_INVALIDARG; - return BindToFolder_Internal(index, resultFolder); + return BindToFolder_Internal((unsigned)index, resultFolder); COM_TRY_END } @@ -933,7 +937,7 @@ return S_OK; } -STDMETHODIMP CAgentFolder::BindToAltStreams(UInt32 index, IFolderFolder **resultFolder) +Z7_COM7F_IMF(CAgentFolder::BindToAltStreams(UInt32 index, IFolderFolder **resultFolder)) { COM_TRY_BEGIN @@ -958,11 +962,11 @@ } else { - unsigned arcIndex = _proxy2->Dirs[_proxyDirIndex].ArcIndex; + const unsigned arcIndex = (unsigned)_proxy2->Dirs[_proxyDirIndex].ArcIndex; const CProxyFile2 &item = _proxy2->Files[arcIndex]; if (item.AltDirIndex == -1) return S_OK; - altDirIndex = item.AltDirIndex; + altDirIndex = (unsigned)item.AltDirIndex; // parentFolder = _parentFolder; } @@ -974,17 +978,17 @@ } SET_realIndex_AND_dir_2 - unsigned arcIndex = dir->Items[realIndex]; + const unsigned arcIndex = dir->Items[realIndex]; const CProxyFile2 &item = _proxy2->Files[arcIndex]; if (item.AltDirIndex == -1) return S_OK; - return BindToAltStreams_Internal(item.AltDirIndex, resultFolder); + return BindToAltStreams_Internal((unsigned)item.AltDirIndex, resultFolder); } COM_TRY_END } -STDMETHODIMP CAgentFolder::BindToAltStreams(const wchar_t *name, IFolderFolder **resultFolder) +Z7_COM7F_IMF(CAgentFolder::BindToAltStreams(const wchar_t *name, IFolderFolder **resultFolder)) { COM_TRY_BEGIN @@ -1006,14 +1010,14 @@ const CProxyFile2 &file = _proxy2->Files[dir.Items[i]]; if (file.AltDirIndex != -1) if (CompareFileNames(file.Name, name) == 0) - return BindToAltStreams_Internal(file.AltDirIndex, resultFolder); + return BindToAltStreams_Internal((unsigned)file.AltDirIndex, resultFolder); } return E_INVALIDARG; } COM_TRY_END } -STDMETHODIMP CAgentFolder::AreAltStreamsSupported(UInt32 index, Int32 *isSupported) +Z7_COM7F_IMF(CAgentFolder::AreAltStreamsSupported(UInt32 index, Int32 *isSupported)) { *isSupported = BoolToInt(false); @@ -1032,7 +1036,7 @@ *isSupported = BoolToInt(true); return S_OK; } - arcIndex = _proxy2->Dirs[_proxyDirIndex].ArcIndex; + arcIndex = (unsigned)_proxy2->Dirs[_proxyDirIndex].ArcIndex; } else { @@ -1046,7 +1050,7 @@ } -STDMETHODIMP CAgentFolder::BindToParentFolder(IFolderFolder **resultFolder) +Z7_COM7F_IMF(CAgentFolder::BindToParentFolder(IFolderFolder **resultFolder)) { COM_TRY_BEGIN /* @@ -1071,15 +1075,15 @@ if (parentIndex == -1) proxyDirIndex = k_Proxy2_RootDirIndex; else - proxyDirIndex = _proxy2->Files[(unsigned)parentIndex].DirIndex; + proxyDirIndex = (unsigned)_proxy2->Files[(unsigned)parentIndex].DirIndex; } } else { - int parent = _proxy->Dirs[_proxyDirIndex].ParentDir; + const int parent = _proxy->Dirs[_proxyDirIndex].ParentDir; if (parent == -1) return S_OK; - proxyDirIndex = parent; + proxyDirIndex = (unsigned)parent; } CAgentFolder *folderSpec = new CAgentFolder; @@ -1091,10 +1095,11 @@ COM_TRY_END } -STDMETHODIMP CAgentFolder::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CAgentFolder::GetStream(UInt32 index, ISequentialInStream **stream)) { - CMyComPtr getStream; - _agentSpec->GetArchive()->QueryInterface(IID_IInArchiveGetStream, (void **)&getStream); + Z7_DECL_CMyComPtr_QI_FROM( + IInArchiveGetStream, + getStream, _agentSpec->GetArchive()) if (!getStream) return S_OK; @@ -1113,7 +1118,7 @@ const CProxyDir &item = _proxy->Dirs[dir->SubDirs[realIndex]]; if (!item.IsLeaf()) return S_OK; - arcIndex = item.ArcIndex; + arcIndex = (unsigned)item.ArcIndex; } else arcIndex = dir->SubFiles[realIndex - dir->SubDirs.Size()]; @@ -1139,11 +1144,11 @@ VARTYPE Type; }; -STDMETHODIMP CAgentFolder::GetNumberOfProperties(UInt32 *numProps) +Z7_COM7F_IMF(CAgentFolder::GetNumberOfProperties(UInt32 *numProps)) { COM_TRY_BEGIN - RINOK(_agentSpec->GetArchive()->GetNumberOfProperties(numProps)); - *numProps += ARRAY_SIZE(kProps); + RINOK(_agentSpec->GetArchive()->GetNumberOfProperties(numProps)) + *numProps += Z7_ARRAY_SIZE(kProps); if (!_flatMode) (*numProps)--; /* @@ -1164,7 +1169,7 @@ COM_TRY_END } -STDMETHODIMP CAgentFolder::GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) +Z7_COM7F_IMF(CAgentFolder::GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) { COM_TRY_BEGIN UInt32 numProps; @@ -1182,7 +1187,7 @@ { *propID = kpidName; *varType = VT_BSTR; - *name = 0; + *name = NULL; return S_OK; } index--; @@ -1190,7 +1195,7 @@ if (index < numProps) { - RINOK(_agentSpec->GetArchive()->GetPropertyInfo(index, name, propID, varType)); + RINOK(_agentSpec->GetArchive()->GetPropertyInfo(index, name, propID, varType)) if (*propID == kpidPath) *propID = kpidName; } @@ -1206,7 +1211,7 @@ */ *propID = kProps[index]; *varType = k7z_PROPID_To_VARTYPE[(unsigned)*propID]; - *name = 0; + *name = NULL; } return S_OK; COM_TRY_END @@ -1221,7 +1226,7 @@ kpidCRC }; -STDMETHODIMP CAgentFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CAgentFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN @@ -1284,21 +1289,23 @@ COM_TRY_END } -STDMETHODIMP CAgentFolder::GetNumberOfFolderProperties(UInt32 *numProps) +Z7_COM7F_IMF(CAgentFolder::GetNumberOfFolderProperties(UInt32 *numProps)) { - *numProps = ARRAY_SIZE(kFolderProps); + *numProps = Z7_ARRAY_SIZE(kFolderProps); return S_OK; } -STDMETHODIMP CAgentFolder::GetFolderPropertyInfo IMP_IFolderFolder_GetProp(kFolderProps) +IMP_IFolderFolder_GetProp( + CAgentFolder::GetFolderPropertyInfo, + kFolderProps) -STDMETHODIMP CAgentFolder::GetParent(UInt32 /* index */, UInt32 * /* parent */, UInt32 * /* parentType */) +Z7_COM7F_IMF(CAgentFolder::GetParent(UInt32 /* index */, UInt32 * /* parent */, UInt32 * /* parentType */)) { return E_FAIL; } -STDMETHODIMP CAgentFolder::GetNumRawProps(UInt32 *numProps) +Z7_COM7F_IMF(CAgentFolder::GetNumRawProps(UInt32 *numProps)) { IArchiveGetRawProps *rawProps = _agentSpec->_archiveLink.GetArchiveGetRawProps(); if (rawProps) @@ -1307,7 +1314,7 @@ return S_OK; } -STDMETHODIMP CAgentFolder::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID) +Z7_COM7F_IMF(CAgentFolder::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID)) { IArchiveGetRawProps *rawProps = _agentSpec->_archiveLink.GetArchiveGetRawProps(); if (rawProps) @@ -1315,7 +1322,7 @@ return E_FAIL; } -STDMETHODIMP CAgentFolder::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) +Z7_COM7F_IMF(CAgentFolder::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType)) { IArchiveGetRawProps *rawProps = _agentSpec->_archiveLink.GetArchiveGetRawProps(); if (rawProps) @@ -1339,7 +1346,7 @@ *propType = 0; return S_OK; } - arcIndex = item.ArcIndex; + arcIndex = (unsigned)item.ArcIndex; } else arcIndex = dir->SubFiles[realIndex - dir->SubDirs.Size()]; @@ -1352,29 +1359,27 @@ return S_OK; } -STDMETHODIMP CAgentFolder::GetFolderArcProps(IFolderArcProps **object) +Z7_COM7F_IMF(CAgentFolder::GetFolderArcProps(IFolderArcProps **object)) { CMyComPtr temp = _agentSpec; *object = temp.Detach(); return S_OK; } -#ifdef NEW_FOLDER_INTERFACE -STDMETHODIMP CAgentFolder::SetFlatMode(Int32 flatMode) +Z7_COM7F_IMF(CAgentFolder::SetFlatMode(Int32 flatMode)) { _flatMode = IntToBool(flatMode); return S_OK; } -#endif int CAgentFolder::GetRealIndex(unsigned index) const { if (!_flatMode) { if (_proxy2) - return _proxy2->GetRealIndex(_proxyDirIndex, index); + return (int)_proxy2->GetRealIndex(_proxyDirIndex, index); else return _proxy->GetRealIndex(_proxyDirIndex, index); } @@ -1383,12 +1388,12 @@ if (_proxy2) { const CProxyDir2 *dir = &_proxy2->Dirs[item.DirIndex]; - return dir->Items[item.Index]; + return (int)dir->Items[item.Index]; } else { const CProxyDir *dir = &_proxy->Dirs[item.DirIndex]; - unsigned realIndex = item.Index; + const unsigned realIndex = item.Index; if (realIndex < dir->SubDirs.Size()) { const CProxyDir &f = _proxy->Dirs[dir->SubDirs[realIndex]]; @@ -1396,7 +1401,7 @@ return -1; return f.ArcIndex; } - return dir->SubFiles[realIndex - dir->SubDirs.Size()]; + return (int)dir->SubFiles[realIndex - dir->SubDirs.Size()]; } } } @@ -1437,7 +1442,7 @@ const CProxyDir &f = _proxy->Dirs[dir->SubDirs[realIndex]]; if (!f.IsLeaf()) continue; - arcIndex = f.ArcIndex; + arcIndex = (unsigned)f.ArcIndex; } else arcIndex = dir->SubFiles[realIndex - dir->SubDirs.Size()]; @@ -1448,7 +1453,7 @@ HeapSort(&realIndices.Front(), realIndices.Size()); } -STDMETHODIMP CAgentFolder::Extract(const UInt32 *indices, +Z7_COM7F_IMF(CAgentFolder::Extract(const UInt32 *indices, UInt32 numItems, Int32 includeAltStreams, Int32 replaceAltStreamColon, @@ -1456,7 +1461,7 @@ NExtract::NOverwriteMode::EEnum overwriteMode, const wchar_t *path, Int32 testMode, - IFolderArchiveExtractCallback *extractCallback2) + IFolderArchiveExtractCallback *extractCallback2)) { COM_TRY_BEGIN @@ -1492,6 +1497,7 @@ { pathU = us2fs(path); if (!pathU.IsEmpty()) + if (!NFile::NName::IsAltStreamPrefixWithColon(pathU)) { NFile::NName::NormalizeDirPathPrefix(pathU); NFile::NDir::CreateComplexDir(pathU); @@ -1524,7 +1530,7 @@ (UInt64)(Int64)-1); if (_proxy2) - extractCallbackSpec->SetBaseParentFolderIndex(_proxy2->Dirs[_proxyDirIndex].ArcIndex); + extractCallbackSpec->SetBaseParentFolderIndex((unsigned)_proxy2->Dirs[_proxyDirIndex].ArcIndex); // do we need another base folder for subfolders ? extractCallbackSpec->DirPathPrefix_for_HashFiles = _agentSpec->_hashBaseFolderPrefix; @@ -1538,7 +1544,7 @@ if (!testMode) { - RINOK(extractCallbackSpec->PrepareHardLinks(&realIndices)); + RINOK(extractCallbackSpec->PrepareHardLinks(&realIndices)) } #endif @@ -1592,12 +1598,12 @@ return true; } -STDMETHODIMP CAgent::Open( +Z7_COM7F_IMF(CAgent::Open( IInStream *inStream, const wchar_t *filePath, const wchar_t *arcFormat, BSTR *archiveType, - IArchiveOpenCallback *openArchiveCallback) + IArchiveOpenCallback *openArchiveCallback)) { COM_TRY_BEGIN _archiveFilePath = filePath; @@ -1609,7 +1615,7 @@ if (!inStream) { if (!fi.Find(us2fs(_archiveFilePath))) - return ::GetLastError(); + return GetLastError_noZero_HRESULT(); if (fi.IsDir()) return E_FAIL; _attrib = fi.Attrib; @@ -1623,7 +1629,7 @@ } CArcInfoEx archiverInfo0, archiverInfo1; - RINOK(LoadGlobalCodecs()); + RINOK(LoadGlobalCodecs()) CObjectVector types; if (!ParseOpenTypes(*g_CodecsObj, arcFormat, types)) @@ -1665,7 +1671,7 @@ ArchiveType = GetTypeOfArc(arc); if (archiveType) { - RINOK(StringToBstr(ArchiveType, archiveType)); + RINOK(StringToBstr(ArchiveType, archiveType)) } if (arc.IsHashHandler(options)) @@ -1678,7 +1684,7 @@ } -STDMETHODIMP CAgent::ReOpen(IArchiveOpenCallback *openArchiveCallback) +Z7_COM7F_IMF(CAgent::ReOpen(IArchiveOpenCallback *openArchiveCallback)) { COM_TRY_BEGIN if (_proxy2) @@ -1704,12 +1710,12 @@ options.filePath = _archiveFilePath; options.callback = openArchiveCallback; - RINOK(_archiveLink.ReOpen(options)); + RINOK(_archiveLink.ReOpen(options)) return ReadItems(); COM_TRY_END } -STDMETHODIMP CAgent::Close() +Z7_COM7F_IMF(CAgent::Close()) { COM_TRY_BEGIN return _archiveLink.Close(); @@ -1717,7 +1723,7 @@ } /* -STDMETHODIMP CAgent::EnumProperties(IEnumSTATPROPSTG **EnumProperties) +Z7_COM7F_IMF(CAgent::EnumProperties(IEnumSTATPROPSTG **EnumProperties) { return _archive->EnumProperties(EnumProperties); } @@ -1748,7 +1754,7 @@ CMyComBSTR name; PROPID propID; VARTYPE varType; - RINOK(arc.Archive->GetPropertyInfo(i, &name, &propID, &varType)); + RINOK(arc.Archive->GetPropertyInfo(i, &name, &propID, &varType)) if (propID == kpidPath) ThereIsPathProp = true; /* @@ -1763,12 +1769,12 @@ return _proxy->Load(GetArc(), NULL); } -STDMETHODIMP CAgent::BindToRootFolder(IFolderFolder **resultFolder) +Z7_COM7F_IMF(CAgent::BindToRootFolder(IFolderFolder **resultFolder)) { COM_TRY_BEGIN if (!_archiveLink.Arcs.IsEmpty()) { - RINOK(ReadItems()); + RINOK(ReadItems()) } CAgentFolder *folderSpec = new CAgentFolder; CMyComPtr rootFolder = folderSpec; @@ -1778,12 +1784,12 @@ COM_TRY_END } -STDMETHODIMP CAgent::Extract( +Z7_COM7F_IMF(CAgent::Extract( NExtract::NPathMode::EEnum pathMode, NExtract::NOverwriteMode::EEnum overwriteMode, const wchar_t *path, Int32 testMode, - IFolderArchiveExtractCallback *extractCallback2) + IFolderArchiveExtractCallback *extractCallback2)) { COM_TRY_BEGIN @@ -1820,40 +1826,40 @@ if (!testMode) { - RINOK(extractCallbackSpec->PrepareHardLinks(NULL)); // NULL means all items + RINOK(extractCallbackSpec->PrepareHardLinks(NULL)) // NULL means all items } #endif - return GetArchive()->Extract(0, (UInt32)(Int32)-1, testMode, extractCallback); + return GetArchive()->Extract(NULL, (UInt32)(Int32)-1, testMode, extractCallback); COM_TRY_END } -STDMETHODIMP CAgent::GetNumberOfProperties(UInt32 *numProps) +Z7_COM7F_IMF(CAgent::GetNumberOfProperties(UInt32 *numProps)) { COM_TRY_BEGIN return GetArchive()->GetNumberOfProperties(numProps); COM_TRY_END } -STDMETHODIMP CAgent::GetPropertyInfo(UInt32 index, - BSTR *name, PROPID *propID, VARTYPE *varType) +Z7_COM7F_IMF(CAgent::GetPropertyInfo(UInt32 index, + BSTR *name, PROPID *propID, VARTYPE *varType)) { COM_TRY_BEGIN - RINOK(GetArchive()->GetPropertyInfo(index, name, propID, varType)); + RINOK(GetArchive()->GetPropertyInfo(index, name, propID, varType)) if (*propID == kpidPath) *propID = kpidName; return S_OK; COM_TRY_END } -STDMETHODIMP CAgent::GetArcNumLevels(UInt32 *numLevels) +Z7_COM7F_IMF(CAgent::GetArcNumLevels(UInt32 *numLevels)) { *numLevels = _archiveLink.Arcs.Size(); return S_OK; } -STDMETHODIMP CAgent::GetArcProp(UInt32 level, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CAgent::GetArcProp(UInt32 level, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -1933,28 +1939,28 @@ COM_TRY_END } -STDMETHODIMP CAgent::GetArcNumProps(UInt32 level, UInt32 *numProps) +Z7_COM7F_IMF(CAgent::GetArcNumProps(UInt32 level, UInt32 *numProps)) { return _archiveLink.Arcs[level].Archive->GetNumberOfArchiveProperties(numProps); } -STDMETHODIMP CAgent::GetArcPropInfo(UInt32 level, UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) +Z7_COM7F_IMF(CAgent::GetArcPropInfo(UInt32 level, UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) { return _archiveLink.Arcs[level].Archive->GetArchivePropertyInfo(index, name, propID, varType); } // MainItemProperty -STDMETHODIMP CAgent::GetArcProp2(UInt32 level, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CAgent::GetArcProp2(UInt32 level, PROPID propID, PROPVARIANT *value)) { return _archiveLink.Arcs[level - 1].Archive->GetProperty(_archiveLink.Arcs[level].SubfileIndex, propID, value); } -STDMETHODIMP CAgent::GetArcNumProps2(UInt32 level, UInt32 *numProps) +Z7_COM7F_IMF(CAgent::GetArcNumProps2(UInt32 level, UInt32 *numProps)) { return _archiveLink.Arcs[level - 1].Archive->GetNumberOfProperties(numProps); } -STDMETHODIMP CAgent::GetArcPropInfo2(UInt32 level, UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) +Z7_COM7F_IMF(CAgent::GetArcPropInfo2(UInt32 level, UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) { return _archiveLink.Arcs[level - 1].Archive->GetPropertyInfo(index, name, propID, varType); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Agent/Agent.h 7zip-23.01+dfsg/CPP/7zip/UI/Agent/Agent.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Agent/Agent.h 2022-06-01 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Agent/Agent.h 2023-04-01 13:00:00.000000000 +0000 @@ -1,19 +1,17 @@ // Agent/Agent.h -#ifndef __AGENT_AGENT_H -#define __AGENT_AGENT_H +#ifndef ZIP7_INC_AGENT_AGENT_H +#define ZIP7_INC_AGENT_AGENT_H #include "../../../Common/MyCom.h" #include "../../../Windows/PropVariant.h" +#include "../Common/LoadCodecs.h" #include "../Common/OpenArchive.h" #include "../Common/UpdateAction.h" -#ifdef NEW_FOLDER_INTERFACE #include "../FileManager/IFolder.h" -#include "../Common/LoadCodecs.h" -#endif #include "AgentProxy.h" #include "IFolderArchive.h" @@ -24,10 +22,13 @@ class CAgentFolder; -DECL_INTERFACE(IArchiveFolderInternal, 0x01, 0xC) -{ - STDMETHOD(GetAgentFolder)(CAgentFolder **agentFolder) PURE; -}; +Z7_PURE_INTERFACES_BEGIN + +#define Z7_IFACEM_IArchiveFolderInternal(x) \ + x(GetAgentFolder(CAgentFolder **agentFolder)) +Z7_IFACE_CONSTR_FOLDERARC(IArchiveFolderInternal, 0xC) + +Z7_PURE_INTERFACES_END struct CProxyItem { @@ -47,7 +48,7 @@ AGENT_OP_Comment }; -class CAgentFolder: +class CAgentFolder Z7_final: public IFolderFolder, public IFolderAltStreams, public IFolderProperties, @@ -59,65 +60,51 @@ public IArchiveFolderInternal, public IInArchiveGetStream, public IFolderSetZoneIdMode, -#ifdef NEW_FOLDER_INTERFACE public IFolderOperations, public IFolderSetFlatMode, -#endif public CMyUnknownImp { - void LoadFolder(unsigned proxyDirIndex); -public: - - MY_QUERYINTERFACE_BEGIN2(IFolderFolder) - MY_QUERYINTERFACE_ENTRY(IFolderAltStreams) - MY_QUERYINTERFACE_ENTRY(IFolderProperties) - MY_QUERYINTERFACE_ENTRY(IArchiveGetRawProps) - MY_QUERYINTERFACE_ENTRY(IGetFolderArcProps) - MY_QUERYINTERFACE_ENTRY(IFolderCompare) - MY_QUERYINTERFACE_ENTRY(IFolderGetItemName) - MY_QUERYINTERFACE_ENTRY(IArchiveFolder) - MY_QUERYINTERFACE_ENTRY(IArchiveFolderInternal) - MY_QUERYINTERFACE_ENTRY(IInArchiveGetStream) - MY_QUERYINTERFACE_ENTRY(IFolderSetZoneIdMode) - #ifdef NEW_FOLDER_INTERFACE - MY_QUERYINTERFACE_ENTRY(IFolderOperations) - MY_QUERYINTERFACE_ENTRY(IFolderSetFlatMode) - #endif - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE + Z7_COM_QI_BEGIN2(IFolderFolder) + Z7_COM_QI_ENTRY(IFolderAltStreams) + Z7_COM_QI_ENTRY(IFolderProperties) + Z7_COM_QI_ENTRY(IArchiveGetRawProps) + Z7_COM_QI_ENTRY(IGetFolderArcProps) + Z7_COM_QI_ENTRY(IFolderCompare) + Z7_COM_QI_ENTRY(IFolderGetItemName) + Z7_COM_QI_ENTRY(IArchiveFolder) + Z7_COM_QI_ENTRY(IArchiveFolderInternal) + Z7_COM_QI_ENTRY(IInArchiveGetStream) + Z7_COM_QI_ENTRY(IFolderSetZoneIdMode) + Z7_COM_QI_ENTRY(IFolderOperations) + Z7_COM_QI_ENTRY(IFolderSetFlatMode) + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(IFolderFolder) + Z7_IFACE_COM7_IMP(IFolderAltStreams) + Z7_IFACE_COM7_IMP(IFolderProperties) + Z7_IFACE_COM7_IMP(IArchiveGetRawProps) + Z7_IFACE_COM7_IMP(IGetFolderArcProps) + Z7_IFACE_COM7_IMP(IFolderCompare) + Z7_IFACE_COM7_IMP(IFolderGetItemName) + Z7_IFACE_COM7_IMP(IArchiveFolder) + Z7_IFACE_COM7_IMP(IArchiveFolderInternal) + Z7_IFACE_COM7_IMP(IInArchiveGetStream) + Z7_IFACE_COM7_IMP(IFolderSetZoneIdMode) + Z7_IFACE_COM7_IMP(IFolderOperations) + Z7_IFACE_COM7_IMP(IFolderSetFlatMode) + void LoadFolder(unsigned proxyDirIndex); +public: HRESULT BindToFolder_Internal(unsigned proxyDirIndex, IFolderFolder **resultFolder); HRESULT BindToAltStreams_Internal(unsigned proxyDirIndex, IFolderFolder **resultFolder); int GetRealIndex(unsigned index) const; void GetRealIndices(const UInt32 *indices, UInt32 numItems, bool includeAltStreams, bool includeFolderSubItemsInFlatMode, CUIntVector &realIndices) const; - INTERFACE_IFolderSetZoneIdMode(;) - - INTERFACE_FolderFolder(;) - INTERFACE_FolderAltStreams(;) - INTERFACE_FolderProperties(;) - INTERFACE_IArchiveGetRawProps(;) - INTERFACE_IFolderGetItemName(;) - - STDMETHOD(GetFolderArcProps)(IFolderArcProps **object); - STDMETHOD_(Int32, CompareItems)(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw); int CompareItems3(UInt32 index1, UInt32 index2, PROPID propID); int CompareItems2(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw); - // IArchiveFolder - INTERFACE_IArchiveFolder(;) - - STDMETHOD(GetAgentFolder)(CAgentFolder **agentFolder); - - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); - - #ifdef NEW_FOLDER_INTERFACE - INTERFACE_FolderOperations(;) - - STDMETHOD(SetFlatMode)(Int32 flatMode); - #endif - CAgentFolder(): _proxyDirIndex(0), _isAltStreamFolder(false), @@ -173,32 +160,32 @@ NExtract::NZoneIdMode::EEnum _zoneMode; }; -class CAgent: +class CAgent Z7_final: public IInFolderArchive, public IFolderArcProps, - #ifndef EXTRACT_ONLY + #ifndef Z7_EXTRACT_ONLY public IOutFolderArchive, public ISetProperties, - #endif + #endif public CMyUnknownImp { -public: + Z7_COM_QI_BEGIN2(IInFolderArchive) + Z7_COM_QI_ENTRY(IFolderArcProps) + #ifndef Z7_EXTRACT_ONLY + Z7_COM_QI_ENTRY(IOutFolderArchive) + Z7_COM_QI_ENTRY(ISetProperties) + #endif + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE - MY_QUERYINTERFACE_BEGIN2(IInFolderArchive) - MY_QUERYINTERFACE_ENTRY(IFolderArcProps) - #ifndef EXTRACT_ONLY - MY_QUERYINTERFACE_ENTRY(IOutFolderArchive) - MY_QUERYINTERFACE_ENTRY(ISetProperties) - #endif - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE + Z7_IFACE_COM7_IMP(IInFolderArchive) + Z7_IFACE_COM7_IMP(IFolderArcProps) - INTERFACE_IInFolderArchive(;) - INTERFACE_IFolderArcProps(;) - - #ifndef EXTRACT_ONLY - INTERFACE_IOutFolderArchive(;) + #ifndef Z7_EXTRACT_ONLY + Z7_IFACE_COM7_IMP(ISetProperties) +public: + Z7_IFACE_COM7_IMP(IOutFolderArchive) HRESULT CommonUpdate(ISequentialOutStream *outArchiveStream, unsigned numUpdateItems, IArchiveUpdateCallback *updateCallback); @@ -216,15 +203,11 @@ HRESULT UpdateOneFile(ISequentialOutStream *outArchiveStream, const UInt32 *indices, UInt32 numItems, const wchar_t *diskFilePath, IFolderArchiveUpdateCallback *updateCallback100); + #endif - // ISetProperties - STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps); - #endif - - CAgent(); - ~CAgent(); private: HRESULT ReadItems(); + public: CProxyArc *_proxy; CProxyArc2 *_proxy2; @@ -248,13 +231,16 @@ bool _isHashHandler; FString _hashBaseFolderPrefix; - #ifndef EXTRACT_ONLY + #ifndef Z7_EXTRACT_ONLY CObjectVector m_PropNames; CObjectVector m_PropValues; - #endif + #endif + + CAgent(); + ~CAgent(); const CArc &GetArc() const { return _archiveLink.Arcs.Back(); } - IInArchive *GetArchive() const { if ( _archiveLink.Arcs.IsEmpty()) return 0; return GetArc().Archive; } + IInArchive *GetArchive() const { if ( _archiveLink.Arcs.IsEmpty()) return NULL; return GetArc().Archive; } bool CanUpdate() const; bool Is_Attrib_ReadOnly() const @@ -285,7 +271,7 @@ UString GetErrorMessage() const { UString s; - for (int i = _archiveLink.Arcs.Size() - 1; i >= 0; i--) + for (int i = (int)_archiveLink.Arcs.Size() - 1; i >= 0; i--) { const CArc &arc = _archiveLink.Arcs[i]; @@ -326,23 +312,42 @@ } void KeepModeForNextOpen() { _archiveLink.KeepModeForNextOpen(); } - }; -#ifdef NEW_FOLDER_INTERFACE +// #ifdef NEW_FOLDER_INTERFACE -class CArchiveFolderManager: - public IFolderManager, - public CMyUnknownImp +struct CCodecIcons { + struct CIconPair + { + UString Ext; + int IconIndex; + }; + CObjectVector IconPairs; + + // void Clear() { IconPairs.Clear(); } + void LoadIcons(HMODULE m); + bool FindIconIndex(const UString &ext, int &iconIndex) const; +}; + + +Z7_CLASS_IMP_COM_1( + CArchiveFolderManager + , IFolderManager +) + CObjectVector CodecIconsVector; + CCodecIcons InternalIcons; + bool WasLoaded; + void LoadFormats(); - int FindFormat(const UString &type); + // int FindFormat(const UString &type); public: - MY_UNKNOWN_IMP1(IFolderManager) - INTERFACE_IFolderManager(;) + CArchiveFolderManager(): + WasLoaded(false) + {} }; -#endif +// #endif #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Agent/AgentOut.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Agent/AgentOut.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Agent/AgentOut.cpp 2022-02-22 06:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Agent/AgentOut.cpp 2023-04-24 18:00:00.000000000 +0000 @@ -20,7 +20,7 @@ using namespace NWindows; using namespace NCOM; -STDMETHODIMP CAgent::SetFolder(IFolderFolder *folder) +Z7_COM7F_IMF(CAgent::SetFolder(IFolderFolder *folder)) { _updatePathPrefix.Empty(); _updatePathPrefix_is_AltFolder = false; @@ -30,11 +30,12 @@ return S_OK; { - CMyComPtr afi; - RINOK(folder->QueryInterface(IID_IArchiveFolderInternal, (void **)&afi)); + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveFolderInternal, + afi, folder) if (afi) { - RINOK(afi->GetAgentFolder(&_agentFolder)); + RINOK(afi->GetAgentFolder(&_agentFolder)) } if (!_agentFolder) return E_FAIL; @@ -47,8 +48,8 @@ return S_OK; } -STDMETHODIMP CAgent::SetFiles(const wchar_t *folderPrefix, - const wchar_t * const *names, UInt32 numNames) +Z7_COM7F_IMF(CAgent::SetFiles(const wchar_t *folderPrefix, + const wchar_t * const *names, UInt32 numNames)) { _folderPrefix = us2fs(folderPrefix); _names.ClearAndReserve(numNames); @@ -69,8 +70,8 @@ unsigned arcIndex = item.SubFiles[i]; const CProxyFile &fileItem = agent->_proxy->Files[arcIndex]; CArcItem ai; - RINOK(agent->GetArc().GetItem_MTime(arcIndex, ai.MTime)); - RINOK(agent->GetArc().GetItem_Size(arcIndex, ai.Size, ai.Size_Defined)); + RINOK(agent->GetArc().GetItem_MTime(arcIndex, ai.MTime)) + RINOK(agent->GetArc().GetItem_Size(arcIndex, ai.Size, ai.Size_Defined)) ai.IsDir = false; ai.Name = prefix + fileItem.Name; ai.Censored = true; // test it @@ -85,15 +86,15 @@ if (dirItem.IsLeaf()) { CArcItem ai; - RINOK(agent->GetArc().GetItem_MTime(dirItem.ArcIndex, ai.MTime)); + RINOK(agent->GetArc().GetItem_MTime((unsigned)dirItem.ArcIndex, ai.MTime)) ai.IsDir = true; ai.Size_Defined = false; ai.Name = fullName; ai.Censored = true; // test it - ai.IndexInServer = dirItem.ArcIndex; + ai.IndexInServer = (unsigned)dirItem.ArcIndex; arcItems.Add(ai); } - RINOK(EnumerateArchiveItems(agent, dirItem, fullName + WCHAR_PATH_SEPARATOR, arcItems)); + RINOK(EnumerateArchiveItems(agent, dirItem, fullName + WCHAR_PATH_SEPARATOR, arcItems)) } return S_OK; @@ -113,38 +114,38 @@ ai.IndexInServer = arcIndex; ai.Name = prefix + file.Name; ai.Censored = true; // test it - RINOK(agent->GetArc().GetItem_MTime(arcIndex, ai.MTime)); + RINOK(agent->GetArc().GetItem_MTime(arcIndex, ai.MTime)) ai.IsDir = file.IsDir(); ai.Size_Defined = false; ai.IsAltStream = file.IsAltStream; if (!ai.IsDir) { - RINOK(agent->GetArc().GetItem_Size(arcIndex, ai.Size, ai.Size_Defined)); + RINOK(agent->GetArc().GetItem_Size(arcIndex, ai.Size, ai.Size_Defined)) ai.IsDir = false; } arcItems.Add(ai); if (file.AltDirIndex != -1) { - RINOK(EnumerateArchiveItems2(agent, file.AltDirIndex, ai.Name + L':', arcItems)); + RINOK(EnumerateArchiveItems2(agent, (unsigned)file.AltDirIndex, ai.Name + L':', arcItems)) } if (ai.IsDir) { - RINOK(EnumerateArchiveItems2(agent, file.DirIndex, ai.Name + WCHAR_PATH_SEPARATOR, arcItems)); + RINOK(EnumerateArchiveItems2(agent, (unsigned)file.DirIndex, ai.Name + WCHAR_PATH_SEPARATOR, arcItems)) } } return S_OK; } -struct CAgUpCallbackImp: public IUpdateProduceCallback +struct CAgUpCallbackImp Z7_final: public IUpdateProduceCallback { const CObjectVector *_arcItems; IFolderArchiveUpdateCallback *_callback; CAgUpCallbackImp(const CObjectVector *a, IFolderArchiveUpdateCallback *callback): _arcItems(a), _callback(callback) {} - HRESULT ShowDeleteFile(unsigned arcIndex); + HRESULT ShowDeleteFile(unsigned arcIndex) Z7_override; }; HRESULT CAgUpCallbackImp::ShowDeleteFile(unsigned arcIndex) @@ -164,7 +165,7 @@ upd->ArcFileName = ExtractFileNameFromPath(arc.Path); } -struct CDirItemsCallback_AgentOut: public IDirItemsCallback +struct CDirItemsCallback_AgentOut Z7_final: public IDirItemsCallback { CMyComPtr FolderScanProgress; IFolderArchiveUpdateCallback *FolderArchiveUpdateCallback; @@ -172,30 +173,28 @@ CDirItemsCallback_AgentOut(): FolderArchiveUpdateCallback(NULL), ErrorCode(S_OK) {} - HRESULT ScanError(const FString &name, DWORD systemError) + HRESULT ScanError(const FString &name, DWORD systemError) Z7_override { - HRESULT hres = HRESULT_FROM_WIN32(systemError); + const HRESULT hres = HRESULT_FROM_WIN32(systemError); if (FolderArchiveUpdateCallback) return FolderScanProgress->ScanError(fs2us(name), hres); ErrorCode = hres; return ErrorCode; } - HRESULT ScanProgress(const CDirItemsStat &st, const FString &path, bool isDir) + HRESULT ScanProgress(const CDirItemsStat &st, const FString &path, bool isDir) Z7_override { if (FolderScanProgress) return FolderScanProgress->ScanProgress(st.NumDirs, st.NumFiles + st.NumAltStreams, st.GetTotalBytes(), fs2us(path), BoolToInt(isDir)); - if (FolderArchiveUpdateCallback) return FolderArchiveUpdateCallback->SetNumFiles(st.NumFiles); - return S_OK; } }; -STDMETHODIMP CAgent::DoOperation( +Z7_COM7F_IMF(CAgent::DoOperation( FStringVector *requestedPaths, FStringVector *processedPaths, CCodecs *codecs, @@ -203,7 +202,7 @@ ISequentialOutStream *outArchiveStream, const Byte *stateActions, const wchar_t *sfxModule, - IFolderArchiveUpdateCallback *updateCallback100) + IFolderArchiveUpdateCallback *updateCallback100)) { if (!CanUpdate()) return E_NOTIMPL; @@ -226,9 +225,10 @@ { FString folderPrefix = _folderPrefix; - NFile::NName::NormalizeDirPathPrefix(folderPrefix); + if (!NFile::NName::IsAltStreamPrefixWithColon(fs2us(folderPrefix))) + NFile::NName::NormalizeDirPathPrefix(folderPrefix); - RINOK(dirItems.EnumerateItems2(folderPrefix, _updatePathPrefix, _names, requestedPaths)); + RINOK(dirItems.EnumerateItems2(folderPrefix, _updatePathPrefix, _names, requestedPaths)) if (_updatePathPrefix_is_AltFolder) { @@ -246,21 +246,21 @@ if (GetArchive()) { - RINOK(GetArchive()->QueryInterface(IID_IOutArchive, (void **)&outArchive)); + RINOK(GetArchive()->QueryInterface(IID_IOutArchive, (void **)&outArchive)) } else { if (formatIndex < 0) return E_FAIL; - RINOK(codecs->CreateOutArchive(formatIndex, outArchive)); + RINOK(codecs->CreateOutArchive((unsigned)formatIndex, outArchive)) - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS { CMyComPtr setCompressCodecsInfo; outArchive.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo); if (setCompressCodecsInfo) { - RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(codecs)); + RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(codecs)) } } #endif @@ -268,7 +268,7 @@ NFileTimeType::EEnum fileTimeType = NFileTimeType::kNotDefined; UInt32 value; - RINOK(outArchive->GetFileTimeType(&value)); + RINOK(outArchive->GetFileTimeType(&value)) // we support any future fileType here. // 22.00: fileTimeType = (NFileTimeType::EEnum)value; @@ -291,15 +291,15 @@ CObjectVector arcItems; if (GetArchive()) { - RINOK(ReadItems()); + RINOK(ReadItems()) if (_proxy2) { - RINOK(EnumerateArchiveItems2(this, k_Proxy2_RootDirIndex, L"", arcItems)); - RINOK(EnumerateArchiveItems2(this, k_Proxy2_AltRootDirIndex, L":", arcItems)); + RINOK(EnumerateArchiveItems2(this, k_Proxy2_RootDirIndex, L"", arcItems)) + RINOK(EnumerateArchiveItems2(this, k_Proxy2_AltRootDirIndex, L":", arcItems)) } else { - RINOK(EnumerateArchiveItems(this, _proxy->Dirs[0], L"", arcItems)); + RINOK(EnumerateArchiveItems(this, _proxy->Dirs[0], L"", arcItems)) } } @@ -321,7 +321,7 @@ if (updateCallback100) { - RINOK(updateCallback100->SetNumFiles(numFiles)); + RINOK(updateCallback100->SetNumFiles(numFiles)) } CUpdateCallbackAgent updateCallbackAgent; @@ -347,12 +347,14 @@ updateCallbackSpec->ProcessedItemsStatuses = processedItems; } - CMyComPtr setProperties; - if (outArchive->QueryInterface(IID_ISetProperties, (void **)&setProperties) == S_OK) + Z7_DECL_CMyComPtr_QI_FROM( + ISetProperties, + setProperties, outArchive) + if (setProperties) { if (m_PropNames.Size() == 0) { - RINOK(setProperties->SetProperties(0, 0, 0)); + RINOK(setProperties->SetProperties(NULL, NULL, 0)) } else { @@ -365,7 +367,7 @@ { FOR_VECTOR (i, m_PropValues) propValues[i] = m_PropValues[i]; - RINOK(setProperties->SetProperties(&names.Front(), propValues, names.Size())); + RINOK(setProperties->SetProperties(&names.Front(), propValues, names.Size())) } catch(...) { @@ -385,7 +387,7 @@ if (!sfxStreamSpec->Open(us2fs(sfxModule))) return E_FAIL; // throw "Can't open sfx module"; - RINOK(NCompress::CopyStream(sfxStream, outArchiveStream, NULL)); + RINOK(NCompress::CopyStream(sfxStream, outArchiveStream, NULL)) } HRESULT res = outArchive->UpdateItems(outArchiveStream, updatePairs2.Size(), updateCallback); @@ -413,11 +415,11 @@ return res; } -STDMETHODIMP CAgent::DoOperation2( +Z7_COM7F_IMF(CAgent::DoOperation2( FStringVector *requestedPaths, FStringVector *processedPaths, ISequentialOutStream *outArchiveStream, - const Byte *stateActions, const wchar_t *sfxModule, IFolderArchiveUpdateCallback *updateCallback100) + const Byte *stateActions, const wchar_t *sfxModule, IFolderArchiveUpdateCallback *updateCallback100)) { return DoOperation(requestedPaths, processedPaths, g_CodecsObj, -1, outArchiveStream, stateActions, sfxModule, updateCallback100); } @@ -428,13 +430,13 @@ if (!CanUpdate()) return E_NOTIMPL; CMyComPtr outArchive; - RINOK(GetArchive()->QueryInterface(IID_IOutArchive, (void **)&outArchive)); + RINOK(GetArchive()->QueryInterface(IID_IOutArchive, (void **)&outArchive)) return outArchive->UpdateItems(outArchiveStream, numUpdateItems, updateCallback); } -STDMETHODIMP CAgent::DeleteItems(ISequentialOutStream *outArchiveStream, +Z7_COM7F_IMF(CAgent::DeleteItems(ISequentialOutStream *outArchiveStream, const UInt32 *indices, UInt32 numItems, - IFolderArchiveUpdateCallback *updateCallback100) + IFolderArchiveUpdateCallback *updateCallback100)) { if (!CanUpdate()) return E_NOTIMPL; @@ -451,7 +453,7 @@ realIndices); unsigned curIndex = 0; UInt32 numItemsInArchive; - RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)); + RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)) UString deletePath; @@ -460,8 +462,8 @@ if (curIndex < realIndices.Size()) if (realIndices[curIndex] == i) { - RINOK(GetArc().GetItem_Path2(i, deletePath)); - RINOK(updateCallback100->DeleteOperation(deletePath)); + RINOK(GetArc().GetItem_Path2(i, deletePath)) + RINOK(updateCallback100->DeleteOperation(deletePath)) curIndex++; continue; @@ -491,7 +493,7 @@ CMyComPtr updateCallback(updateCallbackSpec); UInt32 numItemsInArchive; - RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)); + RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)) for (UInt32 i = 0; i < numItemsInArchive; i++) { CUpdatePair2 up2; @@ -569,7 +571,7 @@ unsigned curIndex = 0; UInt32 numItemsInArchive; - RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)); + RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)) for (UInt32 i = 0; i < numItemsInArchive; i++) { @@ -579,15 +581,15 @@ if (realIndices[curIndex] == i) { up2.NewProps = true; - RINOK(GetArc().IsItem_Anti(i, up2.IsAnti)); // it must work without that line too. + RINOK(GetArc().IsItem_Anti(i, up2.IsAnti)) // it must work without that line too. UString oldFullPath; - RINOK(GetArc().GetItem_Path2(i, oldFullPath)); + RINOK(GetArc().GetItem_Path2(i, oldFullPath)) if (!IsPath1PrefixedByPath2(oldFullPath, oldItemPath)) return E_INVALIDARG; - up2.NewNameIndex = newNames.Add(newItemPath + oldFullPath.Ptr(oldItemPath.Len())); + up2.NewNameIndex = (int)newNames.Add(newItemPath + oldFullPath.Ptr(oldItemPath.Len())); up2.IsMainRenameItem = (mainRealIndex == (int)i); curIndex++; } @@ -627,7 +629,7 @@ return E_NOTIMPL; UInt32 numItemsInArchive; - RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)); + RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)) UString newName = newItemName; @@ -686,7 +688,7 @@ } UInt32 numItemsInArchive; - RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)); + RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)) for (UInt32 i = 0; i < numItemsInArchive; i++) { CUpdatePair2 up2; @@ -710,7 +712,7 @@ return CommonUpdate(outArchiveStream, updatePairs.Size(), updateCallback); } -STDMETHODIMP CAgent::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) +Z7_COM7F_IMF(CAgent::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps)) { m_PropNames.Clear(); m_PropValues.Clear(); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Agent/AgentProxy.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Agent/AgentProxy.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Agent/AgentProxy.cpp 2022-01-25 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Agent/AgentProxy.cpp 2023-01-19 15:00:00.000000000 +0000 @@ -39,7 +39,7 @@ const unsigned dirIndex2 = subDirs[mid]; const int comp = CompareFileNames(name, Dirs[dirIndex2].Name); if (comp == 0) - return dirIndex2; + return (int)dirIndex2; if (comp < 0) right = mid; else @@ -77,18 +77,18 @@ if (item.ArcIndex == -1) item.ArcIndex = arcIndex; } - return subDirIndex; + return (unsigned)subDirIndex; } - subDirIndex = Dirs.Size(); - Dirs[dirIndex].SubDirs.Insert(insertPos, subDirIndex); + subDirIndex = (int)Dirs.Size(); + Dirs[dirIndex].SubDirs.Insert(insertPos, (unsigned)subDirIndex); CProxyDir &item = Dirs.AddNew(); item.NameLen = name.Len(); item.Name = AllocStringAndCopy(name); item.ArcIndex = arcIndex; - item.ParentDir = dirIndex; - return subDirIndex; + item.ParentDir = (int)dirIndex; + return (unsigned)subDirIndex; } void CProxyDir::Clear() @@ -97,14 +97,15 @@ SubFiles.Clear(); } -void CProxyArc::GetDirPathParts(int dirIndex, UStringVector &pathParts) const +void CProxyArc::GetDirPathParts(unsigned dirIndex, UStringVector &pathParts) const { pathParts.Clear(); - while (dirIndex != -1) + // while (dirIndex != -1) + for (;;) { const CProxyDir &dir = Dirs[dirIndex]; - dirIndex = dir.ParentDir; - if (dirIndex == -1) + dirIndex = (unsigned)dir.ParentDir; + if (dir.ParentDir == -1) break; pathParts.Insert(0, dir.Name); // 22.00: we normalize name @@ -112,14 +113,15 @@ } } -UString CProxyArc::GetDirPath_as_Prefix(int dirIndex) const +UString CProxyArc::GetDirPath_as_Prefix(unsigned dirIndex) const { UString s; - while (dirIndex != -1) + // while (dirIndex != -1) + for (;;) { const CProxyDir &dir = Dirs[dirIndex]; - dirIndex = dir.ParentDir; - if (dirIndex == -1) + dirIndex = (unsigned)dir.ParentDir; + if (dir.ParentDir == -1) break; s.InsertAtFront(WCHAR_PATH_SEPARATOR); s.Insert(0, dir.Name); @@ -133,7 +135,7 @@ { const CProxyDir &dir = Dirs[dirIndex]; if (dir.IsLeaf()) - realIndices.Add(dir.ArcIndex); + realIndices.Add((unsigned)dir.ArcIndex); unsigned i; for (i = 0; i < dir.SubDirs.Size(); i++) AddRealIndices(dir.SubDirs[i], realIndices); @@ -152,7 +154,7 @@ return f.ArcIndex; return -1; } - return dir.SubFiles[index - numDirItems]; + return (int)dir.SubFiles[index - numDirItems]; } void CProxyArc::GetRealIndices(unsigned dirIndex, const UInt32 *indices, UInt32 numItems, CUIntVector &realIndices) const @@ -242,10 +244,10 @@ IInArchive *archive = arc.Archive; UInt32 numItems; - RINOK(archive->GetNumberOfItems(&numItems)); + RINOK(archive->GetNumberOfItems(&numItems)) if (progress) - RINOK(progress->SetTotal(numItems)); + RINOK(progress->SetTotal(numItems)) Files.Alloc(numItems); @@ -258,7 +260,7 @@ if (progress && (i & 0xFFFF) == 0) { const UInt64 currentItemIndex = i; - RINOK(progress->SetCompleted(¤tItemIndex)); + RINOK(progress->SetCompleted(¤tItemIndex)) } const wchar_t *s = NULL; @@ -293,7 +295,7 @@ #endif { prop.Clear(); - RINOK(arc.Archive->GetProperty(i, kpidPath, &prop)); + RINOK(arc.Archive->GetProperty(i, kpidPath, &prop)) if (prop.vt == VT_BSTR) { s = prop.bstrVal; @@ -303,7 +305,7 @@ return E_FAIL; if (len == 0) { - RINOK(arc.GetItem_DefaultPath(i, path)); + RINOK(arc.GetItem_DefaultPath(i, path)) len = path.Len(); s = path; } @@ -370,7 +372,7 @@ */ bool isDir; - RINOK(Archive_IsItem_Dir(archive, i, isDir)); + RINOK(Archive_IsItem_Dir(archive, i, isDir)) CProxyFile &f = Files[i]; @@ -407,31 +409,32 @@ // ---------- for Tree-mode archive ---------- -void CProxyArc2::GetDirPathParts(int dirIndex, UStringVector &pathParts, bool &isAltStreamDir) const +void CProxyArc2::GetDirPathParts(unsigned dirIndex, UStringVector &pathParts, bool &isAltStreamDir) const { pathParts.Clear(); isAltStreamDir = false; - if (dirIndex == (int)k_Proxy2_RootDirIndex) + if (dirIndex == k_Proxy2_RootDirIndex) return; - if (dirIndex == (int)k_Proxy2_AltRootDirIndex) + if (dirIndex == k_Proxy2_AltRootDirIndex) { isAltStreamDir = true; return; } - while (dirIndex >= (int)k_Proxy2_NumRootDirs) + while (dirIndex >= k_Proxy2_NumRootDirs) { const CProxyDir2 &dir = Dirs[dirIndex]; const CProxyFile2 &file = Files[(unsigned)dir.ArcIndex]; - if (pathParts.IsEmpty() && dirIndex == file.AltDirIndex) + if (pathParts.IsEmpty() && (int)dirIndex == file.AltDirIndex) isAltStreamDir = true; pathParts.Insert(0, file.Name); - int par = file.Parent; + const int par = file.Parent; if (par == -1) break; - dirIndex = Files[(unsigned)par].DirIndex; + dirIndex = (unsigned)Files[(unsigned)par].DirIndex; + // if ((int)dirIndex == -1) break; } } @@ -465,9 +468,9 @@ realIndices.Add(arcIndex); const CProxyFile2 &file = Files[arcIndex]; if (file.DirIndex != -1) - AddRealIndices_of_Dir(file.DirIndex, includeAltStreams, realIndices); + AddRealIndices_of_Dir((unsigned)file.DirIndex, includeAltStreams, realIndices); if (includeAltStreams && file.AltDirIndex != -1) - AddRealIndices_of_Dir(file.AltDirIndex, includeAltStreams, realIndices); + AddRealIndices_of_Dir((unsigned)file.AltDirIndex, includeAltStreams, realIndices); } void CProxyArc2::AddRealIndices_of_Dir(unsigned dirIndex, bool includeAltStreams, CUIntVector &realIndices) const @@ -538,7 +541,7 @@ dir.NumSubDirs++; CProxyDir2 &f = Dirs[subFile.DirIndex]; f.PathPrefix = dir.PathPrefix + s + WCHAR_PATH_SEPARATOR; - CalculateSizes(subFile.DirIndex, archive); + CalculateSizes((unsigned)subFile.DirIndex, archive); dir.Size += f.Size; dir.PackSize += f.PackSize; dir.NumSubFiles += f.NumSubFiles; @@ -557,7 +560,7 @@ // dir.NumSubDirs++; CProxyDir2 &f = Dirs[subFile.AltDirIndex]; f.PathPrefix = dir.PathPrefix + subFile.Name + L':'; - CalculateSizes(subFile.AltDirIndex, archive); + CalculateSizes((unsigned)subFile.AltDirIndex, archive); } } } @@ -589,9 +592,9 @@ IInArchive *archive = arc.Archive; UInt32 numItems; - RINOK(archive->GetNumberOfItems(&numItems)); + RINOK(archive->GetNumberOfItems(&numItems)) if (progress) - RINOK(progress->SetTotal(numItems)); + RINOK(progress->SetTotal(numItems)) UString fileName; @@ -617,7 +620,7 @@ if (progress && (i & 0xFFFFF) == 0) { UInt64 currentItemIndex = i; - RINOK(progress->SetCompleted(¤tItemIndex)); + RINOK(progress->SetCompleted(¤tItemIndex)) } CProxyFile2 &file = Files[i]; @@ -625,7 +628,7 @@ const void *p; UInt32 size; UInt32 propType; - RINOK(arc.GetRawProps->GetRawProp(i, kpidName, &p, &size, &propType)); + RINOK(arc.GetRawProps->GetRawProp(i, kpidName, &p, &size, &propType)) #ifdef MY_CPU_LE if (p && propType == PROP_DATA_TYPE_wchar_t_PTR_Z_LE) @@ -648,7 +651,7 @@ else { NCOM::CPropVariant prop; - RINOK(arc.Archive->GetProperty(i, kpidName, &prop)); + RINOK(arc.Archive->GetProperty(i, kpidName, &prop)) const wchar_t *s; if (prop.vt == VT_BSTR) s = prop.bstrVal; @@ -663,13 +666,13 @@ UInt32 parent = (UInt32)(Int32)-1; UInt32 parentType = 0; - RINOK(arc.GetRawProps->GetParent(i, &parent, &parentType)); + RINOK(arc.GetRawProps->GetParent(i, &parent, &parentType)) file.Parent = (Int32)parent; if (arc.Ask_Deleted) { bool isDeleted = false; - RINOK(Archive_IsItem_Deleted(archive, i, isDeleted)); + RINOK(Archive_IsItem_Deleted(archive, i, isDeleted)) if (isDeleted) { // continue; @@ -678,16 +681,16 @@ } bool isDir; - RINOK(Archive_IsItem_Dir(archive, i, isDir)); + RINOK(Archive_IsItem_Dir(archive, i, isDir)) if (isDir) { - file.DirIndex = Dirs.Size(); + file.DirIndex = (int)Dirs.Size(); CProxyDir2 &dir = Dirs.AddNew(); - dir.ArcIndex = i; + dir.ArcIndex = (int)i; } if (arc.Ask_AltStream) - RINOK(Archive_IsItem_AltStream(archive, i, file.IsAltStream)); + RINOK(Archive_IsItem_AltStream(archive, i, file.IsAltStream)) } for (i = 0; i < numItems; i++) @@ -704,7 +707,7 @@ int &folderIndex2 = Files[(unsigned)file.Parent].AltDirIndex; if (folderIndex2 == -1) { - folderIndex2 = Dirs.Size(); + folderIndex2 = (int)Dirs.Size(); CProxyDir2 &dir = Dirs.AddNew(); dir.ArcIndex = file.Parent; } @@ -743,7 +746,7 @@ if (foldersOnly && file.DirIndex == -1) continue; if (CompareFileNames(file.Name, name) == 0) - return i; + return (int)i; } return -1; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Agent/AgentProxy.h 7zip-23.01+dfsg/CPP/7zip/UI/Agent/AgentProxy.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Agent/AgentProxy.h 2022-01-08 19:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Agent/AgentProxy.h 2023-01-19 15:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // AgentProxy.h -#ifndef __AGENT_PROXY_H -#define __AGENT_PROXY_H +#ifndef ZIP7_INC_AGENT_PROXY_H +#define ZIP7_INC_AGENT_PROXY_H #include "../Common/OpenArchive.h" @@ -34,7 +34,7 @@ UInt32 NumSubFiles; bool CrcIsDefined; - CProxyDir(): Name(NULL), NameLen(0), ParentDir(-1) {}; + CProxyDir(): Name(NULL), NameLen(0), ParentDir(-1) {} ~CProxyDir() { delete [](wchar_t *)(void *)Name; } void Clear(); @@ -54,9 +54,9 @@ // returns index in Dirs[], or -1, int FindSubDir(unsigned dirIndex, const wchar_t *name) const; - void GetDirPathParts(int dirIndex, UStringVector &pathParts) const; + void GetDirPathParts(unsigned dirIndex, UStringVector &pathParts) const; // returns full path of Dirs[dirIndex], including back slash - UString GetDirPath_as_Prefix(int dirIndex) const; + UString GetDirPath_as_Prefix(unsigned dirIndex) const; // AddRealIndices DOES ADD also item represented by dirIndex (if it's Leaf) void AddRealIndices(unsigned dirIndex, CUIntVector &realIndices) const; @@ -73,7 +73,7 @@ { int DirIndex; // >= 0 for dir. (index in ProxyArchive2->Dirs) int AltDirIndex; // >= 0 if there are alt streams. (index in ProxyArchive2->Dirs) - int Parent; // >= 0 if there is parent. (index in archive and in ProxyArchive2->Files) + int Parent; // >= 0 if there is parent. (index in archive and in ProxyArchive2->Files) const wchar_t *Name; unsigned NameLen; bool NeedDeleteName; @@ -109,7 +109,7 @@ UInt32 NumSubDirs; UInt32 NumSubFiles; - CProxyDir2(): ArcIndex(-1) {}; + CProxyDir2(): ArcIndex(-1) {} void AddFileSubItem(UInt32 index, const UString &name); void Clear(); }; @@ -130,7 +130,7 @@ bool IsThere_SubDir(unsigned dirIndex, const UString &name) const; - void GetDirPathParts(int dirIndex, UStringVector &pathParts, bool &isAltStreamDir) const; + void GetDirPathParts(unsigned dirIndex, UStringVector &pathParts, bool &isAltStreamDir) const; UString GetDirPath_as_Prefix(unsigned dirIndex, bool &isAltStreamDir) const; bool IsAltDir(unsigned dirIndex) const; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Agent/ArchiveFolder.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Agent/ArchiveFolder.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Agent/ArchiveFolder.cpp 2022-06-01 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Agent/ArchiveFolder.cpp 2023-04-01 13:00:00.000000000 +0000 @@ -9,22 +9,23 @@ #include "Agent.h" /* -STDMETHODIMP CAgentFolder::SetReplaceAltStreamCharsMode(Int32 replaceAltStreamCharsMode) +Z7_COM7F_IMF(CAgentFolder::SetReplaceAltStreamCharsMode(Int32 replaceAltStreamCharsMode)) { _replaceAltStreamCharsMode = replaceAltStreamCharsMode; return S_OK; } */ -STDMETHODIMP CAgentFolder::SetZoneIdMode(NExtract::NZoneIdMode::EEnum zoneMode) +Z7_COM7F_IMF(CAgentFolder::SetZoneIdMode(NExtract::NZoneIdMode::EEnum zoneMode)) { _zoneMode = zoneMode; return S_OK; } -STDMETHODIMP CAgentFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems, + +Z7_COM7F_IMF(CAgentFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems, Int32 includeAltStreams, Int32 replaceAltStreamCharsMode, - const wchar_t *path, IFolderOperationsExtractCallback *callback) + const wchar_t *path, IFolderOperationsExtractCallback *callback)) { if (moveMode) return E_NOTIMPL; @@ -32,7 +33,7 @@ CMyComPtr extractCallback2; { CMyComPtr callbackWrap = callback; - RINOK(callbackWrap.QueryInterface(IID_IFolderArchiveExtractCallback, &extractCallback2)); + RINOK(callbackWrap.QueryInterface(IID_IFolderArchiveExtractCallback, &extractCallback2)) } NExtract::NPathMode::EEnum pathMode; if (!_flatMode) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Agent/ArchiveFolderOpen.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Agent/ArchiveFolderOpen.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Agent/ArchiveFolderOpen.cpp 2020-06-07 13:35:11.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Agent/ArchiveFolderOpen.cpp 2023-04-01 14:00:00.000000000 +0000 @@ -2,26 +2,96 @@ #include "StdAfx.h" +// #ifdef NEW_FOLDER_INTERFACE + +#include "../../../Common/StringToInt.h" #include "../../../Windows/DLL.h" +#include "../../../Windows/ResourceString.h" #include "Agent.h" +extern HINSTANCE g_hInstance; +static const UINT kIconTypesResId = 100; + +void CCodecIcons::LoadIcons(HMODULE m) +{ + IconPairs.Clear(); + UString iconTypes; + NWindows::MyLoadString(m, kIconTypesResId, iconTypes); + UStringVector pairs; + SplitString(iconTypes, pairs); + FOR_VECTOR (i, pairs) + { + const UString &s = pairs[i]; + int pos = s.Find(L':'); + CIconPair iconPair; + iconPair.IconIndex = -1; + if (pos < 0) + pos = (int)s.Len(); + else + { + const UString num = s.Ptr((unsigned)pos + 1); + if (!num.IsEmpty()) + { + const wchar_t *end; + iconPair.IconIndex = (int)ConvertStringToUInt32(num, &end); + if (*end != 0) + continue; + } + } + iconPair.Ext = s.Left((unsigned)pos); + IconPairs.Add(iconPair); + } +} + +bool CCodecIcons::FindIconIndex(const UString &ext, int &iconIndex) const +{ + iconIndex = -1; + FOR_VECTOR (i, IconPairs) + { + const CIconPair &pair = IconPairs[i]; + if (ext.IsEqualTo_NoCase(pair.Ext)) + { + iconIndex = pair.IconIndex; + return true; + } + } + return false; +} + + void CArchiveFolderManager::LoadFormats() { + if (WasLoaded) + return; + LoadGlobalCodecs(); + + #ifdef Z7_EXTERNAL_CODECS + CodecIconsVector.Clear(); + FOR_VECTOR (i, g_CodecsObj->Libs) + { + CCodecIcons &ci = CodecIconsVector.AddNew(); + ci.LoadIcons(g_CodecsObj->Libs[i].Lib.Get_HMODULE()); + } + #endif + InternalIcons.LoadIcons(g_hInstance); + WasLoaded = true; } +/* int CArchiveFolderManager::FindFormat(const UString &type) { FOR_VECTOR (i, g_CodecsObj->Formats) if (type.IsEqualTo_NoCase(g_CodecsObj->Formats[i].Name)) - return i; + return (int)i; return -1; } +*/ -STDMETHODIMP CArchiveFolderManager::OpenFolderFile(IInStream *inStream, +Z7_COM7F_IMF(CArchiveFolderManager::OpenFolderFile(IInStream *inStream, const wchar_t *filePath, const wchar_t *arcFormat, - IFolderFolder **resultFolder, IProgress *progress) + IFolderFolder **resultFolder, IProgress *progress)) { CMyComPtr openArchiveCallback; if (progress) @@ -32,7 +102,7 @@ CAgent *agent = new CAgent(); CMyComPtr archive = agent; - HRESULT res = agent->Open(inStream, filePath, arcFormat, NULL, openArchiveCallback); + const HRESULT res = archive->Open(inStream, filePath, arcFormat, NULL, openArchiveCallback); if (res != S_OK) { @@ -44,7 +114,7 @@ return res; } - RINOK(agent->BindToRootFolder(resultFolder)); + RINOK(archive->BindToRootFolder(resultFolder)) return res; } @@ -58,7 +128,7 @@ /* -STDMETHODIMP CArchiveFolderManager::GetExtensions(const wchar_t *type, BSTR *extensions) +Z7_COM7F_IMF(CArchiveFolderManager::GetExtensions(const wchar_t *type, BSTR *extensions)) { *extensions = 0; int formatIndex = FindFormat(type); @@ -78,47 +148,52 @@ } } -STDMETHODIMP CArchiveFolderManager::GetExtensions(BSTR *extensions) + +Z7_COM7F_IMF(CArchiveFolderManager::GetExtensions(BSTR *extensions)) { + *extensions = NULL; LoadFormats(); - *extensions = 0; UString res; - #ifdef EXTERNAL_CODECS - + #ifdef Z7_EXTERNAL_CODECS + /* FOR_VECTOR (i, g_CodecsObj->Libs) - AddIconExt(g_CodecsObj->Libs[i], res); - + AddIconExt(g_CodecsObj->Libs[i].CodecIcons, res); + */ + FOR_VECTOR (i, CodecIconsVector) + AddIconExt(CodecIconsVector[i], res); #endif - AddIconExt(g_CodecsObj->InternalIcons, res); + AddIconExt( + // g_CodecsObj-> + InternalIcons, res); + return StringToBstr(res, extensions); } -STDMETHODIMP CArchiveFolderManager::GetIconPath(const wchar_t *ext, BSTR *iconPath, Int32 *iconIndex) + +Z7_COM7F_IMF(CArchiveFolderManager::GetIconPath(const wchar_t *ext, BSTR *iconPath, Int32 *iconIndex)) { - *iconPath = 0; + *iconPath = NULL; *iconIndex = 0; - LoadFormats(); - #ifdef EXTERNAL_CODECS - - FOR_VECTOR (i, g_CodecsObj->Libs) + #ifdef Z7_EXTERNAL_CODECS + // FOR_VECTOR (i, g_CodecsObj->Libs) + FOR_VECTOR (i, CodecIconsVector) { - const CCodecLib &lib = g_CodecsObj->Libs[i]; int ii; - if (lib.FindIconIndex(ext, ii)) + if (CodecIconsVector[i].FindIconIndex(ext, ii)) { + const CCodecLib &lib = g_CodecsObj->Libs[i]; *iconIndex = ii; return StringToBstr(fs2us(lib.Path), iconPath); } } - #endif int ii; - if (g_CodecsObj->InternalIcons.FindIconIndex(ext, ii)) + if (InternalIcons.FindIconIndex(ext, ii)) { FString path; if (NWindows::NDLL::MyGetModuleFileName(path)) @@ -131,7 +206,7 @@ } /* -STDMETHODIMP CArchiveFolderManager::GetTypes(BSTR *types) +Z7_COM7F_IMF(CArchiveFolderManager::GetTypes(BSTR *types)) { LoadFormats(); UString typesStrings; @@ -146,9 +221,11 @@ } return StringToBstr(typesStrings, types); } -STDMETHODIMP CArchiveFolderManager::CreateFolderFile(const wchar_t * type, - const wchar_t * filePath, IProgress progress) +Z7_COM7F_IMF(CArchiveFolderManager::CreateFolderFile(const wchar_t * type, + const wchar_t * filePath, IProgress progress)) { return E_NOTIMPL; } */ + +// #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Agent/ArchiveFolderOut.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Agent/ArchiveFolderOut.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Agent/ArchiveFolderOut.cpp 2022-01-08 19:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Agent/ArchiveFolderOut.cpp 2023-04-01 13:00:00.000000000 +0000 @@ -83,7 +83,7 @@ try { - RINOK(_agentSpec->SetFolder(this)); + RINOK(_agentSpec->SetFolder(this)) // ---------- Save FolderItem ---------- @@ -95,7 +95,7 @@ FStringVector processedPaths; CWorkDirTempFile tempFile; - RINOK(tempFile.CreateTempFile(us2fs(_agentSpec->_archiveFilePath))); + RINOK(tempFile.CreateTempFile(us2fs(_agentSpec->_archiveFilePath))) { CMyComPtr tailStream; const CArc &arc = *_agentSpec->_archiveLink.GetArc(); @@ -106,8 +106,8 @@ { if (arc.Offset < 0) return E_NOTIMPL; - RINOK(arc.InStream->Seek(0, STREAM_SEEK_SET, NULL)); - RINOK(NCompress::CopyStream_ExactSize(arc.InStream, tempFile.OutStream, arc.ArcStreamOffset, NULL)); + RINOK(arc.InStream->Seek(0, STREAM_SEEK_SET, NULL)) + RINOK(NCompress::CopyStream_ExactSize(arc.InStream, tempFile.OutStream, arc.ArcStreamOffset, NULL)) CTailOutStream *tailStreamSpec = new CTailOutStream; tailStream = tailStreamSpec; tailStreamSpec->Stream = tempFile.OutStream; @@ -117,7 +117,7 @@ HRESULT result; - switch (operation) + switch ((int)operation) { case AGENT_OP_Delete: result = _agentSpec->DeleteItems(tailStream, indices, numItems, updateCallback100); @@ -149,18 +149,18 @@ return E_FAIL; } - RINOK(result); + RINOK(result) } _agentSpec->KeepModeForNextOpen(); - _agentSpec->Close(); + _agent->Close(); // before 9.26: if there was error for MoveToOriginal archive was closed. // now: we reopen archive after close // m_FolderItem = NULL; - HRESULT res = tempFile.MoveToOriginal(true); + const HRESULT res = tempFile.MoveToOriginal(true); // RINOK(res); if (res == S_OK) @@ -185,7 +185,7 @@ CMyComPtr openCallback; if (updateCallback100) updateCallback100->QueryInterface(IID_IArchiveOpenCallback, (void **)&openCallback); - RINOK(_agentSpec->ReOpen(openCallback)); + RINOK(_agent->ReOpen(openCallback)) } // CAgent::ReOpen() deletes _proxy and _proxy2 @@ -199,7 +199,7 @@ // ---------- Restore FolderItem ---------- CMyComPtr archiveFolder; - RINOK(_agentSpec->BindToRootFolder(&archiveFolder)); + RINOK(_agent->BindToRootFolder(&archiveFolder)) // CAgent::BindToRootFolder() changes _proxy and _proxy2 _proxy = _agentSpec->_proxy; @@ -209,10 +209,10 @@ { FOR_VECTOR (i, pathParts) { - int next = _proxy->FindSubDir(_proxyDirIndex, pathParts[i]); + const int next = _proxy->FindSubDir(_proxyDirIndex, pathParts[i]); if (next == -1) break; - _proxyDirIndex = next; + _proxyDirIndex = (unsigned)next; } } @@ -224,19 +224,19 @@ } else FOR_VECTOR (i, pathParts) { - bool dirOnly = (i + 1 < pathParts.Size() || !isAltStreamFolder); - int index = _proxy2->FindItem(_proxyDirIndex, pathParts[i], dirOnly); + const bool dirOnly = (i + 1 < pathParts.Size() || !isAltStreamFolder); + const int index = _proxy2->FindItem(_proxyDirIndex, pathParts[i], dirOnly); if (index == -1) break; const CProxyFile2 &file = _proxy2->Files[_proxy2->Dirs[_proxyDirIndex].Items[index]]; if (dirOnly) - _proxyDirIndex = file.DirIndex; + _proxyDirIndex = (unsigned)file.DirIndex; else { if (file.AltDirIndex != -1) - _proxyDirIndex = file.AltDirIndex; + _proxyDirIndex = (unsigned)file.AltDirIndex; break; } } @@ -295,7 +295,7 @@ { UString s2 ("Error: "); s2 += s; - RINOK(updateCallback100->UpdateErrorMessage(s2)); + RINOK(updateCallback100->UpdateErrorMessage(s2)) return E_FAIL; } throw; @@ -303,16 +303,15 @@ } - -STDMETHODIMP CAgentFolder::CopyFrom(Int32 moveMode, - const wchar_t *fromFolderPath, // test it +Z7_COM7F_IMF(CAgentFolder::CopyFrom(Int32 moveMode, + const wchar_t *fromFolderPath, /* test it */ const wchar_t * const *itemsPaths, UInt32 numItems, - IProgress *progress) + IProgress *progress)) { COM_TRY_BEGIN { - RINOK(_agentSpec->SetFiles(fromFolderPath, itemsPaths, numItems)); + RINOK(_agentSpec->SetFiles(fromFolderPath, itemsPaths, numItems)) return CommonUpdateOperation(AGENT_OP_Uni, (moveMode != 0), NULL, &NUpdateArchive::k_ActionSet_Add, NULL, 0, progress); @@ -320,7 +319,7 @@ COM_TRY_END } -STDMETHODIMP CAgentFolder::CopyFromFile(UInt32 destIndex, const wchar_t *itemPath, IProgress *progress) +Z7_COM7F_IMF(CAgentFolder::CopyFromFile(UInt32 destIndex, const wchar_t *itemPath, IProgress *progress)) { COM_TRY_BEGIN return CommonUpdateOperation(AGENT_OP_CopyFromFile, false, itemPath, @@ -329,7 +328,7 @@ COM_TRY_END } -STDMETHODIMP CAgentFolder::Delete(const UInt32 *indices, UInt32 numItems, IProgress *progress) +Z7_COM7F_IMF(CAgentFolder::Delete(const UInt32 *indices, UInt32 numItems, IProgress *progress)) { COM_TRY_BEGIN return CommonUpdateOperation(AGENT_OP_Delete, false, NULL, @@ -337,7 +336,7 @@ COM_TRY_END } -STDMETHODIMP CAgentFolder::CreateFolder(const wchar_t *name, IProgress *progress) +Z7_COM7F_IMF(CAgentFolder::CreateFolder(const wchar_t *name, IProgress *progress)) { COM_TRY_BEGIN @@ -359,7 +358,7 @@ COM_TRY_END } -STDMETHODIMP CAgentFolder::Rename(UInt32 index, const wchar_t *newName, IProgress *progress) +Z7_COM7F_IMF(CAgentFolder::Rename(UInt32 index, const wchar_t *newName, IProgress *progress)) { COM_TRY_BEGIN return CommonUpdateOperation(AGENT_OP_Rename, false, newName, NULL, @@ -367,13 +366,13 @@ COM_TRY_END } -STDMETHODIMP CAgentFolder::CreateFile(const wchar_t * /* name */, IProgress * /* progress */) +Z7_COM7F_IMF(CAgentFolder::CreateFile(const wchar_t * /* name */, IProgress * /* progress */)) { return E_NOTIMPL; } -STDMETHODIMP CAgentFolder::SetProperty(UInt32 index, PROPID propID, - const PROPVARIANT *value, IProgress *progress) +Z7_COM7F_IMF(CAgentFolder::SetProperty(UInt32 index, PROPID propID, + const PROPVARIANT *value, IProgress *progress)) { COM_TRY_BEGIN if (propID != kpidComment || value->vt != VT_BSTR) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Agent/IFolderArchive.h 7zip-23.01+dfsg/CPP/7zip/UI/Agent/IFolderArchive.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Agent/IFolderArchive.h 2022-06-01 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Agent/IFolderArchive.h 2023-02-01 18:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // IFolderArchive.h -#ifndef __IFOLDER_ARCHIVE_H -#define __IFOLDER_ARCHIVE_H +#ifndef ZIP7_INC_IFOLDER_ARCHIVE_H +#define ZIP7_INC_IFOLDER_ARCHIVE_H #include "../../../Common/MyString.h" @@ -12,8 +12,7 @@ #include "../Common/ExtractMode.h" #include "../Common/IFileExtractCallback.h" -#define FOLDER_ARCHIVE_INTERFACE_SUB(i, base, x) DECL_INTERFACE_SUB(i, base, 0x01, x) -#define FOLDER_ARCHIVE_INTERFACE(i, x) FOLDER_ARCHIVE_INTERFACE_SUB(i, IUnknown, x) +Z7_PURE_INTERFACES_BEGIN /* ---------- IArchiveFolder ---------- IArchiveFolder is implemented by CAgentFolder (Agent/Agent.h) @@ -24,19 +23,16 @@ CPlugin::ExtractFiles */ -#define INTERFACE_IArchiveFolder(x) \ - STDMETHOD(Extract)(const UInt32 *indices, UInt32 numItems, \ +#define Z7_IFACEM_IArchiveFolder(x) \ + x(Extract(const UInt32 *indices, UInt32 numItems, \ Int32 includeAltStreams, \ Int32 replaceAltStreamCharsMode, \ NExtract::NPathMode::EEnum pathMode, \ NExtract::NOverwriteMode::EEnum overwriteMode, \ const wchar_t *path, Int32 testMode, \ - IFolderArchiveExtractCallback *extractCallback2) x; \ + IFolderArchiveExtractCallback *extractCallback2)) \ -FOLDER_ARCHIVE_INTERFACE(IArchiveFolder, 0x0D) -{ - INTERFACE_IArchiveFolder(PURE) -}; +Z7_IFACE_CONSTR_FOLDERARC(IArchiveFolder, 0x0D) /* ---------- IInFolderArchive ---------- @@ -44,85 +40,68 @@ IInFolderArchive Is used by FAR/Plugin */ -#define INTERFACE_IInFolderArchive(x) \ - STDMETHOD(Open)(IInStream *inStream, const wchar_t *filePath, const wchar_t *arcFormat, BSTR *archiveTypeRes, IArchiveOpenCallback *openArchiveCallback) x; \ - STDMETHOD(ReOpen)(IArchiveOpenCallback *openArchiveCallback) x; \ - STDMETHOD(Close)() x; \ - STDMETHOD(GetNumberOfProperties)(UInt32 *numProperties) x; \ - STDMETHOD(GetPropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) x; \ - STDMETHOD(BindToRootFolder)(IFolderFolder **resultFolder) x; \ - STDMETHOD(Extract)(NExtract::NPathMode::EEnum pathMode, \ +#define Z7_IFACEM_IInFolderArchive(x) \ + x(Open(IInStream *inStream, const wchar_t *filePath, const wchar_t *arcFormat, BSTR *archiveTypeRes, IArchiveOpenCallback *openArchiveCallback)) \ + x(ReOpen(IArchiveOpenCallback *openArchiveCallback)) \ + x(Close()) \ + x(GetNumberOfProperties(UInt32 *numProperties)) \ + x(GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \ + x(BindToRootFolder(IFolderFolder **resultFolder)) \ + x(Extract(NExtract::NPathMode::EEnum pathMode, \ NExtract::NOverwriteMode::EEnum overwriteMode, const wchar_t *path, \ - Int32 testMode, IFolderArchiveExtractCallback *extractCallback2) x; \ + Int32 testMode, IFolderArchiveExtractCallback *extractCallback2)) \ -FOLDER_ARCHIVE_INTERFACE(IInFolderArchive, 0x0E) -{ - INTERFACE_IInFolderArchive(PURE) -}; - -#define INTERFACE_IFolderArchiveUpdateCallback(x) \ - STDMETHOD(CompressOperation)(const wchar_t *name) x; \ - STDMETHOD(DeleteOperation)(const wchar_t *name) x; \ - STDMETHOD(OperationResult)(Int32 opRes) x; \ - STDMETHOD(UpdateErrorMessage)(const wchar_t *message) x; \ - STDMETHOD(SetNumFiles)(UInt64 numFiles) x; \ - -FOLDER_ARCHIVE_INTERFACE_SUB(IFolderArchiveUpdateCallback, IProgress, 0x0B) -{ - INTERFACE_IFolderArchiveUpdateCallback(PURE) -}; - -#define INTERFACE_IOutFolderArchive(x) \ - STDMETHOD(SetFolder)(IFolderFolder *folder) x; \ - STDMETHOD(SetFiles)(const wchar_t *folderPrefix, const wchar_t * const *names, UInt32 numNames) x; \ - STDMETHOD(DeleteItems)(ISequentialOutStream *outArchiveStream, \ - const UInt32 *indices, UInt32 numItems, IFolderArchiveUpdateCallback *updateCallback) x; \ - STDMETHOD(DoOperation)( \ +Z7_IFACE_CONSTR_FOLDERARC(IInFolderArchive, 0x0E) + +#define Z7_IFACEM_IFolderArchiveUpdateCallback(x) \ + x(CompressOperation(const wchar_t *name)) \ + x(DeleteOperation(const wchar_t *name)) \ + x(OperationResult(Int32 opRes)) \ + x(UpdateErrorMessage(const wchar_t *message)) \ + x(SetNumFiles(UInt64 numFiles)) \ + +Z7_IFACE_CONSTR_FOLDERARC_SUB(IFolderArchiveUpdateCallback, IProgress, 0x0B) + +#define Z7_IFACEM_IOutFolderArchive(x) \ + x(SetFolder(IFolderFolder *folder)) \ + x(SetFiles(const wchar_t *folderPrefix, const wchar_t * const *names, UInt32 numNames)) \ + x(DeleteItems(ISequentialOutStream *outArchiveStream, \ + const UInt32 *indices, UInt32 numItems, IFolderArchiveUpdateCallback *updateCallback)) \ + x(DoOperation( \ FStringVector *requestedPaths, \ FStringVector *processedPaths, \ CCodecs *codecs, int index, \ ISequentialOutStream *outArchiveStream, const Byte *stateActions, const wchar_t *sfxModule, \ - IFolderArchiveUpdateCallback *updateCallback) x; \ - STDMETHOD(DoOperation2)( \ + IFolderArchiveUpdateCallback *updateCallback)) \ + x(DoOperation2( \ FStringVector *requestedPaths, \ FStringVector *processedPaths, \ ISequentialOutStream *outArchiveStream, const Byte *stateActions, const wchar_t *sfxModule, \ - IFolderArchiveUpdateCallback *updateCallback) x; \ + IFolderArchiveUpdateCallback *updateCallback)) \ -FOLDER_ARCHIVE_INTERFACE(IOutFolderArchive, 0x0F) -{ - INTERFACE_IOutFolderArchive(PURE) -}; +Z7_IFACE_CONSTR_FOLDERARC(IOutFolderArchive, 0x0F) -#define INTERFACE_IFolderArchiveUpdateCallback2(x) \ - STDMETHOD(OpenFileError)(const wchar_t *path, HRESULT errorCode) x; \ - STDMETHOD(ReadingFileError)(const wchar_t *path, HRESULT errorCode) x; \ - STDMETHOD(ReportExtractResult)(Int32 opRes, Int32 isEncrypted, const wchar_t *path) x; \ - STDMETHOD(ReportUpdateOperation)(UInt32 notifyOp, const wchar_t *path, Int32 isDir) x; \ +#define Z7_IFACEM_IFolderArchiveUpdateCallback2(x) \ + x(OpenFileError(const wchar_t *path, HRESULT errorCode)) \ + x(ReadingFileError(const wchar_t *path, HRESULT errorCode)) \ + x(ReportExtractResult(Int32 opRes, Int32 isEncrypted, const wchar_t *path)) \ + x(ReportUpdateOperation(UInt32 notifyOp, const wchar_t *path, Int32 isDir)) \ -FOLDER_ARCHIVE_INTERFACE(IFolderArchiveUpdateCallback2, 0x10) -{ - INTERFACE_IFolderArchiveUpdateCallback2(PURE) -}; +Z7_IFACE_CONSTR_FOLDERARC(IFolderArchiveUpdateCallback2, 0x10) -#define INTERFACE_IFolderScanProgress(x) \ - STDMETHOD(ScanError)(const wchar_t *path, HRESULT errorCode) x; \ - STDMETHOD(ScanProgress)(UInt64 numFolders, UInt64 numFiles, UInt64 totalSize, const wchar_t *path, Int32 isDir) x; \ +#define Z7_IFACEM_IFolderScanProgress(x) \ + x(ScanError(const wchar_t *path, HRESULT errorCode)) \ + x(ScanProgress(UInt64 numFolders, UInt64 numFiles, UInt64 totalSize, const wchar_t *path, Int32 isDir)) \ -FOLDER_ARCHIVE_INTERFACE(IFolderScanProgress, 0x11) -{ - INTERFACE_IFolderScanProgress(PURE) -}; +Z7_IFACE_CONSTR_FOLDERARC(IFolderScanProgress, 0x11) -#define INTERFACE_IFolderSetZoneIdMode(x) \ - STDMETHOD(SetZoneIdMode)(NExtract::NZoneIdMode::EEnum zoneMode) x; \ +#define Z7_IFACEM_IFolderSetZoneIdMode(x) \ + x(SetZoneIdMode(NExtract::NZoneIdMode::EEnum zoneMode)) \ -FOLDER_ARCHIVE_INTERFACE(IFolderSetZoneIdMode, 0x12) -{ - INTERFACE_IFolderSetZoneIdMode(PURE) -}; +Z7_IFACE_CONSTR_FOLDERARC(IFolderSetZoneIdMode, 0x12) +Z7_PURE_INTERFACES_END #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Agent/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/UI/Agent/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Agent/StdAfx.h 2013-01-20 19:25:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Agent/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Agent/UpdateCallbackAgent.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Agent/UpdateCallbackAgent.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Agent/UpdateCallbackAgent.cpp 2021-09-28 10:35:09.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Agent/UpdateCallbackAgent.cpp 2023-04-01 14:00:00.000000000 +0000 @@ -71,12 +71,12 @@ HRESULT CUpdateCallbackAgent::OpenFileError(const FString &path, DWORD systemError) { - HRESULT hres = HRESULT_FROM_WIN32(systemError); + const HRESULT hres = HRESULT_FROM_WIN32(systemError); // if (systemError == ERROR_SHARING_VIOLATION) { if (Callback2) { - RINOK(Callback2->OpenFileError(fs2us(path), hres)); + RINOK(Callback2->OpenFileError(fs2us(path), hres)) return S_FALSE; } @@ -86,7 +86,7 @@ s += NError::MyFormatMessage(systemError); s += ": "; s += fs2us(path); - RINOK(Callback->UpdateErrorMessage(s)); + RINOK(Callback->UpdateErrorMessage(s)) return S_FALSE; } } @@ -96,13 +96,13 @@ HRESULT CUpdateCallbackAgent::ReadingFileError(const FString &path, DWORD systemError) { - HRESULT hres = HRESULT_FROM_WIN32(systemError); + const HRESULT hres = HRESULT_FROM_WIN32(systemError); // if (systemError == ERROR_SHARING_VIOLATION) { if (Callback2) { - RINOK(Callback2->ReadingFileError(fs2us(path), hres)); + RINOK(Callback2->ReadingFileError(fs2us(path), hres)) } else if (Callback) { @@ -110,7 +110,7 @@ s += NError::MyFormatMessage(systemError); s += ": "; s += fs2us(path); - RINOK(Callback->UpdateErrorMessage(s)); + RINOK(Callback->UpdateErrorMessage(s)) } } // FailedFiles.Add(name); @@ -164,12 +164,12 @@ /* HRESULT CUpdateCallbackAgent::SetPassword(const UString & - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO password #endif ) { - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO PasswordIsDefined = true; Password = password; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Agent/UpdateCallbackAgent.h 7zip-23.01+dfsg/CPP/7zip/UI/Agent/UpdateCallbackAgent.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Agent/UpdateCallbackAgent.h 2015-01-07 08:45:19.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Agent/UpdateCallbackAgent.h 2023-01-28 20:00:00.000000000 +0000 @@ -1,15 +1,15 @@ // UpdateCallbackAgent.h -#ifndef __UPDATE_CALLBACK_AGENT_H -#define __UPDATE_CALLBACK_AGENT_H +#ifndef ZIP7_INC_UPDATE_CALLBACK_AGENT_H +#define ZIP7_INC_UPDATE_CALLBACK_AGENT_H #include "../Common/UpdateCallback.h" #include "IFolderArchive.h" -class CUpdateCallbackAgent: public IUpdateCallbackUI +class CUpdateCallbackAgent Z7_final: public IUpdateCallbackUI { - INTERFACE_IUpdateCallbackUI(;) + Z7_IFACE_IMP(IUpdateCallbackUI) CMyComPtr _cryptoGetTextPassword; CMyComPtr Callback; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Client7z/Client7z.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Client7z/Client7z.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Client7z/Client7z.cpp 2022-05-18 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Client7z/Client7z.cpp 2023-03-23 18:00:00.000000000 +0000 @@ -5,10 +5,9 @@ #include #include "../../../Common/MyWindows.h" - -#include "../../../Common/Defs.h" #include "../../../Common/MyInitGuid.h" +#include "../../../Common/Defs.h" #include "../../../Common/IntToString.h" #include "../../../Common/StringConvert.h" @@ -30,13 +29,13 @@ #ifdef _WIN32 extern HINSTANCE g_hInstance; -HINSTANCE g_hInstance = 0; +HINSTANCE g_hInstance = NULL; #endif // You can find full list of all GUIDs supported by 7-Zip in Guid.txt file. // 7z format GUID: {23170F69-40C1-278A-1000-000110070000} -#define DEFINE_GUID_ARC(name, id) DEFINE_GUID(name, \ +#define DEFINE_GUID_ARC(name, id) Z7_DEFINE_GUID(name, \ 0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, id, 0x00, 0x00); enum @@ -154,7 +153,7 @@ static HRESULT IsArchiveItemProp(IInArchive *archive, UInt32 index, PROPID propID, bool &result) { NCOM::CPropVariant prop; - RINOK(archive->GetProperty(index, propID, &prop)); + RINOK(archive->GetProperty(index, propID, &prop)) if (prop.vt == VT_BOOL) result = VARIANT_BOOLToBool(prop.boolVal); else if (prop.vt == VT_EMPTY) @@ -177,18 +176,13 @@ // Archive Open callback class -class CArchiveOpenCallback: +class CArchiveOpenCallback Z7_final: public IArchiveOpenCallback, public ICryptoGetTextPassword, public CMyUnknownImp { + Z7_IFACES_IMP_UNK_2(IArchiveOpenCallback, ICryptoGetTextPassword) public: - MY_UNKNOWN_IMP1(ICryptoGetTextPassword) - - STDMETHOD(SetTotal)(const UInt64 *files, const UInt64 *bytes); - STDMETHOD(SetCompleted)(const UInt64 *files, const UInt64 *bytes); - - STDMETHOD(CryptoGetTextPassword)(BSTR *password); bool PasswordIsDefined; UString Password; @@ -196,17 +190,17 @@ CArchiveOpenCallback() : PasswordIsDefined(false) {} }; -STDMETHODIMP CArchiveOpenCallback::SetTotal(const UInt64 * /* files */, const UInt64 * /* bytes */) +Z7_COM7F_IMF(CArchiveOpenCallback::SetTotal(const UInt64 * /* files */, const UInt64 * /* bytes */)) { return S_OK; } -STDMETHODIMP CArchiveOpenCallback::SetCompleted(const UInt64 * /* files */, const UInt64 * /* bytes */) +Z7_COM7F_IMF(CArchiveOpenCallback::SetCompleted(const UInt64 * /* files */, const UInt64 * /* bytes */)) { return S_OK; } -STDMETHODIMP CArchiveOpenCallback::CryptoGetTextPassword(BSTR *password) +Z7_COM7F_IMF(CArchiveOpenCallback::CryptoGetTextPassword(BSTR *password)) { if (!PasswordIsDefined) { @@ -321,27 +315,14 @@ -class CArchiveExtractCallback: +class CArchiveExtractCallback Z7_final: public IArchiveExtractCallback, public ICryptoGetTextPassword, public CMyUnknownImp { -public: - MY_UNKNOWN_IMP1(ICryptoGetTextPassword) - - // IProgress - STDMETHOD(SetTotal)(UInt64 size); - STDMETHOD(SetCompleted)(const UInt64 *completeValue); + Z7_IFACES_IMP_UNK_2(IArchiveExtractCallback, ICryptoGetTextPassword) + Z7_IFACE_COM7_IMP(IProgress) - // IArchiveExtractCallback - STDMETHOD(GetStream)(UInt32 index, ISequentialOutStream **outStream, Int32 askExtractMode); - STDMETHOD(PrepareOperation)(Int32 askExtractMode); - STDMETHOD(SetOperationResult)(Int32 resultEOperationResult); - - // ICryptoGetTextPassword - STDMETHOD(CryptoGetTextPassword)(BSTR *aPassword); - -private: CMyComPtr _archiveHandler; FString _directoryPath; // Output directory UString _filePath; // name inside arcvhive @@ -376,26 +357,26 @@ NName::NormalizeDirPathPrefix(_directoryPath); } -STDMETHODIMP CArchiveExtractCallback::SetTotal(UInt64 /* size */) +Z7_COM7F_IMF(CArchiveExtractCallback::SetTotal(UInt64 /* size */)) { return S_OK; } -STDMETHODIMP CArchiveExtractCallback::SetCompleted(const UInt64 * /* completeValue */) +Z7_COM7F_IMF(CArchiveExtractCallback::SetCompleted(const UInt64 * /* completeValue */)) { return S_OK; } -STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, - ISequentialOutStream **outStream, Int32 askExtractMode) +Z7_COM7F_IMF(CArchiveExtractCallback::GetStream(UInt32 index, + ISequentialOutStream **outStream, Int32 askExtractMode)) { - *outStream = 0; + *outStream = NULL; _outFileStream.Release(); { // Get Name NCOM::CPropVariant prop; - RINOK(_archiveHandler->GetProperty(index, kpidPath, &prop)); + RINOK(_archiveHandler->GetProperty(index, kpidPath, &prop)) UString fullPath; if (prop.vt == VT_EMPTY) @@ -415,7 +396,7 @@ { // Get Attrib NCOM::CPropVariant prop; - RINOK(_archiveHandler->GetProperty(index, kpidAttrib, &prop)); + RINOK(_archiveHandler->GetProperty(index, kpidAttrib, &prop)) if (prop.vt == VT_EMPTY) { _processedFileInfo.Attrib = 0; @@ -430,13 +411,13 @@ } } - RINOK(IsArchiveItemFolder(_archiveHandler, index, _processedFileInfo.isDir)); + RINOK(IsArchiveItemFolder(_archiveHandler, index, _processedFileInfo.isDir)) { _processedFileInfo.MTime.Clear(); // Get Modified Time NCOM::CPropVariant prop; - RINOK(_archiveHandler->GetProperty(index, kpidMTime, &prop)); + RINOK(_archiveHandler->GetProperty(index, kpidMTime, &prop)) switch (prop.vt) { case VT_EMPTY: @@ -453,7 +434,7 @@ { // Get Size NCOM::CPropVariant prop; - RINOK(_archiveHandler->GetProperty(index, kpidSize, &prop)); + RINOK(_archiveHandler->GetProperty(index, kpidSize, &prop)) UInt64 newFileSize; /* bool newFileSizeDefined = */ ConvertPropVariantToUInt64(prop, newFileSize); } @@ -498,13 +479,13 @@ return S_OK; } -STDMETHODIMP CArchiveExtractCallback::PrepareOperation(Int32 askExtractMode) +Z7_COM7F_IMF(CArchiveExtractCallback::PrepareOperation(Int32 askExtractMode)) { _extractMode = false; switch (askExtractMode) { case NArchive::NExtract::NAskMode::kExtract: _extractMode = true; break; - }; + } switch (askExtractMode) { case NArchive::NExtract::NAskMode::kExtract: Print(kExtractingString); break; @@ -513,12 +494,12 @@ case NArchive::NExtract::NAskMode::kReadExternal: Print(kReadingString); break; default: Print("??? "); break; - }; + } Print(_filePath); return S_OK; } -STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 operationResult) +Z7_COM7F_IMF(CArchiveExtractCallback::SetOperationResult(Int32 operationResult)) { switch (operationResult) { @@ -564,7 +545,7 @@ else { char temp[16]; - ConvertUInt32ToString(operationResult, temp); + ConvertUInt32ToString((UInt32)operationResult, temp); Print("Error #"); Print(temp); } @@ -579,7 +560,7 @@ _processedFileInfo.MTime.Write_To_FiTime(ft); _outFileStreamSpec->SetMTime(&ft); } - RINOK(_outFileStreamSpec->Close()); + RINOK(_outFileStreamSpec->Close()) } _outFileStream.Release(); if (_extractMode && _processedFileInfo.Attrib_Defined) @@ -589,7 +570,7 @@ } -STDMETHODIMP CArchiveExtractCallback::CryptoGetTextPassword(BSTR *password) +Z7_COM7F_IMF(CArchiveExtractCallback::CryptoGetTextPassword(BSTR *password)) { if (!PasswordIsDefined) { @@ -617,28 +598,14 @@ {} }; -class CArchiveUpdateCallback: +class CArchiveUpdateCallback Z7_final: public IArchiveUpdateCallback2, public ICryptoGetTextPassword2, public CMyUnknownImp { -public: - MY_UNKNOWN_IMP2(IArchiveUpdateCallback2, ICryptoGetTextPassword2) - - // IProgress - STDMETHOD(SetTotal)(UInt64 size); - STDMETHOD(SetCompleted)(const UInt64 *completeValue); - - // IUpdateCallback2 - STDMETHOD(GetUpdateItemInfo)(UInt32 index, - Int32 *newData, Int32 *newProperties, UInt32 *indexInArchive); - STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value); - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **inStream); - STDMETHOD(SetOperationResult)(Int32 operationResult); - STDMETHOD(GetVolumeSize)(UInt32 index, UInt64 *size); - STDMETHOD(GetVolumeStream)(UInt32 index, ISequentialOutStream **volumeStream); - - STDMETHOD(CryptoGetTextPassword2)(Int32 *passwordIsDefined, BSTR *password); + Z7_IFACES_IMP_UNK_2(IArchiveUpdateCallback2, ICryptoGetTextPassword2) + Z7_IFACE_COM7_IMP(IProgress) + Z7_IFACE_COM7_IMP(IArchiveUpdateCallback) public: CRecordVector VolumesSizes; @@ -675,18 +642,18 @@ } }; -STDMETHODIMP CArchiveUpdateCallback::SetTotal(UInt64 /* size */) +Z7_COM7F_IMF(CArchiveUpdateCallback::SetTotal(UInt64 /* size */)) { return S_OK; } -STDMETHODIMP CArchiveUpdateCallback::SetCompleted(const UInt64 * /* completeValue */) +Z7_COM7F_IMF(CArchiveUpdateCallback::SetCompleted(const UInt64 * /* completeValue */)) { return S_OK; } -STDMETHODIMP CArchiveUpdateCallback::GetUpdateItemInfo(UInt32 /* index */, - Int32 *newData, Int32 *newProperties, UInt32 *indexInArchive) +Z7_COM7F_IMF(CArchiveUpdateCallback::GetUpdateItemInfo(UInt32 /* index */, + Int32 *newData, Int32 *newProperties, UInt32 *indexInArchive)) { if (newData) *newData = BoolToInt(true); @@ -697,7 +664,7 @@ return S_OK; } -STDMETHODIMP CArchiveUpdateCallback::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CArchiveUpdateCallback::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; @@ -744,9 +711,9 @@ Print(name); } -STDMETHODIMP CArchiveUpdateCallback::GetStream(UInt32 index, ISequentialInStream **inStream) +Z7_COM7F_IMF(CArchiveUpdateCallback::GetStream(UInt32 index, ISequentialInStream **inStream)) { - RINOK(Finilize()); + RINOK(Finilize()) const CDirItem &dirItem = (*DirItems)[index]; GetStream2(dirItem.Path_For_Handler); @@ -760,8 +727,8 @@ FString path = DirPrefix + dirItem.FullPath; if (!inStreamSpec->Open(path)) { - DWORD sysError = ::GetLastError(); - FailedCodes.Add(sysError); + const DWORD sysError = ::GetLastError(); + FailedCodes.Add(HRESULT_FROM_WIN32(sysError)); FailedFiles.Add(path); // if (systemError == ERROR_SHARING_VIOLATION) { @@ -777,13 +744,13 @@ return S_OK; } -STDMETHODIMP CArchiveUpdateCallback::SetOperationResult(Int32 /* operationResult */) +Z7_COM7F_IMF(CArchiveUpdateCallback::SetOperationResult(Int32 /* operationResult */)) { m_NeedBeClosed = true; return S_OK; } -STDMETHODIMP CArchiveUpdateCallback::GetVolumeSize(UInt32 index, UInt64 *size) +Z7_COM7F_IMF(CArchiveUpdateCallback::GetVolumeSize(UInt32 index, UInt64 *size)) { if (VolumesSizes.Size() == 0) return S_FALSE; @@ -793,7 +760,7 @@ return S_OK; } -STDMETHODIMP CArchiveUpdateCallback::GetVolumeStream(UInt32 index, ISequentialOutStream **volumeStream) +Z7_COM7F_IMF(CArchiveUpdateCallback::GetVolumeStream(UInt32 index, ISequentialOutStream **volumeStream)) { wchar_t temp[16]; ConvertUInt32ToString(index + 1, temp); @@ -801,18 +768,18 @@ while (res.Len() < 2) res.InsertAtFront(L'0'); UString fileName = VolName; - fileName += '.'; + fileName.Add_Dot(); fileName += res; fileName += VolExt; COutFileStream *streamSpec = new COutFileStream; CMyComPtr streamLoc(streamSpec); if (!streamSpec->Create(us2fs(fileName), false)) - return ::GetLastError(); + return GetLastError_noZero_HRESULT(); *volumeStream = streamLoc.Detach(); return S_OK; } -STDMETHODIMP CArchiveUpdateCallback::CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password) +Z7_COM7F_IMF(CArchiveUpdateCallback::CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password)) { if (!PasswordIsDefined) { @@ -836,7 +803,7 @@ #define NT_CHECK_FAIL_ACTION PrintError("Unsupported Windows version"); return 1; #endif -int MY_CDECL main(int numArgs, const char *args[]) +int Z7_CDECL main(int numArgs, const char *args[]) { NT_CHECK @@ -872,8 +839,11 @@ return 1; } - Func_CreateObject createObjectFunc = (Func_CreateObject)lib.GetProc("CreateObject"); - if (!createObjectFunc) + Func_CreateObject + f_CreateObject = Z7_GET_PROC_ADDRESS( + Func_CreateObject, lib.Get_HMODULE(), + "CreateObject"); + if (!f_CreateObject) { PrintError("Cannot get CreateObject"); return 1; @@ -966,7 +936,7 @@ } CMyComPtr outArchive; - if (createObjectFunc(&CLSID_Format, &IID_IOutArchive, (void **)&outArchive) != S_OK) + if (f_CreateObject(&CLSID_Format, &IID_IOutArchive, (void **)&outArchive) != S_OK) { PrintError("Cannot get class object"); return 1; @@ -986,7 +956,7 @@ L"s", L"x" }; - const unsigned kNumProps = ARRAY_SIZE(names); + const unsigned kNumProps = Z7_ARRAY_SIZE(names); NCOM::CPropVariant values[kNumProps] = { L"lzma", @@ -1048,7 +1018,7 @@ } CMyComPtr archive; - if (createObjectFunc(&CLSID_Format, &IID_IInArchive, (void **)&archive) != S_OK) + if (f_CreateObject(&CLSID_Format, &IID_IInArchive, (void **)&archive) != S_OK) { PrintError("Cannot get class object"); return 1; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Client7z/Client7z.dsp 7zip-23.01+dfsg/CPP/7zip/UI/Client7z/Client7z.dsp --- 7zip-22.01+dfsg/CPP/7zip/UI/Client7z/Client7z.dsp 2016-12-02 09:58:13.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Client7z/Client7z.dsp 2023-04-01 14:00:00.000000000 +0000 @@ -104,6 +104,10 @@ # PROP Default_Filter "" # Begin Source File +SOURCE=..\..\..\Windows\Defs.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Windows\DLL.cpp # End Source File # Begin Source File @@ -144,6 +148,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Windows\NtCheck.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Windows\PropVariant.cpp # End Source File # Begin Source File @@ -158,12 +166,24 @@ SOURCE=..\..\..\Windows\PropVariantConv.h # End Source File +# Begin Source File + +SOURCE=..\..\..\Windows\TimeUtils.h +# End Source File # End Group # Begin Group "Common" # PROP Default_Filter "" # Begin Source File +SOURCE=..\..\..\Common\Common.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\Common\Defs.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\IntToString.cpp # End Source File # Begin Source File @@ -172,6 +192,22 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyBuffer.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\Common\MyCom.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\Common\MyInitGuid.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\Common\MyLinux.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\MyString.cpp # End Source File # Begin Source File @@ -180,6 +216,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyTypes.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\MyVector.cpp # End Source File # Begin Source File @@ -188,6 +228,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\NewHandler.cpp # End Source File # Begin Source File @@ -222,6 +266,54 @@ SOURCE=..\..\Common\FileStreams.h # End Source File +# Begin Source File + +SOURCE=..\..\Common\UniqBlocks.h +# End Source File +# End Group +# Begin Group "C" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=..\..\..\..\C\7zTypes.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\7zVersion.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\7zWindows.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\Compiler.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\CpuArch.h +# End Source File +# End Group +# Begin Group "7zip" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=..\..\IDecl.h +# End Source File +# Begin Source File + +SOURCE=..\..\IPassword.h +# End Source File +# Begin Source File + +SOURCE=..\..\IProgress.h +# End Source File +# Begin Source File + +SOURCE=..\..\PropID.h +# End Source File # End Group # Begin Source File @@ -229,7 +321,7 @@ # End Source File # Begin Source File -SOURCE=..\..\..\..\C\Sort.h +SOURCE=..\..\Archive\IArchive.h # End Source File # End Target # End Project diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Client7z/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/UI/Client7z/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Client7z/StdAfx.h 2013-01-22 16:33:40.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Client7z/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/ArchiveCommandLine.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/ArchiveCommandLine.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/ArchiveCommandLine.cpp 2022-06-01 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/ArchiveCommandLine.cpp 2023-04-06 09:00:00.000000000 +0000 @@ -15,7 +15,7 @@ #include -#ifdef _7ZIP_LARGE_PAGES +#ifdef Z7_LARGE_PAGES #include "../../../../C/Alloc.h" #endif @@ -42,7 +42,7 @@ extern bool g_CaseSensitive; extern bool g_PathTrailReplaceMode; -#ifdef _7ZIP_LARGE_PAGES +#ifdef Z7_LARGE_PAGES extern bool g_LargePagesMode; bool g_LargePagesMode = false; @@ -174,7 +174,7 @@ kDeleteAfterCompressing, kSetArcMTime - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO , kPassword #endif }; @@ -322,7 +322,7 @@ { "sdel", SWFRM_SIMPLE }, { "stl", SWFRM_SIMPLE } - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO , { "p", SWFRM_STRING } #endif }; @@ -340,7 +340,7 @@ bool CArcCommand::IsFromExtractGroup() const { - switch (CommandType) + switch ((int)CommandType) { case NCommandType::kTest: case NCommandType::kExtract: @@ -353,7 +353,7 @@ NExtract::NPathMode::EEnum CArcCommand::GetPathMode() const { - switch (CommandType) + switch ((int)CommandType) { case NCommandType::kTest: case NCommandType::kExtractFull: @@ -365,7 +365,7 @@ bool CArcCommand::IsFromUpdateGroup() const { - switch (CommandType) + switch ((int)CommandType) { case NCommandType::kAdd: case NCommandType::kUpdate: @@ -438,7 +438,7 @@ { bool recursed = false; - switch (nop.RecursedType) + switch ((int)nop.RecursedType) { case NRecursedType::kWildcardOnlyRecursed: recursed = DoesNameContainWildcard(name); @@ -905,7 +905,7 @@ CUpdateOptions &options) { NUpdateArchive::CActionSet defaultActionSet; - switch (commandType) + switch ((int)commandType) { case NCommandType::kAdd: defaultActionSet = NUpdateArchive::k_ActionSet_Add; @@ -944,8 +944,10 @@ FOR_VECTOR (i, sv) { UInt64 size; - if (!ParseComplexSize(sv[i], size) || size == 0) + if (!ParseComplexSize(sv[i], size)) throw CArcCmdLineException("Incorrect volume size:", sv[i]); + if (i == sv.Size() - 1 && size == 0) + throw CArcCmdLineException("zero size last volume is not allowed"); options.VolumesSizes.Add(size); } } @@ -992,7 +994,7 @@ CArcCmdLineOptions &options) { Parse1Log.Empty(); - if (!parser.ParseStrings(kSwitchForms, ARRAY_SIZE(kSwitchForms), commandStrings)) + if (!parser.ParseStrings(kSwitchForms, Z7_ARRAY_SIZE(kSwitchForms), commandStrings)) throw CArcCmdLineException(parser.ErrorMessage, parser.ErrorLine); options.IsInTerminal = MY_IS_TERMINAL(stdin); @@ -1054,7 +1056,7 @@ if (parser[NKey::kLargePages].ThereIs) { - unsigned slp = 0; + UInt32 slp = 0; const UString &s = parser[NKey::kLargePages].PostStrings[0]; if (s.IsEmpty()) slp = 1; @@ -1064,7 +1066,7 @@ throw CArcCmdLineException("Unsupported switch postfix for -slp", s); } - #ifdef _7ZIP_LARGE_PAGES + #ifdef Z7_LARGE_PAGES if (slp > #if defined(_WIN32) && !defined(UNDER_CE) (unsigned)NSecurity::Get_LargePages_RiskLevel() @@ -1181,8 +1183,8 @@ { "utf-8", CP_UTF8 }, { "win", CP_ACP }, { "dos", CP_OEMCP }, - { "utf-16le", MY__CP_UTF16 }, - { "utf-16be", MY__CP_UTF16BE } + { "utf-16le", Z7_WIN_CP_UTF16 }, + { "utf-16be", Z7_WIN_CP_UTF16BE } }; static Int32 FindCharset(const NCommandLineParser::CParser &parser, unsigned keyIndex, @@ -1197,7 +1199,7 @@ if (v < ((UInt32)1 << 16)) return (Int32)v; name.MakeLower_Ascii(); - unsigned num = byteOnlyCodePages ? kNumByteOnlyCodePages : ARRAY_SIZE(g_CodePagePairs); + const unsigned num = byteOnlyCodePages ? kNumByteOnlyCodePages : Z7_ARRAY_SIZE(g_CodePagePairs); for (unsigned i = 0;; i++) { if (i == num) // to disable warnings from different compilers @@ -1355,7 +1357,7 @@ options.YesToAll = parser[NKey::kYes].ThereIs; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO options.PasswordEnabled = parser[NKey::kPassword].ThereIs; if (options.PasswordEnabled) options.Password = parser[NKey::kPassword].PostStrings[0]; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/ArchiveCommandLine.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/ArchiveCommandLine.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/ArchiveCommandLine.h 2022-04-17 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/ArchiveCommandLine.h 2023-04-05 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ArchiveCommandLine.h -#ifndef __ARCHIVE_COMMAND_LINE_H -#define __ARCHIVE_COMMAND_LINE_H +#ifndef ZIP7_INC_ARCHIVE_COMMAND_LINE_H +#define ZIP7_INC_ARCHIVE_COMMAND_LINE_H #include "../../../Common/CommandLineParser.h" #include "../../../Common/Wildcard.h" @@ -66,6 +66,14 @@ bool TechMode; bool ShowTime; + CBoolPair NtSecurity; + CBoolPair AltStreams; + CBoolPair HardLinks; + CBoolPair SymLinks; + + CBoolPair StoreOwnerId; + CBoolPair StoreOwnerName; + AString ListFields; int ConsoleCodePage; @@ -75,7 +83,7 @@ CArcCommand Command; UString ArchiveName; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO bool PasswordEnabled; UString Password; #endif @@ -83,7 +91,7 @@ UStringVector HashMethods; // UString HashFilePath; - bool AppendName; + // bool AppendName; // UStringVector ArchivePathsSorted; // UStringVector ArchivePathsFullSorted; NWildcard::CCensor arcCensor; @@ -93,14 +101,6 @@ CExtractOptionsBase ExtractOptions; - CBoolPair NtSecurity; - CBoolPair AltStreams; - CBoolPair HardLinks; - CBoolPair SymLinks; - - CBoolPair StoreOwnerId; - CBoolPair StoreOwnerName; - CUpdateOptions UpdateOptions; CHashOptions HashOptions; UString ArcType; @@ -145,7 +145,7 @@ LogLevel(0) { - }; + } }; class CArcCmdLineParser diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/ArchiveExtractCallback.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/ArchiveExtractCallback.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/ArchiveExtractCallback.cpp 2022-06-09 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/ArchiveExtractCallback.cpp 2023-04-06 09:00:00.000000000 +0000 @@ -25,8 +25,8 @@ #include "../../../Windows/PropVariant.h" #include "../../../Windows/PropVariantConv.h" -#if defined(_WIN32) && !defined(UNDER_CE) && !defined(_SFX) -#define _USE_SECURITY_CODE +#if defined(_WIN32) && !defined(UNDER_CE) && !defined(Z7_SFX) +#define Z7_USE_SECURITY_CODE #include "../../../Windows/SecurityUtils.h" #endif @@ -54,9 +54,9 @@ static const char * const kCantCreateSymLink = "Cannot create symbolic link"; #endif -#ifndef _SFX +#ifndef Z7_SFX -STDMETHODIMP COutStreamWithHash::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(COutStreamWithHash::Write(const void *data, UInt32 size, UInt32 *processedSize)) { HRESULT result = S_OK; if (_stream) @@ -69,10 +69,10 @@ return result; } -#endif // _SFX +#endif // Z7_SFX -#ifdef _USE_SECURITY_CODE +#ifdef Z7_USE_SECURITY_CODE bool InitLocalPrivileges(); bool InitLocalPrivileges() { @@ -92,11 +92,11 @@ return false; return (GetLastError() == ERROR_SUCCESS); } -#endif // _USE_SECURITY_CODE +#endif // Z7_USE_SECURITY_CODE -#if defined(_WIN32) && !defined(UNDER_CE) && !defined(_SFX) +#if defined(_WIN32) && !defined(UNDER_CE) && !defined(Z7_SFX) static const char * const kOfficeExtensions = " doc dot wbk" @@ -117,7 +117,7 @@ return false; AString s; - for (unsigned pos = dotPos + 1;; pos++) + for (unsigned pos = (unsigned)(dotPos + 1);; pos++) { const wchar_t c = name[pos]; if (c <= 0) @@ -142,7 +142,7 @@ void ReadZoneFile_Of_BaseFile(CFSTR fileName2, CByteBuffer &buf) { - FString fileName = fileName2; + FString fileName (fileName2); fileName += k_ZoneId_StreamName; buf.Free(); @@ -188,13 +188,13 @@ defined = false; { NCOM::CPropVariant prop; - RINOK(archive->GetProperty(index, kpidINode, &prop)); + RINOK(archive->GetProperty(index, kpidINode, &prop)) if (!ConvertPropVariantToUInt64(prop, h.INode)) return S_OK; } { NCOM::CPropVariant prop; - RINOK(archive->GetProperty(index, kpidStreamId, &prop)); + RINOK(archive->GetProperty(index, kpidStreamId, &prop)) ConvertPropVariantToUInt64(prop, h.StreamId); } defined = true; @@ -218,22 +218,27 @@ numItems = realIndices->Size(); else { - RINOK(archive->GetNumberOfItems(&numItems)); + RINOK(archive->GetNumberOfItems(&numItems)) } for (UInt32 i = 0; i < numItems; i++) { CHardLinkNode h; bool defined; - UInt32 realIndex = realIndices ? (*realIndices)[i] : i; + const UInt32 realIndex = realIndices ? (*realIndices)[i] : i; - RINOK(Archive_Get_HardLinkNode(archive, realIndex, h, defined)); + RINOK(Archive_Get_HardLinkNode(archive, realIndex, h, defined)) if (defined) { bool isAltStream = false; - RINOK(Archive_IsItem_AltStream(archive, realIndex, isAltStream)); + RINOK(Archive_IsItem_AltStream(archive, realIndex, isAltStream)) if (!isAltStream) - hardIDs.Add(h); + { + bool isDir = false; + RINOK(Archive_IsItem_Dir(archive, realIndex, isDir)) + if (!isDir) + hardIDs.Add(h); + } } } } @@ -275,7 +280,7 @@ LocalProgressSpec = new CLocalProgress(); _localProgress = LocalProgressSpec; - #ifdef _USE_SECURITY_CODE + #ifdef Z7_USE_SECURITY_CODE _saclEnabled = InitLocalPrivileges(); #endif } @@ -325,16 +330,18 @@ _extractCallback2 = extractCallback2; + /* _compressProgress.Release(); _extractCallback2.QueryInterface(IID_ICompressProgressInfo, &_compressProgress); _callbackMessage.Release(); - _extractCallback2.QueryInterface(IID_IArchiveExtractCallbackMessage, &_callbackMessage); + _extractCallback2.QueryInterface(IID_IArchiveExtractCallbackMessage2, &_callbackMessage); + */ _folderArchiveExtractCallback2.Release(); _extractCallback2.QueryInterface(IID_IFolderArchiveExtractCallback2, &_folderArchiveExtractCallback2); - #ifndef _SFX + #ifndef Z7_SFX ExtractToStreamCallback.Release(); _extractCallback2.QueryInterface(IID_IFolderExtractToStreamCallback, &ExtractToStreamCallback); @@ -355,7 +362,7 @@ _removePathParts = removePathParts; _removePartsForAltStreams = removePartsForAltStreams; - #ifndef _SFX + #ifndef Z7_SFX _baseParentFolder = (UInt32)(Int32)-1; _use_baseParentFolder_mode = false; #endif @@ -374,7 +381,7 @@ } -STDMETHODIMP CArchiveExtractCallback::SetTotal(UInt64 size) +Z7_COM7F_IMF(CArchiveExtractCallback::SetTotal(UInt64 size)) { COM_TRY_BEGIN _progressTotal = size; @@ -407,7 +414,7 @@ } -STDMETHODIMP CArchiveExtractCallback::SetCompleted(const UInt64 *completeValue) +Z7_COM7F_IMF(CArchiveExtractCallback::SetCompleted(const UInt64 *completeValue)) { COM_TRY_BEGIN @@ -428,7 +435,7 @@ } -STDMETHODIMP CArchiveExtractCallback::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) +Z7_COM7F_IMF(CArchiveExtractCallback::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize)) { COM_TRY_BEGIN return _localProgress->SetRatioInfo(inSize, outSize); @@ -510,7 +517,7 @@ { ft.Clear(); NCOM::CPropVariant prop; - RINOK(_arc->Archive->GetProperty(index, propID, &prop)); + RINOK(_arc->Archive->GetProperty(index, propID, &prop)) if (prop.vt == VT_FILETIME) ft.Set_From_Prop(prop); else if (prop.vt != VT_EMPTY) @@ -521,7 +528,7 @@ HRESULT CArchiveExtractCallback::GetUnpackSize() { - return _arc->GetItem_Size(_index, _curSize, _curSizeDefined); + return _arc->GetItem_Size(_index, _curSize, _curSize_Defined); } static void AddPathToMessage(UString &s, const FString &path) @@ -564,9 +571,9 @@ return _extractCallback2->MessageError(s); } -#ifndef _SFX +#ifndef Z7_SFX -STDMETHODIMP CGetProp::GetProp(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CGetProp::GetProp(PROPID propID, PROPVARIANT *value)) { /* if (propID == kpidName) @@ -581,7 +588,7 @@ return Arc->Archive->GetProperty(IndexInArc, propID, value); } -#endif // _SFX +#endif // Z7_SFX #ifdef SUPPORT_LINKS @@ -749,15 +756,15 @@ NIO::CInFile inFile; NIO::COutFile outFile; - if (!inFile.Open(_CopyFile_Path)) - return SendMessageError_with_LastError("Open error", _CopyFile_Path); + if (!inFile.Open(_copyFile_Path)) + return SendMessageError_with_LastError("Open error", _copyFile_Path); for (;;) { UInt32 num; if (!inFile.Read(buf.Buf, kBufSize, num)) - return SendMessageError_with_LastError("Read error", _CopyFile_Path); + return SendMessageError_with_LastError("Read error", _copyFile_Path); if (num == 0) return S_OK; @@ -777,7 +784,7 @@ { NCOM::CPropVariant prop; - RINOK(archive->GetProperty(index, kpidHardLink, &prop)); + RINOK(archive->GetProperty(index, kpidHardLink, &prop)) if (prop.vt == VT_BSTR) { _link.isHardLink = true; @@ -807,7 +814,7 @@ { NCOM::CPropVariant prop; - RINOK(archive->GetProperty(index, kpidSymLink, &prop)); + RINOK(archive->GetProperty(index, kpidSymLink, &prop)) if (prop.vt == VT_BSTR) { _link.isHardLink = false; @@ -937,7 +944,7 @@ { { NWindows::NCOM::CPropVariant prop; - RINOK(archive->GetProperty(index, pidId, &prop)); + RINOK(archive->GetProperty(index, pidId, &prop)) if (prop.vt == VT_UI4) { res.Id_Defined = true; @@ -951,7 +958,7 @@ } { NWindows::NCOM::CPropVariant prop; - RINOK(archive->GetProperty(index, pidName, &prop)); + RINOK(archive->GetProperty(index, pidName, &prop)) if (prop.vt == VT_BSTR) { const UString s = prop.bstrVal; @@ -981,11 +988,11 @@ #ifndef _WIN32 _fi.Owner.Clear(); _fi.Group.Clear(); - #endif + #endif { NCOM::CPropVariant prop; - RINOK(archive->GetProperty(index, kpidPosixAttrib, &prop)); + RINOK(archive->GetProperty(index, kpidPosixAttrib, &prop)) if (prop.vt == VT_UI4) { _fi.SetFromPosixAttrib(prop.ulVal); @@ -996,7 +1003,7 @@ { NCOM::CPropVariant prop; - RINOK(archive->GetProperty(index, kpidAttrib, &prop)); + RINOK(archive->GetProperty(index, kpidAttrib, &prop)) if (prop.vt == VT_UI4) { _fi.Attrib = prop.ulVal; @@ -1006,9 +1013,9 @@ return E_FAIL; } - RINOK(GetTime(index, kpidCTime, _fi.CTime)); - RINOK(GetTime(index, kpidATime, _fi.ATime)); - RINOK(GetTime(index, kpidMTime, _fi.MTime)); + RINOK(GetTime(index, kpidCTime, _fi.CTime)) + RINOK(GetTime(index, kpidATime, _fi.ATime)) + RINOK(GetTime(index, kpidMTime, _fi.MTime)) #ifndef _WIN32 if (_ntOptions.ExtractOwner) @@ -1104,9 +1111,19 @@ // 21.04 : we don't change original (_item.PathParts) here UStringVector pathParts = _item.PathParts; - if (!_item.IsDir) + if (!pathParts.IsEmpty()) { - if (!pathParts.IsEmpty()) + /* v23: if we extract symlink, and we know that it links to dir: + Linux: we don't create dir item (symlink_from_path) here. + Windows: SetReparseData() will create dir item, if it doesn't exist, + but if we create dir item here, it's not problem. */ + if (!_item.IsDir + #ifdef SUPPORT_LINKS + #ifndef WIN32 + || !_link.linkPath.IsEmpty() + #endif + #endif + ) pathParts.DeleteBack(); } @@ -1167,7 +1184,7 @@ RINOK(_extractCallback2->AskOverwrite( fs2us(realFullProcessedPath), &ft1, &fileInfo.Size, _item.Path, _fi.MTime.Def ? &_fi.MTime.FT : NULL, - _curSizeDefined ? &_curSize : NULL, + _curSize_Defined ? &_curSize : NULL, &overwriteResult)) switch (overwriteResult) @@ -1197,7 +1214,7 @@ { if (!AutoRenamePath(fullProcessedPath)) { - RINOK(SendMessageError(kCantAutoRename, fullProcessedPath)); + RINOK(SendMessageError(kCantAutoRename, fullProcessedPath)) return E_FAIL; } _isRenamed = true; @@ -1207,14 +1224,14 @@ FString existPath (fullProcessedPath); if (!AutoRenamePath(existPath)) { - RINOK(SendMessageError(kCantAutoRename, fullProcessedPath)); + RINOK(SendMessageError(kCantAutoRename, fullProcessedPath)) return E_FAIL; } // MyMoveFile can rename folders. So it's OK to use it for folders too if (!MyMoveFile(fullProcessedPath, existPath)) { HRESULT errorCode = GetLastError_noZero_HRESULT(); - RINOK(SendMessageError2(errorCode, kCantRenameFile, existPath, fullProcessedPath)); + RINOK(SendMessageError2(errorCode, kCantRenameFile, existPath, fullProcessedPath)) return E_FAIL; } } @@ -1225,7 +1242,7 @@ // do we need to delete all files in folder? if (!RemoveDir(fullProcessedPath)) { - RINOK(SendMessageError_with_LastError(kCantDeleteOutputDir, fullProcessedPath)); + RINOK(SendMessageError_with_LastError(kCantDeleteOutputDir, fullProcessedPath)) return S_OK; } } @@ -1235,7 +1252,7 @@ if (!DeleteFileAlways(fullProcessedPath)) if (GetLastError() != ERROR_FILE_NOT_FOUND) // check it in linux { - RINOK(SendMessageError_with_LastError(kCantDeleteOutputFile, fullProcessedPath)); + RINOK(SendMessageError_with_LastError(kCantDeleteOutputFile, fullProcessedPath)) return S_OK; // return E_FAIL; } @@ -1274,7 +1291,7 @@ { needExit = true; - RINOK(Read_fi_Props()); + RINOK(Read_fi_Props()) #ifdef SUPPORT_LINKS IInArchive *archive = _arc->Archive; @@ -1283,7 +1300,7 @@ const UInt32 index = _index; bool isAnti = false; - RINOK(_arc->IsItem_Anti(index, isAnti)); + RINOK(_arc->IsItem_Anti(index, isAnti)) CorrectPathParts(); UString processedPath (MakePathFromParts(_item.PathParts)); @@ -1333,7 +1350,7 @@ } else if (!_isSplit) { - RINOK(CheckExistFile(fullProcessedPath, needExit)); + RINOK(CheckExistFile(fullProcessedPath, needExit)) if (needExit) return S_OK; needExit = true; @@ -1357,7 +1374,7 @@ #ifndef UNDER_CE { bool linkWasSet = false; - RINOK(SetFromLinkPath(fullProcessedPath, _link, linkWasSet)); + RINOK(SetFromLinkPath(fullProcessedPath, _link, linkWasSet)) if (linkWasSet) { _isSymLinkCreated = _link.IsSymLink(); @@ -1367,18 +1384,18 @@ } #endif // UNDER_CE - // if (_CopyFile_Path.IsEmpty()) + // if (_copyFile_Path.IsEmpty()) { needExit = false; return S_OK; } } - if (!_hardLinks.IDs.IsEmpty() && !_item.IsAltStream) + if (!_hardLinks.IDs.IsEmpty() && !_item.IsAltStream && !_item.IsDir) { CHardLinkNode h; bool defined; - RINOK(Archive_Get_HardLinkNode(archive, index, h, defined)); + RINOK(Archive_Get_HardLinkNode(archive, index, h, defined)) if (defined) { const int linkIndex = _hardLinks.IDs.FindInSorted2(h); @@ -1392,7 +1409,7 @@ if (!MyCreateHardLink(fullProcessedPath, hl)) { HRESULT errorCode = GetLastError_noZero_HRESULT(); - RINOK(SendMessageError2(errorCode, kCantCreateHardLink, fullProcessedPath, hl)); + RINOK(SendMessageError2(errorCode, kCantCreateHardLink, fullProcessedPath, hl)) return S_OK; } @@ -1412,13 +1429,13 @@ // ---------- CREATE WRITE FILE ----- _outFileStreamSpec = new COutFileStream; - CMyComPtr outFileStream_Loc(_outFileStreamSpec); + CMyComPtr outFileStream_Loc(_outFileStreamSpec); if (!_outFileStreamSpec->Open(fullProcessedPath, _isSplit ? OPEN_ALWAYS: CREATE_ALWAYS)) { // if (::GetLastError() != ERROR_FILE_EXISTS || !isSplit) { - RINOK(SendMessageError_with_LastError(kCantOpenOutFile, fullProcessedPath)); + RINOK(SendMessageError_with_LastError(kCantOpenOutFile, fullProcessedPath)) return S_OK; } } @@ -1427,7 +1444,7 @@ bool is_SymLink_in_Data = false; - if (_curSizeDefined && _curSize > 0 && _curSize < (1 << 12)) + if (_curSize_Defined && _curSize > 0 && _curSize < (1 << 12)) { if (_fi.IsLinuxSymLink()) { @@ -1451,18 +1468,18 @@ } else // not reprase { - if (_ntOptions.PreAllocateOutFile && !_isSplit && _curSizeDefined && _curSize > (1 << 12)) + if (_ntOptions.PreAllocateOutFile && !_isSplit && _curSize_Defined && _curSize > (1 << 12)) { // UInt64 ticks = GetCpuTicks(); _fileLength_that_WasSet = _curSize; bool res = _outFileStreamSpec->File.SetLength(_curSize); - _fileLengthWasSet = res; + _fileLength_WasSet = res; // ticks = GetCpuTicks() - ticks; // printf("\nticks = %10d\n", (unsigned)ticks); if (!res) { - RINOK(SendMessageError_with_LastError(kCantSetFileLen, fullProcessedPath)); + RINOK(SendMessageError_with_LastError(kCantSetFileLen, fullProcessedPath)) } /* @@ -1484,7 +1501,7 @@ res = _outFileStreamSpec->SeekToBegin_bool(); if (!res) { - RINOK(SendMessageError_with_LastError("Cannot seek to begin of file", fullProcessedPath)); + RINOK(SendMessageError_with_LastError("Cannot seek to begin of file", fullProcessedPath)) } } // PreAllocateOutFile @@ -1501,7 +1518,7 @@ if (_isSplit) { - RINOK(_outFileStreamSpec->Seek((Int64)_position, STREAM_SEEK_SET, NULL)); + RINOK(outFileStream_Loc->Seek((Int64)_position, STREAM_SEEK_SET, NULL)) } outStreamLoc = outFileStream_Loc; } // if not reprase @@ -1516,7 +1533,7 @@ HRESULT CArchiveExtractCallback::GetItem(UInt32 index) { - #ifndef _SFX + #ifndef Z7_SFX _item._use_baseParentFolder_mode = _use_baseParentFolder_mode; if (_use_baseParentFolder_mode) { @@ -1525,7 +1542,7 @@ _pathMode == NExtract::NPathMode::kAbsPaths) _item._baseParentFolder = -1; } - #endif // _SFX + #endif // Z7_SFX #ifdef SUPPORT_ALT_STREAMS _item.WriteToAltStreamIfColon = _ntOptions.WriteToAltStreamIfColon; @@ -1535,13 +1552,13 @@ } -STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStream **outStream, Int32 askExtractMode) +Z7_COM7F_IMF(CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStream **outStream, Int32 askExtractMode)) { COM_TRY_BEGIN *outStream = NULL; - #ifndef _SFX + #ifndef Z7_SFX if (_hashStream) _hashStreamSpec->ReleaseStream(); _hashStreamWasUsed = false; @@ -1555,8 +1572,8 @@ _isSplit = false; _curSize = 0; - _curSizeDefined = false; - _fileLengthWasSet = false; + _curSize_Defined = false; + _fileLength_WasSet = false; _fileLength_that_WasSet = 0; _index = index; @@ -1574,7 +1591,7 @@ _itemFailure = false; #ifdef SUPPORT_LINKS - // _CopyFile_Path.Empty(); + // _copyFile_Path.Empty(); _link.Clear(); #endif @@ -1590,16 +1607,16 @@ else _extractMode = true; break; - }; + } IInArchive *archive = _arc->Archive; - RINOK(GetItem(index)); + RINOK(GetItem(index)) { NCOM::CPropVariant prop; - RINOK(archive->GetProperty(index, kpidPosition, &prop)); + RINOK(archive->GetProperty(index, kpidPosition, &prop)) if (prop.vt != VT_EMPTY) { if (prop.vt != VT_UI8) @@ -1610,13 +1627,13 @@ } #ifdef SUPPORT_LINKS - RINOK(ReadLink()); + RINOK(ReadLink()) #endif // SUPPORT_LINKS - RINOK(Archive_GetItemBoolProp(archive, index, kpidEncrypted, _encrypted)); + RINOK(Archive_GetItemBoolProp(archive, index, kpidEncrypted, _encrypted)) - RINOK(GetUnpackSize()); + RINOK(GetUnpackSize()) #ifdef SUPPORT_ALT_STREAMS if (!_ntOptions.AltStreams.Val && _item.IsAltStream) @@ -1632,7 +1649,7 @@ return S_OK; } - #ifndef _SFX + #ifndef Z7_SFX if (_use_baseParentFolder_mode) { if (!pathParts.IsEmpty()) @@ -1651,7 +1668,7 @@ } } else - #endif // _SFX + #endif // Z7_SFX { if (pathParts.IsEmpty()) { @@ -1734,12 +1751,8 @@ numRemovePathParts = pathParts.Size() - 1; break; } - /* - case NExtract::NPathMode::kFullPaths: case NExtract::NPathMode::kAbsPaths: - break; - */ - default: + // default: break; } @@ -1747,7 +1760,7 @@ } - #ifndef _SFX + #ifndef Z7_SFX if (ExtractToStreamCallback) { @@ -1772,7 +1785,7 @@ return ExtractToStreamCallback->GetStream7(name, BoolToInt(_item.IsDir), outStream, askExtractMode, GetProp); } - #endif // _SFX + #endif // Z7_SFX CMyComPtr outStreamLoc; @@ -1784,13 +1797,13 @@ else { bool needExit = true; - RINOK(GetExtractStream(outStreamLoc, needExit)); + RINOK(GetExtractStream(outStreamLoc, needExit)) if (needExit) return S_OK; } } - #ifndef _SFX + #ifndef Z7_SFX if (_hashStream) { if (askExtractMode == NArchive::NExtract::NAskMode::kExtract || @@ -1802,13 +1815,13 @@ _hashStreamWasUsed = true; } } - #endif // _SFX + #endif // Z7_SFX if (outStreamLoc) { /* #ifdef SUPPORT_LINKS - if (!_CopyFile_Path.IsEmpty()) + if (!_copyFile_Path.IsEmpty()) { RINOK(PrepareOperation(askExtractMode)); RINOK(MyCopyFile(outStreamLoc)); @@ -1836,11 +1849,11 @@ -STDMETHODIMP CArchiveExtractCallback::PrepareOperation(Int32 askExtractMode) +Z7_COM7F_IMF(CArchiveExtractCallback::PrepareOperation(Int32 askExtractMode)) { COM_TRY_BEGIN - #ifndef _SFX + #ifndef Z7_SFX if (ExtractToStreamCallback) return ExtractToStreamCallback->PrepareOperation7(askExtractMode); #endif @@ -1855,10 +1868,10 @@ else _extractMode = true; break; - }; + } return _extractCallback2->PrepareOperation(_item.Path, BoolToInt(_item.IsDir), - askExtractMode, _isSplit ? &_position: 0); + askExtractMode, _isSplit ? &_position: NULL); COM_TRY_END } @@ -1875,28 +1888,28 @@ HRESULT hres = S_OK; const UInt64 processedSize = _outFileStreamSpec->ProcessedSize; - if (_fileLengthWasSet && _fileLength_that_WasSet > processedSize) + if (_fileLength_WasSet && _fileLength_that_WasSet > processedSize) { - bool res = _outFileStreamSpec->File.SetLength(processedSize); - _fileLengthWasSet = res; + const bool res = _outFileStreamSpec->File.SetLength(processedSize); + _fileLength_WasSet = res; if (!res) { - HRESULT hres2 = SendMessageError_with_LastError(kCantSetFileLen, us2fs(_item.Path)); + const HRESULT hres2 = SendMessageError_with_LastError(kCantSetFileLen, us2fs(_item.Path)); if (hres == S_OK) hres = hres2; } } _curSize = processedSize; - _curSizeDefined = true; + _curSize_Defined = true; - #if defined(_WIN32) && !defined(UNDER_CE) && !defined(_SFX) + #if defined(_WIN32) && !defined(UNDER_CE) && !defined(Z7_SFX) if (ZoneBuf.Size() != 0 && !_item.IsAltStream) { // if (NFind::DoesFileExist_Raw(tempFilePath)) if (ZoneMode != NExtract::NZoneIdMode::kOffice || - FindExt2(kOfficeExtensions, _diskFilePath)) + FindExt2(kOfficeExtensions, fs2us(_diskFilePath))) { // we must write zone file before setting of timestamps const FString path = _diskFilePath + k_ZoneId_StreamName; @@ -1920,7 +1933,7 @@ t.MTime_Defined ? &t.MTime : NULL); // #endif - RINOK(_outFileStreamSpec->Close()); + RINOK(_outFileStreamSpec->Close()) _outFileStream.Release(); return hres; } @@ -1964,7 +1977,7 @@ { if (!NName::GetFullPath(_dirPathPrefix_Full, us2fs(relatPath), existPath)) { - RINOK(SendMessageError("Incorrect path", us2fs(relatPath))); + RINOK(SendMessageError("Incorrect path", us2fs(relatPath))) } } else @@ -1982,8 +1995,8 @@ { if (!MyCreateHardLink(fullProcessedPath, existPath)) { - HRESULT errorCode = GetLastError_noZero_HRESULT(); - RINOK(SendMessageError2(errorCode, kCantCreateHardLink, fullProcessedPath, existPath)); + const HRESULT errorCode = GetLastError_noZero_HRESULT(); + RINOK(SendMessageError2(errorCode, kCantCreateHardLink, fullProcessedPath, existPath)) } linkWasSet = true; return S_OK; @@ -1998,8 +2011,8 @@ } else { - if (_curSizeDefined && _curSize == fi.Size) - _CopyFile_Path = existPath; + if (_curSize_Defined && _curSize == fi.Size) + _copyFile_Path = existPath; else { RINOK(SendMessageError2("File size collision for file copying", existPath, fullProcessedPath)); @@ -2060,12 +2073,12 @@ CReparseAttr attr; if (!attr.Parse(data, data.Size())) { - RINOK(SendMessageError("Internal error for symbolic link file", us2fs(_item.Path))); + RINOK(SendMessageError("Internal error for symbolic link file", us2fs(_item.Path))) return S_OK; } if (!NFile::NIO::SetReparseData(fullProcessedPath, _item.IsDir, data, (DWORD)data.Size())) { - RINOK(SendMessageError_with_LastError(kCantCreateSymLink, fullProcessedPath)); + RINOK(SendMessageError_with_LastError(kCantCreateSymLink, fullProcessedPath)) return S_OK; } linkWasSet = true; @@ -2077,7 +2090,7 @@ if (!NFile::NIO::SetSymLink(fullProcessedPath, existPath)) { - RINOK(SendMessageError_with_LastError(kCantCreateSymLink, fullProcessedPath)); + RINOK(SendMessageError_with_LastError(kCantCreateSymLink, fullProcessedPath)) return S_OK; } linkWasSet = true; @@ -2110,7 +2123,7 @@ // if windows link was created, then we also must use linux separator if (u.IsEmpty()) return false; - wchar_t c = u[0]; + const wchar_t c = u[0]; isRelative = !IS_PATH_SEPAR(c); return true; } @@ -2157,7 +2170,7 @@ { repraseMode = true; reparseSize = _bufPtrSeqOutStream_Spec->GetPos(); - if (_curSizeDefined && reparseSize == _outMemBuf.Size()) + if (_curSize_Defined && reparseSize == _outMemBuf.Size()) { /* CReparseAttr reparse; @@ -2181,7 +2194,7 @@ } if (!needSetReparse && _outFileStream) { - HRESULT res2 = WriteStream(_outFileStream, _outMemBuf, reparseSize); + const HRESULT res2 = WriteStream(_outFileStream, _outMemBuf, reparseSize); if (res == S_OK) res = res2; } @@ -2191,18 +2204,18 @@ #endif // SUPPORT_LINKS - HRESULT res2 = CloseFile(); + const HRESULT res2 = CloseFile(); if (res == S_OK) res = res2; - RINOK(res); + RINOK(res) #ifdef SUPPORT_LINKS if (repraseMode) { _curSize = reparseSize; - _curSizeDefined = true; + _curSize_Defined = true; #ifdef SUPPORT_LINKS if (needSetReparse) @@ -2211,19 +2224,19 @@ // in Windows : we can create symbolic link even without file deleting if (!DeleteFileAlways(_diskFilePath)) { - RINOK(SendMessageError_with_LastError("can't delete file", _diskFilePath)); + RINOK(SendMessageError_with_LastError("can't delete file", _diskFilePath)) } { /* // for DEBUG ONLY: we can extract sym links as WSL links - // to elimanate (non-admin) errors for sym links. + // to eliminate (non-admin) errors for sym links. #ifdef _WIN32 if (!linkInfo.isHardLink && !linkInfo.isJunction) linkInfo.isWSL = true; #endif */ bool linkWasSet = false; - RINOK(SetFromLinkPath(_diskFilePath, linkInfo, linkWasSet)); + RINOK(SetFromLinkPath(_diskFilePath, linkInfo, linkWasSet)) if (linkWasSet) _isSymLinkCreated = linkInfo.IsSymLink(); else @@ -2282,13 +2295,13 @@ } -STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 opRes) +Z7_COM7F_IMF(CArchiveExtractCallback::SetOperationResult(Int32 opRes)) { COM_TRY_BEGIN // printf("\nCArchiveExtractCallback::SetOperationResult: %d %s\n", opRes, GetAnsiString(_diskFilePath)); - #ifndef _SFX + #ifndef Z7_SFX if (ExtractToStreamCallback) { GetUnpackSize(); @@ -2296,7 +2309,7 @@ } #endif - #ifndef _SFX + #ifndef Z7_SFX if (_hashStreamWasUsed) { @@ -2308,16 +2321,16 @@ #endif , _item.Path); _curSize = _hashStreamSpec->GetSize(); - _curSizeDefined = true; + _curSize_Defined = true; _hashStreamSpec->ReleaseStream(); _hashStreamWasUsed = false; } - #endif // _SFX + #endif // Z7_SFX - RINOK(CloseReparseAndFile()); + RINOK(CloseReparseAndFile()) - #ifdef _USE_SECURITY_CODE + #ifdef Z7_USE_SECURITY_CODE if (!_stdOutMode && _extractMode && _ntOptions.NtSecurity.Val && _arc->GetRawProps) { const void *data; @@ -2337,12 +2350,12 @@ } } } - #endif // _USE_SECURITY_CODE + #endif // Z7_USE_SECURITY_CODE - if (!_curSizeDefined) + if (!_curSize_Defined) GetUnpackSize(); - if (_curSizeDefined) + if (_curSize_Defined) { #ifdef SUPPORT_ALT_STREAMS if (_item.IsAltStream) @@ -2364,7 +2377,7 @@ if (_needSetAttrib) SetAttrib(); - RINOK(_extractCallback2->SetOperationResult(opRes, BoolToInt(_encrypted))); + RINOK(_extractCallback2->SetOperationResult(opRes, BoolToInt(_encrypted))) return S_OK; @@ -2373,7 +2386,7 @@ -STDMETHODIMP CArchiveExtractCallback::ReportExtractResult(UInt32 indexType, UInt32 index, Int32 opRes) +Z7_COM7F_IMF(CArchiveExtractCallback::ReportExtractResult(UInt32 indexType, UInt32 index, Int32 opRes)) { if (_folderArchiveExtractCallback2) { @@ -2383,9 +2396,9 @@ if (indexType == NArchive::NEventIndexType::kInArcIndex && index != (UInt32)(Int32)-1) { CReadArcItem item; - RINOK(_arc->GetItem(index, item)); + RINOK(_arc->GetItem(index, item)) s = item.Path; - RINOK(Archive_GetItemBoolProp(_arc->Archive, index, kpidEncrypted, isEncrypted)); + RINOK(Archive_GetItemBoolProp(_arc->Archive, index, kpidEncrypted, isEncrypted)) } else { @@ -2401,13 +2414,13 @@ } -STDMETHODIMP CArchiveExtractCallback::CryptoGetTextPassword(BSTR *password) +Z7_COM7F_IMF(CArchiveExtractCallback::CryptoGetTextPassword(BSTR *password)) { COM_TRY_BEGIN if (!_cryptoGetTextPassword) { RINOK(_extractCallback2.QueryInterface(IID_ICryptoGetTextPassword, - &_cryptoGetTextPassword)); + &_cryptoGetTextPassword)) } return _cryptoGetTextPassword->CryptoGetTextPassword(password); COM_TRY_END @@ -2435,13 +2448,13 @@ } -STDMETHODIMP CArchiveExtractCallback::GetDiskProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CArchiveExtractCallback::GetDiskProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; if (propID == kpidSize) { - RINOK(GetItem(index)); + RINOK(GetItem(index)) const FString fullProcessedPath = Hash_GetFullFilePath(); NFile::NFind::CFileInfo fi; if (fi.Find_FollowLink(fullProcessedPath)) @@ -2454,7 +2467,7 @@ } -STDMETHODIMP CArchiveExtractCallback::GetStream2(UInt32 index, ISequentialInStream **inStream, UInt32 mode) +Z7_COM7F_IMF(CArchiveExtractCallback::GetStream2(UInt32 index, ISequentialInStream **inStream, UInt32 mode)) { COM_TRY_BEGIN *inStream = NULL; @@ -2462,7 +2475,7 @@ if (mode != NUpdateNotifyOp::kHashRead) return E_FAIL; - RINOK(GetItem(index)); + RINOK(GetItem(index)) const FString fullProcessedPath = Hash_GetFullFilePath(); CInFileStream *inStreamSpec = new CInFileStream; @@ -2470,7 +2483,7 @@ inStreamSpec->Set_PreserveATime(_ntOptions.PreserveATime); if (!inStreamSpec->OpenShared(fullProcessedPath, _ntOptions.OpenShareForWrite)) { - RINOK(SendMessageError_with_LastError(kCantOpenInFile, fullProcessedPath)); + RINOK(SendMessageError_with_LastError(kCantOpenInFile, fullProcessedPath)) return S_OK; } *inStream = inStreamRef.Detach(); @@ -2479,8 +2492,8 @@ } -STDMETHODIMP CArchiveExtractCallback::ReportOperation( - UInt32 /* indexType */, UInt32 /* index */, UInt32 /* op */) +Z7_COM7F_IMF(CArchiveExtractCallback::ReportOperation( + UInt32 /* indexType */, UInt32 /* index */, UInt32 /* op */)) { // COM_TRY_BEGIN return S_OK; @@ -2571,7 +2584,7 @@ HRESULT CArchiveExtractCallback::CloseArc() { HRESULT res = CloseReparseAndFile(); - HRESULT res2 = SetDirsTimes(); + const HRESULT res2 = SetDirsTimes(); if (res == S_OK) res = res2; _arc = NULL; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/ArchiveExtractCallback.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/ArchiveExtractCallback.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/ArchiveExtractCallback.h 2022-06-09 16:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/ArchiveExtractCallback.h 2023-04-06 09:36:00.000000000 +0000 @@ -1,7 +1,7 @@ // ArchiveExtractCallback.h -#ifndef __ARCHIVE_EXTRACT_CALLBACK_H -#define __ARCHIVE_EXTRACT_CALLBACK_H +#ifndef ZIP7_INC_ARCHIVE_EXTRACT_CALLBACK_H +#define ZIP7_INC_ARCHIVE_EXTRACT_CALLBACK_H #include "../../../Common/MyCom.h" #include "../../../Common/MyLinux.h" @@ -21,20 +21,18 @@ #include "HashCalc.h" -#ifndef _SFX +#ifndef Z7_SFX -class COutStreamWithHash: - public ISequentialOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + COutStreamWithHash + , ISequentialOutStream +) CMyComPtr _stream; UInt64 _size; bool _calculate; public: IHashCalc *_hash; - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); void SetStream(ISequentialOutStream *stream) { _stream = stream; } void ReleaseStream() { _stream.Release(); } void Init(bool calculate = true) @@ -89,24 +87,21 @@ } }; -#ifndef _SFX +#ifndef Z7_SFX -class CGetProp: - public IGetProp, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CGetProp + , IGetProp +) public: - const CArc *Arc; UInt32 IndexInArc; + const CArc *Arc; // UString Name; // relative path - - MY_UNKNOWN_IMP1(IGetProp) - INTERFACE_IGetProp(;) }; #endif -#ifndef _SFX +#ifndef Z7_SFX #ifndef UNDER_CE #define SUPPORT_LINKS @@ -249,32 +244,75 @@ #endif -class CArchiveExtractCallback: +class CArchiveExtractCallback Z7_final: public IArchiveExtractCallback, - public IArchiveExtractCallbackMessage, + public IArchiveExtractCallbackMessage2, public ICryptoGetTextPassword, public ICompressProgressInfo, public IArchiveUpdateCallbackFile, public IArchiveGetDiskProperty, public CMyUnknownImp { + Z7_COM_UNKNOWN_IMP_5( + /* IArchiveExtractCallback, */ + IArchiveExtractCallbackMessage2, + ICryptoGetTextPassword, + ICompressProgressInfo, + IArchiveUpdateCallbackFile, + IArchiveGetDiskProperty) + + Z7_IFACE_COM7_IMP(IProgress) + Z7_IFACE_COM7_IMP(IArchiveExtractCallback) + Z7_IFACE_COM7_IMP(IArchiveExtractCallbackMessage2) + Z7_IFACE_COM7_IMP(ICryptoGetTextPassword) + Z7_IFACE_COM7_IMP(ICompressProgressInfo) + Z7_IFACE_COM7_IMP(IArchiveUpdateCallbackFile) + Z7_IFACE_COM7_IMP(IArchiveGetDiskProperty) + const CArc *_arc; CExtractNtOptions _ntOptions; + bool _isSplit; + + bool _extractMode; + + bool Write_CTime; + bool Write_ATime; + bool Write_MTime; + bool _keepAndReplaceEmptyDirPrefixes; // replace them to "_"; + + bool _encrypted; + + // bool _is_SymLink_in_Data; + bool _is_SymLink_in_Data_Linux; // false = WIN32, true = LINUX + + bool _needSetAttrib; + bool _isSymLinkCreated; + bool _itemFailure; + + bool _curSize_Defined; + bool _fileLength_WasSet; + + bool _removePartsForAltStreams; + + bool _stdOutMode; + bool _testMode; + bool _multiArchives; + + NExtract::NPathMode::EEnum _pathMode; + NExtract::NOverwriteMode::EEnum _overwriteMode; + const NWildcard::CCensorNode *_wildcardCensor; // we need wildcard for single pass mode (stdin) CMyComPtr _extractCallback2; - CMyComPtr _compressProgress; - CMyComPtr _cryptoGetTextPassword; - CMyComPtr _callbackMessage; + // CMyComPtr _compressProgress; + // CMyComPtr _callbackMessage; CMyComPtr _folderArchiveExtractCallback2; + CMyComPtr _cryptoGetTextPassword; FString _dirPathPrefix; FString _dirPathPrefix_Full; - NExtract::NPathMode::EEnum _pathMode; - NExtract::NOverwriteMode::EEnum _overwriteMode; - bool _keepAndReplaceEmptyDirPrefixes; // replace them to "_"; - #ifndef _SFX + #ifndef Z7_SFX CMyComPtr ExtractToStreamCallback; CGetProp *GetProp_Spec; @@ -285,15 +323,6 @@ CReadArcItem _item; FString _diskFilePath; UInt64 _position; - bool _isSplit; - - bool _extractMode; - - bool Write_CTime; - bool Write_ATime; - bool Write_MTime; - - bool _encrypted; struct CProcessedFileInfo { @@ -339,17 +368,8 @@ } } _fi; - // bool _is_SymLink_in_Data; - bool _is_SymLink_in_Data_Linux; // false = WIN32, true = LINUX - - bool _needSetAttrib; - bool _isSymLinkCreated; - bool _itemFailure; - UInt32 _index; UInt64 _curSize; - bool _curSizeDefined; - bool _fileLengthWasSet; UInt64 _fileLength_that_WasSet; COutFileStream *_outFileStreamSpec; @@ -360,25 +380,17 @@ CMyComPtr _bufPtrSeqOutStream; - #ifndef _SFX + #ifndef Z7_SFX COutStreamWithHash *_hashStreamSpec; CMyComPtr _hashStream; bool _hashStreamWasUsed; - #endif - - bool _removePartsForAltStreams; - UStringVector _removePathParts; - - #ifndef _SFX bool _use_baseParentFolder_mode; UInt32 _baseParentFolder; - #endif + #endif - bool _stdOutMode; - bool _testMode; - bool _multiArchives; + UStringVector _removePathParts; CMyComPtr _localProgress; UInt64 _packTotal; @@ -392,7 +404,7 @@ // CObjectVector _delayedSymLinks; #endif - #if defined(_WIN32) && !defined(UNDER_CE) && !defined(_SFX) + #if defined(_WIN32) && !defined(UNDER_CE) && !defined(Z7_SFX) bool _saclEnabled; #endif @@ -425,23 +437,6 @@ FString DirPathPrefix_for_HashFiles; - MY_UNKNOWN_IMP5( - IArchiveExtractCallbackMessage, - ICryptoGetTextPassword, - ICompressProgressInfo, - IArchiveUpdateCallbackFile, - IArchiveGetDiskProperty - ) - - INTERFACE_IArchiveExtractCallback(;) - INTERFACE_IArchiveExtractCallbackMessage(;) - INTERFACE_IArchiveUpdateCallbackFile(;) - INTERFACE_IArchiveGetDiskProperty(;) - - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); - - STDMETHOD(CryptoGetTextPassword)(BSTR *password); - CArchiveExtractCallback(); void InitForMulti(bool multiArchives, @@ -462,7 +457,7 @@ NumFolders = NumFiles = NumAltStreams = UnpackSize = AltStreams_UnpackSize = 0; } - #ifndef _SFX + #ifndef Z7_SFX void SetHashMethods(IHashCalc *hash) { @@ -494,7 +489,7 @@ CHardLinks _hardLinks; CLinkInfo _link; - // FString _CopyFile_Path; + // FString _copyFile_Path; // HRESULT MyCopyFile(ISequentialOutStream *outStream); HRESULT Link(const FString &fullProcessedPath); HRESULT ReadLink(); @@ -512,7 +507,7 @@ // call it after Init() - #ifndef _SFX + #ifndef Z7_SFX void SetBaseParentFolderIndex(UInt32 indexInArc) { _baseParentFolder = indexInArc; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/ArchiveName.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/ArchiveName.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/ArchiveName.cpp 2021-01-26 12:24:38.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/ArchiveName.cpp 2023-01-17 09:00:00.000000000 +0000 @@ -2,154 +2,175 @@ #include "StdAfx.h" +#include "../../../../C/Sort.h" + #include "../../../Common/Wildcard.h" +#include "../../../Common/StringToInt.h" #include "../../../Windows/FileDir.h" #include "../../../Windows/FileName.h" -#include "ExtractingFilePath.h" #include "ArchiveName.h" +#include "ExtractingFilePath.h" using namespace NWindows; using namespace NFile; -static UString CreateArchiveName(const NFind::CFileInfo &fi, bool keepName) + +static const char *g_ArcExts = + "7z" + "\0" "zip" + "\0" "tar" + "\0" "wim" + "\0"; + +static const char *g_HashExts = + "sha256" + "\0"; + + +UString CreateArchiveName( + const UStringVector &paths, + bool isHash, + const NFind::CFileInfo *fi, + UString &baseName) { - FString resultName = fi.Name; - if (!fi.IsDir() && !keepName) + bool keepName = isHash; + /* + if (paths.Size() == 1) { - int dotPos = resultName.ReverseFind_Dot(); - if (dotPos > 0) - { - FString archiveName2 = resultName.Left((unsigned)dotPos); - if (archiveName2.ReverseFind_Dot() < 0) - resultName = archiveName2; - } + const UString &name = paths[0]; + if (name.Len() > 4) + if (CompareFileNames(name.RightPtr(4), L".tar") == 0) + keepName = true; } - return Get_Correct_FsFile_Name(fs2us(resultName)); -} + */ -static FString CreateArchiveName2(const FString &path, bool fromPrev, bool keepName) -{ - FString resultName ("Archive"); - if (fromPrev) + UString name ("Archive"); + NFind::CFileInfo fi3; + if (paths.Size() > 1) + fi = NULL; + if (!fi && paths.Size() != 0) { - FString dirPrefix; - if (NDir::GetOnlyDirPrefix(path, dirPrefix)) + const UString &path = paths.Front(); + if (paths.Size() == 1) { - if (!dirPrefix.IsEmpty() && IsPathSepar(dirPrefix.Back())) - { - #if defined(_WIN32) && !defined(UNDER_CE) - if (NName::IsDriveRootPath_SuperAllowed(dirPrefix)) - resultName = dirPrefix[dirPrefix.Len() - 3]; // only letter - else - #endif - { - dirPrefix.DeleteBack(); - NFind::CFileInfo fi; - if (fi.Find(dirPrefix)) - resultName = fi.Name; - } - } + if (fi3.Find(us2fs(path))) + fi = &fi3; } - } - else - { - NFind::CFileInfo fi; - if (fi.Find(path)) + else { - resultName = fi.Name; - if (!fi.IsDir() && !keepName) + // we try to use name of parent folder + FString dirPrefix; + if (NDir::GetOnlyDirPrefix(us2fs(path), dirPrefix)) { - int dotPos = resultName.ReverseFind_Dot(); - if (dotPos > 0) + if (!dirPrefix.IsEmpty() && IsPathSepar(dirPrefix.Back())) { - FString name2 = resultName.Left((unsigned)dotPos); - if (name2.ReverseFind_Dot() < 0) - resultName = name2; + #if defined(_WIN32) && !defined(UNDER_CE) + if (NName::IsDriveRootPath_SuperAllowed(dirPrefix)) + { + if (path != fs2us(dirPrefix)) + name = dirPrefix[dirPrefix.Len() - 3]; // only letter + } + else + #endif + { + dirPrefix.DeleteBack(); + if (!dirPrefix.IsEmpty()) + { + const int slash = dirPrefix.ReverseFind_PathSepar(); + if (slash >= 0 && slash != (int)dirPrefix.Len() - 1) + name = dirPrefix.Ptr(slash + 1); + else if (fi3.Find(dirPrefix)) + name = fs2us(fi3.Name); + } + } } } } } - return resultName; -} - -UString CreateArchiveName(const UStringVector &paths, const NFind::CFileInfo *fi) -{ - bool keepName = false; - /* - if (paths.Size() == 1) - { - const UString &name = paths[0]; - if (name.Len() > 4) - if (CompareFileNames(name.RightPtr(4), L".tar") == 0) - keepName = true; - } - */ - - UString name; if (fi) - name = CreateArchiveName(*fi, keepName); - else { - if (paths.IsEmpty()) - return L"archive"; - bool fromPrev = (paths.Size() > 1); - name = Get_Correct_FsFile_Name(fs2us(CreateArchiveName2(us2fs(paths.Front()), fromPrev, keepName))); + name = fs2us(fi->Name); + if (!fi->IsDir() && !keepName) + { + const int dotPos = name.Find(L'.'); + if (dotPos > 0 && name.Find(L'.', (unsigned)dotPos + 1) < 0) + name.DeleteFrom((unsigned)dotPos); + } } + name = Get_Correct_FsFile_Name(name); - UStringVector names; - + CRecordVector ids; + bool simple_IsAllowed = true; + // for (int y = 0; y < 10000; y++) // for debug { + // ids.Clear(); + UString n; + FOR_VECTOR (i, paths) { - NFind::CFileInfo fi2; - const NFind::CFileInfo *fp; - if (fi && paths.Size() == 1) - fp = fi; - else + const UString &a = paths[i]; + const int slash = a.ReverseFind_PathSepar(); + // if (name.Len() >= a.Len() - slash + 1) continue; + const wchar_t *s = a.Ptr(slash + 1); + if (!IsPath1PrefixedByPath2(s, name)) + continue; + s += name.Len(); + const char *exts = isHash ? g_HashExts : g_ArcExts; + + for (;;) { - if (!fi2.Find(us2fs(paths[i]))) + const char *ext = exts; + const unsigned len = MyStringLen(ext); + if (len == 0) + break; + exts += len + 1; + n = s; + if (n.Len() <= len) + continue; + if (!StringsAreEqualNoCase_Ascii(n.RightPtr(len), ext)) + continue; + n.DeleteFrom(n.Len() - len); + if (n.Back() != '.') + continue; + n.DeleteBack(); + if (n.IsEmpty()) + { + simple_IsAllowed = false; + break; + } + if (n.Len() < 2) + continue; + if (n[0] != '_') + continue; + const wchar_t *end; + const UInt32 v = ConvertStringToUInt32(n.Ptr(1), &end); + if (*end != 0) continue; - fp = &fi2; + ids.Add(v); + break; } - names.Add(fs2us(fp->Name)); } } - UString postfix; - UInt32 index = 1; - - for (;;) + baseName = name; + if (!simple_IsAllowed) { - // we don't want cases when we include archive to itself. - // so we find first available name for archive - const UString name2 = name + postfix; - const UString name2_zip = name2 + L".zip"; - const UString name2_7z = name2 + L".7z"; - const UString name2_tar = name2 + L".tar"; - const UString name2_wim = name2 + L".wim"; - - unsigned i = 0; - - for (i = 0; i < names.Size(); i++) + HeapSort(&ids.Front(), ids.Size()); + UInt32 v = 2; + const unsigned num = ids.Size(); + for (unsigned i = 0; i < num; i++) { - const UString &fname = names[i]; - if ( 0 == CompareFileNames(fname, name2_zip) - || 0 == CompareFileNames(fname, name2_7z) - || 0 == CompareFileNames(fname, name2_tar) - || 0 == CompareFileNames(fname, name2_wim)) + const UInt32 id = ids[i]; + if (id > v) break; + if (id == v) + v = id + 1; } - - if (i == names.Size()) - break; - index++; - postfix = "_"; - postfix.Add_UInt32(index); + name += '_'; + name.Add_UInt32(v); } - - name += postfix; return name; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/ArchiveName.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/ArchiveName.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/ArchiveName.h 2018-12-22 10:00:52.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/ArchiveName.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,10 +1,16 @@ // ArchiveName.h -#ifndef __ARCHIVE_NAME_H -#define __ARCHIVE_NAME_H +#ifndef ZIP7_INC_ARCHIVE_NAME_H +#define ZIP7_INC_ARCHIVE_NAME_H #include "../../../Windows/FileFind.h" -UString CreateArchiveName(const UStringVector &paths, const NWindows::NFile::NFind::CFileInfo *fi = NULL); +/* (fi != NULL) only if (paths.Size() == 1) */ + +UString CreateArchiveName( + const UStringVector &paths, + bool isHash, + const NWindows::NFile::NFind::CFileInfo *fi, + UString &baseName); #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/ArchiveOpenCallback.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/ArchiveOpenCallback.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/ArchiveOpenCallback.cpp 2022-04-06 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/ArchiveOpenCallback.cpp 2023-03-26 19:00:00.000000000 +0000 @@ -6,14 +6,54 @@ #include "../../../Windows/FileName.h" #include "../../../Windows/PropVariant.h" +#include "../../../Windows/System.h" -#include "../../Common/FileStreams.h" +#include "../../Common/StreamUtils.h" #include "ArchiveOpenCallback.h" +// #define DEBUG_VOLUMES + +#ifdef DEBUG_VOLUMES +#include +#endif + + +#ifdef DEBUG_VOLUMES + #define PRF(x) x +#else + #define PRF(x) +#endif + using namespace NWindows; -STDMETHODIMP COpenCallbackImp::SetTotal(const UInt64 *files, const UInt64 *bytes) +HRESULT COpenCallbackImp::Init2(const FString &folderPrefix, const FString &fileName) +{ + Volumes.Init(); + FileNames.Clear(); + FileNames_WasUsed.Clear(); + FileSizes.Clear(); + _subArchiveMode = false; + // TotalSize = 0; + PasswordWasAsked = false; + _folderPrefix = folderPrefix; + if (!_fileInfo.Find_FollowLink(_folderPrefix + fileName)) + { + // throw 20121118; + return GetLastError_noZero_HRESULT(); + } + return S_OK; +} + +Z7_COM7F_IMF(COpenCallbackImp::SetSubArchiveName(const wchar_t *name)) +{ + _subArchiveMode = true; + _subArchiveName = name; + // TotalSize = 0; + return S_OK; +} + +Z7_COM7F_IMF(COpenCallbackImp::SetTotal(const UInt64 *files, const UInt64 *bytes)) { COM_TRY_BEGIN if (ReOpenCallback) @@ -24,7 +64,7 @@ COM_TRY_END } -STDMETHODIMP COpenCallbackImp::SetCompleted(const UInt64 *files, const UInt64 *bytes) +Z7_COM7F_IMF(COpenCallbackImp::SetCompleted(const UInt64 *files, const UInt64 *bytes)) { COM_TRY_BEGIN if (ReOpenCallback) @@ -36,7 +76,7 @@ } -STDMETHODIMP COpenCallbackImp::GetProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(COpenCallbackImp::GetProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -63,24 +103,180 @@ COM_TRY_END } -struct CInFileStreamVol: public CInFileStream -{ - unsigned FileNameIndex; + +// ---------- CInFileStreamVol ---------- + +Z7_CLASS_IMP_COM_2( + CInFileStreamVol + , IInStream + , IStreamGetSize +) + Z7_IFACE_COM7_IMP(ISequentialInStream) +public: + unsigned FileIndex; COpenCallbackImp *OpenCallbackImp; CMyComPtr OpenCallbackRef; - + + HRESULT EnsureOpen() + { + return OpenCallbackImp->Volumes.EnsureOpen(FileIndex); + } + ~CInFileStreamVol() { if (OpenCallbackRef) - OpenCallbackImp->FileNames_WasUsed[FileNameIndex] = false; + OpenCallbackImp->AtCloseFile(FileIndex); } }; +void CMultiStreams::InsertToList(unsigned index) +{ + { + CSubStream &s = Streams[index]; + s.Next = Head; + s.Prev = -1; + } + if (Head != -1) + Streams[(unsigned)Head].Prev = (int)index; + else + { + // if (Tail != -1) throw 1; + Tail = (int)index; + } + Head = (int)index; + NumListItems++; +} + +// s must bee in List +void CMultiStreams::RemoveFromList(CSubStream &s) +{ + if (s.Next != -1) Streams[(unsigned)s.Next].Prev = s.Prev; else Tail = s.Prev; + if (s.Prev != -1) Streams[(unsigned)s.Prev].Next = s.Next; else Head = s.Next; + s.Next = -1; // optional + s.Prev = -1; // optional + NumListItems--; +} + +void CMultiStreams::CloseFile(unsigned index) +{ + CSubStream &s = Streams[index]; + if (s.Stream) + { + s.Stream.Release(); + RemoveFromList(s); + // s.InFile->Close(); + // s.IsOpen = false; + #ifdef DEBUG_VOLUMES + static int numClosing = 0; + numClosing++; + printf("\nCloseFile %u, total_closes = %u, num_open_files = %u\n", index, numClosing, NumListItems); + #endif + } +} + +void CMultiStreams::Init() +{ + Head = -1; + Tail = -1; + NumListItems = 0; + Streams.Clear(); +} + +CMultiStreams::CMultiStreams(): + Head(-1), + Tail(-1), + NumListItems(0) +{ + NumOpenFiles_AllowedMax = NSystem::Get_File_OPEN_MAX_Reduced_for_3_tasks(); + PRF(printf("\nNumOpenFiles_Limit = %u\n", NumOpenFiles_AllowedMax)); +} + + +HRESULT CMultiStreams::PrepareToOpenNew() +{ + if (NumListItems < NumOpenFiles_AllowedMax) + return S_OK; + if (Tail == -1) + return E_FAIL; + CMultiStreams::CSubStream &tailStream = Streams[(unsigned)Tail]; + RINOK(InStream_GetPos(tailStream.Stream, tailStream.LocalPos)) + CloseFile((unsigned)Tail); + return S_OK; +} + + +HRESULT CMultiStreams::EnsureOpen(unsigned index) +{ + CMultiStreams::CSubStream &s = Streams[index]; + if (s.Stream) + { + if ((int)index != Head) + { + RemoveFromList(s); + InsertToList(index); + } + } + else + { + RINOK(PrepareToOpenNew()) + { + CInFileStream *inFile = new CInFileStream; + CMyComPtr inStreamTemp = inFile; + if (!inFile->Open(s.Path)) + return GetLastError_noZero_HRESULT(); + s.FileSpec = inFile; + s.Stream = s.FileSpec; + InsertToList(index); + } + // s.IsOpen = true; + if (s.LocalPos != 0) + { + RINOK(s.Stream->Seek((Int64)s.LocalPos, STREAM_SEEK_SET, &s.LocalPos)) + } + #ifdef DEBUG_VOLUMES + static int numOpens = 0; + numOpens++; + printf("\n-- %u, ReOpen, total_reopens = %u, num_open_files = %u\n", index, numOpens, NumListItems); + #endif + } + return S_OK; +} + + +Z7_COM7F_IMF(CInFileStreamVol::Read(void *data, UInt32 size, UInt32 *processedSize)) +{ + if (processedSize) + *processedSize = 0; + if (size == 0) + return S_OK; + RINOK(EnsureOpen()) + CMultiStreams::CSubStream &s = OpenCallbackImp->Volumes.Streams[FileIndex]; + PRF(printf("\n== %u, Read =%u \n", FileIndex, size)); + return s.Stream->Read(data, size, processedSize); +} + +Z7_COM7F_IMF(CInFileStreamVol::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) +{ + // if (seekOrigin >= 3) return STG_E_INVALIDFUNCTION; + RINOK(EnsureOpen()) + CMultiStreams::CSubStream &s = OpenCallbackImp->Volumes.Streams[FileIndex]; + PRF(printf("\n-- %u, Seek seekOrigin=%u Seek =%u\n", FileIndex, seekOrigin, (unsigned)offset)); + return s.Stream->Seek(offset, seekOrigin, newPosition); +} + +Z7_COM7F_IMF(CInFileStreamVol::GetSize(UInt64 *size)) +{ + RINOK(EnsureOpen()) + CMultiStreams::CSubStream &s = OpenCallbackImp->Volumes.Streams[FileIndex]; + return s.FileSpec->GetSize(size); +} + + // from ArchiveExtractCallback.cpp bool IsSafePath(const UString &path); -STDMETHODIMP COpenCallbackImp::GetStream(const wchar_t *name, IInStream **inStream) +Z7_COM7F_IMF(COpenCallbackImp::GetStream(const wchar_t *name, IInStream **inStream)) { COM_TRY_BEGIN *inStream = NULL; @@ -89,13 +285,13 @@ return S_FALSE; if (Callback) { - RINOK(Callback->Open_CheckBreak()); + RINOK(Callback->Open_CheckBreak()) } UString name2 = name; - #ifndef _SFX + #ifndef Z7_SFX #ifdef _WIN32 name2.Replace(L'/', WCHAR_PATH_SEPARATOR); @@ -112,7 +308,7 @@ if (name2.Find(L'*') >= 0) return S_FALSE; { - int startPos = 0; + unsigned startPos = 0; if (name2.IsPrefixedBy_Ascii_NoCase("\\\\?\\")) startPos = 3; if (name2.Find(L'?', startPos) >= 0) @@ -130,16 +326,32 @@ return S_FALSE; if (_fileInfo.IsDir()) return S_FALSE; - CInFileStreamVol *inFile = new CInFileStreamVol; - CMyComPtr inStreamTemp = inFile; - if (!inFile->Open(fullPath)) + + CMultiStreams::CSubStream s; + { - return GetLastError_noZero_HRESULT(); + CInFileStream *inFile = new CInFileStream; + CMyComPtr inStreamTemp = inFile; + if (!inFile->Open(fullPath)) + return GetLastError_noZero_HRESULT(); + RINOK(Volumes.PrepareToOpenNew()) + s.FileSpec = inFile; + s.Stream = s.FileSpec; + s.Path = fullPath; + // s.Size = _fileInfo.Size; + // s.IsOpen = true; } + const unsigned fileIndex = Volumes.Streams.Add(s); + Volumes.InsertToList(fileIndex); + FileSizes.Add(_fileInfo.Size); FileNames.Add(name2); - inFile->FileNameIndex = FileNames_WasUsed.Add(true); + FileNames_WasUsed.Add(true); + + CInFileStreamVol *inFile = new CInFileStreamVol; + CMyComPtr inStreamTemp = inFile; + inFile->FileIndex = fileIndex; inFile->OpenCallbackImp = this; inFile->OpenCallbackRef = this; // TotalSize += _fileInfo.Size; @@ -148,14 +360,16 @@ COM_TRY_END } -#ifndef _NO_CRYPTO -STDMETHODIMP COpenCallbackImp::CryptoGetTextPassword(BSTR *password) + +#ifndef Z7_NO_CRYPTO +Z7_COM7F_IMF(COpenCallbackImp::CryptoGetTextPassword(BSTR *password)) { COM_TRY_BEGIN if (ReOpenCallback) { - CMyComPtr getTextPassword; - ReOpenCallback.QueryInterface(IID_ICryptoGetTextPassword, &getTextPassword); + Z7_DECL_CMyComPtr_QI_FROM( + ICryptoGetTextPassword, + getTextPassword, ReOpenCallback) if (getTextPassword) return getTextPassword->CryptoGetTextPassword(password); } @@ -166,3 +380,14 @@ COM_TRY_END } #endif + +// IProgress +Z7_COM7F_IMF(COpenCallbackImp::SetTotal(const UInt64 /* total */)) +{ + return S_OK; +} + +Z7_COM7F_IMF(COpenCallbackImp::SetCompleted(const UInt64 * /* completed */)) +{ + return S_OK; +} diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/ArchiveOpenCallback.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/ArchiveOpenCallback.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/ArchiveOpenCallback.h 2021-03-06 09:02:02.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/ArchiveOpenCallback.h 2023-04-06 09:00:00.000000000 +0000 @@ -1,112 +1,176 @@ // ArchiveOpenCallback.h -#ifndef __ARCHIVE_OPEN_CALLBACK_H -#define __ARCHIVE_OPEN_CALLBACK_H +#ifndef ZIP7_INC_ARCHIVE_OPEN_CALLBACK_H +#define ZIP7_INC_ARCHIVE_OPEN_CALLBACK_H #include "../../../Common/MyCom.h" #include "../../../Windows/FileFind.h" -#include "../../../Windows/FileIO.h" -#ifndef _NO_CRYPTO +#include "../../Common/FileStreams.h" + +#ifndef Z7_NO_CRYPTO #include "../../IPassword.h" #endif #include "../../Archive/IArchive.h" -#ifdef _NO_CRYPTO +Z7_PURE_INTERFACES_BEGIN + +#ifdef Z7_NO_CRYPTO -#define INTERFACE_IOpenCallbackUI_Crypto(x) +#define Z7_IFACEM_IOpenCallbackUI_Crypto(x) #else -#define INTERFACE_IOpenCallbackUI_Crypto(x) \ - virtual HRESULT Open_CryptoGetTextPassword(BSTR *password) x; \ - /* virtual HRESULT Open_GetPasswordIfAny(bool &passwordIsDefined, UString &password) x; */ \ - /* virtual bool Open_WasPasswordAsked() x; */ \ - /* virtual void Open_Clear_PasswordWasAsked_Flag() x; */ \ +#define Z7_IFACEM_IOpenCallbackUI_Crypto(x) \ + virtual HRESULT Open_CryptoGetTextPassword(BSTR *password) x \ + /* virtual HRESULT Open_GetPasswordIfAny(bool &passwordIsDefined, UString &password) x */ \ + /* virtual bool Open_WasPasswordAsked() x */ \ + /* virtual void Open_Clear_PasswordWasAsked_Flag() x */ \ #endif -#define INTERFACE_IOpenCallbackUI(x) \ - virtual HRESULT Open_CheckBreak() x; \ - virtual HRESULT Open_SetTotal(const UInt64 *files, const UInt64 *bytes) x; \ - virtual HRESULT Open_SetCompleted(const UInt64 *files, const UInt64 *bytes) x; \ - virtual HRESULT Open_Finished() x; \ - INTERFACE_IOpenCallbackUI_Crypto(x) +#define Z7_IFACEN_IOpenCallbackUI(x) \ + virtual HRESULT Open_CheckBreak() x \ + virtual HRESULT Open_SetTotal(const UInt64 *files, const UInt64 *bytes) x \ + virtual HRESULT Open_SetCompleted(const UInt64 *files, const UInt64 *bytes) x \ + virtual HRESULT Open_Finished() x \ + Z7_IFACEM_IOpenCallbackUI_Crypto(x) + +Z7_IFACE_DECL_PURE(IOpenCallbackUI) + +Z7_PURE_INTERFACES_END + -struct IOpenCallbackUI +class CMultiStreams Z7_final { - INTERFACE_IOpenCallbackUI(=0) +public: + struct CSubStream + { + CMyComPtr Stream; + CInFileStream *FileSpec; + FString Path; + // UInt64 Size; + UInt64 LocalPos; + int Next; // next older + int Prev; // prev newer + // bool IsOpen; + + CSubStream(): + FileSpec(NULL), + // Size(0), + LocalPos(0), + Next(-1), + Prev(-1) + // IsOpen(false) + {} + }; + + CObjectVector Streams; +private: + // we must use critical section here, if we want to access from different volumnes simultaneously + int Head; // newest + int Tail; // oldest + unsigned NumListItems; + unsigned NumOpenFiles_AllowedMax; +public: + + CMultiStreams(); + void Init(); + HRESULT PrepareToOpenNew(); + void InsertToList(unsigned index); + void RemoveFromList(CSubStream &s); + void CloseFile(unsigned index); + HRESULT EnsureOpen(unsigned index); }; -class COpenCallbackImp: + +/* + We need COpenCallbackImp class for multivolume processing. + Also we use it as proxy from COM interfaces (IArchiveOpenCallback) to internal (IOpenCallbackUI) interfaces. + If archive is multivolume: + COpenCallbackImp object will exist after Open stage. + COpenCallbackImp object will be deleted when last reference + from each volume object (CInFileStreamVol) will be closed (when archive will be closed). +*/ + +class COpenCallbackImp Z7_final: public IArchiveOpenCallback, public IArchiveOpenVolumeCallback, public IArchiveOpenSetSubArchiveName, - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO public ICryptoGetTextPassword, - #endif + #endif + public IProgress, // IProgress is used for 7zFM public CMyUnknownImp { + Z7_COM_QI_BEGIN2(IArchiveOpenCallback) + Z7_COM_QI_ENTRY(IArchiveOpenVolumeCallback) + Z7_COM_QI_ENTRY(IArchiveOpenSetSubArchiveName) + #ifndef Z7_NO_CRYPTO + Z7_COM_QI_ENTRY(ICryptoGetTextPassword) + #endif + // Z7_COM_QI_ENTRY(IProgress) // the code doesn't require it + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(IArchiveOpenCallback) + Z7_IFACE_COM7_IMP(IArchiveOpenVolumeCallback) + Z7_IFACE_COM7_IMP(IProgress) +public: + Z7_IFACE_COM7_IMP(IArchiveOpenSetSubArchiveName) +private: + #ifndef Z7_NO_CRYPTO + Z7_IFACE_COM7_IMP(ICryptoGetTextPassword) + #endif + + bool _subArchiveMode; + public: - MY_QUERYINTERFACE_BEGIN2(IArchiveOpenVolumeCallback) - MY_QUERYINTERFACE_ENTRY(IArchiveOpenSetSubArchiveName) - #ifndef _NO_CRYPTO - MY_QUERYINTERFACE_ENTRY(ICryptoGetTextPassword) - #endif - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IArchiveOpenCallback(;) - INTERFACE_IArchiveOpenVolumeCallback(;) - - #ifndef _NO_CRYPTO - STDMETHOD(CryptoGetTextPassword)(BSTR *password); - #endif + bool PasswordWasAsked; + UStringVector FileNames; + CBoolVector FileNames_WasUsed; + CRecordVector FileSizes; - STDMETHOD(SetSubArchiveName(const wchar_t *name)) + void AtCloseFile(unsigned fileIndex) { - _subArchiveMode = true; - _subArchiveName = name; - // TotalSize = 0; - return S_OK; + FileNames_WasUsed[fileIndex] = false; + Volumes.CloseFile(fileIndex); } + /* we have two ways to Callback from this object + 1) IArchiveOpenCallback * ReOpenCallback - for ReOpen function, when IOpenCallbackUI is not available + 2) IOpenCallbackUI *Callback - for usual callback + we can't transfer IOpenCallbackUI pointer via internal interface, + so we use ReOpenCallback to callback without IOpenCallbackUI. + */ + + /* we use Callback/ReOpenCallback only at Open stage. + So the CMyComPtr reference counter is not required, + and we don't want additional reference to unused object, + if COpenCallbackImp is not closed + */ + IArchiveOpenCallback *ReOpenCallback; + // CMyComPtr ReOpenCallback; + IOpenCallbackUI *Callback; + // CMyComPtr Callback_Ref; + private: FString _folderPrefix; - NWindows::NFile::NFind::CFileInfo _fileInfo; - bool _subArchiveMode; UString _subArchiveName; + NWindows::NFile::NFind::CFileInfo _fileInfo; public: - UStringVector FileNames; - CBoolVector FileNames_WasUsed; - CRecordVector FileSizes; + CMultiStreams Volumes; - bool PasswordWasAsked; - - IOpenCallbackUI *Callback; - CMyComPtr ReOpenCallback; // UInt64 TotalSize; - COpenCallbackImp(): _subArchiveMode(false), Callback(NULL) {} + COpenCallbackImp(): + _subArchiveMode(false), + ReOpenCallback(NULL), + Callback(NULL) {} - HRESULT Init2(const FString &folderPrefix, const FString &fileName) - { - FileNames.Clear(); - FileNames_WasUsed.Clear(); - FileSizes.Clear(); - _subArchiveMode = false; - // TotalSize = 0; - PasswordWasAsked = false; - _folderPrefix = folderPrefix; - if (!_fileInfo.Find_FollowLink(_folderPrefix + fileName)) - { - // throw 20121118; - return GetLastError_noZero_HRESULT(); - } - return S_OK; - } + HRESULT Init2(const FString &folderPrefix, const FString &fileName); bool SetSecondFileInfo(CFSTR newName) { diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/Bench.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/Bench.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/Bench.cpp 2021-12-25 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/Bench.cpp 2023-05-03 13:00:00.000000000 +0000 @@ -36,19 +36,20 @@ #include "../../../../C/7zCrc.h" #include "../../../../C/RotateDefs.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "../../../Windows/Synchronization.h" #include "../../../Windows/Thread.h" #endif -#include "../../../Windows/FileIO.h" #include "../../../Windows/FileFind.h" +#include "../../../Windows/FileIO.h" #include "../../../Windows/SystemInfo.h" -#include "../../../Common/IntToString.h" #include "../../../Common/MyBuffer2.h" +#include "../../../Common/IntToString.h" #include "../../../Common/StringConvert.h" #include "../../../Common/StringToInt.h" +#include "../../../Common/Wildcard.h" #include "../../Common/MethodProps.h" #include "../../Common/StreamObjects.h" @@ -58,7 +59,7 @@ using namespace NWindows; -#ifndef _7ZIP_ST +#ifndef Z7_ST static const UInt32 k_LZMA = 0x030101; #endif @@ -122,7 +123,7 @@ public: CBaseRandomGenerator(UInt32 salt = 0): Salt(salt) { Init(); } void Init() { A1 = 362436069; A2 = 521288629;} - MY_FORCE_INLINE + Z7_FORCE_INLINE UInt32 GetRnd() { return Salt ^ @@ -134,7 +135,7 @@ }; -MY_NO_INLINE +Z7_NO_INLINE static void RandGen(Byte *buf, size_t size) { CBaseRandomGenerator RG; @@ -143,7 +144,7 @@ for (i = 0; i < size4; i += 4) { const UInt32 v = RG.GetRnd(); - SetUi32(buf + i, v); + SetUi32(buf + i, v) } UInt32 v = RG.GetRnd(); for (; i < size; i++) @@ -255,16 +256,14 @@ }; -class CBenchmarkInStream: - public ISequentialInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + CBenchmarkInStream + , ISequentialInStream +) const Byte *Data; size_t Pos; size_t Size; - public: - MY_UNKNOWN_IMP void Init(const Byte *data, size_t size) { Data = data; @@ -272,10 +271,9 @@ Pos = 0; } bool WasFinished() const { return Pos == Size; } - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); }; -STDMETHODIMP CBenchmarkInStream::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CBenchmarkInStream::Read(void *data, UInt32 size, UInt32 *processedSize)) { const UInt32 kMaxBlockSize = (1 << 20); if (size > kMaxBlockSize) @@ -293,11 +291,14 @@ return S_OK; } -class CBenchmarkOutStream: + +class CBenchmarkOutStream Z7_final: public ISequentialOutStream, - public CMidAlignedBuffer, - public CMyUnknownImp + public CMyUnknownImp, + public CMidAlignedBuffer { + Z7_COM_UNKNOWN_IMP_0 + Z7_IFACE_COM7_IMP(ISequentialOutStream) // bool _overflow; public: size_t Pos; @@ -328,12 +329,9 @@ size_t GetPos() const { return Pos; } // void Print() { printf("\n%8d %8d\n", (unsigned)BufferSize, (unsigned)Pos); } - - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); }; -STDMETHODIMP CBenchmarkOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CBenchmarkOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { size_t curSize = Size() - Pos; if (curSize > size) @@ -357,27 +355,24 @@ } -class CCrcOutStream: - public ISequentialOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + CCrcOutStream + , ISequentialOutStream +) public: bool CalcCrc; UInt32 Crc; UInt64 Pos; - MY_UNKNOWN_IMP - - CCrcOutStream(): CalcCrc(true) {}; + CCrcOutStream(): CalcCrc(true) {} void Init() { Crc = CRC_INIT_VAL; Pos = 0; } void Calc(const void *data, size_t size) { Crc = CrcUpdate(Crc, data, size); } - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); }; -STDMETHODIMP CCrcOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CCrcOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)) { if (CalcCrc) Calc(data, size); @@ -394,7 +389,7 @@ #ifdef USE_POSIX_TIME #ifdef USE_POSIX_TIME2 timeval v; - if (gettimeofday(&v, 0) == 0) + if (gettimeofday(&v, NULL) == 0) return (UInt64)(v.tv_sec) * 1000000 + (UInt64)v.tv_usec; return (UInt64)time(NULL) * 1000000; #else @@ -531,9 +526,9 @@ #endif } -class CBenchProgressStatus +class CBenchProgressStatus Z7_final { - #ifndef _7ZIP_ST + #ifndef Z7_ST NSynchronization::CCriticalSection CS; #endif public: @@ -541,14 +536,14 @@ bool EncodeMode; void SetResult(HRESULT res) { - #ifndef _7ZIP_ST + #ifndef Z7_ST NSynchronization::CCriticalSectionLock lock(CS); #endif Res = res; } HRESULT GetResult() { - #ifndef _7ZIP_ST + #ifndef Z7_ST NSynchronization::CCriticalSectionLock lock(CS); #endif return Res; @@ -580,22 +575,22 @@ dest.UserTime = UserTime.GetUserTime(); } -class CBenchProgressInfo: +class CBenchProgressInfo Z7_final: public ICompressProgressInfo, public CMyUnknownImp, public CBenchInfoCalc { + Z7_COM_UNKNOWN_IMP_0 + Z7_IFACE_COM7_IMP(ICompressProgressInfo) public: CBenchProgressStatus *Status; IBenchCallback *Callback; CBenchProgressInfo(): Callback(NULL) {} - MY_UNKNOWN_IMP - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); }; -STDMETHODIMP CBenchProgressInfo::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) +Z7_COM7F_IMF(CBenchProgressInfo::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize)) { HRESULT res = Status->GetResult(); if (res != S_OK) @@ -760,13 +755,20 @@ return MyMultDiv64(numUnits, GlobalFreq, GlobalTime); } +static UInt64 GetNumCommands_from_Size_and_Complexity(UInt64 size, Int32 complexity) +{ + return complexity >= 0 ? + size * (UInt32)complexity : + size / (UInt32)(-complexity); +} + struct CBenchProps { bool LzmaRatingMode; - UInt32 EncComplex; - UInt32 DecComplexCompr; - UInt32 DecComplexUnc; + Int32 EncComplex; + Int32 DecComplexCompr; + Int32 DecComplexUnc; unsigned KeySize; @@ -777,21 +779,23 @@ void SetLzmaCompexity(); - UInt64 GeComprCommands(UInt64 unpackSize) + UInt64 GetNumCommands_Enc(UInt64 unpackSize) const { const UInt32 kMinSize = 100; if (unpackSize < kMinSize) unpackSize = kMinSize; - return unpackSize * EncComplex; + return GetNumCommands_from_Size_and_Complexity(unpackSize, EncComplex); } - UInt64 GeDecomprCommands(UInt64 packSize, UInt64 unpackSize) + UInt64 GetNumCommands_Dec(UInt64 packSize, UInt64 unpackSize) const { - return (packSize * DecComplexCompr + unpackSize * DecComplexUnc); + return + GetNumCommands_from_Size_and_Complexity(packSize, DecComplexCompr) + + GetNumCommands_from_Size_and_Complexity(unpackSize, DecComplexUnc); } - UInt64 GetCompressRating(UInt64 dictSize, UInt64 elapsedTime, UInt64 freq, UInt64 size); - UInt64 GetDecompressRating(UInt64 elapsedTime, UInt64 freq, UInt64 outSize, UInt64 inSize, UInt64 numIterations); + UInt64 GetRating_Enc(UInt64 dictSize, UInt64 elapsedTime, UInt64 freq, UInt64 size) const; + UInt64 GetRating_Dec(UInt64 elapsedTime, UInt64 freq, UInt64 outSize, UInt64 inSize, UInt64 numIterations) const; }; void CBenchProps::SetLzmaCompexity() @@ -802,11 +806,11 @@ LzmaRatingMode = true; } -UInt64 CBenchProps::GetCompressRating(UInt64 dictSize, UInt64 elapsedTime, UInt64 freq, UInt64 size) +UInt64 CBenchProps::GetRating_Enc(UInt64 dictSize, UInt64 elapsedTime, UInt64 freq, UInt64 size) const { if (dictSize < (1 << kBenchMinDicLogSize)) dictSize = (1 << kBenchMinDicLogSize); - UInt64 encComplex = EncComplex; + Int32 encComplex = EncComplex; if (LzmaRatingMode) { /* @@ -822,13 +826,13 @@ const UInt32 t = GetLogSize_Sub(dictSize) - (kBenchMinDicLogSize << kSubBits); encComplex = 870 + ((t * t * 5) >> (2 * kSubBits)); } - const UInt64 numCommands = (UInt64)size * encComplex; + const UInt64 numCommands = GetNumCommands_from_Size_and_Complexity(size, encComplex); return MyMultDiv64(numCommands, freq, elapsedTime); } -UInt64 CBenchProps::GetDecompressRating(UInt64 elapsedTime, UInt64 freq, UInt64 outSize, UInt64 inSize, UInt64 numIterations) +UInt64 CBenchProps::GetRating_Dec(UInt64 elapsedTime, UInt64 freq, UInt64 outSize, UInt64 inSize, UInt64 numIterations) const { - const UInt64 numCommands = (inSize * DecComplexCompr + outSize * DecComplexUnc) * numIterations; + const UInt64 numCommands = GetNumCommands_Dec(inSize, outSize) * numIterations; return MyMultDiv64(numCommands, freq, elapsedTime); } @@ -838,18 +842,18 @@ { CBenchProps props; props.SetLzmaCompexity(); - return props.GetCompressRating(dictSize, GlobalTime, GlobalFreq, UnpackSize * NumIterations); + return props.GetRating_Enc(dictSize, GlobalTime, GlobalFreq, UnpackSize * NumIterations); } UInt64 CBenchInfo::GetRating_LzmaDec() const { CBenchProps props; props.SetLzmaCompexity(); - return props.GetDecompressRating(GlobalTime, GlobalFreq, UnpackSize, PackSize, NumIterations); + return props.GetRating_Dec(GlobalTime, GlobalFreq, UnpackSize, PackSize, NumIterations); } -#ifndef _7ZIP_ST +#ifndef Z7_ST #define NUM_CPU_LEVELS_MAX 3 @@ -988,15 +992,22 @@ +enum E_CheckCrcMode +{ + k_CheckCrcMode_Never = 0, + k_CheckCrcMode_Always = 1, + k_CheckCrcMode_FirstPass = 2 +}; + class CEncoderInfo; -class CEncoderInfo +class CEncoderInfo Z7_final { - CLASS_NO_COPY(CEncoderInfo) + Z7_CLASS_NO_COPY(CEncoderInfo) public: - #ifndef _7ZIP_ST + #ifndef Z7_ST NWindows::CThread thread[2]; NSynchronization::CManualResetEvent ReadyEvent; UInt32 NumDecoderSubThreads; @@ -1004,6 +1015,7 @@ UInt32 EncoderIndex; UInt32 NumEncoderInternalThreads; CAffinityMode AffinityMode; + bool IsGlobalMtMode; // if more than one benchmark encoder threads #endif CMyComPtr _encoder; @@ -1024,14 +1036,17 @@ HRESULT Set_Key_and_IV(ICryptoProperties *cp) { - RINOK(cp->SetKey(_key, KeySize)); + RINOK(cp->SetKey(_key, KeySize)) return cp->SetInitVector(_iv, sizeof(_iv)); } Byte _psw[16]; - bool CheckCrc_Enc; - bool CheckCrc_Dec; + bool CheckCrc_Enc; /* = 1, if we want to check packed data crcs after each pass + used for filter and usual coders */ + bool UseRealData_Enc; /* = 1, if we want to use only original data for each pass + used only for filter */ + E_CheckCrcMode CheckCrcMode_Dec; struct CDecoderInfo { @@ -1079,13 +1094,15 @@ HRESULT Decode(UInt32 decoderIndex); CEncoderInfo(): - #ifndef _7ZIP_ST + #ifndef Z7_ST Common(NULL), + IsGlobalMtMode(true), #endif Salt(0), KeySize(0), CheckCrc_Enc(true), - CheckCrc_Dec(true), + UseRealData_Enc(true), + CheckCrcMode_Dec(k_CheckCrcMode_Always), outStreamSpec(NULL), callback(NULL), printCallback(NULL), @@ -1093,7 +1110,7 @@ propStreamSpec(NULL) {} - #ifndef _7ZIP_ST + #ifndef Z7_ST static THREAD_FUNC_DECL EncodeThreadFunction(void *param) { @@ -1115,7 +1132,7 @@ if (res != S_OK) encoder->progressInfoSpec[0]->Status->SetResult(res); encoder->ReadyEvent.Set(); - return 0; + return THREAD_FUNC_RET_ZERO; } static THREAD_FUNC_DECL DecodeThreadFunction(void *param) @@ -1128,7 +1145,7 @@ CEncoderInfo *encoder = decoder->Encoder; encoder->Results[decoder->DecoderIndex] = encoder->Decode(decoder->DecoderIndex); - return 0; + return THREAD_FUNC_RET_ZERO; } HRESULT CreateEncoderThread() @@ -1184,17 +1201,30 @@ const COneMethodInfo &method = _method; // we need extra space, if input data is already compressed - const size_t kCompressedBufferSize = GetBenchCompressedSize(kBufferSize); + const size_t kCompressedBufferSize = _encoderFilter ? + kBufferSize : + GetBenchCompressedSize(kBufferSize); if (kCompressedBufferSize < kBufferSize) return E_FAIL; uncompressedDataPtr = fileData; - - if (!fileData) + if (fileData) { - ALLOC_WITH_HRESULT(&rg, kBufferSize); - + #if !defined(Z7_ST) + if (IsGlobalMtMode) + { + /* we copy the data to local buffer of thread to eliminate + using of shared buffer by different threads */ + ALLOC_WITH_HRESULT(&rg, kBufferSize) + memcpy((Byte *)rg, fileData, kBufferSize); + uncompressedDataPtr = (const Byte *)rg; + } + #endif + } + else + { + ALLOC_WITH_HRESULT(&rg, kBufferSize) // DWORD ttt = GetTickCount(); if (generateDictBits == 0) rg.GenerateSimpleRandom(Salt); @@ -1211,12 +1241,6 @@ crc = CrcCalc((const Byte *)rg, rg.Size()); uncompressedDataPtr = (const Byte *)rg; } - - if (_encoderFilter) - { - ALLOC_WITH_HRESULT(&rgCopy, kBufferSize); - } - if (!outStream) { @@ -1226,6 +1250,15 @@ ALLOC_WITH_HRESULT(outStreamSpec, kCompressedBufferSize) + if (_encoderFilter) + { + /* we try to reduce the number of memcpy() in main encoding loop. + so we copy data to temp buffers here */ + ALLOC_WITH_HRESULT(&rgCopy, kBufferSize) + memcpy((Byte *)*outStreamSpec, uncompressedDataPtr, kBufferSize); + memcpy((Byte *)rgCopy, uncompressedDataPtr, kBufferSize); + } + if (!propStream) { propStreamSpec = new CBufPtrSeqOutStream; // CBenchmarkOutStream; @@ -1251,7 +1284,7 @@ /* in posix new thread uses same affinity as parent thread, so we don't need to send affinity to coder in posix */ UInt64 affMask; - #if !defined(_7ZIP_ST) && defined(_WIN32) + #if !defined(Z7_ST) && defined(_WIN32) { CCpuSet cpuSet; affMask = AffinityMode.GetAffinityMask(EncoderIndex, &cpuSet); @@ -1262,7 +1295,7 @@ // affMask <<= 3; // debug line: to test no affinity in coder; // affMask = 0; - RINOK(method.SetCoderProps_DSReduce_Aff(scp, &reduceSize, (affMask != 0 ? &affMask : NULL))); + RINOK(method.SetCoderProps_DSReduce_Aff(scp, &reduceSize, (affMask != 0 ? &affMask : NULL))) } else { @@ -1274,7 +1307,7 @@ coder.QueryInterface(IID_ICompressWriteCoderProperties, &writeCoderProps); if (writeCoderProps) { - RINOK(writeCoderProps->WriteCoderProperties(propStream)); + RINOK(writeCoderProps->WriteCoderProperties(propStream)) } { @@ -1282,7 +1315,7 @@ coder.QueryInterface(IID_ICryptoSetPassword, &sp); if (sp) { - RINOK(sp->CryptoSetPassword(_psw, sizeof(_psw))); + RINOK(sp->CryptoSetPassword(_psw, sizeof(_psw))) // we must call encoding one time to calculate password key for key cache. // it must be after WriteCoderProperties! @@ -1304,7 +1337,7 @@ CMyComPtr crcStream = crcStreamSpec; crcStreamSpec->Init(); - RINOK(_encoder->Code(inStream, crcStream, 0, 0, NULL)); + RINOK(_encoder->Code(inStream, crcStream, NULL, NULL, NULL)) } } } @@ -1314,19 +1347,22 @@ } -static void My_FilterBench(ICompressFilter *filter, Byte *data, size_t size) +static void My_FilterBench(ICompressFilter *filter, Byte *data, size_t size, UInt32 *crc) { while (size != 0) { - UInt32 cur = (UInt32)1 << 31; + UInt32 cur = crc ? 1 << 17 : 1 << 24; if (cur > size) cur = (UInt32)size; UInt32 processed = filter->Filter(data, cur); - data += processed; - // if (processed > size) (in AES filter), we must fill last block with zeros. - // but it is not important for benchmark. So we just copy that data without filtering. + /* if (processed > size) (in AES filter), we must fill last block with zeros. + but it is not important for benchmark. So we just copy that data without filtering. + if (processed == 0) then filter can't process more */ if (processed > size || processed == 0) - break; + processed = (UInt32)size; + if (crc) + *crc = CrcUpdate(*crc, data, processed); + data += processed; size -= processed; } } @@ -1336,11 +1372,11 @@ { // printf("\nCEncoderInfo::Generate\n"); - RINOK(Generate()); + RINOK(Generate()) // printf("\n2222\n"); - #ifndef _7ZIP_ST + #ifndef Z7_ST if (Common) { Results[0] = S_OK; @@ -1375,7 +1411,7 @@ if (cp) { - RINOK(Set_Key_and_IV(cp)); + RINOK(Set_Key_and_IV(cp)) } compressedSize = 0; @@ -1384,20 +1420,32 @@ // CBenchmarkOutStream *outStreamSpec = this->outStreamSpec; UInt64 prev = 0; - const UInt32 mask = (CheckCrc_Enc ? 0 : 0xFFF); - bool useCrc = (mask < NumIterations); + + const UInt32 mask = (CheckCrc_Enc ? 0 : 0xFFFF); + const bool useCrc = (mask < NumIterations); bool crcPrev_defined = false; UInt32 crcPrev = 0; - UInt64 i = NumIterations; + + bool useRealData_Enc = UseRealData_Enc; + bool data_Was_Changed = false; + if (useRealData_Enc) + { + /* we want memcpy() for each iteration including first iteration. + So results will be equal for different number of iterations */ + data_Was_Changed = true; + } + + const UInt64 numIterations = NumIterations; + UInt64 i = numIterations; // printCallback->NewLine(); while (i != 0) { i--; - if (printCallback && bi.UnpackSize - prev >= (1 << 24)) + if (printCallback && bi.UnpackSize - prev >= (1 << 26)) { - RINOK(printCallback->CheckBreak()); prev = bi.UnpackSize; + RINOK(printCallback->CheckBreak()) } /* @@ -1411,21 +1459,25 @@ if (_encoderFilter) { - // if (needRealData) - memcpy((Byte *)*outStreamSpec, uncompressedDataPtr, kBufferSize); + Byte *filterData = rgCopy; + if (i == numIterations - 1 || calcCrc || useRealData_Enc) + { + filterData = (Byte *)*outStreamSpec; + if (data_Was_Changed) + memcpy(filterData, uncompressedDataPtr, kBufferSize); + data_Was_Changed = true; + } _encoderFilter->Init(); - My_FilterBench(_encoderFilter, (Byte *)*outStreamSpec, kBufferSize); if (calcCrc) - { outStreamSpec->InitCrc(); - outStreamSpec->Calc((Byte *)*outStreamSpec, kBufferSize); - } + My_FilterBench(_encoderFilter, filterData, kBufferSize, + calcCrc ? &outStreamSpec->Crc : NULL); } else { outStreamSpec->Init(true, calcCrc); // write real data for speed consistency at any number of iterations inStreamSpec->Init(uncompressedDataPtr, kBufferSize); - RINOK(_encoder->Code(inStream, outStream, NULL, NULL, progressInfo[0])); + RINOK(_encoder->Code(inStream, outStream, NULL, NULL, progressInfo[0])) if (!inStreamSpec->WasFinished()) return E_FAIL; if (compressedSize != outStreamSpec->Pos) @@ -1461,7 +1513,7 @@ info.PackSize = compressedSize; // printf("\n%7d\n", encoder.compressedSize); - RINOK(callback->SetEncodeResult(info, true)); + RINOK(callback->SetEncodeResult(info, true)) printCallback->NewLine(); } */ @@ -1501,13 +1553,13 @@ pi->BenchInfo.UnpackSize = 0; pi->BenchInfo.PackSize = 0; - #ifndef _7ZIP_ST + #ifndef Z7_ST { CMyComPtr setCoderMt; coder.QueryInterface(IID_ICompressSetCoderMt, &setCoderMt); if (setCoderMt) { - RINOK(setCoderMt->SetNumberOfThreads(NumDecoderSubThreads)); + RINOK(setCoderMt->SetNumberOfThreads(NumDecoderSubThreads)) } } #endif @@ -1517,7 +1569,7 @@ if (scp) { const UInt64 reduceSize = _uncompressedDataSize; - RINOK(_method.SetCoderProps(scp, &reduceSize)); + RINOK(_method.SetCoderProps(scp, &reduceSize)) } CMyComPtr cp; @@ -1528,7 +1580,7 @@ RINOK(setDecProps->SetDecoderProperties2( /* (const Byte *)*propStreamSpec, */ propsData, - (UInt32)propStreamSpec->GetPos())); + (UInt32)propStreamSpec->GetPos())) } { @@ -1536,7 +1588,7 @@ coder.QueryInterface(IID_ICryptoSetPassword, &sp); if (sp) { - RINOK(sp->CryptoSetPassword(_psw, sizeof(_psw))); + RINOK(sp->CryptoSetPassword(_psw, sizeof(_psw))) } } @@ -1544,7 +1596,7 @@ if (cp) { - RINOK(Set_Key_and_IV(cp)); + RINOK(Set_Key_and_IV(cp)) } CMyComPtr setFinishMode; @@ -1559,32 +1611,38 @@ decoder->QueryInterface(IID_ICompressSetFinishMode, (void **)&setFinishMode); } - const UInt64 numIterations = this->NumIterations; - const UInt32 mask = (CheckCrc_Dec ? 0 : 0xFFF); + const UInt64 numIterations = NumIterations; + const E_CheckCrcMode checkCrcMode = CheckCrcMode_Dec; for (UInt64 i = 0; i < numIterations; i++) { - if (printCallback && pi->BenchInfo.UnpackSize - prev >= (1 << 24)) + if (printCallback && pi->BenchInfo.UnpackSize - prev >= (1 << 26)) { - RINOK(printCallback->CheckBreak()); + RINOK(printCallback->CheckBreak()) prev = pi->BenchInfo.UnpackSize; } const UInt64 outSize = kBufferSize; - bool calcCrc = false; - if (((UInt32)i & mask) == 0) - calcCrc = true; + bool calcCrc = (checkCrcMode != k_CheckCrcMode_Never); + crcOutStreamSpec->Init(); - + if (_decoderFilter) { - if (calcCrc) // for pure filter speed test without multi-iteration consistency - // if (needRealData) - memcpy((Byte *)rgCopy, (const Byte *)*outStreamSpec, compressedSize); - _decoderFilter->Init(); - My_FilterBench(_decoderFilter, (Byte *)rgCopy, compressedSize); + Byte *filterData = (Byte *)*outStreamSpec; if (calcCrc) - crcOutStreamSpec->Calc((const Byte *)rgCopy, compressedSize); + { + calcCrc = (i == 0); + if (checkCrcMode == k_CheckCrcMode_Always) + { + calcCrc = true; + memcpy((Byte *)rgCopy, (const Byte *)*outStreamSpec, compressedSize); + filterData = rgCopy; + } + } + _decoderFilter->Init(); + My_FilterBench(_decoderFilter, filterData, compressedSize, + calcCrc ? &crcOutStreamSpec->Crc : NULL); } else { @@ -1593,10 +1651,10 @@ if (setFinishMode) { - RINOK(setFinishMode->SetFinishMode(BoolToUInt(true))); + RINOK(setFinishMode->SetFinishMode(BoolToUInt(true))) } - RINOK(decoder->Code(inStream, crcOutStream, 0, &outSize, progressInfo[decoderIndex])); + RINOK(decoder->Code(inStream, crcOutStream, NULL, &outSize, progressInfo[decoderIndex])) if (setFinishMode) { @@ -1609,7 +1667,7 @@ if (getInStreamProcessedSize) { UInt64 processed; - RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&processed)); + RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&processed)) if (processed != compressedSize) return S_FALSE; } @@ -1652,7 +1710,7 @@ -#ifndef _7ZIP_ST +#ifndef Z7_ST // ---------- CBenchThreadsFlusher ---------- @@ -1696,7 +1754,7 @@ return res; } -#endif // _7ZIP_ST +#endif // Z7_ST @@ -1714,7 +1772,7 @@ static HRESULT MethodBench( DECL_EXTERNAL_CODECS_LOC_VARS UInt64 complexInCommands, - #ifndef _7ZIP_ST + #ifndef Z7_ST bool oldLzmaBenchMode, UInt32 numThreads, const CAffinityMode *affinityMode, @@ -1731,10 +1789,11 @@ COneMethodInfo method = method2; UInt64 methodId; UInt32 numStreams; + bool isFilter; const int codecIndex = FindMethod_Index( EXTERNAL_CODECS_LOC_VARS method.MethodName, true, - methodId, numStreams); + methodId, numStreams, isFilter); if (codecIndex < 0) return E_NOTIMPL; if (numStreams != 1) @@ -1743,7 +1802,7 @@ UInt32 numEncoderThreads = 1; UInt32 numSubDecoderThreads = 1; - #ifndef _7ZIP_ST + #ifndef Z7_ST numEncoderThreads = numThreads; if (oldLzmaBenchMode) @@ -1759,7 +1818,7 @@ } } - bool mtEncMode = (numEncoderThreads > 1) || affinityMode->NeedAffinity(); + const bool mtEncMode = (numEncoderThreads > 1) || affinityMode->NeedAffinity(); #endif @@ -1771,10 +1830,10 @@ for (i = 0; i < numEncoderThreads; i++) { CEncoderInfo &encoder = encoders[i]; - encoder.callback = (i == 0) ? callback : 0; + encoder.callback = (i == 0) ? callback : NULL; encoder.printCallback = printCallback; - #ifndef _7ZIP_ST + #ifndef Z7_ST encoder.EncoderIndex = i; encoder.NumEncoderInternalThreads = numSubDecoderThreads; encoder.AffinityMode = *affinityMode; @@ -1794,15 +1853,12 @@ { CCreatedCoder cod; - RINOK(CreateCoder_Index(EXTERNAL_CODECS_LOC_VARS (unsigned)codecIndex, true, encoder._encoderFilter, cod)); + RINOK(CreateCoder_Index(EXTERNAL_CODECS_LOC_VARS (unsigned)codecIndex, true, encoder._encoderFilter, cod)) encoder._encoder = cod.Coder; if (!encoder._encoder && !encoder._encoderFilter) return E_NOTIMPL; } - encoder.CheckCrc_Enc = (benchProps->EncComplex) > 30; - encoder.CheckCrc_Dec = (benchProps->DecComplexCompr + benchProps->DecComplexUnc) > 30; - SetPseudoRand(encoder._iv, sizeof(encoder._iv), 17); SetPseudoRand(encoder._key, sizeof(encoder._key), 51); SetPseudoRand(encoder._psw, sizeof(encoder._psw), 123); @@ -1811,11 +1867,27 @@ { CCreatedCoder cod; CMyComPtr &decoder = encoder._decoders[j]; - RINOK(CreateCoder_Id(EXTERNAL_CODECS_LOC_VARS methodId, false, encoder._decoderFilter, cod)); + RINOK(CreateCoder_Id(EXTERNAL_CODECS_LOC_VARS methodId, false, encoder._decoderFilter, cod)) decoder = cod.Coder; if (!encoder._decoderFilter && !decoder) return E_NOTIMPL; } + + encoder.UseRealData_Enc = + encoder.CheckCrc_Enc = (benchProps->EncComplex) > 30; + + encoder.CheckCrcMode_Dec = k_CheckCrcMode_Always; + if (benchProps->DecComplexCompr + + benchProps->DecComplexUnc <= 30) + encoder.CheckCrcMode_Dec = + k_CheckCrcMode_FirstPass; // for filters + // k_CheckCrcMode_Never; // for debug + // k_CheckCrcMode_Always; // for debug + if (fileData) + { + encoder.UseRealData_Enc = true; + encoder.CheckCrcMode_Dec = k_CheckCrcMode_Always; + } } UInt32 crc = 0; @@ -1837,7 +1909,7 @@ status.Res = S_OK; status.EncodeMode = true; - #ifndef _7ZIP_ST + #ifndef Z7_ST CBenchThreadsFlusher encoderFlusher; if (mtEncMode) { @@ -1853,7 +1925,7 @@ for (i = 0; i < numEncoderThreads; i++) { CEncoderInfo &encoder = encoders[i]; - encoder.NumIterations = GetNumIterations(benchProps->GeComprCommands(uncompressedDataSize), complexInCommands); + encoder.NumIterations = GetNumIterations(benchProps->GetNumCommands_Enc(uncompressedDataSize), complexInCommands); // encoder.NumIterations = 3; encoder.Salt = g_CrcTable[i & 0xFF]; encoder.Salt ^= (g_CrcTable[(i >> 8) & 0xFF] << 3); @@ -1877,7 +1949,7 @@ bpi->BenchInfo.NumIterations = numEncoderThreads; } - #ifndef _7ZIP_ST + #ifndef Z7_ST if (mtEncMode) { #ifdef USE_ALLOCA @@ -1885,6 +1957,7 @@ #endif encoder.Common = &encoderFlusher.Common; + encoder.IsGlobalMtMode = numEncoderThreads > 1; RINOK(encoder.CreateEncoderThread()) } #endif @@ -1892,35 +1965,35 @@ if (printCallback) { - RINOK(printCallback->CheckBreak()); + RINOK(printCallback->CheckBreak()) } - #ifndef _7ZIP_ST + #ifndef Z7_ST if (mtEncMode) { for (i = 0; i < numEncoderThreads; i++) { CEncoderInfo &encoder = encoders[i]; - WRes wres = encoder.ReadyEvent.Lock(); + const WRes wres = encoder.ReadyEvent.Lock(); if (wres != 0) return HRESULT_FROM_WIN32(wres); - RINOK(encoder.Results[0]); + RINOK(encoder.Results[0]) } CBenchProgressInfo *bpi = encoders[0].progressInfoSpec[0]; bpi->SetStartTime(); - WRes wres = encoderFlusher.StartAndWait(); + const WRes wres = encoderFlusher.StartAndWait(); if (status.Res == 0 && wres != 0) return HRESULT_FROM_WIN32(wres); } else #endif { - RINOK(encoders[0].Encode()); + RINOK(encoders[0].Encode()) } - RINOK(status.Res); + RINOK(status.Res) CBenchInfo info; @@ -1931,13 +2004,13 @@ for (i = 0; i < numEncoderThreads; i++) { - CEncoderInfo &encoder = encoders[i]; + const CEncoderInfo &encoder = encoders[i]; info.UnpackSize += encoder.kBufferSize; info.PackSize += encoder.compressedSize; // printf("\n%7d\n", encoder.compressedSize); } - RINOK(callback->SetEncodeResult(info, true)); + RINOK(callback->SetEncodeResult(info, true)) @@ -1948,7 +2021,7 @@ status.EncodeMode = false; const UInt32 numDecoderThreads = numEncoderThreads * numSubDecoderThreads; - #ifndef _7ZIP_ST + #ifndef Z7_ST const bool mtDecoderMode = (numDecoderThreads > 1) || affinityMode->NeedAffinity(); #endif @@ -1957,7 +2030,7 @@ CEncoderInfo &encoder = encoders[i]; /* - #ifndef _7ZIP_ST + #ifndef Z7_ST // encoder.affinityMode = *affinityMode; if (encoder.NumEncoderInternalThreads != 1) encoder.AffinityMode.DivideNum = encoder.NumEncoderInternalThreads; @@ -1967,7 +2040,11 @@ if (i == 0) { - encoder.NumIterations = GetNumIterations(benchProps->GeDecomprCommands(encoder.compressedSize, encoder.kBufferSize), complexInCommands); + encoder.NumIterations = GetNumIterations( + benchProps->GetNumCommands_Dec( + encoder.compressedSize, + encoder.kBufferSize), + complexInCommands); CBenchProgressInfo *bpi = encoder.progressInfoSpec[0]; bpi->Callback = callback; bpi->BenchInfo.NumIterations = numDecoderThreads; @@ -1976,7 +2053,7 @@ else encoder.NumIterations = encoders[0].NumIterations; - #ifndef _7ZIP_ST + #ifndef Z7_ST { int numSubThreads = method.Get_NumThreads(); encoder.NumDecoderSubThreads = (numSubThreads <= 0) ? 1 : (unsigned)numSubThreads; @@ -1985,22 +2062,22 @@ { for (UInt32 j = 0; j < numSubDecoderThreads; j++) { - HRESULT res = encoder.CreateDecoderThread(j, (i == 0 && j == 0) + const HRESULT res = encoder.CreateDecoderThread(j, (i == 0 && j == 0) #ifdef USE_ALLOCA , ((i * numSubDecoderThreads + j) * 16 * 21) & 0x7FF #endif ); - RINOK(res); + RINOK(res) } } else #endif { - RINOK(encoder.Decode(0)); + RINOK(encoder.Decode(0)) } } - #ifndef _7ZIP_ST + #ifndef Z7_ST if (mtDecoderMode) { WRes wres = 0; @@ -2009,26 +2086,26 @@ for (UInt32 j = 0; j < numSubDecoderThreads; j++) { CEncoderInfo &encoder = encoders[i]; - WRes wres2 = encoder.thread[j]. + const WRes wres2 = encoder.thread[j]. // Wait(); // later we can get thread times from thread in UNDER_CE Wait_Close(); if (wres == 0 && wres2 != 0) wres = wres2; - HRESULT res2 = encoder.Results[j]; + const HRESULT res2 = encoder.Results[j]; if (res == 0 && res2 != 0) res = res2; } if (wres != 0) return HRESULT_FROM_WIN32(wres); - RINOK(res); + RINOK(res) } - #endif // _7ZIP_ST + #endif // Z7_ST - RINOK(status.Res); + RINOK(status.Res) encoders[0].progressInfoSpec[0]->SetFinishTime(info); /* - #ifndef _7ZIP_ST + #ifndef Z7_ST #ifdef UNDER_CE if (mtDecoderMode) for (i = 0; i < numEncoderThreads; i++) @@ -2048,13 +2125,13 @@ for (i = 0; i < numEncoderThreads; i++) { - CEncoderInfo &encoder = encoders[i]; + const CEncoderInfo &encoder = encoders[i]; info.UnpackSize += encoder.kBufferSize; info.PackSize += encoder.compressedSize; } - // RINOK(callback->SetDecodeResult(info, false)); // why we called before 21.03 ?? - RINOK(callback->SetDecodeResult(info, true)); + // RINOK(callback->SetDecodeResult(info, false)) // why we called before 21.03 ?? + RINOK(callback->SetDecodeResult(info, true)) return S_OK; } @@ -2234,7 +2311,7 @@ if (cur - prev >= ((UInt32)1 << 30)) { prev = cur; - RINOK(callback->CheckBreak()); + RINOK(callback->CheckBreak()) } } } @@ -2266,7 +2343,7 @@ EXTERN_C_END -#ifndef _7ZIP_ST +#ifndef Z7_ST struct CBaseThreadInfo { @@ -2300,12 +2377,12 @@ { p->CallbackRes = p->Callback->CheckBreak(); if (p->CallbackRes != S_OK) - return 0; + break; } sum = CountCpuFreq(sum, p->Size, g_BenchCpuFreqTemp); } p->ValRes = sum; - return 0; + return THREAD_FUNC_RET_ZERO; } struct CFreqThreads @@ -2349,7 +2426,7 @@ HRESULT Res; UInt32 CheckSum_Res; - #ifndef _7ZIP_ST + #ifndef Z7_ST NSynchronization::CManualResetEvent ReadyEvent; UInt32 ThreadIndex; CBenchSyncCommon *Common; @@ -2433,7 +2510,7 @@ alloca(p->AllocaSize); #endif p->Process(); - return 0; + return THREAD_FUNC_RET_ZERO; } @@ -2480,7 +2557,7 @@ static UInt32 CrcCalc1(const Byte *buf, size_t size) { - UInt32 crc = CRC_INIT_VAL;; + UInt32 crc = CRC_INIT_VAL; for (size_t i = 0; i < size; i++) crc = CRC_UPDATE_BYTE(crc, buf[i]); return CRC_GET_DIGEST(crc); @@ -2522,9 +2599,9 @@ { unsigned Weight; unsigned DictBits; - UInt32 EncComplex; - UInt32 DecComplexCompr; - UInt32 DecComplexUnc; + Int32 EncComplex; + Int32 DecComplexCompr; + Int32 DecComplexUnc; const char *Name; // unsigned KeySize; }; @@ -2563,6 +2640,9 @@ // { 10, 22, 1655, 0, 1830, "PPMDZip:x5" }, { 10, 22, 1655, 0, 1830, "PPMD:x5" }, + // { 2, 0, -16, 0, -16, "Swap2" }, + { 2, 0, -16, 0, -16, "Swap4" }, + // { 2, 0, 3, 0, 4, "Delta:1" }, // { 2, 0, 3, 0, 4, "Delta:2" }, // { 2, 0, 3, 0, 4, "Delta:3" }, @@ -2570,8 +2650,9 @@ // { 2, 0, 3, 0, 4, "Delta:8" }, // { 2, 0, 3, 0, 4, "Delta:32" }, - { 2, 0, 4, 0, 4, "BCJ" }, - + { 2, 0, 2, 0, 2, "BCJ" }, + { 2, 0, 1, 0, 1, "ARM64" }, + // { 10, 0, 18, 0, 18, "AES128CBC:1" }, // { 10, 0, 21, 0, 21, "AES192CBC:1" }, { 10, 0, 24, 0, 24, "AES256CBC:1" }, @@ -2607,11 +2688,13 @@ // #define ARM_CRC_MUL 100 #define ARM_CRC_MUL 1 +#define k_Hash_Complex_Mult 256 + static const CBenchHash g_Hash[] = { - { 1, 1820, 0x21e207bb, "CRC32:1" }, - { 10, 558, 0x21e207bb, "CRC32:4" }, - { 10, 339, 0x21e207bb, "CRC32:8" } , + // { 1, 1820, 0x21e207bb, "CRC32:1" }, + // { 10, 558, 0x21e207bb, "CRC32:4" }, + { 20, 339, 0x21e207bb, "CRC32:8" } , { 2, 128 *ARM_CRC_MUL, 0x21e207bb, "CRC32:32" }, { 2, 64 *ARM_CRC_MUL, 0x21e207bb, "CRC32:64" }, { 10, 512, 0x41b901d1, "CRC64" }, @@ -2656,6 +2739,8 @@ static const unsigned kFieldSize_Rating = 6; static const unsigned kFieldSize_EU = 5; static const unsigned kFieldSize_Effec = 5; +static const unsigned kFieldSize_CrcSpeed = 8; + static const unsigned kFieldSize_TotalSize = 4 + kFieldSize_Speed + kFieldSize_Usage + kFieldSize_RU + kFieldSize_Rating; static const unsigned kFieldSize_EUAndEffec = 2 + kFieldSize_EU + kFieldSize_Effec; @@ -2830,7 +2915,7 @@ } -#ifdef _7ZIP_LARGE_PAGES +#ifdef Z7_LARGE_PAGES #ifdef _WIN32 extern bool g_LargePagesMode; @@ -2875,7 +2960,7 @@ f.Print(" ?"); f.Print(" MB"); - #ifdef _7ZIP_LARGE_PAGES + #ifdef Z7_LARGE_PAGES { AString s; Add_LargePages_String(s); @@ -2890,30 +2975,34 @@ -struct CBenchCallbackToPrint: public IBenchCallback +struct CBenchCallbackToPrint Z7_final: public IBenchCallback { - CBenchProps BenchProps; - CTotalBenchRes EncodeRes; - CTotalBenchRes DecodeRes; - IBenchPrintCallback *_file; - UInt64 DictSize; - + bool NeedPrint; bool Use2Columns; - unsigned NameFieldSize; - bool ShowFreq; - UInt64 CpuFreq; + unsigned NameFieldSize; unsigned EncodeWeight; unsigned DecodeWeight; + UInt64 CpuFreq; + UInt64 DictSize; + + IBenchPrintCallback *_file; + CBenchProps BenchProps; + CTotalBenchRes EncodeRes; + CTotalBenchRes DecodeRes; + + CBenchInfo BenchInfo_Results[2]; + CBenchCallbackToPrint(): + NeedPrint(true), Use2Columns(false), - NameFieldSize(0), ShowFreq(false), - CpuFreq(0), + NameFieldSize(0), EncodeWeight(1), - DecodeWeight(1) + DecodeWeight(1), + CpuFreq(0) {} void Init() { EncodeRes.Init(); DecodeRes.Init(); } @@ -2921,8 +3010,8 @@ void NewLine(); HRESULT SetFreq(bool showFreq, UInt64 cpuFreq); - HRESULT SetEncodeResult(const CBenchInfo &info, bool final); - HRESULT SetDecodeResult(const CBenchInfo &info, bool final); + HRESULT SetEncodeResult(const CBenchInfo &info, bool final) Z7_override; + HRESULT SetDecodeResult(const CBenchInfo &info, bool final) Z7_override; }; HRESULT CBenchCallbackToPrint::SetFreq(bool showFreq, UInt64 cpuFreq) @@ -2934,10 +3023,13 @@ HRESULT CBenchCallbackToPrint::SetEncodeResult(const CBenchInfo &info, bool final) { - RINOK(_file->CheckBreak()); + RINOK(_file->CheckBreak()) + if (final) + BenchInfo_Results[0] = info; if (final) + if (NeedPrint) { - UInt64 rating = BenchProps.GetCompressRating(DictSize, info.GlobalTime, info.GlobalFreq, info.UnpackSize * info.NumIterations); + const UInt64 rating = BenchProps.GetRating_Enc(DictSize, info.GlobalTime, info.GlobalFreq, info.UnpackSize * info.NumIterations); PrintResults(_file, info, EncodeWeight, rating, ShowFreq, CpuFreq, &EncodeRes); @@ -2951,10 +3043,13 @@ HRESULT CBenchCallbackToPrint::SetDecodeResult(const CBenchInfo &info, bool final) { - RINOK(_file->CheckBreak()); + RINOK(_file->CheckBreak()) if (final) + BenchInfo_Results[1] = info; + if (final) + if (NeedPrint) { - UInt64 rating = BenchProps.GetDecompressRating(info.GlobalTime, info.GlobalFreq, info.UnpackSize, info.PackSize, info.NumIterations); + const UInt64 rating = BenchProps.GetRating_Dec(info.GlobalTime, info.GlobalFreq, info.UnpackSize, info.PackSize, info.NumIterations); if (Use2Columns) _file->Print(kSep); else @@ -2996,10 +3091,22 @@ f.Print(s); } + +static bool DoesWildcardMatchName_NoCase(const AString &mask, const char *name) +{ + UString wildc = GetUnicodeString(mask); + UString bname = GetUnicodeString(name); + wildc.MakeLower_Ascii(); + bname.MakeLower_Ascii(); + return DoesWildcardMatchName(wildc, bname); +} + + static HRESULT TotalBench( DECL_EXTERNAL_CODECS_LOC_VARS + const COneMethodInfo &methodMask, UInt64 complexInCommands, - #ifndef _7ZIP_ST + #ifndef Z7_ST UInt32 numThreads, const CAffinityMode *affinityMode, #endif @@ -3008,9 +3115,11 @@ const Byte *fileData, IBenchPrintCallback *printCallback, CBenchCallbackToPrint *callback) { - for (unsigned i = 0; i < ARRAY_SIZE(g_Bench); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Bench); i++) { const CBenchMethod &bench = g_Bench[i]; + if (!DoesWildcardMatchName_NoCase(methodMask.MethodName, bench.Name)) + continue; PrintLeft(*callback->_file, bench.Name, kFieldSize_Name); { unsigned keySize = 32; @@ -3025,7 +3134,7 @@ COneMethodInfo method; NCOM::CPropVariant propVariant; propVariant = bench.Name; - RINOK(method.ParseMethodFromPROPVARIANT(UString(), propVariant)); + RINOK(method.ParseMethodFromPROPVARIANT(UString(), propVariant)) size_t unpackSize2 = unpackSize; if (!forceUnpackSize && bench.DictBits == 0) @@ -3034,10 +3143,10 @@ callback->EncodeWeight = bench.Weight; callback->DecodeWeight = bench.Weight; - HRESULT res = MethodBench( + const HRESULT res = MethodBench( EXTERNAL_CODECS_LOC_VARS complexInCommands, - #ifndef _7ZIP_ST + #ifndef Z7_ST false, numThreads, affinityMode, #endif method, @@ -3054,7 +3163,7 @@ } else { - RINOK(res); + RINOK(res) } callback->NewLine(); @@ -3080,7 +3189,7 @@ {} HRESULT FreqBench(IBenchPrintCallback *_file - #ifndef _7ZIP_ST + #ifndef Z7_ST , const CAffinityMode *affinityMode #endif ); @@ -3088,7 +3197,7 @@ HRESULT CFreqBench::FreqBench(IBenchPrintCallback *_file - #ifndef _7ZIP_ST + #ifndef Z7_ST , const CAffinityMode *affinityMode #endif ) @@ -3100,7 +3209,7 @@ if (numThreads == 0) numThreads = 1; - #ifdef _7ZIP_ST + #ifdef Z7_ST numThreads = 1; #endif @@ -3117,7 +3226,7 @@ CBenchInfoCalc progressInfoSpec; - #ifndef _7ZIP_ST + #ifndef Z7_ST bool mtMode = (numThreads > 1) || affinityMode->NeedAffinity(); @@ -3150,7 +3259,7 @@ return HRESULT_FROM_WIN32(wres); for (i = 0; i < numThreads; i++) { - RINOK(threads.Items[i].CallbackRes); + RINOK(threads.Items[i].CallbackRes) } } else @@ -3163,7 +3272,7 @@ sum = CountCpuFreq(sum, numIterations2, g_BenchCpuFreqTemp); if (_file) { - RINOK(_file->CheckBreak()); + RINOK(_file->CheckBreak()) } } res += sum; @@ -3172,7 +3281,7 @@ if (res == 0x12345678) if (_file) { - RINOK(_file->CheckBreak()); + RINOK(_file->CheckBreak()) } CBenchInfo info; @@ -3193,7 +3302,7 @@ 0, // weight rating, showFreq, showFreq ? (specifiedFreq != 0 ? specifiedFreq : CpuFreqRes) : 0, NULL); - RINOK(_file->CheckBreak()); + RINOK(_file->CheckBreak()) } return S_OK; @@ -3215,7 +3324,7 @@ const UInt32 *checkSum, const COneMethodInfo &method, IBenchPrintCallback *_file, - #ifndef _7ZIP_ST + #ifndef Z7_ST const CAffinityMode *affinityMode, #endif bool showRating, @@ -3225,7 +3334,7 @@ if (numThreads == 0) numThreads = 1; - #ifdef _7ZIP_ST + #ifdef Z7_ST numThreads = 1; #endif @@ -3249,14 +3358,14 @@ */ const size_t bsize = (bufferSize == 0 ? 1 : bufferSize); - UInt64 numIterations = complexInCommands * 256 / complexity / bsize; + UInt64 numIterations = complexInCommands * k_Hash_Complex_Mult / complexity / bsize; if (numIterations == 0) numIterations = 1; CBenchInfoCalc progressInfoSpec; CBenchInfo info; - #ifndef _7ZIP_ST + #ifndef Z7_ST bool mtEncMode = (numThreads > 1) || affinityMode->NeedAffinity(); if (mtEncMode) @@ -3275,14 +3384,14 @@ { CCrcInfo &ci = threads.Items[i]; AString name; - RINOK(CreateHasher(EXTERNAL_CODECS_LOC_VARS hashID, name, ci.Hasher)); + RINOK(CreateHasher(EXTERNAL_CODECS_LOC_VARS hashID, name, ci.Hasher)) if (!ci.Hasher) return E_NOTIMPL; CMyComPtr scp; ci.Hasher.QueryInterface(IID_ICompressSetCoderProperties, &scp); if (scp) { - RINOK(method.SetCoderProps(scp)); + RINOK(method.SetCoderProps(scp)) } ci.Callback = _file; @@ -3320,7 +3429,7 @@ WRes wres = ci.ReadyEvent.Lock(); if (wres != 0) return HRESULT_FROM_WIN32(wres); - RINOK(ci.Res); + RINOK(ci.Res) } progressInfoSpec.SetStartTime(); @@ -3333,7 +3442,7 @@ for (i = 0; i < numThreads; i++) { - RINOK(threads.Items[i].Res); + RINOK(threads.Items[i].Res) if (i != 0) if (threads.Items[i].CheckSum_Res != threads.Items[i - 1].CheckSum_Res) @@ -3345,20 +3454,20 @@ { CMyComPtr hasher; AString name; - RINOK(CreateHasher(EXTERNAL_CODECS_LOC_VARS hashID, name, hasher)); + RINOK(CreateHasher(EXTERNAL_CODECS_LOC_VARS hashID, name, hasher)) if (!hasher) return E_NOTIMPL; CMyComPtr scp; hasher.QueryInterface(IID_ICompressSetCoderProperties, &scp); if (scp) { - RINOK(method.SetCoderProps(scp)); + RINOK(method.SetCoderProps(scp)) } CCrcInfo_Base crcib; crcib.CreateLocalBuf = false; - RINOK(crcib.Generate(fileData, bufferSize)); + RINOK(crcib.Generate(fileData, bufferSize)) progressInfoSpec.SetStartTime(); - RINOK(crcib.CrcProcess(numIterations, checkSum, hasher, _file)); + RINOK(crcib.CrcProcess(numIterations, checkSum, hasher, _file)) progressInfoSpec.SetFinishTime(info); } @@ -3382,7 +3491,7 @@ benchWeight, rating, showFreq, cpuFreq, encodeRes); } - RINOK(_file->CheckBreak()); + RINOK(_file->CheckBreak()) } speed = info.GetSpeed(unpSizeThreads); @@ -3395,20 +3504,23 @@ static HRESULT TotalBench_Hash( DECL_EXTERNAL_CODECS_LOC_VARS + const COneMethodInfo &methodMask, UInt64 complexInCommands, UInt32 numThreads, size_t bufSize, const Byte *fileData, IBenchPrintCallback *printCallback, CBenchCallbackToPrint *callback, - #ifndef _7ZIP_ST + #ifndef Z7_ST const CAffinityMode *affinityMode, #endif CTotalBenchRes *encodeRes, bool showFreq, UInt64 cpuFreq) { - for (unsigned i = 0; i < ARRAY_SIZE(g_Hash); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Hash); i++) { const CBenchHash &bench = g_Hash[i]; + if (!DoesWildcardMatchName_NoCase(methodMask.MethodName, bench.Name)) + continue; PrintLeft(*callback->_file, bench.Name, kFieldSize_Name); // callback->BenchProps.DecComplexUnc = bench.DecComplexUnc; // callback->BenchProps.DecComplexCompr = bench.DecComplexCompr; @@ -3417,11 +3529,11 @@ COneMethodInfo method; NCOM::CPropVariant propVariant; propVariant = bench.Name; - RINOK(method.ParseMethodFromPROPVARIANT(UString(), propVariant)); + RINOK(method.ParseMethodFromPROPVARIANT(UString(), propVariant)) UInt64 speed, usage; - HRESULT res = CrcBench( + const HRESULT res = CrcBench( EXTERNAL_CODECS_LOC_VARS complexInCommands, numThreads, bufSize, fileData, @@ -3430,7 +3542,7 @@ (!fileData && bufSize == (1 << kNumHashDictBits)) ? &bench.CheckSum : NULL, method, printCallback, - #ifndef _7ZIP_ST + #ifndef Z7_ST affinityMode, #endif true, // showRating @@ -3441,7 +3553,7 @@ } else { - RINOK(res); + RINOK(res) } callback->NewLine(); } @@ -3451,7 +3563,8 @@ struct CTempValues { UInt64 *Values; - CTempValues(UInt32 num) { Values = new UInt64[num]; } + CTempValues(): Values(NULL) {} + void Alloc(UInt32 num) { Values = new UInt64[num]; } ~CTempValues() { delete []Values; } }; @@ -3482,6 +3595,29 @@ } +static void Print_Delimiter(IBenchPrintCallback &f) +{ + f.Print(" |"); +} + +static void Print_Pow(IBenchPrintCallback &f, unsigned pow) +{ + char s[16]; + ConvertUInt32ToString(pow, s); + unsigned pos = MyStringLen(s); + s[pos++] = ':'; + s[pos] = 0; + PrintLeft(f, s, kFieldSize_SmallName); // 4 +} + +static void Bench_BW_Print_Usage_Speed(IBenchPrintCallback &f, + UInt64 usage, UInt64 speed) +{ + PrintUsage(f, usage, kFieldSize_Usage); + PrintNumber(f, speed / 1000000, kFieldSize_CrcSpeed); +} + + HRESULT Bench( DECL_EXTERNAL_CODECS_LOC_VARS IBenchPrintCallback *printCallback, @@ -3500,7 +3636,7 @@ NSystem::CProcessAffinity threadsInfo; threadsInfo.InitST(); - #ifndef _7ZIP_ST + #ifndef Z7_ST if (threadsInfo.Get() && threadsInfo.GetNumProcessThreads() != 0) numCPUs = threadsInfo.GetNumProcessThreads(); @@ -3533,7 +3669,7 @@ UInt64 complexInCommands = kComplexInCommands; UInt32 numThreads_Start = 1; - #ifndef _7ZIP_ST + #ifndef Z7_ST CAffinityMode affinityMode; #endif @@ -3597,7 +3733,7 @@ // (len == 0) is allowed. Also it's allowed if Alloc(0) returns NULL here - ALLOC_WITH_HRESULT(&fileDataBuffer, len); + ALLOC_WITH_HRESULT(&fileDataBuffer, len) use_fileData = true; { @@ -3616,7 +3752,7 @@ if (name.IsEqualTo("time")) { - RINOK(ParsePropToUInt32(UString(), propVariant, testTimeMs)); + RINOK(ParsePropToUInt32(UString(), propVariant, testTimeMs)) needSetComplexity = true; testTimeMs *= 1000; continue; @@ -3624,7 +3760,7 @@ if (name.IsEqualTo("timems")) { - RINOK(ParsePropToUInt32(UString(), propVariant, testTimeMs)); + RINOK(ParsePropToUInt32(UString(), propVariant, testTimeMs)) needSetComplexity = true; continue; } @@ -3632,7 +3768,7 @@ if (name.IsEqualTo("tic")) { UInt32 v; - RINOK(ParsePropToUInt32(UString(), propVariant, v)); + RINOK(ParsePropToUInt32(UString(), propVariant, v)) if (v >= 64) return E_INVALIDARG; complexInCommands = (UInt64)1 << v; @@ -3644,7 +3780,7 @@ isFixedDict = true; if (isCurrent_fixedDict || name.IsEqualTo("ds")) { - RINOK(ParsePropToUInt32(UString(), propVariant, startDicLog)); + RINOK(ParsePropToUInt32(UString(), propVariant, startDicLog)) if (startDicLog > 32) return E_INVALIDARG; startDicLog_Defined = true; @@ -3653,17 +3789,17 @@ if (name.IsEqualTo("mts")) { - RINOK(ParsePropToUInt32(UString(), propVariant, numThreads_Start)); + RINOK(ParsePropToUInt32(UString(), propVariant, numThreads_Start)) continue; } if (name.IsEqualTo("af")) { UInt32 bundle; - RINOK(ParsePropToUInt32(UString(), propVariant, bundle)); + RINOK(ParsePropToUInt32(UString(), propVariant, bundle)) if (bundle > 0 && bundle < numCPUs) { - #ifndef _7ZIP_ST + #ifndef Z7_ST affinityMode.SetLevels(numCPUs, 2); affinityMode.NumBundleThreads = bundle; #endif @@ -3674,7 +3810,7 @@ if (name.IsEqualTo("freq")) { UInt32 freq32 = 0; - RINOK(ParsePropToUInt32(UString(), propVariant, freq32)); + RINOK(ParsePropToUInt32(UString(), propVariant, freq32)) if (freq32 == 0) return E_INVALIDARG; specifiedFreq = (UInt64)freq32 * 1000000; @@ -3691,7 +3827,7 @@ if (name.IsPrefixedBy_Ascii_NoCase("mt")) { - UString s = name.Ptr(2); + const UString s = name.Ptr(2); if (s.IsEqualTo("*") || (s.IsEmpty() && propVariant.vt == VT_BSTR @@ -3700,13 +3836,13 @@ multiThreadTests = true; continue; } - #ifndef _7ZIP_ST - RINOK(ParseMtProp(s, propVariant, numCPUs, numThreadsSpecified)); + #ifndef Z7_ST + RINOK(ParseMtProp(s, propVariant, numCPUs, numThreadsSpecified)) #endif continue; } - RINOK(method.ParseMethodFromPROPVARIANT(name, propVariant)); + RINOK(method.ParseMethodFromPROPVARIANT(name, propVariant)) } } @@ -3714,13 +3850,13 @@ { AString s; - #ifndef _WIN32 + #ifndef _WIN32 s += "Compiler: "; GetCompiler(s); printCallback->Print(s); printCallback->NewLine(); s.Empty(); - #endif + #endif GetSystemInfoText(s); printCallback->Print(s); @@ -3744,7 +3880,7 @@ for (int jj = 0;; jj++) { if (printCallback) - RINOK(printCallback->CheckBreak()); + RINOK(printCallback->CheckBreak()) UInt64 start = ::GetTimeCount(); UInt32 sum = (UInt32)start; @@ -3776,7 +3912,7 @@ } if (freqCallback) { - RINOK(freqCallback->AddCpuFreq(1, hz, kBenchmarkUsageMult)); + RINOK(freqCallback->AddCpuFreq(1, hz, kBenchmarkUsageMult)) } if (jj >= 1) @@ -3806,7 +3942,7 @@ } if (freqCallback) { - RINOK(freqCallback->FreqsFinished(1)); + RINOK(freqCallback->FreqsFinished(1)) } } @@ -3830,17 +3966,24 @@ printCallback->Print(s); printCallback->Print("T CPU Freq (MHz):"); } - UInt64 numMilCommands = 1 << 10; + UInt64 numMilCommands = 1 << + #ifdef _DEBUG + 7; + #else + 10; + #endif + if (specifiedFreq != 0) { while (numMilCommands > 1 && specifiedFreq < (numMilCommands * 1000000)) numMilCommands >>= 1; } - for (int jj = 0;; jj++) + // for (int jj = 0;; jj++) + for (;;) { if (printCallback) - RINOK(printCallback->CheckBreak()); + RINOK(printCallback->CheckBreak()) { // PrintLeft(f, "CPU", kFieldSize_Name); @@ -3855,16 +3998,16 @@ fb.showFreq = true; fb.specifiedFreq = 1; - HRESULT res = fb.FreqBench(NULL /* printCallback */ - #ifndef _7ZIP_ST + const HRESULT res = fb.FreqBench(NULL /* printCallback */ + #ifndef Z7_ST , &affinityMode #endif ); - RINOK(res); + RINOK(res) if (freqCallback) { - RINOK(freqCallback->AddCpuFreq(numThreads, fb.CpuFreqRes, fb.UsageRes)); + RINOK(freqCallback->AddCpuFreq(numThreads, fb.CpuFreqRes, fb.UsageRes)) } if (printCallback) @@ -3889,7 +4032,7 @@ } // if (jj >= 1) { - bool needStop = (numMilCommands >= (1 << + const bool needStop = (numMilCommands >= (1 << #ifdef _DEBUG 7 #else @@ -3903,7 +4046,7 @@ } if (freqCallback) { - RINOK(freqCallback->FreqsFinished(numThreads)); + RINOK(freqCallback->FreqsFinished(numThreads)) } } @@ -3923,10 +4066,12 @@ UInt64 dict = (UInt64)1 << startDicLog; const bool dictIsDefined = (isFixedDict || method.Get_DicSize(dict)); - const int level = method.GetLevel(); + const unsigned level = method.GetLevel(); - if (method.MethodName.IsEmpty()) - method.MethodName = "LZMA"; + AString &methodName = method.MethodName; + const AString original_MethodName = methodName; + if (methodName.IsEmpty()) + methodName = "LZMA"; if (benchCallback) { @@ -3949,7 +4094,7 @@ return MethodBench( EXTERNAL_CODECS_LOC_VARS complexInCommands, - #ifndef _7ZIP_ST + #ifndef Z7_ST true, numThreadsSpecified, &affinityMode, #endif @@ -3958,13 +4103,28 @@ kOldLzmaDictBits, printCallback, benchCallback, &benchProps); } - AString methodName (method.MethodName); if (methodName.IsEqualTo_Ascii_NoCase("CRC")) methodName = "crc32"; - method.MethodName = methodName; + CMethodId hashID; - - if (FindHashMethod(EXTERNAL_CODECS_LOC_VARS methodName, hashID)) + const bool isHashMethod = FindHashMethod(EXTERNAL_CODECS_LOC_VARS methodName, hashID); + int codecIndex = -1; + bool isFilter = false; + if (!isHashMethod) + { + UInt32 numStreams; + codecIndex = FindMethod_Index(EXTERNAL_CODECS_LOC_VARS original_MethodName, + true, // encode + hashID, numStreams, isFilter); + // we can allow non filter for BW tests + if (!isFilter) codecIndex = -1; + } + + CBenchCallbackToPrint callback; + callback.Init(); + callback._file = printCallback; + + if (isHashMethod || codecIndex != -1) { if (!printCallback) return S_FALSE; @@ -3981,17 +4141,27 @@ dict64 = fileDataBuffer.Size(); } - // methhodName.RemoveChar(L'-'); - UInt32 complexity = 10000; + for (;;) + { + const int index = method.FindProp(NCoderPropID::kDictionarySize); + if (index < 0) + break; + method.Props.Delete((unsigned)index); + } + + // methodName.RemoveChar(L'-'); + Int32 complexity = 16 * k_Hash_Complex_Mult; // for unknown hash method const UInt32 *checkSum = NULL; + int benchIndex = -1; + + if (isHashMethod) { - unsigned i; - for (i = 0; i < ARRAY_SIZE(g_Hash); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Hash); i++) { const CBenchHash &h = g_Hash[i]; AString benchMethod (h.Name); AString benchProps; - int propPos = benchMethod.Find(':'); + const int propPos = benchMethod.Find(':'); if (propPos >= 0) { benchProps = benchMethod.Ptr((unsigned)(propPos + 1)); @@ -4000,45 +4170,80 @@ if (AreSameMethodNames(benchMethod, methodName)) { - bool isMainMathed = method.PropsString.IsEmpty(); - if (isMainMathed) - isMainMathed = !checkSum - || (benchMethod.IsEqualTo_Ascii_NoCase("crc32") && benchProps.IsEqualTo_Ascii_NoCase("8")); const bool sameProps = method.PropsString.IsEqualTo_Ascii_NoCase(benchProps); - if (sameProps || isMainMathed) + /* + bool isMainMethod = method.PropsString.IsEmpty(); + if (isMainMethod) + isMainMethod = !checkSum + || (benchMethod.IsEqualTo_Ascii_NoCase("crc32") && benchProps.IsEqualTo_Ascii_NoCase("8")); + if (sameProps || isMainMethod) + */ { - complexity = h.Complex; + complexity = (Int32)h.Complex; checkSum = &h.CheckSum; if (sameProps) break; + /* + if property. is not specified, we use the complexity + for latest fastest method (crc32:64) + */ } } } - if (!checkSum) - return E_NOTIMPL; + // if (!checkSum) return E_NOTIMPL; + } + else + { + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Bench); i++) + { + const CBenchMethod &bench = g_Bench[i]; + AString benchMethod (bench.Name); + AString benchProps; + const int propPos = benchMethod.Find(':'); + if (propPos >= 0) + { + benchProps = benchMethod.Ptr((unsigned)(propPos + 1)); + benchMethod.DeleteFrom((unsigned)propPos); + } + + if (AreSameMethodNames(benchMethod, methodName)) + { + const bool sameProps = method.PropsString.IsEqualTo_Ascii_NoCase(benchProps); + // bool isMainMethod = method.PropsString.IsEmpty(); + // if (sameProps || isMainMethod) + { + benchIndex = (int)i; + if (sameProps) + break; + } + } + } + // if (benchIndex < 0) return E_NOTIMPL; } { - UInt64 usage = 1 << 20; + /* we count usage only for crc and filter. non-filters are not supported */ + UInt64 usage = (1 << 20); UInt64 bufSize = dict64; + UInt32 numBlocks = isHashMethod ? 1 : 3; if (use_fileData) { usage += fileDataBuffer.Size(); if (bufSize > fileDataBuffer.Size()) bufSize = fileDataBuffer.Size(); - #ifndef _7ZIP_ST - if (numThreadsSpecified != 1) - usage += bufSize * numThreadsSpecified * (k_Crc_CreateLocalBuf_For_File ? 1 : 0); - #endif + if (isHashMethod) + { + numBlocks = 0; + #ifndef Z7_ST + if (numThreadsSpecified != 1) + numBlocks = (k_Crc_CreateLocalBuf_For_File ? 1 : 0); + #endif + } } - else - usage += numThreadsSpecified * bufSize; + usage += numThreadsSpecified * bufSize * numBlocks; Print_Usage_and_Threads(f, usage, numThreadsSpecified); } - - f.NewLine(); - - const unsigned kFieldSize_CrcSpeed = 7; + CUIntVector numThreadsVector; { unsigned nt = numThreads_Start; @@ -4047,136 +4252,225 @@ if (nt > numThreadsSpecified) break; numThreadsVector.Add(nt); - unsigned next = nt * 2; - UInt32 ntHalf= numThreadsSpecified / 2; + const unsigned next = nt * 2; + const UInt32 ntHalf= numThreadsSpecified / 2; if (ntHalf > nt && ntHalf < next) numThreadsVector.Add(ntHalf); if (numThreadsSpecified > nt && numThreadsSpecified < next) numThreadsVector.Add(numThreadsSpecified); nt = next; } + } + + unsigned numColumns = isHashMethod ? 1 : 2; + CTempValues speedTotals; + CTempValues usageTotals; + { + const unsigned numItems = numThreadsVector.Size() * numColumns; + speedTotals.Alloc(numItems); + usageTotals.Alloc(numItems); + for (unsigned i = 0; i < numItems; i++) { - f.NewLine(); - f.Print("THRD"); - FOR_VECTOR (ti, numThreadsVector) - { - PrintNumber(f, numThreadsVector[ti], 1 + kFieldSize_Usage + kFieldSize_CrcSpeed); - } + speedTotals.Values[i] = 0; + usageTotals.Values[i] = 0; } + } + + f.NewLine(); + for (unsigned line = 0; line < 3; line++) + { + f.NewLine(); + f.Print(line == 0 ? "THRD" : line == 1 ? " " : "Size"); + FOR_VECTOR (ti, numThreadsVector) { - f.NewLine(); - f.Print(" "); - FOR_VECTOR (ti, numThreadsVector) + if (ti != 0) + Print_Delimiter(f); + if (line == 0) { - PrintRight(f, "Usage", kFieldSize_Usage + 1); - PrintRight(f, "BW", kFieldSize_CrcSpeed + 1); + PrintSpaces(f, (kFieldSize_CrcSpeed + kFieldSize_Usage + 2) * (numColumns - 1)); + PrintNumber(f, numThreadsVector[ti], 1 + kFieldSize_Usage + kFieldSize_CrcSpeed); } - } - { - f.NewLine(); - f.Print("Size"); - FOR_VECTOR (ti, numThreadsVector) + else { - PrintRight(f, "%", kFieldSize_Usage + 1); - PrintRight(f, "MB/s", kFieldSize_CrcSpeed + 1); + for (unsigned c = 0; c < numColumns; c++) + { + PrintRight(f, line == 1 ? "Usage" : "%", kFieldSize_Usage + 1); + PrintRight(f, line == 1 ? "BW" : "MB/s", kFieldSize_CrcSpeed + 1); + } } } } - - f.NewLine(); f.NewLine(); - CTempValues speedTotals(numThreadsVector.Size()); - CTempValues usageTotals(numThreadsVector.Size()); - { - FOR_VECTOR (ti, numThreadsVector) - { - speedTotals.Values[ti] = 0; - usageTotals.Values[ti] = 0; - } - } - UInt64 numSteps = 0; - for (UInt32 i = 0; i < numIterations; i++) - { - unsigned pow = 10; // kNumHashDictBits - if (startDicLog_Defined) - pow = startDicLog; - for (;; pow++) - { - const UInt64 bufSize = (UInt64)1 << pow; - char s[16]; - ConvertUInt32ToString(pow, s); - unsigned pos = MyStringLen(s); - s[pos++] = ':'; - s[pos++] = ' '; - s[pos] = 0; - PrintRight(f, s, 4); - - size_t dataSize = fileDataBuffer.Size(); - if (dataSize > bufSize || !use_fileData) - dataSize = (size_t)bufSize; - + // for (UInt32 iter = 0; iter < numIterations; iter++) + // { + unsigned pow = 10; // kNumHashDictBits + if (startDicLog_Defined) + pow = startDicLog; + + // #define NUM_SUB_BITS 2 + // pow <<= NUM_SUB_BITS; + for (;; pow++) + { + const UInt64 bufSize = (UInt64)1 << pow; + // UInt64 bufSize = (UInt64)1 << (pow >> NUM_SUB_BITS); + // bufSize += ((UInt64)pow & ((1 << NUM_SUB_BITS) - 1)) << ((pow >> NUM_SUB_BITS) - NUM_SUB_BITS); + + size_t dataSize = fileDataBuffer.Size(); + if (dataSize > bufSize || !use_fileData) + dataSize = (size_t)bufSize; + + for (UInt32 iter = 0; iter < numIterations; iter++) + { + Print_Pow(f, pow); + // PrintNumber(f, bufSize >> 10, 4); + FOR_VECTOR (ti, numThreadsVector) { - RINOK(f.CheckBreak()); - const UInt32 t = numThreadsVector[ti]; - UInt64 speed = 0; - UInt64 usage = 0; - - HRESULT res = CrcBench(EXTERNAL_CODECS_LOC_VARS complexInCommands, - t, + RINOK(f.CheckBreak()) + const UInt32 numThreads = numThreadsVector[ti]; + if (isHashMethod) + { + UInt64 speed = 0; + UInt64 usage = 0; + const HRESULT res = CrcBench(EXTERNAL_CODECS_LOC_VARS complexInCommands, + numThreads, dataSize, (const Byte *)fileDataBuffer, speed, usage, - complexity, + (UInt32)complexity, 1, // benchWeight, (pow == kNumHashDictBits && !use_fileData) ? checkSum : NULL, method, &f, - #ifndef _7ZIP_ST + #ifndef Z7_ST &affinityMode, #endif false, // showRating NULL, false, 0); - - RINOK(res); - - PrintUsage(f, usage, kFieldSize_Usage); - PrintNumber(f, speed / 1000000, kFieldSize_CrcSpeed); - speedTotals.Values[ti] += speed; - usageTotals.Values[ti] += usage; + RINOK(res) + + if (ti != 0) + Print_Delimiter(f); + + Bench_BW_Print_Usage_Speed(f, usage, speed); + speedTotals.Values[ti] += speed; + usageTotals.Values[ti] += usage; + } + else + { + { + unsigned keySize = 32; + if (IsString1PrefixedByString2(methodName, "AES128")) keySize = 16; + else if (IsString1PrefixedByString2(methodName, "AES192")) keySize = 24; + callback.BenchProps.KeySize = keySize; + } + + COneMethodInfo method2 = method; + unsigned bench_DictBits; + + if (benchIndex >= 0) + { + const CBenchMethod &bench = g_Bench[benchIndex]; + callback.BenchProps.EncComplex = bench.EncComplex; + callback.BenchProps.DecComplexUnc = bench.DecComplexUnc; + callback.BenchProps.DecComplexCompr = bench.DecComplexCompr; + bench_DictBits = bench.DictBits; + // bench_DictBits = kOldLzmaDictBits; = 32 default : for debug + } + else + { + bench_DictBits = kOldLzmaDictBits; // = 32 default + if (isFilter) + { + const unsigned k_UnknownCoderComplexity = 4; + callback.BenchProps.EncComplex = k_UnknownCoderComplexity; + callback.BenchProps.DecComplexUnc = k_UnknownCoderComplexity; + } + else + { + callback.BenchProps.EncComplex = 1 << 10; + callback.BenchProps.DecComplexUnc = 1 << 6; + } + callback.BenchProps.DecComplexCompr = 0; + } + callback.NeedPrint = false; + + if (StringsAreEqualNoCase_Ascii(method2.MethodName, "LZMA")) + { + const NCOM::CPropVariant propVariant = (UInt32)pow; + RINOK(method2.ParseMethodFromPROPVARIANT((UString)"d", propVariant)) + } + + const HRESULT res = MethodBench( + EXTERNAL_CODECS_LOC_VARS + complexInCommands, + #ifndef Z7_ST + false, // oldLzmaBenchMode + numThreadsVector[ti], + &affinityMode, + #endif + method2, + dataSize, (const Byte *)fileDataBuffer, + bench_DictBits, + printCallback, + &callback, + &callback.BenchProps); + RINOK(res) + + if (ti != 0) + Print_Delimiter(f); + + for (unsigned i = 0; i < 2; i++) + { + const CBenchInfo &bi = callback.BenchInfo_Results[i]; + const UInt64 usage = bi.GetUsage(); + const UInt64 speed = bi.GetUnpackSizeSpeed(); + usageTotals.Values[ti * 2 + i] += usage; + speedTotals.Values[ti * 2 + i] += speed; + Bench_BW_Print_Usage_Speed(f, usage, speed); + } + } } f.NewLine(); numSteps++; - if (dataSize >= dict64) - break; } + if (dataSize >= dict64) + break; } + if (numSteps != 0) { - f.NewLine(); f.Print("Avg:"); for (unsigned ti = 0; ti < numThreadsVector.Size(); ti++) { - PrintUsage(f, usageTotals.Values[ti] / numSteps, kFieldSize_Usage); - PrintNumber(f, speedTotals.Values[ti] / numSteps / 1000000, kFieldSize_CrcSpeed); + if (ti != 0) + Print_Delimiter(f); + for (unsigned i = 0; i < numColumns; i++) + Bench_BW_Print_Usage_Speed(f, + usageTotals.Values[ti * numColumns + i] / numSteps, + speedTotals.Values[ti * numColumns + i] / numSteps); } f.NewLine(); } + return S_OK; } bool use2Columns = false; - bool totalBenchMode = (method.MethodName.IsEqualTo_Ascii_NoCase("*")); + bool totalBenchMode = false; bool onlyHashBench = false; - if (method.MethodName.IsEqualTo_Ascii_NoCase("hash")) + if (methodName.IsEqualTo_Ascii_NoCase("hash")) { onlyHashBench = true; + methodName = "*"; totalBenchMode = true; } + else if (methodName.Find('*') >= 0) + totalBenchMode = true; // ---------- Threads loop ---------- for (unsigned threadsPassIndex = 0; threadsPassIndex < 3; threadsPassIndex++) @@ -4207,10 +4501,6 @@ } } - CBenchCallbackToPrint callback; - callback.Init(); - callback._file = printCallback; - IBenchPrintCallback &f = *printCallback; if (threadsPassIndex > 0) @@ -4230,7 +4520,7 @@ if (ramSize_Defined) for (; dicSizeLog > kBenchMinDicLogSize; dicSizeLog--) - if (GetBenchMemoryUsage(numThreads, level, ((UInt64)1 << dicSizeLog), totalBenchMode) + (8 << 20) <= ramSize) + if (GetBenchMemoryUsage(numThreads, (int)level, ((UInt64)1 << dicSizeLog), totalBenchMode) + (8 << 20) <= ramSize) break; dict = (UInt64)1 << dicSizeLog; @@ -4246,7 +4536,7 @@ Print_Usage_and_Threads(f, onlyHashBench ? GetBenchMemoryUsage_Hash(numThreads, dict) : - GetBenchMemoryUsage(numThreads, level, dict, totalBenchMode), + GetBenchMemoryUsage(numThreads, (int)level, dict, totalBenchMode), numThreads); f.NewLine(); @@ -4355,12 +4645,12 @@ fb.showFreq = (freqTest == kNumCpuTests - 1 || specifiedFreq != 0); fb.specifiedFreq = specifiedFreq; - HRESULT res = fb.FreqBench(printCallback - #ifndef _7ZIP_ST + const HRESULT res = fb.FreqBench(printCallback + #ifndef Z7_ST , &affinityMode #endif ); - RINOK(res); + RINOK(res) cpuFreq = fb.CpuFreqRes; callback.NewLine(); @@ -4390,9 +4680,9 @@ dataSize = (size_t)dict; } - HRESULT res = TotalBench(EXTERNAL_CODECS_LOC_VARS - complexInCommands, - #ifndef _7ZIP_ST + const HRESULT res = TotalBench(EXTERNAL_CODECS_LOC_VARS + method, complexInCommands, + #ifndef Z7_ST numThreads, &affinityMode, #endif @@ -4400,7 +4690,7 @@ dataSize, (const Byte *)fileDataBuffer, printCallback, &callback); - RINOK(res); + RINOK(res) } { @@ -4418,14 +4708,16 @@ dataSize = (size_t)dict; } - HRESULT res = TotalBench_Hash(EXTERNAL_CODECS_LOC_VARS complexInCommands, numThreads, + const HRESULT res = TotalBench_Hash(EXTERNAL_CODECS_LOC_VARS + method, complexInCommands, + numThreads, dataSize, (const Byte *)fileDataBuffer, printCallback, &callback, - #ifndef _7ZIP_ST + #ifndef Z7_ST &affinityMode, #endif &callback.EncodeRes, true, cpuFreq); - RINOK(res); + RINOK(res) } callback.NewLine(); @@ -4439,12 +4731,12 @@ fb.showFreq = (specifiedFreq != 0); fb.specifiedFreq = specifiedFreq; - HRESULT res = fb.FreqBench(printCallback - #ifndef _7ZIP_ST + const HRESULT res = fb.FreqBench(printCallback + #ifndef Z7_ST , &affinityMode #endif ); - RINOK(res); + RINOK(res) callback.NewLine(); } } @@ -4455,12 +4747,12 @@ if (!methodName.IsEqualTo_Ascii_NoCase("LZMA")) { unsigned i; - for (i = 0; i < ARRAY_SIZE(g_Bench); i++) + for (i = 0; i < Z7_ARRAY_SIZE(g_Bench); i++) { const CBenchMethod &h = g_Bench[i]; AString benchMethod (h.Name); AString benchProps; - int propPos = benchMethod.Find(':'); + const int propPos = benchMethod.Find(':'); if (propPos >= 0) { benchProps = benchMethod.Ptr((unsigned)(propPos + 1)); @@ -4475,14 +4767,16 @@ { callback.BenchProps.EncComplex = h.EncComplex; callback.BenchProps.DecComplexCompr = h.DecComplexCompr; - callback.BenchProps.DecComplexUnc = h.DecComplexUnc;; + callback.BenchProps.DecComplexUnc = h.DecComplexUnc; needSetComplexity = false; break; } } } - if (i == ARRAY_SIZE(g_Bench)) + /* + if (i == Z7_ARRAY_SIZE(g_Bench)) return E_NOTIMPL; + */ } if (needSetComplexity) callback.BenchProps.SetLzmaCompexity(); @@ -4499,12 +4793,7 @@ pow--; for (; GetDictSizeFromLog(pow) <= dict; pow++) { - char s[16]; - ConvertUInt32ToString(pow, s); - unsigned pos = MyStringLen(s); - s[pos++] = ':'; - s[pos] = 0; - PrintLeft(f, s, kFieldSize_SmallName); + Print_Pow(f, pow); callback.DictSize = (UInt64)1 << pow; COneMethodInfo method2 = method; @@ -4515,7 +4804,7 @@ // method2 can have two different dictionary size properties. // And last property is main. NCOM::CPropVariant propVariant = (UInt32)pow; - RINOK(method2.ParseMethodFromPROPVARIANT((UString)"d", propVariant)); + RINOK(method2.ParseMethodFromPROPVARIANT((UString)"d", propVariant)) } size_t uncompressedDataSize; @@ -4532,10 +4821,10 @@ uncompressedDataSize += kAdditionalSize; } - HRESULT res = MethodBench( + const HRESULT res = MethodBench( EXTERNAL_CODECS_LOC_VARS complexInCommands, - #ifndef _7ZIP_ST + #ifndef Z7_ST true, numThreads, &affinityMode, #endif @@ -4543,7 +4832,7 @@ uncompressedDataSize, (const Byte *)fileDataBuffer, kOldLzmaDictBits, printCallback, &callback, &callback.BenchProps); f.NewLine(); - RINOK(res); + RINOK(res) if (!multiDict) break; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/Bench.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/Bench.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/Bench.h 2021-07-15 08:35:51.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/Bench.h 2023-04-06 08:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Bench.h -#ifndef __7ZIP_BENCH_H -#define __7ZIP_BENCH_H +#ifndef ZIP7_INC_7ZIP_BENCH_H +#define ZIP7_INC_7ZIP_BENCH_H #include "../../../Windows/System.h" @@ -71,32 +71,31 @@ }; +const unsigned kBenchMinDicLogSize = 18; + +UInt64 GetBenchMemoryUsage(UInt32 numThreads, int level, UInt64 dictionary, bool totalBench); -struct IBenchCallback +Z7_PURE_INTERFACES_BEGIN +DECLARE_INTERFACE(IBenchCallback) { // virtual HRESULT SetFreq(bool showFreq, UInt64 cpuFreq) = 0; virtual HRESULT SetEncodeResult(const CBenchInfo &info, bool final) = 0; virtual HRESULT SetDecodeResult(const CBenchInfo &info, bool final) = 0; }; - - -const unsigned kBenchMinDicLogSize = 18; - -UInt64 GetBenchMemoryUsage(UInt32 numThreads, int level, UInt64 dictionary, bool totalBench); - -struct IBenchPrintCallback +DECLARE_INTERFACE(IBenchPrintCallback) { virtual void Print(const char *s) = 0; virtual void NewLine() = 0; virtual HRESULT CheckBreak() = 0; }; -struct IBenchFreqCallback +DECLARE_INTERFACE(IBenchFreqCallback) { virtual HRESULT AddCpuFreq(unsigned numThreads, UInt64 freq, UInt64 usage) = 0; virtual HRESULT FreqsFinished(unsigned numThreads) = 0; }; +Z7_PURE_INTERFACES_END HRESULT Bench( DECL_EXTERNAL_CODECS_LOC_VARS @@ -113,7 +112,7 @@ void GetCpuName(AString &s); void AddCpuFeatures(AString &s); -#ifdef _7ZIP_LARGE_PAGES +#ifdef Z7_LARGE_PAGES void Add_LargePages_String(AString &s); #else // #define Add_LargePages_String diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/CompressCall2.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/CompressCall2.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/CompressCall2.cpp 2022-06-06 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/CompressCall2.cpp 2023-01-29 17:00:00.000000000 +0000 @@ -2,6 +2,8 @@ #include "StdAfx.h" +#ifndef Z7_EXTERNAL_CODECS + #include "../../../Common/MyException.h" #include "../../UI/Common/EnumDirItems.h" @@ -33,7 +35,7 @@ throw CSystemException(res); } -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS #define CREATE_CODECS \ CCodecs *codecs = new CCodecs; \ @@ -42,10 +44,10 @@ Codecs_AddHashArcHandler(codecs); #define LOAD_EXTERNAL_CODECS \ - CExternalCodecs __externalCodecs; \ - __externalCodecs.GetCodecs = codecs; \ - __externalCodecs.GetHashers = codecs; \ - ThrowException_if_Error(__externalCodecs.Load()); + CExternalCodecs _externalCodecs; \ + _externalCodecs.GetCodecs = codecs; \ + _externalCodecs.GetHashers = codecs; \ + ThrowException_if_Error(_externalCodecs.Load()); #else @@ -321,3 +323,5 @@ MY_TRY_FINISH } + +#endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/CompressCall.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/CompressCall.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/CompressCall.cpp 2022-05-26 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/CompressCall.cpp 2023-04-06 08:00:00.000000000 +0000 @@ -83,7 +83,7 @@ const WRes wres = process.Create(imageName, params, NULL); // curDir); if (wres != 0) { - HRESULT hres = HRESULT_FROM_WIN32(wres); + const HRESULT hres = HRESULT_FROM_WIN32(wres); ErrorMessageHRESULT(hres, imageName); return hres; } @@ -92,7 +92,7 @@ else if (event != NULL) { HANDLE handles[] = { process, *event }; - ::WaitForMultipleObjects(ARRAY_SIZE(handles), handles, FALSE, INFINITE); + ::WaitForMultipleObjects(Z7_ARRAY_SIZE(handles), handles, FALSE, INFINITE); } return S_OK; } @@ -175,7 +175,7 @@ FOR_VECTOR (i, names) { const UString &s = names[i]; - unsigned len = s.Len() + 1; + const unsigned len = s.Len() + 1; wmemcpy(cur, (const wchar_t *)s, len); cur += len; } @@ -197,7 +197,7 @@ CFileMapping fileMapping; NSynchronization::CManualResetEvent event; params += kIncludeSwitch; - RINOK(CreateMap(names, fileMapping, event, params)); + RINOK(CreateMap(names, fileMapping, event, params)) if (!arcType.IsEmpty()) { @@ -336,7 +336,7 @@ if (totalMode) params += " -mm=*"; AddLagePagesSwitch(params); - HRESULT result = Call7zGui(params, false, NULL); + const HRESULT result = Call7zGui(params, false, NULL); if (result != S_OK) ErrorMessageHRESULT(result); MY_TRY_FINISH_VOID diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/CompressCall.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/CompressCall.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/CompressCall.h 2022-05-26 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/CompressCall.h 2023-01-10 18:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // CompressCall.h -#ifndef __COMPRESS_CALL_H -#define __COMPRESS_CALL_H +#ifndef ZIP7_INC_COMPRESS_CALL_H +#define ZIP7_INC_COMPRESS_CALL_H #include "../../../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/DefaultName.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/DefaultName.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/DefaultName.h 2013-01-17 09:52:29.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/DefaultName.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // DefaultName.h -#ifndef __DEFAULT_NAME_H -#define __DEFAULT_NAME_H +#ifndef ZIP7_INC_DEFAULT_NAME_H +#define ZIP7_INC_DEFAULT_NAME_H #include "../../../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/DirItem.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/DirItem.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/DirItem.h 2022-05-13 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/DirItem.h 2023-02-01 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // DirItem.h -#ifndef __DIR_ITEM_H -#define __DIR_ITEM_H +#ifndef ZIP7_INC_DIR_ITEM_H +#define ZIP7_INC_DIR_ITEM_H #ifdef _WIN32 #include "../../../Common/MyLinux.h" @@ -72,15 +72,15 @@ }; +Z7_PURE_INTERFACES_BEGIN -#define INTERFACE_IDirItemsCallback(x) \ - virtual HRESULT ScanError(const FString &path, DWORD systemError) x; \ - virtual HRESULT ScanProgress(const CDirItemsStat &st, const FString &path, bool isDir) x; \ +#define Z7_IFACEN_IDirItemsCallback(x) \ + virtual HRESULT ScanError(const FString &path, DWORD systemError) x \ + virtual HRESULT ScanProgress(const CDirItemsStat &st, const FString &path, bool isDir) x \ -struct IDirItemsCallback -{ - INTERFACE_IDirItemsCallback(=0) -}; +Z7_IFACE_DECL_PURE(IDirItemsCallback) + +Z7_PURE_INTERFACES_END struct CArcTime diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/EnumDirItems.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/EnumDirItems.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/EnumDirItems.cpp 2022-06-27 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/EnumDirItems.cpp 2023-05-06 05:00:00.000000000 +0000 @@ -18,7 +18,7 @@ #include "../../../Windows/FileName.h" #if defined(_WIN32) && !defined(UNDER_CE) -#define _USE_SECURITY_CODE +#define Z7_USE_SECURITY_CODE #include "../../../Windows/SecurityUtils.h" #endif @@ -183,7 +183,7 @@ , ExcludeDirItems(false) , ExcludeFileItems(false) , ShareForWrite(false) - #ifdef _USE_SECURITY_CODE + #ifdef Z7_USE_SECURITY_CODE , ReadSecure(false) #endif #ifndef _WIN32 @@ -191,13 +191,13 @@ #endif , Callback(NULL) { - #ifdef _USE_SECURITY_CODE + #ifdef Z7_USE_SECURITY_CODE _saclEnabled = InitLocalPrivileges(); #endif } -#ifdef _USE_SECURITY_CODE +#ifdef Z7_USE_SECURITY_CODE HRESULT CDirItems::AddSecurityItem(const FString &path, int &secureIndex) { @@ -236,7 +236,7 @@ if (res) { if (secureSize != TempSecureBuf.Size()) - errorCode = ERROR_INVALID_FUNCTION;; + errorCode = ERROR_INVALID_FUNCTION; } else errorCode = GetLastError(); @@ -253,7 +253,7 @@ return AddError(path, errorCode); } -#endif // _USE_SECURITY_CODE +#endif // Z7_USE_SECURITY_CODE HRESULT CDirItems::EnumerateOneDir(const FString &phyPrefix, CObjectVector &files) @@ -277,7 +277,7 @@ files.Add(fi); if (Callback && (ttt & kScanProgressStepMask) == kScanProgressStepMask) { - RINOK(ScanProgress(phyPrefix)); + RINOK(ScanProgress(phyPrefix)) } } @@ -309,7 +309,7 @@ { const FString path = phyPrefix + de.Name; { - RINOK(AddError(path)); + RINOK(AddError(path)) continue; } } @@ -318,7 +318,7 @@ if (Callback && (i & kScanProgressStepMask) == kScanProgressStepMask) { - RINOK(ScanProgress(phyPrefix)); + RINOK(ScanProgress(phyPrefix)) } } @@ -332,10 +332,10 @@ HRESULT CDirItems::EnumerateDir(int phyParent, int logParent, const FString &phyPrefix) { - RINOK(ScanProgress(phyPrefix)); + RINOK(ScanProgress(phyPrefix)) CObjectVector files; - RINOK(EnumerateOneDir(phyPrefix, files)); + RINOK(EnumerateOneDir(phyPrefix, files)) FOR_VECTOR (i, files) { @@ -361,10 +361,10 @@ if (CanIncludeItem(fi.IsDir())) { int secureIndex = -1; - #ifdef _USE_SECURITY_CODE + #ifdef Z7_USE_SECURITY_CODE if (ReadSecure) { - RINOK(AddSecurityItem(phyPrefix + fi.Name, secureIndex)); + RINOK(AddSecurityItem(phyPrefix + fi.Name, secureIndex)) } #endif AddDirFileInfo(phyParent, logParent, secureIndex, fi); @@ -372,14 +372,14 @@ if (Callback && (i & kScanProgressStepMask) == kScanProgressStepMask) { - RINOK(ScanProgress(phyPrefix)); + RINOK(ScanProgress(phyPrefix)) } if (fi.IsDir()) { const FString name2 = fi.Name + FCHAR_PATH_SEPARATOR; unsigned parent = AddPrefix(phyParent, logParent, fs2us(name2)); - RINOK(EnumerateDir((int)parent, (int)parent, phyPrefix + name2)); + RINOK(EnumerateDir((int)parent, (int)parent, phyPrefix + name2)) } } return S_OK; @@ -412,6 +412,11 @@ const int phyParent = phyPrefix.IsEmpty() ? -1 : (int)AddPrefix(-1, -1, fs2us(phyPrefix)); const int logParent = logPrefix.IsEmpty() ? -1 : (int)AddPrefix(-1, -1, logPrefix); + #ifdef _WIN32 + const bool phyPrefix_isAltStreamPrefix = + NFile::NName::IsAltStreamPrefixWithColon(fs2us(phyPrefix)); + #endif + FOR_VECTOR (i, filePaths) { const FString &filePath = filePaths[i]; @@ -419,7 +424,7 @@ const FString phyPath = phyPrefix + filePath; if (!FindFile_KeepDots(fi, phyPath FOLLOW_LINK_PARAM)) { - RINOK(AddError(phyPath)); + RINOK(AddError(phyPath)) continue; } if (requestedPaths) @@ -437,20 +442,28 @@ if (CanIncludeItem(fi.IsDir())) { int secureIndex = -1; - #ifdef _USE_SECURITY_CODE + #ifdef Z7_USE_SECURITY_CODE if (ReadSecure) { - RINOK(AddSecurityItem(phyPath, secureIndex)); + RINOK(AddSecurityItem(phyPath, secureIndex)) } #endif + #ifdef _WIN32 + if (phyPrefix_isAltStreamPrefix && fi.IsAltStream) + { + const int pos = fi.Name.Find(FChar(':')); + if (pos >= 0) + fi.Name.DeleteFrontal((unsigned)pos + 1); + } + #endif AddDirFileInfo(phyParentCur, logParent, secureIndex, fi); } if (fi.IsDir()) { const FString name2 = fi.Name + FCHAR_PATH_SEPARATOR; - unsigned parent = AddPrefix(phyParentCur, logParent, fs2us(name2)); - RINOK(EnumerateDir((int)parent, (int)parent, phyPrefix + phyPrefixCur + name2)); + const unsigned parent = AddPrefix(phyParentCur, logParent, fs2us(name2)); + RINOK(EnumerateDir((int)parent, (int)parent, phyPrefix + phyPrefixCur + name2)) } } @@ -625,10 +638,10 @@ if (dirItems.CanIncludeItem(fi.IsDir())) { int secureIndex = -1; - #ifdef _USE_SECURITY_CODE + #ifdef Z7_USE_SECURITY_CODE if (dirItems.ReadSecure) { - RINOK(dirItems.AddSecurityItem(phyPrefix + fi.Name, secureIndex)); + RINOK(dirItems.AddSecurityItem(phyPrefix + fi.Name, secureIndex)) } #endif #if !defined(UNDER_CE) @@ -654,7 +667,7 @@ if (dirItemIndex >= 0) { CDirItem &dirItem = dirItems.Items[(unsigned)dirItemIndex]; - RINOK(dirItems.SetLinkInfo(dirItem, fi, phyPrefix)); + RINOK(dirItems.SetLinkInfo(dirItem, fi, phyPrefix)) if (dirItem.ReparseData.Size() != 0) return S_OK; } @@ -666,7 +679,7 @@ phyPrefix + fi.Name, // with (fi.Name) newParts, // with (fi.Name) addAllSubStreams, - dirItems)); + dirItems)) } #endif @@ -787,7 +800,7 @@ enterToSubFolders = true; } - RINOK(dirItems.ScanProgress(phyPrefix)); + RINOK(dirItems.ScanProgress(phyPrefix)) // try direct_names case at first if (addParts.IsEmpty() && !enterToSubFolders) @@ -818,7 +831,7 @@ bool needAltStreams = true; #endif - #ifdef _USE_SECURITY_CODE + #ifdef Z7_USE_SECURITY_CODE bool needSecurity = true; #endif @@ -838,7 +851,7 @@ /* // do we need to ignore security info for "\\" folder ? - #ifdef _USE_SECURITY_CODE + #ifdef Z7_USE_SECURITY_CODE needSecurity = false; #endif */ @@ -866,7 +879,7 @@ #endif if (!FindFile_KeepDots(fi, fullPath FOLLOW_LINK_PARAM2)) { - RINOK(dirItems.AddError(fullPath)); + RINOK(dirItems.AddError(fullPath)) continue; } @@ -884,7 +897,7 @@ if (isDir ? !item.ForDir : !item.ForFile) { // RINOK(dirItems.AddError(fullPath, isDir ? MY_ERROR_IS_DIR: MY_ERROR_NOT_DIR)); - RINOK(dirItems.AddError(fullPath, DI_DEFAULT_ERROR)); + RINOK(dirItems.AddError(fullPath, DI_DEFAULT_ERROR)) continue; } { @@ -898,10 +911,10 @@ if (dirItems.CanIncludeItem(fi.IsDir())) { int secureIndex = -1; - #ifdef _USE_SECURITY_CODE + #ifdef Z7_USE_SECURITY_CODE if (needSecurity && dirItems.ReadSecure) { - RINOK(dirItems.AddSecurityItem(fullPath, secureIndex)); + RINOK(dirItems.AddSecurityItem(fullPath, secureIndex)) } #endif @@ -912,7 +925,7 @@ #if !defined(UNDER_CE) { CDirItem &dirItem = dirItems.Items.Back(); - RINOK(dirItems.SetLinkInfo(dirItem, fi, phyPrefix)); + RINOK(dirItems.SetLinkInfo(dirItem, fi, phyPrefix)) if (dirItem.ReparseData.Size() != 0) continue; } @@ -926,7 +939,7 @@ fullPath, // including (name) pathParts, // including (fi.Name) true, /* addAllSubStreams */ - dirItems)); + dirItems)) } #endif // defined(_WIN32) @@ -975,9 +988,9 @@ } RINOK(EnumerateDirItems_Spec(*nextNode, phyParent, logParent, fi.Name, phyPrefix, - newParts, dirItems, true)); + newParts, dirItems, true)) } - + for (i = 0; i < curNode.SubNodes.Size(); i++) { if (i < needEnterVector.Size()) @@ -987,17 +1000,20 @@ FString fullPath = phyPrefix + us2fs(nextNode.Name); NFind::CFileInfo fi; - if (phyPrefix.IsEmpty()) + if (nextNode.Name.IsEmpty()) { - { - if (nextNode.Name.IsEmpty()) - fullPath = CHAR_PATH_SEPARATOR; - #ifdef _WIN32 - else if (NWildcard::IsDriveColonName(nextNode.Name)) - fullPath.Add_PathSepar(); - #endif - } + if (phyPrefix.IsEmpty()) + fullPath = CHAR_PATH_SEPARATOR; + } + #ifdef _WIN32 + else if(phyPrefix.IsEmpty() + || (phyPrefix.Len() == NName::kSuperPathPrefixSize + && IsSuperPath(phyPrefix))) + { + if (NWildcard::IsDriveColonName(nextNode.Name)) + fullPath.Add_PathSepar(); } + #endif // we don't want to call fi.Find() for root folder or virtual folder if ((phyPrefix.IsEmpty() && nextNode.Name.IsEmpty()) @@ -1015,19 +1031,19 @@ { if (!nextNode.AreThereIncludeItems()) continue; - RINOK(dirItems.AddError(fullPath)); + RINOK(dirItems.AddError(fullPath)) continue; } if (!fi.IsDir()) { - RINOK(dirItems.AddError(fullPath, DI_DEFAULT_ERROR)); + RINOK(dirItems.AddError(fullPath, DI_DEFAULT_ERROR)) continue; } } RINOK(EnumerateDirItems_Spec(nextNode, phyParent, logParent, fi.Name, phyPrefix, - UStringVector(), dirItems, false)); + UStringVector(), dirItems, false)) } return S_OK; @@ -1073,7 +1089,7 @@ fi.Name = driveName; RINOK(EnumerateForItem(fi, curNode, phyParent, logParent, phyPrefix, - addParts, dirItems, enterToSubFolders)); + addParts, dirItems, enterToSubFolders)) } return S_OK; } @@ -1088,7 +1104,7 @@ // for (int y = 0; y < 1; y++) { // files.Clear(); - RINOK(dirItems.EnumerateOneDir(phyPrefix, files)); + RINOK(dirItems.EnumerateOneDir(phyPrefix, files)) /* FOR_VECTOR (i, files) { @@ -1134,10 +1150,10 @@ #endif RINOK(EnumerateForItem(fi, curNode, phyParent, logParent, phyPrefix, - addParts, dirItems, enterToSubFolders)); + addParts, dirItems, enterToSubFolders)) if (dirItems.Callback && (i & kScanProgressStepMask) == kScanProgressStepMask) { - RINOK(dirItems.ScanProgress(phyPrefix)); + RINOK(dirItems.ScanProgress(phyPrefix)) } } @@ -1170,16 +1186,16 @@ RINOK(EnumerateDirItems(pair.Head, phyParent, logParent, us2fs(pair.Prefix), UStringVector(), dirItems, false // enterToSubFolders - )); + )) } dirItems.ReserveDown(); #if defined(_WIN32) && !defined(UNDER_CE) - RINOK(dirItems.FillFixedReparse()); + RINOK(dirItems.FillFixedReparse()) #endif #ifndef _WIN32 - RINOK(dirItems.FillDeviceSizes()); + RINOK(dirItems.FillDeviceSizes()) #endif return S_OK; @@ -1237,7 +1253,7 @@ } */ - RINOK(AddError(phyPath)); + RINOK(AddError(phyPath)) continue; } @@ -1485,7 +1501,7 @@ { HRESULT res = EnumerateItems(censor, censorPathMode, addPathPrefix, dirItems); st = dirItems.Stat; - RINOK(res); + RINOK(res) } FOR_VECTOR (i, dirItems.Items) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/EnumDirItems.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/EnumDirItems.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/EnumDirItems.h 2020-09-16 17:17:51.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/EnumDirItems.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // EnumDirItems.h -#ifndef __ENUM_DIR_ITEMS_H -#define __ENUM_DIR_ITEMS_H +#ifndef ZIP7_INC_ENUM_DIR_ITEMS_H +#define ZIP7_INC_ENUM_DIR_ITEMS_H #include "../../../Common/Wildcard.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/ExitCode.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/ExitCode.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/ExitCode.h 2008-08-06 07:50:21.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/ExitCode.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ExitCode.h -#ifndef __EXIT_CODE_H -#define __EXIT_CODE_H +#ifndef ZIP7_INC_EXIT_CODE_H +#define ZIP7_INC_EXIT_CODE_H namespace NExitCode { diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/Extract.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/Extract.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/Extract.cpp 2022-06-09 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/Extract.cpp 2023-04-05 20:00:00.000000000 +0000 @@ -43,6 +43,7 @@ const CExtractOptions &options, bool calcCrc, IExtractCallbackUI *callback, + IFolderArchiveExtractCallback *callbackFAE, CArchiveExtractCallback *ecs, UString &errorMessage, UInt64 &stdInProcessed) @@ -94,7 +95,7 @@ if (!options.StdInMode) { UInt32 numItems; - RINOK(archive->GetNumberOfItems(&numItems)); + RINOK(archive->GetNumberOfItems(&numItems)) CReadArcItem item; @@ -105,7 +106,7 @@ || options.ExcludeDirItems || options.ExcludeFileItems) { - RINOK(arc.GetItem(i, item)); + RINOK(arc.GetItem(i, item)) if (item.IsDir ? options.ExcludeDirItems : options.ExcludeFileItems) continue; } @@ -115,7 +116,7 @@ item.IsAltStream = false; if (!options.NtOptions.AltStreams.Val && arc.Ask_AltStream) { - RINOK(Archive_IsItem_AltStream(arc.Archive, i, item.IsAltStream)); + RINOK(Archive_IsItem_AltStream(arc.Archive, i, item.IsAltStream)) } #endif } @@ -194,7 +195,7 @@ options.NtOptions, options.StdInMode ? &wildcardCensor : NULL, &arc, - callback, + callbackFAE, options.StdOutMode, options.TestMode, outDir, removePathParts, false, @@ -207,14 +208,14 @@ !options.TestMode && options.NtOptions.HardLinks.Val) { - RINOK(ecs->PrepareHardLinks(&realIndices)); + RINOK(ecs->PrepareHardLinks(&realIndices)) } #endif HRESULT result; - Int32 testMode = (options.TestMode && !calcCrc) ? 1: 0; + const Int32 testMode = (options.TestMode && !calcCrc) ? 1: 0; CArchiveExtractCallback_Closer ecsCloser(ecs); @@ -228,7 +229,7 @@ else result = archive->Extract(&realIndices.Front(), realIndices.Size(), testMode, ecs); - HRESULT res2 = ecsCloser.Close(); + const HRESULT res2 = ecsCloser.Close(); if (result == S_OK) result = res2; @@ -270,7 +271,8 @@ const CExtractOptions &options, IOpenCallbackUI *openCallback, IExtractCallbackUI *extractCallback, - #ifndef _SFX + IFolderArchiveExtractCallback *faeCallback, + #ifndef Z7_SFX IHashCalc *hash, #endif UString &errorMessage, @@ -323,13 +325,13 @@ options.ZoneMode, false // keepEmptyDirParts ); - #ifndef _SFX + #ifndef Z7_SFX ecs->SetHashMethods(hash); #endif if (multi) { - RINOK(extractCallback->SetTotal(totalPackSize)); + RINOK(faeCallback->SetTotal(totalPackSize)) } UInt64 totalPackProcessed = 0; @@ -364,17 +366,17 @@ } /* - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO openCallback->Open_Clear_PasswordWasAsked_Flag(); #endif */ - RINOK(extractCallback->BeforeOpen(arcPath, options.TestMode)); + RINOK(extractCallback->BeforeOpen(arcPath, options.TestMode)) CArchiveLink arcLink; CObjectVector types2 = types; /* - #ifndef _SFX + #ifndef Z7_SFX if (types.IsEmpty()) { int pos = arcPath.ReverseFind(L'.'); @@ -402,7 +404,7 @@ */ COpenOptions op; - #ifndef _SFX + #ifndef Z7_SFX op.props = &options.Properties; #endif op.codecs = codecs; @@ -418,7 +420,7 @@ return result; // arcLink.Set_ErrorsText(); - RINOK(extractCallback->OpenResult(codecs, arcLink, arcPath, result)); + RINOK(extractCallback->OpenResult(codecs, arcLink, arcPath, result)) if (result != S_OK) { @@ -428,7 +430,7 @@ continue; } - #if defined(_WIN32) && !defined(UNDER_CE) && !defined(_SFX) + #if defined(_WIN32) && !defined(UNDER_CE) && !defined(Z7_SFX) if (options.ZoneMode != NExtract::NZoneIdMode::kNone && !options.StdInMode) { @@ -446,7 +448,13 @@ /* real Extracting to files is possible. But user can think that hash archive contains real files. So we block extracting here. */ - return E_NOTIMPL; + // v23.00 : we don't break process. + RINOK(extractCallback->OpenResult(codecs, arcLink, arcPath, E_NOTIMPL)) + thereAreNotOpenArcs = true; + if (!options.StdInMode) + totalPackProcessed += fi.Size; + continue; + // return E_NOTIMPL; // before v23 } FString dirPrefix = us2fs(options.HashDir); if (dirPrefix.IsEmpty()) @@ -490,7 +498,7 @@ if (newPackSize < 0) newPackSize = 0; totalPackSize = (UInt64)newPackSize; - RINOK(extractCallback->SetTotal(totalPackSize)); + RINOK(faeCallback->SetTotal(totalPackSize)) } } } @@ -498,13 +506,13 @@ /* // Now openCallback and extractCallback use same object. So we don't need to send password. - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO bool passwordIsDefined; UString password; - RINOK(openCallback->Open_GetPasswordIfAny(passwordIsDefined, password)); + RINOK(openCallback->Open_GetPasswordIfAny(passwordIsDefined, password)) if (passwordIsDefined) { - RINOK(extractCallback->SetPassword(password)); + RINOK(extractCallback->SetPassword(password)) } #endif */ @@ -520,7 +528,7 @@ UInt64 packProcessed; const bool calcCrc = - #ifndef _SFX + #ifndef Z7_SFX (hash != NULL); #else false; @@ -533,7 +541,8 @@ wildcardCensor, options, calcCrc, - extractCallback, ecs, errorMessage, packProcessed)); + extractCallback, faeCallback, ecs, + errorMessage, packProcessed)) if (!options.StdInMode) packProcessed = fi.Size + arcLink.VolumesSize; @@ -546,8 +555,8 @@ if (multi || thereAreNotOpenArcs) { - RINOK(extractCallback->SetTotal(totalPackSize)); - RINOK(extractCallback->SetCompleted(&totalPackProcessed)); + RINOK(faeCallback->SetTotal(totalPackSize)) + RINOK(faeCallback->SetCompleted(&totalPackProcessed)) } st.NumFolders = ecs->NumFolders; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/Extract.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/Extract.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/Extract.h 2022-06-03 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/Extract.h 2023-01-31 11:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Extract.h -#ifndef __EXTRACT_H -#define __EXTRACT_H +#ifndef ZIP7_INC_EXTRACT_H +#define ZIP7_INC_EXTRACT_H #include "../../../Windows/FileFind.h" @@ -52,12 +52,12 @@ // bool ShowDialog; // bool PasswordEnabled; // UString Password; - #ifndef _SFX + #ifndef Z7_SFX CObjectVector Properties; #endif /* - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS CCodecs *Codecs; #endif */ @@ -96,7 +96,8 @@ const CExtractOptions &options, IOpenCallbackUI *openCallback, IExtractCallbackUI *extractCallback, - #ifndef _SFX + IFolderArchiveExtractCallback *faeCallback, + #ifndef Z7_SFX IHashCalc *hash, #endif UString &errorMessage, diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/ExtractingFilePath.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/ExtractingFilePath.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/ExtractingFilePath.cpp 2022-01-09 19:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/ExtractingFilePath.cpp 2023-03-06 16:00:00.000000000 +0000 @@ -124,7 +124,7 @@ static bool IsSupportedName(const UString &name) { - for (unsigned i = 0; i < ARRAY_SIZE(g_ReservedNames); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_ReservedNames); i++) { const char *reservedName = g_ReservedNames[i]; unsigned len = MyStringLen(reservedName); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/ExtractingFilePath.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/ExtractingFilePath.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/ExtractingFilePath.h 2019-03-01 17:24:26.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/ExtractingFilePath.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ExtractingFilePath.h -#ifndef __EXTRACTING_FILE_PATH_H -#define __EXTRACTING_FILE_PATH_H +#ifndef ZIP7_INC_EXTRACTING_FILE_PATH_H +#define ZIP7_INC_EXTRACTING_FILE_PATH_H #include "../../../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/ExtractMode.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/ExtractMode.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/ExtractMode.h 2022-05-26 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/ExtractMode.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ExtractMode.h -#ifndef __EXTRACT_MODE_H -#define __EXTRACT_MODE_H +#ifndef ZIP7_INC_EXTRACT_MODE_H +#define ZIP7_INC_EXTRACT_MODE_H namespace NExtract { diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/HashCalc.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/HashCalc.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/HashCalc.cpp 2022-04-04 15:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/HashCalc.cpp 2023-03-26 19:00:00.000000000 +0000 @@ -22,7 +22,7 @@ using namespace NWindows; -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS extern const CExternalCodecs *g_ExternalCodecs_Ptr; #endif @@ -57,7 +57,7 @@ for (i = 0; i < names.Size(); i++) { COneMethodInfo m; - RINOK(m.ParseMethodFromString(names[i])); + RINOK(m.ParseMethodFromString(names[i])) if (m.MethodName.IsEmpty()) m.MethodName = k_DefaultHashMethod; @@ -92,7 +92,7 @@ { CMyComPtr hasher; AString name; - RINOK(CreateHasher(EXTERNAL_CODECS_LOC_VARS ids[i], name, hasher)); + RINOK(CreateHasher(EXTERNAL_CODECS_LOC_VARS ids[i], name, hasher)) if (!hasher) throw "Can't create hasher"; const COneMethodInfo &m = methods[i]; @@ -100,7 +100,7 @@ CMyComPtr scp; hasher.QueryInterface(IID_ICompressSetCoderProperties, &scp); if (scp) - RINOK(m.SetCoderProps(scp, NULL)); + RINOK(m.SetCoderProps(scp, NULL)) } const UInt32 digestSize = hasher->GetDigestSize(); if (digestSize > k_HashCalc_DigestSize_Max) @@ -330,14 +330,14 @@ if (numSpaces > 0) SetSpacesAndNul(s + pos, (unsigned)numSpaces); if (i != 0) - _s += ' '; + _s.Add_Space(); _s += s; } /* if (showSize) { - _s += ' '; + _s.Add_Space(); static const unsigned kSizeField_Len = 13; // same as in HashCon.cpp char s[kSizeField_Len + 32]; char *p = s; @@ -467,7 +467,7 @@ } else { - RINOK(callback->StartScanning()); + RINOK(callback->StartScanning()) dirItems.SymLinks = options.SymLinks.Val; dirItems.ScanAltStreams = options.AltStreamsMode; @@ -487,12 +487,12 @@ errorInfo = "Scanning error"; return res; } - RINOK(callback->FinishScanning(dirItems.Stat)); + RINOK(callback->FinishScanning(dirItems.Stat)) } unsigned i; CHashBundle hb; - RINOK(hb.SetMethods(EXTERNAL_CODECS_LOC_VARS options.Methods)); + RINOK(hb.SetMethods(EXTERNAL_CODECS_LOC_VARS options.Methods)) // hb.Init(); hb.NumErrors = dirItems.Stat.NumErrors; @@ -500,12 +500,12 @@ UInt64 totalSize = 0; if (options.StdInMode) { - RINOK(callback->SetNumFiles(1)); + RINOK(callback->SetNumFiles(1)) } else { totalSize = dirItems.Stat.GetTotalBytes(); - RINOK(callback->SetTotal(totalSize)); + RINOK(callback->SetTotal(totalSize)) } const UInt32 kBufSize = 1 << 15; @@ -515,7 +515,7 @@ UInt64 completeValue = 0; - RINOK(callback->BeforeFirstFile(hb)); + RINOK(callback->BeforeFirstFile(hb)) /* CDynLimBuf hashFileString((size_t)1 << 31); @@ -575,7 +575,7 @@ if (curSize > di.Size) { totalSize += curSize - di.Size; - RINOK(callback->SetTotal(totalSize)); + RINOK(callback->SetTotal(totalSize)) // printf("\ntotal = %d MiB\n", (unsigned)(totalSize >> 20)); } } @@ -585,7 +585,7 @@ } } - RINOK(callback->GetStream(path, isDir)); + RINOK(callback->GetStream(path, isDir)) UInt64 fileSize = 0; hb.InitForNewFile(); @@ -597,10 +597,10 @@ if ((step & 0xFF) == 0) { // printf("\ncompl = %d\n", (unsigned)(completeValue >> 20)); - RINOK(callback->SetCompleted(&completeValue)); + RINOK(callback->SetCompleted(&completeValue)) } UInt32 size; - RINOK(inStream->Read(buf, kBufSize, &size)); + RINOK(inStream->Read(buf, kBufSize, &size)) if (size == 0) break; hb.Update(buf, size); @@ -626,8 +626,8 @@ } */ - RINOK(callback->SetOperationResult(fileSize, hb, !isDir)); - RINOK(callback->SetCompleted(&completeValue)); + RINOK(callback->SetOperationResult(fileSize, hb, !isDir)) + RINOK(callback->SetCompleted(&completeValue)) } /* @@ -776,7 +776,7 @@ Name = end; Hash.Alloc(4); - SetBe32(Hash, crc); + SetBe32(Hash, crc) Size_from_Arc = size; Size_from_Arc_Defined = true; @@ -823,7 +823,7 @@ } const char *m = ""; unsigned i; - for (i = 0; i < ARRAY_SIZE(k_CsumMethodNames); i++) + for (i = 0; i < Z7_ARRAY_SIZE(k_CsumMethodNames); i++) { m = k_CsumMethodNames[i]; if (isExtension) @@ -836,7 +836,7 @@ break; } UString res; - if (i != ARRAY_SIZE(k_CsumMethodNames)) + if (i != Z7_ARRAY_SIZE(k_CsumMethodNames)) res = m; return res; } @@ -1033,27 +1033,27 @@ }; -STDMETHODIMP CHandler::GetParent(UInt32 /* index */ , UInt32 *parent, UInt32 *parentType) +Z7_COM7F_IMF(CHandler::GetParent(UInt32 /* index */ , UInt32 *parent, UInt32 *parentType)) { *parentType = NParentType::kDir; *parent = (UInt32)(Int32)-1; return S_OK; } -STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) +Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps)) { - *numProps = ARRAY_SIZE(kRawProps); + *numProps = Z7_ARRAY_SIZE(kRawProps); return S_OK; } -STDMETHODIMP CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID) +Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID)) { *propID = kRawProps[index]; - *name = 0; + *name = NULL; return S_OK; } -STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) +Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType)) { *data = NULL; *dataSize = 0; @@ -1077,7 +1077,7 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = HashPairs.Size(); return S_OK; @@ -1089,7 +1089,7 @@ dest += src; } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { NWindows::NCOM::CPropVariant prop; switch (propID) @@ -1152,7 +1152,7 @@ } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { // COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -1206,10 +1206,9 @@ { buf.Free(); UInt64 len; - RINOK(stream->Seek(0, STREAM_SEEK_END, &len)); + RINOK(InStream_AtBegin_GetSize(stream, len)) if (len == 0 || len >= ((UInt64)1 << 31)) return S_FALSE; - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); buf.Alloc((size_t)len); UInt64 pos = 0; // return ReadStream_FALSE(stream, buf, (size_t)len); @@ -1218,7 +1217,7 @@ const UInt32 kBlockSize = ((UInt32)1 << 24); const UInt32 curSize = (len < kBlockSize) ? (UInt32)len : kBlockSize; UInt32 processedSizeLoc; - RINOK(stream->Read((Byte *)buf + pos, curSize, &processedSizeLoc)); + RINOK(stream->Read((Byte *)buf + pos, curSize, &processedSizeLoc)) if (processedSizeLoc == 0) return E_FAIL; len -= processedSizeLoc; @@ -1228,13 +1227,13 @@ if (openCallback) { const UInt64 files = 0; - RINOK(openCallback->SetCompleted(&files, &pos)); + RINOK(openCallback->SetCompleted(&files, &pos)) } } } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *openCallback) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *openCallback)) { COM_TRY_BEGIN { @@ -1261,12 +1260,13 @@ if (openCallback) { - CMyComPtr openVolumeCallback; - openCallback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&openVolumeCallback); - NCOM::CPropVariant prop; + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveOpenVolumeCallback, + openVolumeCallback, openCallback) if (openVolumeCallback) { - RINOK(openVolumeCallback->GetProperty(kpidName, &prop)); + NCOM::CPropVariant prop; + RINOK(openVolumeCallback->GetProperty(kpidName, &prop)) if (prop.vt == VT_BSTR) _nameExtenstion = GetMethod_from_FileName(prop.bstrVal); } @@ -1376,7 +1376,7 @@ } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { ClearVars(); _nameExtenstion.Empty(); @@ -1416,8 +1416,8 @@ else if (size == 4) m = "crc32"; else return; - #ifdef EXTERNAL_CODECS - const CExternalCodecs *__externalCodecs = g_ExternalCodecs_Ptr; + #ifdef Z7_EXTERNAL_CODECS + const CExternalCodecs *_externalCodecs = g_ExternalCodecs_Ptr; #endif CMethodId id; if (FindHashMethod(EXTERNAL_CODECS_LOC_VARS @@ -1426,8 +1426,8 @@ } -STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN @@ -1442,8 +1442,8 @@ if (numItems == 0) return S_OK; - #ifdef EXTERNAL_CODECS - const CExternalCodecs *__externalCodecs = g_ExternalCodecs_Ptr; + #ifdef Z7_EXTERNAL_CODECS + const CExternalCodecs *_externalCodecs = g_ExternalCodecs_Ptr; #endif CHashBundle hb_Glob; @@ -1471,15 +1471,17 @@ RINOK(hb_Glob.SetMethods( EXTERNAL_CODECS_LOC_VARS - methods)); + methods)) - CMyComPtr updateCallbackFile; - extractCallback->QueryInterface(IID_IArchiveUpdateCallbackFile, (void **)&updateCallbackFile); + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveUpdateCallbackFile, + updateCallbackFile, extractCallback) if (!updateCallbackFile) return E_NOTIMPL; { - CMyComPtr GetDiskProperty; - extractCallback->QueryInterface(IID_IArchiveGetDiskProperty, (void **)&GetDiskProperty); + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveGetDiskProperty, + GetDiskProperty, extractCallback) if (GetDiskProperty) { UInt64 totalSize = 0; @@ -1492,13 +1494,13 @@ continue; { NCOM::CPropVariant prop; - RINOK(GetDiskProperty->GetDiskProperty(index, kpidSize, &prop)); + RINOK(GetDiskProperty->GetDiskProperty(index, kpidSize, &prop)) if (prop.vt != VT_UI8) continue; totalSize += prop.uhVal.QuadPart; } } - RINOK(extractCallback->SetTotal(totalSize)); + RINOK(extractCallback->SetTotal(totalSize)) // RINOK(Hash_SetTotalUnpacked->Hash_SetTotalUnpacked(indices, numItems)); } } @@ -1516,7 +1518,7 @@ UInt32 i; for (i = 0; i < numItems; i++) { - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) const UInt32 index = allFilesMode ? i : indices[i]; CHashPair &hp = HashPairs[index]; @@ -1528,7 +1530,7 @@ const bool isDir = hp.IsDir(); if (!isDir) { - RINOK(updateCallbackFile->GetStream2(index, &inStream, NUpdateNotifyOp::kHashRead)); + RINOK(updateCallbackFile->GetStream2(index, &inStream, NUpdateNotifyOp::kHashRead)) if (!inStream) { continue; // we have shown error in GetStream2() @@ -1541,7 +1543,7 @@ NArchive::NExtract::NAskMode::kExtract; CMyComPtr realOutStream; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) /* PrepareOperation() can expect kExtract to set Attrib and security of output file */ @@ -1570,7 +1572,7 @@ methods_loc.Add(UString(hp.Method)); RINOK(hb_Loc.SetMethods( EXTERNAL_CODECS_LOC_VARS - methods_loc)); + methods_loc)) } else res_SetMethods = E_NOTIMPL; @@ -1583,7 +1585,7 @@ hb_Use = &hb_Loc; RINOK(hb_Loc.SetMethods( EXTERNAL_CODECS_LOC_VARS - methods_loc)); + methods_loc)) } } @@ -1596,16 +1598,16 @@ { if ((step & 0xFF) == 0) { - RINOK(lps->SetRatioInfo(NULL, &fileSize)); + RINOK(progress->SetRatioInfo(NULL, &fileSize)) } UInt32 size; - RINOK(inStream->Read(buf, kBufSize, &size)); + RINOK(inStream->Read(buf, kBufSize, &size)) if (size == 0) break; hb_Use->Update(buf, size); if (realOutStream) { - RINOK(WriteStream(realOutStream, buf, size)); + RINOK(WriteStream(realOutStream, buf, size)) } fileSize += size; } @@ -1638,7 +1640,7 @@ } } - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } return lps->SetCur(); @@ -1668,7 +1670,7 @@ bool convertSlash) { NCOM::CPropVariant prop; - RINOK(callback->GetProperty(index, propId, &prop)); + RINOK(callback->GetProperty(index, propId, &prop)) if (prop.vt == VT_BSTR) { res = prop.bstrVal; @@ -1681,15 +1683,15 @@ } -STDMETHODIMP CHandler::GetFileTimeType(UInt32 *type) +Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *type)) { *type = NFileTimeType::kUnix; return S_OK; } -STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, - IArchiveUpdateCallback *callback) +Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, + IArchiveUpdateCallback *callback)) { COM_TRY_BEGIN @@ -1697,8 +1699,8 @@ return E_NOTIMPL; /* - CMyComPtr reportArcProp; - callback->QueryInterface(IID_IArchiveUpdateCallbackArcProp, (void **)&reportArcProp); + Z7_DECL_CMyComPtr_QI_FROM(IArchiveUpdateCallbackArcProp, + reportArcProp, callback) */ CObjectVector updateItems; @@ -1716,7 +1718,7 @@ if (!callback) return E_FAIL; - RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArc)); + RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArc)) ui.NewProps = IntToBool(newProps); ui.NewData = IntToBool(newData); @@ -1726,7 +1728,7 @@ { { NCOM::CPropVariant prop; - RINOK(callback->GetProperty(i, kpidIsDir, &prop)); + RINOK(callback->GetProperty(i, kpidIsDir, &prop)) if (prop.vt == VT_EMPTY) ui.IsDir = false; else if (prop.vt != VT_BOOL) @@ -1736,7 +1738,7 @@ } RINOK(GetPropString(callback, i, kpidPath, ui.Path, - true)); // convertSlash + true)) // convertSlash /* if (ui.IsDir && !ui.Name.IsEmpty() && ui.Name.Back() != '/') ui.Name += '/'; @@ -1746,7 +1748,7 @@ if (IntToBool(newData)) { NCOM::CPropVariant prop; - RINOK(callback->GetProperty(i, kpidSize, &prop)); + RINOK(callback->GetProperty(i, kpidSize, &prop)) if (prop.vt == VT_UI8) { ui.Size = prop.uhVal.QuadPart; @@ -1763,11 +1765,11 @@ if (complexity != 0) { - RINOK(callback->SetTotal(complexity)); + RINOK(callback->SetTotal(complexity)) } - #ifdef EXTERNAL_CODECS - const CExternalCodecs *__externalCodecs = g_ExternalCodecs_Ptr; + #ifdef Z7_EXTERNAL_CODECS + const CExternalCodecs *_externalCodecs = g_ExternalCodecs_Ptr; #endif CHashBundle hb; @@ -1785,13 +1787,13 @@ } else { - CMyComPtr getRootProps; - callback->QueryInterface(IID_IArchiveGetRootProps, (void **)&getRootProps); - - NCOM::CPropVariant prop; + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveGetRootProps, + getRootProps, callback) if (getRootProps) { - RINOK(getRootProps->GetRootProp(kpidArcFileName, &prop)); + NCOM::CPropVariant prop; + RINOK(getRootProps->GetRootProp(kpidArcFileName, &prop)) if (prop.vt == VT_BSTR) { const UString method = GetMethod_from_FileName(prop.bstrVal); @@ -1801,7 +1803,7 @@ } } - RINOK(hb.SetMethods(EXTERNAL_CODECS_LOC_VARS methods)); + RINOK(hb.SetMethods(EXTERNAL_CODECS_LOC_VARS methods)) CLocalProgress *lps = new CLocalProgress; CMyComPtr progress = lps; @@ -1834,7 +1836,7 @@ for (i = 0; i < updateItems.Size(); i++) { lps->InSize = complexity; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) const CUpdateItem &ui = updateItems[i]; @@ -1858,12 +1860,13 @@ needWrite = false; else { - RINOK(res); + RINOK(res) if (fileInStream) { - CMyComPtr streamGetSize; - fileInStream->QueryInterface(IID_IStreamGetSize, (void **)&streamGetSize); + Z7_DECL_CMyComPtr_QI_FROM( + IStreamGetSize, + streamGetSize, fileInStream) if (streamGetSize) { UInt64 size; @@ -1871,8 +1874,9 @@ currentComplexity = size; } /* - CMyComPtr getProps; - fileInStream->QueryInterface(IID_IStreamGetProps, (void **)&getProps); + Z7_DECL_CMyComPtr_QI_FROM( + IStreamGetProps, + getProps, fileInStream) if (getProps) { FILETIME mTime; @@ -1901,11 +1905,11 @@ { if ((step & 0xFF) == 0) { - RINOK(lps->SetRatioInfo(&fileSize, NULL)); + RINOK(progress->SetRatioInfo(&fileSize, NULL)) // RINOK(callback->SetCompleted(&completeValue)); } UInt32 size; - RINOK(fileInStream->Read(buf, kBufSize, &size)); + RINOK(fileInStream->Read(buf, kBufSize, &size)) if (size == 0) break; hb.Update(buf, size); @@ -1962,7 +1966,7 @@ } } */ - RINOK(callback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); + RINOK(callback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)) } else { @@ -1987,7 +1991,7 @@ return E_OUTOFMEMORY; } - RINOK(WriteStream(outStream, hashFileString, hashFileString.Len())); + RINOK(WriteStream(outStream, hashFileString, hashFileString.Len())) return S_OK; COM_TRY_END @@ -2040,7 +2044,7 @@ } -STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) +Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps)) { COM_TRY_BEGIN @@ -2048,7 +2052,7 @@ for (UInt32 i = 0; i < numProps; i++) { - RINOK(SetProperty(names[i], values[i])); + RINOK(SetProperty(names[i], values[i])) } return S_OK; COM_TRY_END diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/HashCalc.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/HashCalc.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/HashCalc.h 2022-02-08 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/HashCalc.h 2023-04-05 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // HashCalc.h -#ifndef __HASH_CALC_H -#define __HASH_CALC_H +#ifndef ZIP7_INC_HASH_CALC_H +#define ZIP7_INC_HASH_CALC_H #include "../../../Common/UTFConvert.h" #include "../../../Common/Wildcard.h" @@ -65,8 +65,10 @@ }; +Z7_PURE_INTERFACES_BEGIN -struct IHashCalc + +DECLARE_INTERFACE(IHashCalc) { virtual void InitForNewFile() = 0; virtual void Update(const void *data, UInt32 size) = 0; @@ -74,7 +76,9 @@ virtual void Final(bool isDir, bool isAltStream, const UString &path) = 0; }; -struct CHashBundle: public IHashCalc +Z7_PURE_INTERFACES_END + +struct CHashBundle Z7_final: public IHashCalc { CObjectVector Hashers; @@ -98,32 +102,32 @@ NumDirs = NumFiles = NumAltStreams = FilesSize = AltStreamsSize = NumErrors = 0; } - virtual ~CHashBundle() {}; - - void InitForNewFile(); - void Update(const void *data, UInt32 size); - void SetSize(UInt64 size); - void Final(bool isDir, bool isAltStream, const UString &path); + void InitForNewFile() Z7_override; + void Update(const void *data, UInt32 size) Z7_override; + void SetSize(UInt64 size) Z7_override; + void Final(bool isDir, bool isAltStream, const UString &path) Z7_override; }; -#define INTERFACE_IHashCallbackUI(x) \ - INTERFACE_IDirItemsCallback(x) \ - virtual HRESULT StartScanning() x; \ - virtual HRESULT FinishScanning(const CDirItemsStat &st) x; \ - virtual HRESULT SetNumFiles(UInt64 numFiles) x; \ - virtual HRESULT SetTotal(UInt64 size) x; \ - virtual HRESULT SetCompleted(const UInt64 *completeValue) x; \ - virtual HRESULT CheckBreak() x; \ - virtual HRESULT BeforeFirstFile(const CHashBundle &hb) x; \ - virtual HRESULT GetStream(const wchar_t *name, bool isFolder) x; \ - virtual HRESULT OpenFileError(const FString &path, DWORD systemError) x; \ - virtual HRESULT SetOperationResult(UInt64 fileSize, const CHashBundle &hb, bool showHash) x; \ - virtual HRESULT AfterLastFile(CHashBundle &hb) x; \ +Z7_PURE_INTERFACES_BEGIN -struct IHashCallbackUI: public IDirItemsCallback -{ - INTERFACE_IHashCallbackUI(=0) -}; +// INTERFACE_IDirItemsCallback(x) + +#define Z7_IFACEN_IHashCallbackUI(x) \ + virtual HRESULT StartScanning() x \ + virtual HRESULT FinishScanning(const CDirItemsStat &st) x \ + virtual HRESULT SetNumFiles(UInt64 numFiles) x \ + virtual HRESULT SetTotal(UInt64 size) x \ + virtual HRESULT SetCompleted(const UInt64 *completeValue) x \ + virtual HRESULT CheckBreak() x \ + virtual HRESULT BeforeFirstFile(const CHashBundle &hb) x \ + virtual HRESULT GetStream(const wchar_t *name, bool isFolder) x \ + virtual HRESULT OpenFileError(const FString &path, DWORD systemError) x \ + virtual HRESULT SetOperationResult(UInt64 fileSize, const CHashBundle &hb, bool showHash) x \ + virtual HRESULT AfterLastFile(CHashBundle &hb) x \ + +Z7_IFACE_DECL_PURE_(IHashCallbackUI, IDirItemsCallback) + +Z7_PURE_INTERFACES_END struct CHashOptionsLocal @@ -200,7 +204,7 @@ OpenShareForWrite(false), StdInMode(false), AltStreamsMode(false), - PathMode(NWildcard::k_RelatPath) {}; + PathMode(NWildcard::k_RelatPath) {} }; @@ -213,7 +217,7 @@ -#ifndef _SFX +#ifndef Z7_SFX namespace NHash { @@ -264,14 +268,12 @@ }; -class CHandler: - public IInArchive, - public IArchiveGetRawProps, - // public IGetArchiveHashHandler, - public IOutArchive, - public ISetProperties, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_3( + IArchiveGetRawProps, + /* public IGetArchiveHashHandler, */ + IOutArchive, + ISetProperties +) bool _isArc; UInt64 _phySize; CObjectVector HashPairs; @@ -313,21 +315,7 @@ HRESULT SetProperty(const wchar_t *nameSpec, const PROPVARIANT &value); public: - CHandler(); - - MY_UNKNOWN_IMP4( - IInArchive, - IArchiveGetRawProps, - IOutArchive, - ISetProperties - /*, IGetArchiveHashHandler */ - ) - INTERFACE_IInArchive(;) - INTERFACE_IOutArchive(;) - INTERFACE_IArchiveGetRawProps(;) - // STDMETHOD(GetArchiveHashHandler)(CHandler **handler); - STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps); }; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/IFileExtractCallback.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/IFileExtractCallback.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/IFileExtractCallback.h 2021-09-21 16:07:43.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/IFileExtractCallback.h 2023-04-05 20:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // IFileExtractCallback.h -#ifndef __I_FILE_EXTRACT_CALLBACK_H -#define __I_FILE_EXTRACT_CALLBACK_H +#ifndef ZIP7_INC_I_FILE_EXTRACT_CALLBACK_H +#define ZIP7_INC_I_FILE_EXTRACT_CALLBACK_H #include "../../../Common/MyString.h" @@ -10,6 +10,15 @@ #include "LoadCodecs.h" #include "OpenArchive.h" +Z7_PURE_INTERFACES_BEGIN + +#define Z7_IFACE_CONSTR_FOLDERARC_SUB(i, base, n) \ + Z7_DECL_IFACE_7ZIP_SUB(i, base, 1, n) \ + { Z7_IFACE_COM7_PURE(i) }; + +#define Z7_IFACE_CONSTR_FOLDERARC(i, n) \ + Z7_IFACE_CONSTR_FOLDERARC_SUB(i, IUnknown, n) + namespace NOverwriteAnswer { enum EEnum @@ -42,27 +51,21 @@ IFolderArchiveExtractCallback is used by Common/ArchiveExtractCallback.cpp */ -#define INTERFACE_IFolderArchiveExtractCallback(x) \ - STDMETHOD(AskOverwrite)( \ +#define Z7_IFACEM_IFolderArchiveExtractCallback(x) \ + x(AskOverwrite( \ const wchar_t *existName, const FILETIME *existTime, const UInt64 *existSize, \ const wchar_t *newName, const FILETIME *newTime, const UInt64 *newSize, \ - Int32 *answer) x; \ - STDMETHOD(PrepareOperation)(const wchar_t *name, Int32 isFolder, Int32 askExtractMode, const UInt64 *position) x; \ - STDMETHOD(MessageError)(const wchar_t *message) x; \ - STDMETHOD(SetOperationResult)(Int32 opRes, Int32 encrypted) x; \ + Int32 *answer)) \ + x(PrepareOperation(const wchar_t *name, Int32 isFolder, Int32 askExtractMode, const UInt64 *position)) \ + x(MessageError(const wchar_t *message)) \ + x(SetOperationResult(Int32 opRes, Int32 encrypted)) \ -DECL_INTERFACE_SUB(IFolderArchiveExtractCallback, IProgress, 0x01, 0x07) -{ - INTERFACE_IFolderArchiveExtractCallback(PURE) -}; +Z7_IFACE_CONSTR_FOLDERARC_SUB(IFolderArchiveExtractCallback, IProgress, 0x07) -#define INTERFACE_IFolderArchiveExtractCallback2(x) \ - STDMETHOD(ReportExtractResult)(Int32 opRes, Int32 encrypted, const wchar_t *name) x; \ +#define Z7_IFACEM_IFolderArchiveExtractCallback2(x) \ + x(ReportExtractResult(Int32 opRes, Int32 encrypted, const wchar_t *name)) \ -DECL_INTERFACE_SUB(IFolderArchiveExtractCallback2, IUnknown, 0x01, 0x08) -{ - INTERFACE_IFolderArchiveExtractCallback2(PURE) -}; +Z7_IFACE_CONSTR_FOLDERARC(IFolderArchiveExtractCallback2, 0x08) /* ---------- IExtractCallbackUI ---------- is implemented by @@ -70,45 +73,40 @@ FileManager/ExtractCallback.h CExtractCallbackImp */ -#ifdef _NO_CRYPTO - #define INTERFACE_IExtractCallbackUI_Crypto(x) +#ifdef Z7_NO_CRYPTO + #define Z7_IFACEM_IExtractCallbackUI_Crypto(px) #else - #define INTERFACE_IExtractCallbackUI_Crypto(x) \ - virtual HRESULT SetPassword(const UString &password) x; + #define Z7_IFACEM_IExtractCallbackUI_Crypto(px) \ + virtual HRESULT SetPassword(const UString &password) px #endif -#define INTERFACE_IExtractCallbackUI(x) \ - virtual HRESULT BeforeOpen(const wchar_t *name, bool testMode) x; \ - virtual HRESULT OpenResult(const CCodecs *codecs, const CArchiveLink &arcLink, const wchar_t *name, HRESULT result) x; \ - virtual HRESULT ThereAreNoFiles() x; \ - virtual HRESULT ExtractResult(HRESULT result) x; \ - INTERFACE_IExtractCallbackUI_Crypto(x) +#define Z7_IFACEN_IExtractCallbackUI(px) \ + virtual HRESULT BeforeOpen(const wchar_t *name, bool testMode) px \ + virtual HRESULT OpenResult(const CCodecs *codecs, const CArchiveLink &arcLink, const wchar_t *name, HRESULT result) px \ + virtual HRESULT ThereAreNoFiles() px \ + virtual HRESULT ExtractResult(HRESULT result) px \ + Z7_IFACEM_IExtractCallbackUI_Crypto(px) -struct IExtractCallbackUI: IFolderArchiveExtractCallback -{ - INTERFACE_IExtractCallbackUI(PURE) -}; +// IExtractCallbackUI - is non-COM interface +// IFolderArchiveExtractCallback - is COM interface +// Z7_IFACE_DECL_PURE_(IExtractCallbackUI, IFolderArchiveExtractCallback) +Z7_IFACE_DECL_PURE(IExtractCallbackUI) -#define INTERFACE_IGetProp(x) \ - STDMETHOD(GetProp)(PROPID propID, PROPVARIANT *value) x; \ +#define Z7_IFACEM_IGetProp(x) \ + x(GetProp(PROPID propID, PROPVARIANT *value)) \ -DECL_INTERFACE_SUB(IGetProp, IUnknown, 0x01, 0x20) -{ - INTERFACE_IGetProp(PURE) -}; +Z7_IFACE_CONSTR_FOLDERARC(IGetProp, 0x20) -#define INTERFACE_IFolderExtractToStreamCallback(x) \ - STDMETHOD(UseExtractToStream)(Int32 *res) x; \ - STDMETHOD(GetStream7)(const wchar_t *name, Int32 isDir, ISequentialOutStream **outStream, Int32 askExtractMode, IGetProp *getProp) x; \ - STDMETHOD(PrepareOperation7)(Int32 askExtractMode) x; \ - STDMETHOD(SetOperationResult8)(Int32 resultEOperationResult, Int32 encrypted, UInt64 size) x; \ +#define Z7_IFACEM_IFolderExtractToStreamCallback(x) \ + x(UseExtractToStream(Int32 *res)) \ + x(GetStream7(const wchar_t *name, Int32 isDir, ISequentialOutStream **outStream, Int32 askExtractMode, IGetProp *getProp)) \ + x(PrepareOperation7(Int32 askExtractMode)) \ + x(SetOperationResult8(Int32 resultEOperationResult, Int32 encrypted, UInt64 size)) \ -DECL_INTERFACE_SUB(IFolderExtractToStreamCallback, IUnknown, 0x01, 0x31) -{ - INTERFACE_IFolderExtractToStreamCallback(PURE) -}; +Z7_IFACE_CONSTR_FOLDERARC(IFolderExtractToStreamCallback, 0x31) +Z7_PURE_INTERFACES_END #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/LoadCodecs.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/LoadCodecs.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/LoadCodecs.cpp 2022-05-11 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/LoadCodecs.cpp 2023-04-05 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // LoadCodecs.cpp /* -EXTERNAL_CODECS +Z7_EXTERNAL_CODECS --------------- CCodecs::Load() tries to detect the directory with plugins. It stops the checking, if it can find any of the following items: @@ -22,7 +22,7 @@ EXPORT_CODECS ------------- - if (EXTERNAL_CODECS) is defined, then the code exports internal + if (Z7_EXTERNAL_CODECS) is defined, then the code exports internal codecs of client from CCodecs object to external plugins. 7-Zip doesn't use that feature. 7-Zip uses the scheme: - client application without internal plugins. @@ -43,29 +43,15 @@ #include "LoadCodecs.h" -using namespace NWindows; - -#ifdef NEW_FOLDER_INTERFACE -#include "../../../Common/StringToInt.h" -#endif - #include "../../ICoder.h" #include "../../Common/RegisterArc.h" #include "../../Common/RegisterCodec.h" -#ifdef EXTERNAL_CODECS - +#ifdef Z7_EXTERNAL_CODECS // #define EXPORT_CODECS - -#endif - -#ifdef NEW_FOLDER_INTERFACE -extern HINSTANCE g_hInstance; -#include "../../../Windows/ResourceString.h" -static const UINT kIconTypesResId = 100; #endif -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS #include "../../../Windows/FileFind.h" #include "../../../Windows/DLL.h" @@ -75,6 +61,7 @@ #include "../../../Windows/Registry.h" #endif +using namespace NWindows; using namespace NFile; @@ -119,10 +106,10 @@ #endif // _WIN32 -#endif // EXTERNAL_CODECS +#endif // Z7_EXTERNAL_CODECS -static const unsigned kNumArcsMax = 64; +static const unsigned kNumArcsMax = 72; static unsigned g_NumArcs = 0; static const CArcInfo *g_Arcs[kNumArcsMax]; @@ -133,8 +120,10 @@ g_Arcs[g_NumArcs] = arcInfo; g_NumArcs++; } + // else throw 1; } +/* static void SplitString(const UString &srcString, UStringVector &destStrings) { destStrings.Clear(); @@ -159,6 +148,7 @@ if (!s.IsEmpty()) destStrings.Add(s); } +*/ int CArcInfoEx::FindExtension(const UString &ext) const { @@ -187,7 +177,7 @@ } } -#ifndef _SFX +#ifndef Z7_SFX static bool ParseSignatures(const Byte *data, unsigned size, CObjectVector &signatures) { @@ -205,11 +195,11 @@ return true; } -#endif // _SFX +#endif // Z7_SFX // #include -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS static FString GetBaseFolderPrefixFromRegistry() { @@ -238,7 +228,7 @@ { NCOM::CPropVariant prop; isAssigned = false; - RINOK(getMethodProperty(index, propId, &prop)); + RINOK(getMethodProperty(index, propId, &prop)) if (prop.vt == VT_BSTR) { if (::SysStringByteLen(prop.bstrVal) != sizeof(GUID)) @@ -258,7 +248,7 @@ NCOM::CPropVariant prop; resVal = false; isAssigned = false; - RINOK(getMethodProperty(index, propId, &prop)); + RINOK(getMethodProperty(index, propId, &prop)) if (prop.vt == VT_BOOL) { isAssigned = true; @@ -269,45 +259,49 @@ return S_OK; } +#if defined(__clang__) +#pragma GCC diagnostic ignored "-Wc++98-compat-pedantic" +#endif -#define MY_GET_FUNC(dest, type, func) *(void **)(&dest) = (func); +#define MY_GET_FUNC(dest, type, lib, func) \ + dest = Z7_GET_PROC_ADDRESS(type, lib.Get_HMODULE(), func); // #define MY_GET_FUNC(dest, type, func) dest = (type)(func); -#define MY_GET_FUNC_LOC(dest, type, func) \ - type dest; MY_GET_FUNC(dest, type, func) +#define MY_GET_FUNC_LOC(dest, type, lib, func) \ + type dest; MY_GET_FUNC(dest, type, lib, func) HRESULT CCodecs::LoadCodecs() { CCodecLib &lib = Libs.Back(); - MY_GET_FUNC (lib.CreateDecoder, Func_CreateDecoder, lib.Lib.GetProc("CreateDecoder")); - MY_GET_FUNC (lib.CreateEncoder, Func_CreateEncoder, lib.Lib.GetProc("CreateEncoder")); - MY_GET_FUNC (lib.GetMethodProperty, Func_GetMethodProperty, lib.Lib.GetProc("GetMethodProperty")); + MY_GET_FUNC (lib.CreateDecoder, Func_CreateDecoder, lib.Lib, "CreateDecoder") + MY_GET_FUNC (lib.CreateEncoder, Func_CreateEncoder, lib.Lib, "CreateEncoder") + MY_GET_FUNC (lib.GetMethodProperty, Func_GetMethodProperty, lib.Lib, "GetMethodProperty") if (lib.GetMethodProperty) { UInt32 numMethods = 1; - MY_GET_FUNC_LOC (getNumberOfMethods, Func_GetNumberOfMethods, lib.Lib.GetProc("GetNumberOfMethods")); + MY_GET_FUNC_LOC (getNumberOfMethods, Func_GetNumberOfMethods, lib.Lib, "GetNumberOfMethods") if (getNumberOfMethods) { - RINOK(getNumberOfMethods(&numMethods)); + RINOK(getNumberOfMethods(&numMethods)) } for (UInt32 i = 0; i < numMethods; i++) { CDllCodecInfo info; info.LibIndex = Libs.Size() - 1; info.CodecIndex = i; - RINOK(GetCoderClass(lib.GetMethodProperty, i, NMethodPropID::kEncoder, info.Encoder, info.EncoderIsAssigned)); - RINOK(GetCoderClass(lib.GetMethodProperty, i, NMethodPropID::kDecoder, info.Decoder, info.DecoderIsAssigned)); - RINOK(GetMethodBoolProp(lib.GetMethodProperty, i, NMethodPropID::kIsFilter, info.IsFilter, info.IsFilter_Assigned)); + RINOK(GetCoderClass(lib.GetMethodProperty, i, NMethodPropID::kEncoder, info.Encoder, info.EncoderIsAssigned)) + RINOK(GetCoderClass(lib.GetMethodProperty, i, NMethodPropID::kDecoder, info.Decoder, info.DecoderIsAssigned)) + RINOK(GetMethodBoolProp(lib.GetMethodProperty, i, NMethodPropID::kIsFilter, info.IsFilter, info.IsFilter_Assigned)) Codecs.Add(info); } } - MY_GET_FUNC_LOC (getHashers, Func_GetHashers, lib.Lib.GetProc("GetHashers")); + MY_GET_FUNC_LOC (getHashers, Func_GetHashers, lib.Lib, "GetHashers") if (getHashers) { - RINOK(getHashers(&lib.ComHashers)); + RINOK(getHashers(&lib.ComHashers)) if (lib.ComHashers) { UInt32 numMethods = lib.ComHashers->GetNumHashers(); @@ -330,7 +324,7 @@ UInt32 index, PROPID propID, NCOM::CPropVariant &prop) { if (getProp2) - return getProp2(index, propID, &prop);; + return getProp2(index, propID, &prop); return getProp(propID, &prop); } @@ -341,7 +335,7 @@ { res = false; NCOM::CPropVariant prop; - RINOK(GetProp(getProp, getProp2, index, propID, prop)); + RINOK(GetProp(getProp, getProp2, index, propID, prop)) if (prop.vt == VT_BOOL) res = VARIANT_BOOLToBool(prop.boolVal); else if (prop.vt != VT_EMPTY) @@ -357,7 +351,7 @@ res = 0; defined = false; NCOM::CPropVariant prop; - RINOK(GetProp(getProp, getProp2, index, propID, prop)); + RINOK(GetProp(getProp, getProp2, index, propID, prop)) if (prop.vt == VT_UI4) { res = prop.ulVal; @@ -375,7 +369,7 @@ { res.Empty(); NCOM::CPropVariant prop; - RINOK(GetProp(getProp, getProp2, index, propID, prop)); + RINOK(GetProp(getProp, getProp2, index, propID, prop)) if (prop.vt == VT_BSTR) res.SetFromBstr(prop.bstrVal); else if (prop.vt != VT_EMPTY) @@ -390,7 +384,7 @@ { bb.Free(); NCOM::CPropVariant prop; - RINOK(GetProp(getProp, getProp2, index, propID, prop)); + RINOK(GetProp(getProp, getProp2, index, propID, prop)) if (prop.vt == VT_BSTR) { UINT len = ::SysStringByteLen(prop.bstrVal); @@ -413,22 +407,22 @@ const NDLL::CLibrary &lib = Libs.Back().Lib; Func_GetHandlerProperty getProp = NULL; - MY_GET_FUNC_LOC (getProp2, Func_GetHandlerProperty2, lib.GetProc("GetHandlerProperty2")); - MY_GET_FUNC_LOC (getIsArc, Func_GetIsArc, lib.GetProc("GetIsArc")); + MY_GET_FUNC_LOC (getProp2, Func_GetHandlerProperty2, lib, "GetHandlerProperty2") + MY_GET_FUNC_LOC (getIsArc, Func_GetIsArc, lib, "GetIsArc") UInt32 numFormats = 1; if (getProp2) { - MY_GET_FUNC_LOC (getNumberOfFormats, Func_GetNumberOfFormats, lib.GetProc("GetNumberOfFormats")); + MY_GET_FUNC_LOC (getNumberOfFormats, Func_GetNumberOfFormats, lib, "GetNumberOfFormats") if (getNumberOfFormats) { - RINOK(getNumberOfFormats(&numFormats)); + RINOK(getNumberOfFormats(&numFormats)) } } else { - MY_GET_FUNC (getProp, Func_GetHandlerProperty, lib.GetProc("GetHandlerProperty")); + MY_GET_FUNC (getProp, Func_GetHandlerProperty, lib, "GetHandlerProperty") if (!getProp) return S_OK; } @@ -439,7 +433,7 @@ item.LibIndex = (int)(Libs.Size() - 1); item.FormatIndex = i; - RINOK(GetProp_String(getProp, getProp2, i, NArchive::NHandlerPropID::kName, item.Name)); + RINOK(GetProp_String(getProp, getProp2, i, NArchive::NHandlerPropID::kName, item.Name)) { NCOM::CPropVariant prop; @@ -454,18 +448,18 @@ } UString ext, addExt; - RINOK(GetProp_String(getProp, getProp2, i, NArchive::NHandlerPropID::kExtension, ext)); - RINOK(GetProp_String(getProp, getProp2, i, NArchive::NHandlerPropID::kAddExtension, addExt)); + RINOK(GetProp_String(getProp, getProp2, i, NArchive::NHandlerPropID::kExtension, ext)) + RINOK(GetProp_String(getProp, getProp2, i, NArchive::NHandlerPropID::kAddExtension, addExt)) item.AddExts(ext, addExt); GetProp_Bool(getProp, getProp2, i, NArchive::NHandlerPropID::kUpdate, item.UpdateEnabled); bool flags_Defined = false; - RINOK(GetProp_UInt32(getProp, getProp2, i, NArchive::NHandlerPropID::kFlags, item.Flags, flags_Defined)); + RINOK(GetProp_UInt32(getProp, getProp2, i, NArchive::NHandlerPropID::kFlags, item.Flags, flags_Defined)) item.NewInterface = flags_Defined; if (!flags_Defined) // && item.UpdateEnabled { // support for DLL version before 9.31: - for (unsigned j = 0; j < ARRAY_SIZE(kArcFlagsPars); j += 2) + for (unsigned j = 0; j < Z7_ARRAY_SIZE(kArcFlagsPars); j += 2) { bool val = false; GetProp_Bool(getProp, getProp2, i, kArcFlagsPars[j], val); @@ -476,21 +470,21 @@ { bool defined = false; - RINOK(GetProp_UInt32(getProp, getProp2, i, NArchive::NHandlerPropID::kTimeFlags, item.TimeFlags, defined)); + RINOK(GetProp_UInt32(getProp, getProp2, i, NArchive::NHandlerPropID::kTimeFlags, item.TimeFlags, defined)) } CByteBuffer sig; - RINOK(GetProp_RawData(getProp, getProp2, i, NArchive::NHandlerPropID::kSignature, sig)); + RINOK(GetProp_RawData(getProp, getProp2, i, NArchive::NHandlerPropID::kSignature, sig)) if (sig.Size() != 0) item.Signatures.Add(sig); else { - RINOK(GetProp_RawData(getProp, getProp2, i, NArchive::NHandlerPropID::kMultiSignature, sig)); + RINOK(GetProp_RawData(getProp, getProp2, i, NArchive::NHandlerPropID::kMultiSignature, sig)) ParseSignatures(sig, (unsigned)sig.Size(), item.Signatures); } bool signatureOffset_Defined; - RINOK(GetProp_UInt32(getProp, getProp2, i, NArchive::NHandlerPropID::kSignatureOffset, item.SignatureOffset, signatureOffset_Defined)); + RINOK(GetProp_UInt32(getProp, getProp2, i, NArchive::NHandlerPropID::kSignatureOffset, item.SignatureOffset, signatureOffset_Defined)) // bool version_Defined; // RINOK(GetProp_UInt32(getProp, getProp2, i, NArchive::NHandlerPropID::kVersion, item.Version, version_Defined)); @@ -503,7 +497,7 @@ return S_OK; } -#ifdef _7ZIP_LARGE_PAGES +#ifdef Z7_LARGE_PAGES extern "C" { extern SIZE_T g_LargePageSize; @@ -513,12 +507,57 @@ void CCodecs::AddLastError(const FString &path) { - HRESULT res = GetLastError_noZero_HRESULT(); + const HRESULT res = GetLastError_noZero_HRESULT(); CCodecError &error = Errors.AddNew(); error.Path = path; error.ErrorCode = res; } + +static bool IsSupportedDll(CCodecLib &lib) +{ + MY_GET_FUNC_LOC ( + f_GetModuleProp, + Func_GetModuleProp, lib.Lib, + "GetModuleProp") + /* p7zip and 7-Zip before v23 used virtual destructor in IUnknown, + if _WIN32 is not defined */ + UInt32 flags = + #ifdef _WIN32 + NModuleInterfaceType::k_IUnknown_VirtDestructor_No; + #else + NModuleInterfaceType::k_IUnknown_VirtDestructor_Yes; + #endif + if (f_GetModuleProp) + { + { + NCOM::CPropVariant prop; + if (f_GetModuleProp(NModulePropID::kInterfaceType, &prop) == S_OK) + { + if (prop.vt == VT_UI4) + flags = prop.ulVal; + else if (prop.vt != VT_EMPTY) + return false; + } + } + { + NCOM::CPropVariant prop; + if (f_GetModuleProp(NModulePropID::kVersion, &prop) == S_OK) + { + if (prop.vt == VT_UI4) + lib.Version = prop.ulVal; + } + } + } + if ( + flags + // (flags & NModuleFlags::kMask) + != NModuleInterfaceType::k_IUnknown_VirtDestructor_ThisModule) + return false; + return true; +} + + HRESULT CCodecs::LoadDll(const FString &dllPath, bool needCheckDll, bool *loadedOK) { if (loadedOK) @@ -537,7 +576,7 @@ // #define ERROR_BAD_EXE_FORMAT 193L */ // return GetLastError_noZero_HRESULT(); - DWORD lastError = GetLastError(); + const DWORD lastError = GetLastError(); if (lastError != ERROR_BAD_EXE_FORMAT) { CCodecError &error = Errors.AddNew(); @@ -558,20 +597,30 @@ bool used = false; // HRESULT res = S_OK; - if (lib.Lib.Load(dllPath)) + if (lib.Lib.Load(dllPath)) + { + if (!IsSupportedDll(lib)) + { + CCodecError &error = Errors.AddNew(); + error.Path = dllPath; + error.Message = "the module is not compatible with program"; + } + else { if (loadedOK) *loadedOK = true; + /* #ifdef NEW_FOLDER_INTERFACE lib.LoadIcons(); #endif + */ /* { - MY_GET_FUNC_LOC (_LibStartup, Func_LibStartup, lib.Lib.GetProc("LibStartup")); - if (_LibStartup) + MY_GET_FUNC_LOC (_libStartup, Func_libStartup, lib.Lib, "LibStartup") + if (_libStartup) { - HRESULT res = _LibStartup(); + HRESULT res = _libStartup(); if (res != 0) { CCodecError &error = Errors.AddNew(); @@ -582,10 +631,10 @@ } */ - #ifdef _7ZIP_LARGE_PAGES + #ifdef Z7_LARGE_PAGES if (g_LargePageSize != 0) { - MY_GET_FUNC_LOC (setLargePageMode, Func_SetLargePageMode, lib.Lib.GetProc("SetLargePageMode")); + MY_GET_FUNC_LOC (setLargePageMode, Func_SetLargePageMode, lib.Lib, "SetLargePageMode") if (setLargePageMode) setLargePageMode(); } @@ -593,14 +642,14 @@ if (CaseSensitive_Change) { - MY_GET_FUNC_LOC (setCaseSensitive, Func_SetCaseSensitive, lib.Lib.GetProc("SetCaseSensitive")); + MY_GET_FUNC_LOC (setCaseSensitive, Func_SetCaseSensitive, lib.Lib, "SetCaseSensitive") if (setCaseSensitive) setCaseSensitive(CaseSensitive ? 1 : 0); } /* { - MY_GET_FUNC_LOC (setClientVersion, Func_SetClientVersion, lib.Lib.GetProc("SetClientVersion")); + MY_GET_FUNC_LOC (setClientVersion, Func_SetClientVersion, lib.Lib, "SetClientVersion") if (setClientVersion) { // const UInt32 kVersion = (MY_VER_MAJOR << 16) | MY_VER_MINOR; @@ -610,7 +659,7 @@ */ - MY_GET_FUNC (lib.CreateObject, Func_CreateObject, lib.Lib.GetProc("CreateObject")); + MY_GET_FUNC (lib.CreateObject, Func_CreateObject, lib.Lib, "CreateObject") { unsigned startSize = Codecs.Size() + Hashers.Size(); HRESULT res = LoadCodecs(); @@ -640,7 +689,8 @@ } */ } - else + } + else { AddLastError(dllPath); } @@ -686,7 +736,7 @@ continue; #endif - RINOK(LoadDll(folderPrefix + fi.Name, true)); + RINOK(LoadDll(folderPrefix + fi.Name, true)) } return S_OK; } @@ -714,18 +764,20 @@ // OutputDebugStringA("~CloseLibs end"); } -#endif // EXTERNAL_CODECS +#endif // Z7_EXTERNAL_CODECS HRESULT CCodecs::Load() { + /* #ifdef NEW_FOLDER_INTERFACE InternalIcons.LoadIcons(g_hInstance); #endif + */ Formats.Clear(); - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS Errors.Clear(); MainDll_ErrorPath.Empty(); Codecs.Clear(); @@ -751,7 +803,7 @@ item.AddExts(e, ae); } - #ifndef _SFX + #ifndef Z7_SFX item.CreateOutArchive = arc.CreateOutArchive; item.UpdateEnabled = (arc.CreateOutArchive != NULL); @@ -774,16 +826,16 @@ // printf("\nLoad codecs \n"); - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS const FString baseFolder = GetBaseFolderPrefixFromRegistry(); { bool loadedOK; - RINOK(LoadDll(baseFolder + kMainDll, false, &loadedOK)); + RINOK(LoadDll(baseFolder + kMainDll, false, &loadedOK)) if (!loadedOK) MainDll_ErrorPath = kMainDll; } - RINOK(LoadDllsFromFolder(baseFolder + kCodecsFolderName)); - RINOK(LoadDllsFromFolder(baseFolder + kFormatsFolderName)); + RINOK(LoadDllsFromFolder(baseFolder + kCodecsFolderName)) + RINOK(LoadDllsFromFolder(baseFolder + kFormatsFolderName)) NeedSetLibCodecs = true; @@ -806,10 +858,10 @@ FOR_VECTOR(i, Libs) { CCodecLib &lib = Libs[i]; - MY_GET_FUNC (lib.SetCodecs, Func_SetCodecs, lib.Lib.GetProc("SetCodecs")); + MY_GET_FUNC (lib.SetCodecs, Func_SetCodecs, lib.Lib, "SetCodecs") if (lib.SetCodecs) { - RINOK(lib.SetCodecs(this)); + RINOK(lib.SetCodecs(this)) } } } @@ -821,7 +873,7 @@ return S_OK; } -#ifndef _SFX +#ifndef Z7_SFX int CCodecs::FindFormatForArchiveName(const UString &arcPath) const { @@ -887,60 +939,10 @@ return true; } -#endif // _SFX - - -#ifdef NEW_FOLDER_INTERFACE - -void CCodecIcons::LoadIcons(HMODULE m) -{ - UString iconTypes; - MyLoadString(m, kIconTypesResId, iconTypes); - UStringVector pairs; - SplitString(iconTypes, pairs); - FOR_VECTOR (i, pairs) - { - const UString &s = pairs[i]; - int pos = s.Find(L':'); - CIconPair iconPair; - iconPair.IconIndex = -1; - if (pos < 0) - pos = (int)s.Len(); - else - { - const UString num = s.Ptr((unsigned)pos + 1); - if (!num.IsEmpty()) - { - const wchar_t *end; - iconPair.IconIndex = (int)ConvertStringToUInt32(num, &end); - if (*end != 0) - continue; - } - } - iconPair.Ext = s.Left((unsigned)pos); - IconPairs.Add(iconPair); - } -} - -bool CCodecIcons::FindIconIndex(const UString &ext, int &iconIndex) const -{ - iconIndex = -1; - FOR_VECTOR (i, IconPairs) - { - const CIconPair &pair = IconPairs[i]; - if (ext.IsEqualTo_NoCase(pair.Ext)) - { - iconIndex = pair.IconIndex; - return true; - } - } - return false; -} - -#endif // NEW_FOLDER_INTERFACE +#endif // Z7_SFX -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS // #define EXPORT_CODECS @@ -964,24 +966,24 @@ #endif // EXPORT_CODECS -STDMETHODIMP CCodecs::GetNumMethods(UInt32 *numMethods) +Z7_COM7F_IMF(CCodecs::GetNumMethods(UInt32 *numMethods)) { *numMethods = NUM_EXPORT_CODECS - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS + Codecs.Size() #endif ; return S_OK; } -STDMETHODIMP CCodecs::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CCodecs::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { #ifdef EXPORT_CODECS if (index < g_NumCodecs) return GetMethodProperty(index, propID, value); #endif - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS const CDllCodecInfo &ci = Codecs[index - NUM_EXPORT_CODECS]; if (propID == NMethodPropID::kDecoderIsAssigned || @@ -1010,14 +1012,14 @@ #endif } -STDMETHODIMP CCodecs::CreateDecoder(UInt32 index, const GUID *iid, void **coder) +Z7_COM7F_IMF(CCodecs::CreateDecoder(UInt32 index, const GUID *iid, void **coder)) { #ifdef EXPORT_CODECS if (index < g_NumCodecs) return CreateDecoder(index, iid, coder); #endif - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS const CDllCodecInfo &ci = Codecs[index - NUM_EXPORT_CODECS]; if (ci.DecoderIsAssigned) { @@ -1033,14 +1035,14 @@ #endif } -STDMETHODIMP CCodecs::CreateEncoder(UInt32 index, const GUID *iid, void **coder) +Z7_COM7F_IMF(CCodecs::CreateEncoder(UInt32 index, const GUID *iid, void **coder)) { #ifdef EXPORT_CODECS if (index < g_NumCodecs) return CreateEncoder(index, iid, coder); #endif - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS const CDllCodecInfo &ci = Codecs[index - NUM_EXPORT_CODECS]; if (ci.EncoderIsAssigned) { @@ -1057,23 +1059,23 @@ } -STDMETHODIMP_(UInt32) CCodecs::GetNumHashers() +Z7_COM7F_IMF2(UInt32, CCodecs::GetNumHashers()) { return NUM_EXPORT_HASHERS - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS + Hashers.Size() #endif ; } -STDMETHODIMP CCodecs::GetHasherProp(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CCodecs::GetHasherProp(UInt32 index, PROPID propID, PROPVARIANT *value)) { #ifdef EXPORT_CODECS if (index < g_NumHashers) return ::GetHasherProp(index, propID, value); #endif - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS const CDllHasherInfo &ci = Hashers[index - NUM_EXPORT_HASHERS]; return Libs[ci.LibIndex].ComHashers->GetHasherProp(ci.HasherIndex, propID, value); #else @@ -1081,13 +1083,13 @@ #endif } -STDMETHODIMP CCodecs::CreateHasher(UInt32 index, IHasher **hasher) +Z7_COM7F_IMF(CCodecs::CreateHasher(UInt32 index, IHasher **hasher)) { #ifdef EXPORT_CODECS if (index < g_NumHashers) return CreateHasher(index, hasher); #endif - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS const CDllHasherInfo &ci = Hashers[index - NUM_EXPORT_HASHERS]; return Libs[ci.LibIndex].ComHashers->CreateHasher(ci.HasherIndex, hasher); #else @@ -1102,7 +1104,7 @@ return -1; #endif - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS const CDllCodecInfo &ci = Codecs[index - NUM_EXPORT_CODECS]; return (int)ci.LibIndex; #else @@ -1117,7 +1119,7 @@ return -1; #endif - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS const CDllHasherInfo &ci = Hashers[index - NUM_EXPORT_HASHERS]; return (int)ci.LibIndex; #else @@ -1140,7 +1142,7 @@ } #endif - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS return Codecs[index - NUM_EXPORT_CODECS].DecoderIsAssigned; #else return false; @@ -1163,7 +1165,7 @@ } #endif - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS return Codecs[index - NUM_EXPORT_CODECS].EncoderIsAssigned; #else return false; @@ -1190,7 +1192,7 @@ } #endif - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS { const CDllCodecInfo &c = Codecs[index - NUM_EXPORT_CODECS]; isAssigned = c.IsFilter_Assigned; @@ -1217,7 +1219,7 @@ HRESULT CCodecs::GetCodec_Id(UInt32 index, UInt64 &id) { NCOM::CPropVariant prop; - RINOK(GetProperty(index, NMethodPropID::kID, &prop)); + RINOK(GetProperty(index, NMethodPropID::kID, &prop)) if (prop.vt != VT_UI8) return E_INVALIDARG; id = prop.uhVal.QuadPart; @@ -1286,9 +1288,9 @@ } } -#endif // EXTERNAL_CODECS +#endif // Z7_EXTERNAL_CODECS -#ifndef _SFX +#ifndef Z7_SFX extern unsigned g_NumCodecs; extern const CCodecInfo *g_Codecs[]; @@ -1311,7 +1313,7 @@ } - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS { UInt32 numMethods; if (GetNumMethods(&numMethods) == S_OK) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/LoadCodecs.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/LoadCodecs.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/LoadCodecs.h 2022-05-11 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/LoadCodecs.h 2023-04-06 09:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // LoadCodecs.h -#ifndef __LOAD_CODECS_H -#define __LOAD_CODECS_H +#ifndef ZIP7_INC_LOAD_CODECS_H +#define ZIP7_INC_LOAD_CODECS_H /* Client application uses LoadCodecs.* to load plugins to @@ -10,26 +10,26 @@ 2) Codecs - external codecs 3) Hashers - external hashers -EXTERNAL_CODECS +Z7_EXTERNAL_CODECS --------------- - if EXTERNAL_CODECS is defined, then the code tries to load external + if Z7_EXTERNAL_CODECS is defined, then the code tries to load external plugins from DLL files (shared libraries). There are two types of executables in 7-Zip: 1) Executable that uses external plugins must be compiled - with EXTERNAL_CODECS defined: + with Z7_EXTERNAL_CODECS defined: - 7z.exe, 7zG.exe, 7zFM.exe - Note: EXTERNAL_CODECS is used also in CPP/7zip/Common/CreateCoder.h + Note: Z7_EXTERNAL_CODECS is used also in CPP/7zip/Common/CreateCoder.h that code is used in plugin module (7z.dll). - 2) Standalone modules are compiled without EXTERNAL_CODECS: + 2) Standalone modules are compiled without Z7_EXTERNAL_CODECS: - SFX modules: 7z.sfx, 7zCon.sfx - standalone versions of console 7-Zip: 7za.exe, 7zr.exe - if EXTERNAL_CODECS is defined, CCodecs class implements interfaces: + if Z7_EXTERNAL_CODECS is defined, CCodecs class implements interfaces: - ICompressCodecsInfo : for Codecs - IHashers : for Hashers @@ -51,7 +51,7 @@ #include "../../../Common/MyString.h" #include "../../../Common/ComTry.h" -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS #include "../../../Windows/DLL.h" #endif @@ -60,7 +60,7 @@ #include "../../Archive/IArchive.h" -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS struct CDllCodecInfo { @@ -104,19 +104,21 @@ UString Name; CObjectVector Exts; - #ifndef _SFX + #ifndef Z7_SFX Func_CreateOutArchive CreateOutArchive; bool UpdateEnabled; bool NewInterface; // UInt32 Version; UInt32 SignatureOffset; CObjectVector Signatures; + /* #ifdef NEW_FOLDER_INTERFACE UStringVector AssociateExts; #endif + */ #endif - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS int LibIndex; UInt32 FormatIndex; CLSID ClassID; @@ -124,10 +126,10 @@ int Compare(const CArcInfoEx &a) const { - int res = Name.Compare(a.Name); + const int res = Name.Compare(a.Name); if (res != 0) return res; - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS return MyCompare(LibIndex, a.LibIndex); #else return 0; @@ -192,6 +194,7 @@ bool Is_Tar() const { return Name.IsEqualTo_Ascii_NoCase("tar"); } bool Is_Zip() const { return Name.IsEqualTo_Ascii_NoCase("zip"); } bool Is_Rar() const { return Name.IsEqualTo_Ascii_NoCase("rar"); } + bool Is_Zstd() const { return Name.IsEqualTo_Ascii_NoCase("zstd"); } /* UString GetAllExtensions() const @@ -200,7 +203,7 @@ for (int i = 0; i < Exts.Size(); i++) { if (i > 0) - s += ' '; + s.Add_Space(); s += Exts[i].Ext; } return s; @@ -215,42 +218,23 @@ TimeFlags(0), CreateInArchive(NULL), IsArcFunc(NULL) - #ifndef _SFX + #ifndef Z7_SFX , CreateOutArchive(NULL) , UpdateEnabled(false) , NewInterface(false) // , Version(0) , SignatureOffset(0) #endif - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS , LibIndex(-1) #endif {} }; -#ifdef NEW_FOLDER_INTERFACE - -struct CCodecIcons -{ - struct CIconPair - { - UString Ext; - int IconIndex; - }; - CObjectVector IconPairs; - - void LoadIcons(HMODULE m); - bool FindIconIndex(const UString &ext, int &iconIndex) const; -}; - -#endif -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS struct CCodecLib - #ifdef NEW_FOLDER_INTERFACE - : public CCodecIcons - #endif { NWindows::NDLL::CLibrary Lib; FString Path; @@ -262,17 +246,23 @@ Func_SetCodecs SetCodecs; CMyComPtr ComHashers; + + UInt32 Version; + /* #ifdef NEW_FOLDER_INTERFACE - void LoadIcons() { CCodecIcons::LoadIcons((HMODULE)Lib); } + CCodecIcons CodecIcons; + void LoadIcons() { CodecIcons.LoadIcons((HMODULE)Lib); } #endif + */ CCodecLib(): CreateObject(NULL), GetMethodProperty(NULL), CreateDecoder(NULL), CreateEncoder(NULL), - SetCodecs(NULL) + SetCodecs(NULL), + Version(0) {} }; @@ -301,8 +291,8 @@ }; -class CCodecs: - #ifdef EXTERNAL_CODECS +class CCodecs Z7_final: + #ifdef Z7_EXTERNAL_CODECS public ICompressCodecsInfo, public IHashers, #else @@ -310,9 +300,15 @@ #endif public CMyUnknownImp { - CLASS_NO_COPY(CCodecs); +#ifdef Z7_EXTERNAL_CODECS + Z7_IFACES_IMP_UNK_2(ICompressCodecsInfo, IHashers) +#else + Z7_COM_UNKNOWN_IMP_0 +#endif // Z7_EXTERNAL_CODECS + + Z7_CLASS_NO_COPY(CCodecs) public: - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS CObjectVector Libs; FString MainDll_ErrorPath; @@ -323,7 +319,7 @@ class CReleaser { - CLASS_NO_COPY(CReleaser); + Z7_CLASS_NO_COPY(CReleaser) /* CCodecsReleaser object releases CCodecs links. 1) CCodecs is COM object that is deleted when all links to that object will be released/ @@ -352,13 +348,15 @@ #endif + /* #ifdef NEW_FOLDER_INTERFACE CCodecIcons InternalIcons; #endif + */ CObjectVector Formats; - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS CRecordVector Codecs; CRecordVector Hashers; #endif @@ -367,7 +365,7 @@ bool CaseSensitive; CCodecs(): - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS NeedSetLibCodecs(true), #endif CaseSensitive_Change(false), @@ -386,34 +384,14 @@ HRESULT Load(); - #ifndef _SFX + #ifndef Z7_SFX int FindFormatForArchiveName(const UString &arcPath) const; int FindFormatForExtension(const UString &ext) const; int FindFormatForArchiveType(const UString &arcType) const; bool FindFormatForArchiveType(const UString &arcType, CIntVector &formatIndices) const; #endif - #ifdef EXTERNAL_CODECS - - MY_UNKNOWN_IMP2(ICompressCodecsInfo, IHashers) - - STDMETHOD(GetNumMethods)(UInt32 *numMethods); - STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value); - STDMETHOD(CreateDecoder)(UInt32 index, const GUID *iid, void **coder); - STDMETHOD(CreateEncoder)(UInt32 index, const GUID *iid, void **coder); - - STDMETHOD_(UInt32, GetNumHashers)(); - STDMETHOD(GetHasherProp)(UInt32 index, PROPID propID, PROPVARIANT *value); - STDMETHOD(CreateHasher)(UInt32 index, IHasher **hasher); - - #else - - MY_UNKNOWN_IMP - - #endif // EXTERNAL_CODECS - - - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS int GetCodec_LibIndex(UInt32 index) const; bool GetCodec_DecoderIsAssigned(UInt32 index) const; @@ -435,7 +413,7 @@ HRESULT CreateInArchive(unsigned formatIndex, CMyComPtr &archive) const { const CArcInfoEx &ai = Formats[formatIndex]; - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS if (ai.LibIndex < 0) #endif { @@ -444,17 +422,17 @@ return S_OK; COM_TRY_END } - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS return CreateArchiveHandler(ai, false, (void **)&archive); #endif } - #ifndef _SFX + #ifndef Z7_SFX HRESULT CreateOutArchive(unsigned formatIndex, CMyComPtr &archive) const { const CArcInfoEx &ai = Formats[formatIndex]; - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS if (ai.LibIndex < 0) #endif { @@ -464,7 +442,7 @@ COM_TRY_END } - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS return CreateArchiveHandler(ai, true, (void **)&archive); #endif } @@ -484,21 +462,21 @@ void Get_CodecsInfoUser_Vector(CObjectVector &v); - #endif // _SFX + #endif // Z7_SFX }; -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS #define CREATE_CODECS_OBJECT \ CCodecs *codecs = new CCodecs; \ - CExternalCodecs __externalCodecs; \ - __externalCodecs.GetCodecs = codecs; \ - __externalCodecs.GetHashers = codecs; \ + CExternalCodecs _externalCodecs; \ + _externalCodecs.GetCodecs = codecs; \ + _externalCodecs.GetHashers = codecs; \ CCodecs::CReleaser codecsReleaser; \ codecsReleaser.Set(codecs); #else #define CREATE_CODECS_OBJECT \ CCodecs *codecs = new CCodecs; \ - CMyComPtr __codecsRef = codecs; + CMyComPtr _codecsRef = codecs; #endif #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/OpenArchive.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/OpenArchive.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/OpenArchive.cpp 2022-04-30 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/OpenArchive.cpp 2023-04-06 05:00:00.000000000 +0000 @@ -29,11 +29,11 @@ #include "DefaultName.h" #include "OpenArchive.h" -#ifndef _SFX +#ifndef Z7_SFX #include "SetProperties.h" #endif -#ifndef _SFX +#ifndef Z7_SFX #ifdef SHOW_DEBUG_INFO #define PRF(x) x #else @@ -95,7 +95,7 @@ using namespace NWindows; /* -#ifdef _SFX +#ifdef Z7_SFX #define OPEN_PROPS_PARAM #else #define OPEN_PROPS_PARAM , props @@ -111,7 +111,7 @@ } */ -#ifndef _SFX +#ifndef Z7_SFX namespace NArchive { namespace NParser { @@ -172,23 +172,14 @@ } }; -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_1( + IInArchiveGetStream +) public: CObjectVector _items; UInt64 _maxEndOffset; CMyComPtr _stream; - MY_UNKNOWN_IMP2( - IInArchive, - IInArchiveGetStream) - - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); - UInt64 GetLastEnd() const { if (_items.IsEmpty()) @@ -300,7 +291,7 @@ IMP_IInArchive_Props IMP_IInArchive_ArcProps_NO -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback * /* openArchiveCallback */) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback * /* openArchiveCallback */)) { COM_TRY_BEGIN { @@ -311,20 +302,20 @@ COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _items.Clear(); _stream.Release(); return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _items.Size(); return S_OK; } -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -340,12 +331,12 @@ UString s(sz); if (!item.Name.IsEmpty()) { - s += '.'; + s.Add_Dot(); s += item.Name; } if (!item.Extension.IsEmpty()) { - s += '.'; + s.Add_Dot(); s += item.Extension; } prop = s; break; @@ -365,12 +356,12 @@ COM_TRY_END } -HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback) +Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems, + Int32 testMode, IArchiveExtractCallback *extractCallback)) { COM_TRY_BEGIN - bool allFilesMode = (numItems == (UInt32)(Int32)-1); + const bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _items.Size(); if (_stream && numItems == 0) @@ -401,35 +392,35 @@ { lps->InSize = totalSize; lps->OutSize = totalSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr realOutStream; - Int32 askMode = testMode ? + const Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; - UInt32 index = allFilesMode ? i : indices[i]; + const UInt32 index = allFilesMode ? i : indices[i]; const CParseItem &item = _items[index]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); + RINOK(extractCallback->GetStream(index, &realOutStream, askMode)) UInt64 unpackSize = item.Size; totalSize += unpackSize; bool skipMode = false; if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) outStreamSpec->SetStream(realOutStream); realOutStream.Release(); outStreamSpec->Init(skipMode ? 0 : unpackSize, true); Int32 opRes = NExtract::NOperationResult::kOK; - RINOK(_stream->Seek((Int64)item.Offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(_stream, item.Offset)) streamSpec->Init(unpackSize); - RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); + RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)) if (outStreamSpec->GetRem() != 0) opRes = NExtract::NOperationResult::kDataError; outStreamSpec->ReleaseStream(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } return S_OK; @@ -438,7 +429,7 @@ } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN const CParseItem &item = _items[index]; @@ -454,7 +445,7 @@ { NCOM::CPropVariant prop; result = false; - RINOK(arc->GetProperty(index, propID, &prop)); + RINOK(arc->GetProperty(index, propID, &prop)) if (prop.vt == VT_BOOL) result = VARIANT_BOOLToBool(prop.boolVal); else if (prop.vt != VT_EMPTY) @@ -486,7 +477,7 @@ { NCOM::CPropVariant prop; result = false; - RINOK(arc->GetArchiveProperty(propid, &prop)); + RINOK(arc->GetArchiveProperty(propid, &prop)) if (prop.vt == VT_BOOL) result = VARIANT_BOOLToBool(prop.boolVal); else if (prop.vt != VT_EMPTY) @@ -498,7 +489,7 @@ { defined = false; NCOM::CPropVariant prop; - RINOK(arc->GetArchiveProperty(propid, &prop)); + RINOK(arc->GetArchiveProperty(propid, &prop)) switch (prop.vt) { case VT_UI4: result = prop.ulVal; break; @@ -516,7 +507,7 @@ { defined = false; NCOM::CPropVariant prop; - RINOK(arc->GetArchiveProperty(propid, &prop)); + RINOK(arc->GetArchiveProperty(propid, &prop)) switch (prop.vt) { case VT_UI4: result = prop.ulVal; break; @@ -530,7 +521,7 @@ return S_OK; } -#ifndef _SFX +#ifndef Z7_SFX HRESULT CArc::GetItem_PathToParent(UInt32 index, UInt32 parent, UStringVector &parts) const { @@ -550,14 +541,14 @@ const void *p; UInt32 size; UInt32 propType; - RINOK(GetRawProps->GetRawProp(curIndex, kpidName, &p, &size, &propType)); + RINOK(GetRawProps->GetRawProp(curIndex, kpidName, &p, &size, &propType)) if (p && propType == PROP_DATA_TYPE_wchar_t_PTR_Z_LE) s = (const wchar_t *)p; else #endif { NCOM::CPropVariant prop; - RINOK(Archive->GetProperty(curIndex, kpidName, &prop)); + RINOK(Archive->GetProperty(curIndex, kpidName, &prop)) if (prop.vt == VT_BSTR && prop.bstrVal) s.SetFromBstr(prop.bstrVal); else if (prop.vt == VT_EMPTY) @@ -568,7 +559,7 @@ UInt32 curParent = (UInt32)(Int32)-1; UInt32 parentType = 0; - RINOK(GetRawProps->GetParent(curIndex, &curParent, &parentType)); + RINOK(GetRawProps->GetParent(curIndex, &curParent, &parentType)) // 18.06: fixed : we don't want to split name to parts /* @@ -742,7 +733,7 @@ { NCOM::CPropVariant prop; - RINOK(Archive->GetProperty(index, kpidPath, &prop)); + RINOK(Archive->GetProperty(index, kpidPath, &prop)) if (prop.vt == VT_BSTR && prop.bstrVal) result.SetFromBstr(prop.bstrVal); else if (prop.vt == VT_EMPTY) @@ -762,15 +753,15 @@ { result.Empty(); bool isDir; - RINOK(Archive_IsItem_Dir(Archive, index, isDir)); + RINOK(Archive_IsItem_Dir(Archive, index, isDir)) if (!isDir) { result = DefaultName; NCOM::CPropVariant prop; - RINOK(Archive->GetProperty(index, kpidExtension, &prop)); + RINOK(Archive->GetProperty(index, kpidExtension, &prop)) if (prop.vt == VT_BSTR) { - result += '.'; + result.Add_Dot(); result += prop.bstrVal; } else if (prop.vt != VT_EMPTY) @@ -781,11 +772,11 @@ HRESULT CArc::GetItem_Path2(UInt32 index, UString &result) const { - RINOK(GetItem_Path(index, result)); + RINOK(GetItem_Path(index, result)) if (Ask_Deleted) { bool isDeleted = false; - RINOK(Archive_IsItem_Deleted(Archive, index, isDeleted)); + RINOK(Archive_IsItem_Deleted(Archive, index, isDeleted)) if (isDeleted) result.Insert(0, L"[DELETED]" WSTRING_PATH_SEPARATOR); } @@ -830,12 +821,12 @@ item.PathParts.Clear(); - RINOK(Archive_IsItem_Dir(Archive, index, item.IsDir)); + RINOK(Archive_IsItem_Dir(Archive, index, item.IsDir)) item.MainIsDir = item.IsDir; - RINOK(GetItem_Path2(index, item.Path)); + RINOK(GetItem_Path2(index, item.Path)) - #ifndef _SFX + #ifndef Z7_SFX UInt32 mainIndex = index; #endif @@ -844,7 +835,7 @@ item.MainPath = item.Path; if (Ask_AltStream) { - RINOK(Archive_IsItem_AltStream(Archive, index, item.IsAltStream)); + RINOK(Archive_IsItem_AltStream(Archive, index, item.IsAltStream)) } bool needFindAltStream = false; @@ -856,11 +847,11 @@ { UInt32 parentType = 0; UInt32 parentIndex; - RINOK(GetRawProps->GetParent(index, &parentIndex, &parentType)); + RINOK(GetRawProps->GetParent(index, &parentIndex, &parentType)) if (parentType == NParentType::kAltStream) { NCOM::CPropVariant prop; - RINOK(Archive->GetProperty(index, kpidName, &prop)); + RINOK(Archive->GetProperty(index, kpidName, &prop)) if (prop.vt == VT_BSTR && prop.bstrVal) item.AltStreamName.SetFromBstr(prop.bstrVal); else if (prop.vt != VT_EMPTY) @@ -885,8 +876,8 @@ } else { - RINOK(GetItem_Path2(parentIndex, item.MainPath)); - RINOK(Archive_IsItem_Dir(Archive, parentIndex, item.MainIsDir)); + RINOK(GetItem_Path2(parentIndex, item.MainPath)) + RINOK(Archive_IsItem_Dir(Archive, parentIndex, item.MainIsDir)) } } } @@ -908,10 +899,10 @@ #endif - #ifndef _SFX + #ifndef Z7_SFX if (item._use_baseParentFolder_mode) { - RINOK(GetItem_PathToParent(mainIndex, (unsigned)item._baseParentFolder, item.PathParts)); + RINOK(GetItem_PathToParent(mainIndex, (unsigned)item._baseParentFolder, item.PathParts)) #ifdef SUPPORT_ALT_STREAMS if ((item.WriteToAltStreamIfColon || needFindAltStream) && !item.PathParts.IsEmpty()) @@ -947,14 +938,14 @@ return S_OK; } -#ifndef _SFX +#ifndef Z7_SFX static HRESULT Archive_GetItem_Size(IInArchive *archive, UInt32 index, UInt64 &size, bool &defined) { NCOM::CPropVariant prop; defined = false; size = 0; - RINOK(archive->GetProperty(index, kpidSize, &prop)); + RINOK(archive->GetProperty(index, kpidSize, &prop)) switch (prop.vt) { case VT_UI1: size = prop.bVal; break; @@ -975,7 +966,7 @@ NCOM::CPropVariant prop; defined = false; size = 0; - RINOK(Archive->GetProperty(index, kpidSize, &prop)); + RINOK(Archive->GetProperty(index, kpidSize, &prop)) switch (prop.vt) { case VT_UI1: size = prop.bVal; break; @@ -993,7 +984,7 @@ { at.Clear(); NCOM::CPropVariant prop; - RINOK(Archive->GetProperty(index, kpidMTime, &prop)); + RINOK(Archive->GetProperty(index, kpidMTime, &prop)) if (prop.vt == VT_FILETIME) { @@ -1011,7 +1002,7 @@ // (at.Prec == 0) before version 22. // so kpidTimeType is required for that code prop.Clear(); - RINOK(Archive->GetProperty(index, kpidTimeType, &prop)); + RINOK(Archive->GetProperty(index, kpidTimeType, &prop)) if (prop.vt == VT_UI4) { UInt32 val = prop.ulVal; @@ -1038,7 +1029,7 @@ return S_OK; } -#ifndef _SFX +#ifndef Z7_SFX static inline bool TestSignature(const Byte *p1, const Byte *p2, size_t size) { @@ -1121,7 +1112,7 @@ { if (ai.Flags_PreArc()) return true; - return IsNameFromList(ai.Name, k_PreArcFormats, ARRAY_SIZE(k_PreArcFormats)); + return IsNameFromList(ai.Name, k_PreArcFormats, Z7_ARRAY_SIZE(k_PreArcFormats)); } static const char * const k_Formats_with_simple_signuature[] = @@ -1143,44 +1134,46 @@ // if (ai.Version >= 0x91F) if (ai.NewInterface) return true; - return IsNameFromList(ai.Name, k_Formats_with_simple_signuature, ARRAY_SIZE(k_Formats_with_simple_signuature)); + return IsNameFromList(ai.Name, k_Formats_with_simple_signuature, Z7_ARRAY_SIZE(k_Formats_with_simple_signuature)); } -class CArchiveOpenCallback_Offset: + + +class CArchiveOpenCallback_Offset Z7_final: public IArchiveOpenCallback, public IArchiveOpenVolumeCallback, - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO public ICryptoGetTextPassword, - #endif + #endif public CMyUnknownImp { + Z7_COM_QI_BEGIN2(IArchiveOpenCallback) + Z7_COM_QI_ENTRY(IArchiveOpenVolumeCallback) + #ifndef Z7_NO_CRYPTO + Z7_COM_QI_ENTRY(ICryptoGetTextPassword) + #endif + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(IArchiveOpenCallback) + Z7_IFACE_COM7_IMP(IArchiveOpenVolumeCallback) + #ifndef Z7_NO_CRYPTO + Z7_IFACE_COM7_IMP(ICryptoGetTextPassword) + #endif + public: CMyComPtr Callback; CMyComPtr OpenVolumeCallback; UInt64 Files; UInt64 Offset; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO CMyComPtr GetTextPassword; #endif - - MY_QUERYINTERFACE_BEGIN2(IArchiveOpenCallback) - MY_QUERYINTERFACE_ENTRY(IArchiveOpenVolumeCallback) - #ifndef _NO_CRYPTO - MY_QUERYINTERFACE_ENTRY(ICryptoGetTextPassword) - #endif - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IArchiveOpenCallback(;) - INTERFACE_IArchiveOpenVolumeCallback(;) - #ifndef _NO_CRYPTO - STDMETHOD(CryptoGetTextPassword)(BSTR *password); - #endif }; -#ifndef _NO_CRYPTO -STDMETHODIMP CArchiveOpenCallback_Offset::CryptoGetTextPassword(BSTR *password) +#ifndef Z7_NO_CRYPTO +Z7_COM7F_IMF(CArchiveOpenCallback_Offset::CryptoGetTextPassword(BSTR *password)) { COM_TRY_BEGIN if (GetTextPassword) @@ -1190,12 +1183,12 @@ } #endif -STDMETHODIMP CArchiveOpenCallback_Offset::SetTotal(const UInt64 *, const UInt64 *) +Z7_COM7F_IMF(CArchiveOpenCallback_Offset::SetTotal(const UInt64 *, const UInt64 *)) { return S_OK; } -STDMETHODIMP CArchiveOpenCallback_Offset::SetCompleted(const UInt64 *, const UInt64 *bytes) +Z7_COM7F_IMF(CArchiveOpenCallback_Offset::SetCompleted(const UInt64 *, const UInt64 *bytes)) { if (!Callback) return S_OK; @@ -1205,7 +1198,7 @@ return Callback->SetCompleted(&Files, &value); } -STDMETHODIMP CArchiveOpenCallback_Offset::GetProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CArchiveOpenCallback_Offset::GetProperty(PROPID propID, PROPVARIANT *value)) { if (OpenVolumeCallback) return OpenVolumeCallback->GetProperty(propID, value); @@ -1214,7 +1207,7 @@ // return E_NOTIMPL; } -STDMETHODIMP CArchiveOpenCallback_Offset::GetStream(const wchar_t *name, IInStream **inStream) +Z7_COM7F_IMF(CArchiveOpenCallback_Offset::GetStream(const wchar_t *name, IInStream **inStream)) { if (OpenVolumeCallback) return OpenVolumeCallback->GetStream(name, inStream); @@ -1266,32 +1259,32 @@ ErrorInfo.ClearErrors(); { NCOM::CPropVariant prop; - RINOK(archive->GetArchiveProperty(kpidErrorFlags, &prop)); + RINOK(archive->GetArchiveProperty(kpidErrorFlags, &prop)) ErrorInfo.ErrorFlags = GetOpenArcErrorFlags(prop, &ErrorInfo.ErrorFlags_Defined); } { NCOM::CPropVariant prop; - RINOK(archive->GetArchiveProperty(kpidWarningFlags, &prop)); + RINOK(archive->GetArchiveProperty(kpidWarningFlags, &prop)) ErrorInfo.WarningFlags = GetOpenArcErrorFlags(prop); } { NCOM::CPropVariant prop; - RINOK(archive->GetArchiveProperty(kpidError, &prop)); + RINOK(archive->GetArchiveProperty(kpidError, &prop)) if (prop.vt != VT_EMPTY) ErrorInfo.ErrorMessage = (prop.vt == VT_BSTR ? prop.bstrVal : L"Unknown error"); } { NCOM::CPropVariant prop; - RINOK(archive->GetArchiveProperty(kpidWarning, &prop)); + RINOK(archive->GetArchiveProperty(kpidWarning, &prop)) if (prop.vt != VT_EMPTY) ErrorInfo.WarningMessage = (prop.vt == VT_BSTR ? prop.bstrVal : L"Unknown warning"); } if (openRes == S_OK || ErrorInfo.IsArc_After_NonOpen()) { - RINOK(Archive_GetArcProp_UInt(archive, kpidPhySize, PhySize, PhySize_Defined)); + RINOK(Archive_GetArcProp_UInt(archive, kpidPhySize, PhySize, PhySize_Defined)) /* RINOK(Archive_GetArcProp_UInt(archive, kpidOkPhySize, OkPhySize, OkPhySize_Defined)); if (!OkPhySize_Defined) @@ -1302,7 +1295,7 @@ */ bool offsetDefined; - RINOK(Archive_GetArcProp_Int(archive, kpidOffset, Offset, offsetDefined)); + RINOK(Archive_GetArcProp_Int(archive, kpidOffset, Offset, offsetDefined)) Int64 globalOffset = (Int64)startPos + Offset; AvailPhySize = (UInt64)((Int64)FileSize - globalOffset); @@ -1338,12 +1331,12 @@ // OutputDebugStringA("a1"); // PrintNumber("formatIndex", formatIndex); - RINOK(op.codecs->CreateInArchive(formatIndex, archive)); + RINOK(op.codecs->CreateInArchive(formatIndex, archive)) // OutputDebugStringA("a2"); if (!archive) return S_OK; - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS if (op.codecs->NeedSetLibCodecs) { const CArcInfoEx &ai = op.codecs->Formats[formatIndex]; @@ -1355,14 +1348,14 @@ archive.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo); if (setCompressCodecsInfo) { - RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(op.codecs)); + RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(op.codecs)) } } } #endif - #ifndef _SFX + #ifndef Z7_SFX const CArcInfoEx &ai = op.codecs->Formats[formatIndex]; @@ -1392,14 +1385,14 @@ } } */ - RINOK(SetProperties(archive, *op.props)); + RINOK(SetProperties(archive, *op.props)) } #endif return S_OK; } -#ifndef _SFX +#ifndef Z7_SFX static HRESULT ReadParseItemProps(IInArchive *archive, const CArcInfoEx &ai, NArchive::NParser::CParseItem &pi) { @@ -1407,14 +1400,14 @@ pi.FileTime_Defined = false; pi.ArcType = ai.Name; - RINOK(Archive_GetArcProp_Bool(archive, kpidIsNotArcType, pi.IsNotArcType)); + RINOK(Archive_GetArcProp_Bool(archive, kpidIsNotArcType, pi.IsNotArcType)) // RINOK(Archive_GetArcProp_Bool(archive, kpidIsSelfExe, pi.IsSelfExe)); pi.IsSelfExe = ai.Flags_PreArc(); { NCOM::CPropVariant prop; - RINOK(archive->GetArchiveProperty(kpidMTime, &prop)); + RINOK(archive->GetArchiveProperty(kpidMTime, &prop)) if (prop.vt == VT_FILETIME) { pi.FileTime_Defined = true; @@ -1425,7 +1418,7 @@ if (!pi.FileTime_Defined) { NCOM::CPropVariant prop; - RINOK(archive->GetArchiveProperty(kpidCTime, &prop)); + RINOK(archive->GetArchiveProperty(kpidCTime, &prop)) if (prop.vt == VT_FILETIME) { pi.FileTime_Defined = true; @@ -1435,7 +1428,7 @@ { NCOM::CPropVariant prop; - RINOK(archive->GetArchiveProperty(kpidName, &prop)); + RINOK(archive->GetArchiveProperty(kpidName, &prop)) if (prop.vt == VT_BSTR) { pi.Name.SetFromBstr(prop.bstrVal); @@ -1443,7 +1436,7 @@ } else { - RINOK(archive->GetArchiveProperty(kpidExtension, &prop)); + RINOK(archive->GetArchiveProperty(kpidExtension, &prop)) if (prop.vt == VT_BSTR) pi.Extension.SetFromBstr(prop.bstrVal); } @@ -1451,14 +1444,14 @@ { NCOM::CPropVariant prop; - RINOK(archive->GetArchiveProperty(kpidShortComment, &prop)); + RINOK(archive->GetArchiveProperty(kpidShortComment, &prop)) if (prop.vt == VT_BSTR) pi.Comment.SetFromBstr(prop.bstrVal); } UInt32 numItems; - RINOK(archive->GetNumberOfItems(&numItems)); + RINOK(archive->GetNumberOfItems(&numItems)) // pi.NumSubFiles = numItems; // RINOK(Archive_GetArcProp_UInt(archive, kpidUnpackSize, pi.UnpackSize, pi.UnpackSize_Defined)); @@ -1499,14 +1492,14 @@ { if (!op.stream) return S_OK; - RINOK(op.stream->Seek((Int64)offset, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(op.stream, offset)) const UInt32 kBufSize = 1 << 11; Byte buf[kBufSize]; for (;;) { UInt32 processed = 0; - RINOK(op.stream->Read(buf, kBufSize, &processed)); + RINOK(op.stream->Read(buf, kBufSize, &processed)) if (processed == 0) { // ErrorInfo.NonZerosTail = false; @@ -1527,21 +1520,19 @@ -#ifndef _SFX +#ifndef Z7_SFX -class CExtractCallback_To_OpenCallback: - public IArchiveExtractCallback, - public ICompressProgressInfo, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_2( + CExtractCallback_To_OpenCallback + , IArchiveExtractCallback + , ICompressProgressInfo +) + Z7_IFACE_COM7_IMP(IProgress) public: CMyComPtr Callback; UInt64 Files; UInt64 Offset; - MY_UNKNOWN_IMP2(IArchiveExtractCallback, ICompressProgressInfo) - INTERFACE_IArchiveExtractCallback(;) - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); void Init(IArchiveOpenCallback *callback) { Callback = callback; @@ -1550,17 +1541,17 @@ } }; -STDMETHODIMP CExtractCallback_To_OpenCallback::SetTotal(UInt64 /* size */) +Z7_COM7F_IMF(CExtractCallback_To_OpenCallback::SetTotal(UInt64 /* size */)) { return S_OK; } -STDMETHODIMP CExtractCallback_To_OpenCallback::SetCompleted(const UInt64 * /* completeValue */) +Z7_COM7F_IMF(CExtractCallback_To_OpenCallback::SetCompleted(const UInt64 * /* completeValue */)) { return S_OK; } -STDMETHODIMP CExtractCallback_To_OpenCallback::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */) +Z7_COM7F_IMF(CExtractCallback_To_OpenCallback::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */)) { if (Callback) { @@ -1572,18 +1563,18 @@ return S_OK; } -STDMETHODIMP CExtractCallback_To_OpenCallback::GetStream(UInt32 /* index */, ISequentialOutStream **outStream, Int32 /* askExtractMode */) +Z7_COM7F_IMF(CExtractCallback_To_OpenCallback::GetStream(UInt32 /* index */, ISequentialOutStream **outStream, Int32 /* askExtractMode */)) { *outStream = NULL; return S_OK; } -STDMETHODIMP CExtractCallback_To_OpenCallback::PrepareOperation(Int32 /* askExtractMode */) +Z7_COM7F_IMF(CExtractCallback_To_OpenCallback::PrepareOperation(Int32 /* askExtractMode */)) { return S_OK; } -STDMETHODIMP CExtractCallback_To_OpenCallback::SetOperationResult(Int32 /* operationResult */) +Z7_COM7F_IMF(CExtractCallback_To_OpenCallback::SetOperationResult(Int32 /* operationResult */)) { return S_OK; } @@ -1597,30 +1588,31 @@ /* if (needPhySize) { - CMyComPtr open2; - archive->QueryInterface(IID_IArchiveOpen2, (void **)&open2); + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveOpen2, + open2, archive) if (open2) return open2->ArcOpen2(stream, kOpenFlags_RealPhySize, openCallback); } */ - RINOK(archive->Open(stream, maxCheckStartPosition, openCallback)); + RINOK(archive->Open(stream, maxCheckStartPosition, openCallback)) if (needPhySize) { bool phySize_Defined = false; UInt64 phySize = 0; - RINOK(Archive_GetArcProp_UInt(archive, kpidPhySize, phySize, phySize_Defined)); + RINOK(Archive_GetArcProp_UInt(archive, kpidPhySize, phySize, phySize_Defined)) if (phySize_Defined) return S_OK; bool phySizeCantBeDetected = false; - RINOK(Archive_GetArcProp_Bool(archive, kpidPhySizeCantBeDetected, phySizeCantBeDetected)); + RINOK(Archive_GetArcProp_Bool(archive, kpidPhySizeCantBeDetected, phySizeCantBeDetected)) if (!phySizeCantBeDetected) { PRF(printf("\n-- !phySize_Defined after Open, call archive->Extract()")); // It's for bzip2/gz and some xz archives, where Open operation doesn't know phySize. // But the Handler will know phySize after full archive testing. - RINOK(archive->Extract(NULL, (UInt32)(Int32)-1, BoolToInt(true), extractCallback)); + RINOK(archive->Extract(NULL, (UInt32)(Int32)-1, BoolToInt(true), extractCallback)) PRF(printf("\n-- OK")); } } @@ -1663,7 +1655,7 @@ const UString fileName = ExtractFileNameFromPath(Path); UString extension; { - int dotPos = fileName.ReverseFind_Dot(); + const int dotPos = fileName.ReverseFind_Dot(); if (dotPos >= 0) extension = fileName.Ptr((unsigned)(dotPos + 1)); } @@ -1671,7 +1663,7 @@ CIntVector orderIndices; bool searchMarkerInHandler = false; - #ifdef _SFX + #ifdef Z7_SFX searchMarkerInHandler = true; #endif @@ -1681,25 +1673,25 @@ isMainFormatArr[i] = false; } - UInt64 maxStartOffset = + const UInt64 maxStartOffset = op.openType.MaxStartOffset_Defined ? op.openType.MaxStartOffset : kMaxCheckStartPosition; - #ifndef _SFX + #ifndef Z7_SFX bool isUnknownExt = false; #endif - #ifndef _SFX + #ifndef Z7_SFX bool isForced = false; #endif unsigned numMainTypes = 0; - int formatIndex = op.openType.FormatIndex; + const int formatIndex = op.openType.FormatIndex; if (formatIndex >= 0) { - #ifndef _SFX + #ifndef Z7_SFX isForced = true; #endif orderIndices.Add(formatIndex); @@ -1711,12 +1703,12 @@ else { unsigned numFinded = 0; - #ifndef _SFX + #ifndef Z7_SFX bool isPrearcExt = false; #endif { - #ifndef _SFX + #ifndef Z7_SFX bool isZip = false; bool isRar = false; @@ -1758,13 +1750,13 @@ if (op.excludedFormats->FindInSorted((int)i) >= 0) continue; - #ifndef _SFX + #ifndef Z7_SFX if (IsPreArcFormat(ai)) isPrearcExt = true; #endif if (ai.FindExtension(extension) >= 0 - #ifndef _SFX + #ifndef Z7_SFX || (isZip && ai.Is_Zip()) || (isRar && ai.Is_Rar()) #endif @@ -1795,11 +1787,11 @@ } */ - #ifndef _SFX + #ifndef Z7_SFX if (op.stream && orderIndices.Size() >= 2) { - RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(op.stream)) CByteBuffer byteBuffer; CIntVector orderIndices2; if (numFinded == 0 || IsExeExt(extension)) @@ -1808,13 +1800,13 @@ } else if (extension.IsEqualTo("000") || extension.IsEqualTo("001")) { - int i = FindFormatForArchiveType(op.codecs, orderIndices, "rar"); + const int i = FindFormatForArchiveType(op.codecs, orderIndices, "rar"); if (i >= 0) { const size_t kBufSize = (1 << 10); byteBuffer.Alloc(kBufSize); size_t processedSize = kBufSize; - RINOK(ReadStream(op.stream, byteBuffer, &processedSize)); + RINOK(ReadStream(op.stream, byteBuffer, &processedSize)) if (processedSize >= 16) { const Byte *buf = byteBuffer; @@ -1834,7 +1826,7 @@ const size_t kBufSize = (1 << 10); byteBuffer.Alloc(kBufSize); size_t processedSize = kBufSize; - RINOK(ReadStream(op.stream, byteBuffer, &processedSize)); + RINOK(ReadStream(op.stream, byteBuffer, &processedSize)) if (processedSize == 0) return S_FALSE; @@ -1870,7 +1862,7 @@ FOR_VECTOR (i, orderIndices) { - int val = orderIndices[i]; + const int val = orderIndices[i]; if (val != -1) orderIndices2.Add(val); } @@ -1879,12 +1871,12 @@ if (orderIndices.Size() >= 2) { - int iIso = FindFormatForArchiveType(op.codecs, orderIndices, "iso"); - int iUdf = FindFormatForArchiveType(op.codecs, orderIndices, "udf"); + const int iIso = FindFormatForArchiveType(op.codecs, orderIndices, "iso"); + const int iUdf = FindFormatForArchiveType(op.codecs, orderIndices, "udf"); if (iUdf > iIso && iIso >= 0) { - int isoIndex = orderIndices[(unsigned)iIso]; - int udfIndex = orderIndices[(unsigned)iUdf]; + const int isoIndex = orderIndices[(unsigned)iIso]; + const int udfIndex = orderIndices[(unsigned)iUdf]; orderIndices[(unsigned)iUdf] = isoIndex; orderIndices[(unsigned)iIso] = udfIndex; } @@ -1893,7 +1885,7 @@ numMainTypes = numFinded; isUnknownExt = (numMainTypes == 0) || isPrearcExt; - #else // _SFX + #else // Z7_SFX numMainTypes = orderIndices.Size(); @@ -1907,13 +1899,12 @@ UInt64 fileSize = 0; if (op.stream) { - RINOK(op.stream->Seek(0, STREAM_SEEK_END, &fileSize)); - RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_GetSize_SeekToBegin(op.stream, fileSize)) } FileSize = fileSize; - #ifndef _SFX + #ifndef Z7_SFX CBoolArr skipFrontalFormat(op.codecs->Formats.Size()); { @@ -1945,7 +1936,7 @@ bool exactOnly = false; - #ifndef _SFX + #ifndef Z7_SFX const CArcInfoEx &ai = op.codecs->Formats[(unsigned)FormatIndex]; // OutputDebugStringW(ai.Name); @@ -1963,16 +1954,16 @@ // Some handlers do not set total bytes. So we set it here if (op.callback) - RINOK(op.callback->SetTotal(NULL, &fileSize)); + RINOK(op.callback->SetTotal(NULL, &fileSize)) if (op.stream) { - RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(op.stream)) } CMyComPtr archive; - RINOK(PrepareToOpen(op, (unsigned)FormatIndex, archive)); + RINOK(PrepareToOpen(op, (unsigned)FormatIndex, archive)) if (!archive) continue; @@ -1991,13 +1982,13 @@ result = openSeq->OpenSeq(op.seqStream); } - RINOK(ReadBasicProps(archive, 0, result)); + RINOK(ReadBasicProps(archive, 0, result)) if (result == S_FALSE) { bool isArc = ErrorInfo.IsArc_After_NonOpen(); - #ifndef _SFX + #ifndef Z7_SFX // if it's archive, we allow another open attempt for parser if (!mode.CanReturnParser || !isArc) skipFrontalFormat[(unsigned)FormatIndex] = true; @@ -2017,7 +2008,7 @@ // if (formatIndex < 0 && !searchMarkerInHandler) { // if bad archive was detected, we don't need additional open attempts - #ifndef _SFX + #ifndef Z7_SFX if (!IsPreArcFormat(ai) /* || !mode.SkipSfxStub */) #endif return S_FALSE; @@ -2026,7 +2017,7 @@ } /* - #ifndef _SFX + #ifndef Z7_SFX if (IsExeExt(extension) || ai.Flags_PreArc()) { // openOnlyFullArc = false; @@ -2039,9 +2030,9 @@ continue; } - RINOK(result); + RINOK(result) - #ifndef _SFX + #ifndef Z7_SFX bool isMainFormat = isMainFormatArr[(unsigned)FormatIndex]; const COpenSpecFlags &specFlags = mode.GetSpec(isForced, isMainFormat, isUnknownExt); @@ -2049,7 +2040,7 @@ bool thereIsTail = ErrorInfo.ThereIsTail; if (thereIsTail && mode.ZerosTailIsAllowed) { - RINOK(CheckZerosTail(op, (UInt64)(Offset + (Int64)PhySize))); + RINOK(CheckZerosTail(op, (UInt64)(Offset + (Int64)PhySize))) if (ErrorInfo.IgnoreTail) thereIsTail = false; } @@ -2103,7 +2094,7 @@ - #ifndef _SFX + #ifndef Z7_SFX if (!op.stream) return S_FALSE; @@ -2148,9 +2139,9 @@ endOfFile = true; } byteBuffer.Alloc(bufSize); - RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(op.stream)) processedSize = bufSize; - RINOK(ReadStream(op.stream, byteBuffer, &processedSize)); + RINOK(ReadStream(op.stream, byteBuffer, &processedSize)) if (processedSize == 0) return S_FALSE; if (processedSize < bufSize) @@ -2232,12 +2223,12 @@ const CArcInfoEx &ai = op.codecs->Formats[(unsigned)FormatIndex]; if (op.callback) - RINOK(op.callback->SetTotal(NULL, &fileSize)); + RINOK(op.callback->SetTotal(NULL, &fileSize)) - RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(op.stream)) CMyComPtr archive; - RINOK(PrepareToOpen(op, (unsigned)FormatIndex, archive)); + RINOK(PrepareToOpen(op, (unsigned)FormatIndex, archive)) if (!archive) continue; @@ -2263,9 +2254,9 @@ // printf(" OpenForSize Error"); continue; } - RINOK(result); + RINOK(result) - RINOK(ReadBasicProps(archive, 0, result)); + RINOK(ReadBasicProps(archive, 0, result)) if (Offset > 0) { @@ -2302,7 +2293,7 @@ if (mode.CanReturnArc) { - bool isMainFormat = isMainFormatArr[(unsigned)FormatIndex]; + const bool isMainFormat = isMainFormatArr[(unsigned)FormatIndex]; const COpenSpecFlags &specFlags = mode.GetSpec(isForced, isMainFormat, isUnknownExt); bool openCur = false; @@ -2312,7 +2303,7 @@ { if (mode.ZerosTailIsAllowed) { - RINOK(CheckZerosTail(op, (UInt64)(Offset + (Int64)PhySize))); + RINOK(CheckZerosTail(op, (UInt64)(Offset + (Int64)PhySize))) if (ErrorInfo.IgnoreTail) openCur = true; } @@ -2352,7 +2343,7 @@ continue; // printf("\nAdd offset = %d", (int)pi.Offset); - RINOK(ReadParseItemProps(archive, ai, pi)); + RINOK(ReadParseItemProps(archive, ai, pi)) handlerSpec->AddItem(pi); } } @@ -2451,7 +2442,7 @@ // canReturnTailArc = true; } - RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(op.stream)) CLimitedCachedInStream *limitedStreamSpec = new CLimitedCachedInStream; CMyComPtr limitedStream = limitedStreamSpec; @@ -2465,13 +2456,13 @@ openCallback_Offset = openCallback_Offset_Spec; openCallback_Offset_Spec->Callback = op.callback; openCallback_Offset_Spec->Callback.QueryInterface(IID_IArchiveOpenVolumeCallback, &openCallback_Offset_Spec->OpenVolumeCallback); - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO openCallback_Offset_Spec->Callback.QueryInterface(IID_ICryptoGetTextPassword, &openCallback_Offset_Spec->GetTextPassword); #endif } if (op.callback) - RINOK(op.callback->SetTotal(NULL, &fileSize)); + RINOK(op.callback->SetTotal(NULL, &fileSize)) CByteBuffer &byteBuffer = limitedStreamSpec->Buffer; byteBuffer.Alloc(kBufSize); @@ -2509,8 +2500,8 @@ size_t processedSize = kBufSize - bytesInBuf; // printf("\nRead ask = %d", (unsigned)processedSize); UInt64 seekPos = bufPhyPos + bytesInBuf; - RINOK(op.stream->Seek((Int64)(bufPhyPos + bytesInBuf), STREAM_SEEK_SET, NULL)); - RINOK(ReadStream(op.stream, byteBuffer + bytesInBuf, &processedSize)); + RINOK(InStream_SeekSet(op.stream, bufPhyPos + bytesInBuf)) + RINOK(ReadStream(op.stream, byteBuffer + bytesInBuf, &processedSize)) // printf(" processed = %d", (unsigned)processedSize); if (processedSize == 0) { @@ -2568,7 +2559,7 @@ if (pos >= callbackPrev + (1 << 23)) { - RINOK(openCallback_Offset_Spec->SetCompleted(NULL, NULL)); + RINOK(openCallback_Offset->SetCompleted(NULL, NULL)) callbackPrev = pos; } } @@ -2691,10 +2682,10 @@ if (ai.IsArcFunc && startArcPos >= bufPhyPos) { - size_t offsetInBuf = (size_t)(startArcPos - bufPhyPos); + const size_t offsetInBuf = (size_t)(startArcPos - bufPhyPos); if (offsetInBuf < bytesInBuf) { - UInt32 isArcRes = ai.IsArcFunc(byteBuffer + offsetInBuf, bytesInBuf - offsetInBuf); + const UInt32 isArcRes = ai.IsArcFunc(byteBuffer + offsetInBuf, bytesInBuf - offsetInBuf); if (isArcRes == k_IsArc_Res_NO) continue; if (isArcRes == k_IsArc_Res_NEED_MORE && endOfFile) @@ -2716,7 +2707,7 @@ const COpenSpecFlags &specFlags = mode.GetSpec(isForced, isMainFormat, isUnknownExt); CMyComPtr archive; - RINOK(PrepareToOpen(op, index, archive)); + RINOK(PrepareToOpen(op, index, archive)) if (!archive) return E_FAIL; @@ -2728,12 +2719,12 @@ if (ai.Flags_UseGlobalOffset()) { - limitedStreamSpec->InitAndSeek(0, fileSize); - limitedStream->Seek((Int64)startArcPos, STREAM_SEEK_SET, NULL); + RINOK(limitedStreamSpec->InitAndSeek(0, fileSize)) + RINOK(InStream_SeekSet(limitedStream, startArcPos)) } else { - limitedStreamSpec->InitAndSeek(startArcPos, rem); + RINOK(limitedStreamSpec->InitAndSeek(startArcPos, rem)) arcStreamOffset = startArcPos; } @@ -2755,7 +2746,7 @@ useOffsetCallback ? (IArchiveOpenCallback *)openCallback_Offset : (IArchiveOpenCallback *)op.callback, extractCallback_To_OpenCallback); - RINOK(ReadBasicProps(archive, ai.Flags_UseGlobalOffset() ? 0 : startArcPos, result)); + RINOK(ReadBasicProps(archive, ai.Flags_UseGlobalOffset() ? 0 : startArcPos, result)) bool isOpen = false; @@ -2784,7 +2775,7 @@ continue; } isOpen = true; - RINOK(result); + RINOK(result) PRF(printf(" OK ")); } @@ -2874,7 +2865,7 @@ pos = pi.Offset + pi.Size; - RINOK(ReadParseItemProps(archive, ai, pi)); + RINOK(ReadParseItemProps(archive, ai, pi)) if (pi.Offset < startArcPos && !mode.EachPos /* && phySize_Defined */) { @@ -2903,7 +2894,7 @@ bool thereIsTail = ErrorInfo.ThereIsTail; if (thereIsTail && mode.ZerosTailIsAllowed) { - RINOK(CheckZerosTail(op, (UInt64)((Int64)arcStreamOffset + Offset + (Int64)PhySize))); + RINOK(CheckZerosTail(op, (UInt64)((Int64)arcStreamOffset + Offset + (Int64)PhySize))) if (ErrorInfo.IgnoreTail) thereIsTail = false; } @@ -3029,7 +3020,7 @@ HRESULT CArc::OpenStream(const COpenOptions &op) { - RINOK(OpenStream2(op)); + RINOK(OpenStream2(op)) // PrintNumber("op.formatIndex 3", op.formatIndex); if (Archive) @@ -3039,12 +3030,12 @@ Archive->QueryInterface(IID_IArchiveGetRawProps, (void **)&GetRawProps); Archive->QueryInterface(IID_IArchiveGetRootProps, (void **)&GetRootProps); - RINOK(Archive_GetArcProp_Bool(Archive, kpidIsTree, IsTree)); - RINOK(Archive_GetArcProp_Bool(Archive, kpidIsDeleted, Ask_Deleted)); - RINOK(Archive_GetArcProp_Bool(Archive, kpidIsAltStream, Ask_AltStream)); - RINOK(Archive_GetArcProp_Bool(Archive, kpidIsAux, Ask_Aux)); - RINOK(Archive_GetArcProp_Bool(Archive, kpidINode, Ask_INode)); - RINOK(Archive_GetArcProp_Bool(Archive, kpidReadOnly, IsReadOnly)); + RINOK(Archive_GetArcProp_Bool(Archive, kpidIsTree, IsTree)) + RINOK(Archive_GetArcProp_Bool(Archive, kpidIsDeleted, Ask_Deleted)) + RINOK(Archive_GetArcProp_Bool(Archive, kpidIsAltStream, Ask_AltStream)) + RINOK(Archive_GetArcProp_Bool(Archive, kpidIsAux, Ask_Aux)) + RINOK(Archive_GetArcProp_Bool(Archive, kpidINode, Ask_INode)) + RINOK(Archive_GetArcProp_Bool(Archive, kpidReadOnly, IsReadOnly)) const UString fileName = ExtractFileNameFromPath(Path); UString extension; @@ -3074,7 +3065,7 @@ return S_OK; } -#ifdef _SFX +#ifdef Z7_SFX #ifdef _WIN32 #define k_ExeExt ".exe" @@ -3105,7 +3096,7 @@ if (!fileStreamSpec->Open(us2fs(Path))) return GetLastError_noZero_HRESULT(); op.stream = fileStream; - #ifdef _SFX + #ifdef Z7_SFX IgnoreSplit = true; #endif } @@ -3114,7 +3105,7 @@ if (callback) { UInt64 fileSize; - RINOK(op.stream->Seek(0, STREAM_SEEK_END, &fileSize)); + RINOK(InStream_GetSize_SeekToEnd(op.stream, fileSize)); RINOK(op.callback->SetTotal(NULL, &fileSize)) } */ @@ -3122,7 +3113,7 @@ HRESULT res = OpenStream(op); IgnoreSplit = false; - #ifdef _SFX + #ifdef Z7_SFX if (res != S_FALSE || !fileStreamSpec @@ -3141,7 +3132,7 @@ if (ai.Is_Split()) continue; UString path3 = path2; - path3 += '.'; + path3.Add_Dot(); path3 += ai.GetMainExt(); // "7z" for SFX. Path = path3; Path += ".001"; @@ -3187,7 +3178,7 @@ for (unsigned i = Arcs.Size(); i != 0;) { i--; - RINOK(Arcs[i].Close()); + RINOK(Arcs[i].Close()) } IsOpen = false; // ErrorsText.Empty(); @@ -3320,13 +3311,13 @@ UInt32 mainSubfile; { NCOM::CPropVariant prop; - RINOK(arc.Archive->GetArchiveProperty(kpidMainSubfile, &prop)); + RINOK(arc.Archive->GetArchiveProperty(kpidMainSubfile, &prop)) if (prop.vt == VT_UI4) mainSubfile = prop.ulVal; else break; UInt32 numItems; - RINOK(arc.Archive->GetNumberOfItems(&numItems)); + RINOK(arc.Archive->GetNumberOfItems(&numItems)) if (mainSubfile >= numItems) break; } @@ -3345,16 +3336,17 @@ break; CArc arc2; - RINOK(arc.GetItem_Path(mainSubfile, arc2.Path)); + RINOK(arc.GetItem_Path(mainSubfile, arc2.Path)) bool zerosTailIsAllowed; - RINOK(Archive_GetItemBoolProp(arc.Archive, mainSubfile, kpidZerosTailIsAllowed, zerosTailIsAllowed)); + RINOK(Archive_GetItemBoolProp(arc.Archive, mainSubfile, kpidZerosTailIsAllowed, zerosTailIsAllowed)) if (op.callback) { - CMyComPtr setSubArchiveName; - op.callback->QueryInterface(IID_IArchiveOpenSetSubArchiveName, (void **)&setSubArchiveName); + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveOpenSetSubArchiveName, + setSubArchiveName, op.callback) if (setSubArchiveName) setSubArchiveName->SetSubArchiveName(arc2.Path); } @@ -3365,7 +3357,7 @@ CIntVector excl; COpenOptions op2; - #ifndef _SFX + #ifndef Z7_SFX op2.props = op.props; #endif op2.codecs = op.codecs; @@ -3388,8 +3380,8 @@ NonOpen_ArcPath = arc2.Path; break; } - RINOK(result); - RINOK(arc.GetItem_MTime(mainSubfile, arc2.MTime)); + RINOK(result) + RINOK(arc.GetItem_MTime(mainSubfile, arc2.MTime)) Arcs.Add(arc2); } IsOpen = !Arcs.IsEmpty(); @@ -3408,7 +3400,7 @@ if (!op.stream && !op.stdInMode) { NFile::NDir::GetFullPathAndSplit(us2fs(op.filePath), prefix, name); - RINOK(openCallbackSpec->Init2(prefix, name)); + RINOK(openCallbackSpec->Init2(prefix, name)) } else { @@ -3423,7 +3415,7 @@ PasswordWasAsked = openCallbackSpec->PasswordWasAsked; // Password = openCallbackSpec->Password; - RINOK(res); + RINOK(res) // VolumePaths.Add(fs2us(prefix + name)); FOR_VECTOR (i, openCallbackSpec->FileNames_WasUsed) @@ -3446,8 +3438,9 @@ UInt64 fileSize = 0; if (op.stream) { - RINOK(op.stream->Seek(0, STREAM_SEEK_END, &fileSize)); - RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(op.stream)) + RINOK(InStream_AtBegin_GetSize(op.stream, fileSize)) + // RINOK(InStream_GetSize_SeekToBegin(op.stream, fileSize)) } FileSize = fileSize; @@ -3462,7 +3455,7 @@ tailStreamSpec->Stream = op.stream; tailStreamSpec->Offset = (UInt64)globalOffset; tailStreamSpec->Init(); - RINOK(tailStreamSpec->SeekToStart()); + RINOK(tailStreamSpec->SeekToStart()) } // There are archives with embedded STUBs (like ZIP), so we must support signature scanning @@ -3475,7 +3468,7 @@ if (res == S_OK) { - RINOK(ReadBasicProps(Archive, (UInt64)globalOffset, res)); + RINOK(ReadBasicProps(Archive, (UInt64)globalOffset, res)) ArcStreamOffset = (UInt64)globalOffset; if (ArcStreamOffset != 0) InStream = op.stream; @@ -3488,7 +3481,7 @@ HRESULT res = Open2(op, callbackUI); if (callbackUI) { - RINOK(callbackUI->Open_Finished()); + RINOK(callbackUI->Open_Finished()) } return res; } @@ -3508,6 +3501,8 @@ if (Arcs.Size() == 0) // ??? return Open2(op, NULL); + /* if archive is multivolume (unsupported here still) + COpenCallbackImp object will exist after Open stage. */ COpenCallbackImp *openCallbackSpec = new COpenCallbackImp; CMyComPtr openCallbackNew = openCallbackSpec; @@ -3516,7 +3511,7 @@ { FString dirPrefix, fileName; NFile::NDir::GetFullPathAndSplit(us2fs(op.filePath), dirPrefix, fileName); - RINOK(openCallbackSpec->Init2(dirPrefix, fileName)); + RINOK(openCallbackSpec->Init2(dirPrefix, fileName)) } @@ -3527,7 +3522,9 @@ op.stream = stream; CArc &arc = Arcs[0]; - HRESULT res = arc.ReOpen(op, openCallbackNew); + const HRESULT res = arc.ReOpen(op, openCallbackNew); + + openCallbackSpec->ReOpenCallback = NULL; PasswordWasAsked = openCallbackSpec->PasswordWasAsked; // Password = openCallbackSpec->Password; @@ -3536,7 +3533,7 @@ return res; } -#ifndef _SFX +#ifndef Z7_SFX bool ParseComplexSize(const wchar_t *s, UInt64 &result); bool ParseComplexSize(const wchar_t *s, UInt64 &result) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/OpenArchive.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/OpenArchive.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/OpenArchive.h 2022-04-07 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/OpenArchive.h 2023-04-06 04:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // OpenArchive.h -#ifndef __OPEN_ARCHIVE_H -#define __OPEN_ARCHIVE_H +#ifndef ZIP7_INC_OPEN_ARCHIVE_H +#define ZIP7_INC_OPEN_ARCHIVE_H #include "../../../Windows/PropVariant.h" @@ -10,7 +10,7 @@ #include "Property.h" #include "DirItem.h" -#ifndef _SFX +#ifndef Z7_SFX #define SUPPORT_ALT_STREAMS @@ -34,7 +34,7 @@ }; */ -#ifdef _SFX +#ifdef Z7_SFX #define OPEN_PROPS_DECL #else #define OPEN_PROPS_DECL const CObjectVector *props; @@ -243,7 +243,7 @@ bool MainIsDir; UInt32 ParentIndex; // use it, if IsAltStream - #ifndef _SFX + #ifndef Z7_SFX bool _use_baseParentFolder_mode; int _baseParentFolder; #endif @@ -254,7 +254,7 @@ WriteToAltStreamIfColon = false; #endif - #ifndef _SFX + #ifndef Z7_SFX _use_baseParentFolder_mode = false; _baseParentFolder = -1; #endif @@ -270,7 +270,7 @@ HRESULT CheckZerosTail(const COpenOptions &op, UInt64 offset); HRESULT OpenStream2(const COpenOptions &options); - #ifndef _SFX + #ifndef Z7_SFX // parts.Back() can contain alt stream name "nams:AltName" HRESULT GetItem_PathToParent(UInt32 index, UInt32 parent, UStringVector &parts) const; #endif @@ -285,8 +285,17 @@ CMyComPtr GetRawProps; CMyComPtr GetRootProps; - CArcErrorInfo ErrorInfo; // for OK archives - CArcErrorInfo NonOpen_ErrorInfo; // ErrorInfo for mainArchive (false OPEN) + bool IsParseArc; + + bool IsTree; + bool IsReadOnly; + + bool Ask_Deleted; + bool Ask_AltStream; + bool Ask_Aux; + bool Ask_INode; + + bool IgnoreSplit; // don't try split handler UString Path; UString filePath; @@ -305,7 +314,9 @@ // bool OkPhySize_Defined; UInt64 FileSize; UInt64 AvailPhySize; // PhySize, but it's reduced if exceed end of file - // bool offsetDefined; + + CArcErrorInfo ErrorInfo; // for OK archives + CArcErrorInfo NonOpen_ErrorInfo; // ErrorInfo for mainArchive (false OPEN) UInt64 GetEstmatedPhySize() const { return PhySize_Defined ? PhySize : FileSize; } @@ -314,18 +325,6 @@ // AString ErrorFlagsText; - bool IsParseArc; - - bool IsTree; - bool IsReadOnly; - - bool Ask_Deleted; - bool Ask_AltStream; - bool Ask_Aux; - bool Ask_INode; - - bool IgnoreSplit; // don't try split handler - // void Set_ErrorFlagsText(); CArc(): @@ -341,8 +340,6 @@ HRESULT ReadBasicProps(IInArchive *archive, UInt64 startPos, HRESULT openRes); - // ~CArc(); - HRESULT Close() { InStream.Release(); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/Property.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/Property.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/Property.h 2011-01-31 21:05:24.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/Property.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Property.h -#ifndef __7Z_PROPERTY_H -#define __7Z_PROPERTY_H +#ifndef ZIP7_INC_7Z_PROPERTY_H +#define ZIP7_INC_7Z_PROPERTY_H #include "../../../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/PropIDUtils.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/PropIDUtils.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/PropIDUtils.cpp 2022-05-13 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/PropIDUtils.cpp 2023-04-05 20:00:00.000000000 +0000 @@ -14,7 +14,7 @@ #include "PropIDUtils.h" -#ifndef _SFX +#ifndef Z7_SFX #define Get16(x) GetUi16(x) #define Get32(x) GetUi32(x) #endif @@ -54,7 +54,7 @@ static const char kPosixTypes[16] = { '0', 'p', 'c', '3', 'd', '5', 'b', '7', '-', '9', 'l', 'B', 's', 'D', 'E', 'F' }; -#define MY_ATTR_CHAR(a, n, c) ((a) & (1 << (n))) ? c : '-'; +#define MY_ATTR_CHAR(a, n, c) (((a) & (1 << (n))) ? c : '-') static void ConvertPosixAttribToString(char *s, UInt32 a) throw() { @@ -88,7 +88,7 @@ info-zip - no additional marker. */ - bool isPosix = ((wa & 0xF0000000) != 0); + const bool isPosix = ((wa & 0xF0000000) != 0); UInt32 posix = 0; if (isPosix) @@ -183,7 +183,7 @@ { if (prop.vt != VT_UI4) break; - UInt32 a = prop.ulVal; + const UInt32 a = prop.ulVal; /* if ((a & 0x8000) && (a & 0x7FFF) == 0) @@ -207,7 +207,7 @@ ConvertUInt32ToString((UInt32)(prop.uhVal.QuadPart >> 48), dest); dest += strlen(dest); *dest++ = '-'; - UInt64 low = prop.uhVal.QuadPart & (((UInt64)1 << 48) - 1); + const UInt64 low = prop.uhVal.QuadPart & (((UInt64)1 << 48) - 1); ConvertUInt64ToString(low, dest); return; } @@ -260,7 +260,7 @@ dest = temp; } -#ifndef _SFX +#ifndef Z7_SFX static inline unsigned GetHex(unsigned v) { @@ -387,33 +387,33 @@ s += "ERROR"; return; } - UInt32 rev = p[0]; + const UInt32 rev = p[0]; if (rev != 1) { s += "UNSUPPORTED"; return; } - UInt32 num = p[1]; + const UInt32 num = p[1]; if (8 + num * 4 > lim) { s += "ERROR"; return; } sidSize = 8 + num * 4; - UInt32 authority = GetBe32(p + 4); + const UInt32 authority = GetBe32(p + 4); if (p[2] == 0 && p[3] == 0 && authority == 5 && num >= 1) { - UInt32 v0 = Get32(p + 8); - if (v0 < ARRAY_SIZE(sidNames)) + const UInt32 v0 = Get32(p + 8); + if (v0 < Z7_ARRAY_SIZE(sidNames)) { s += sidNames[v0]; return; } if (v0 == 32 && num == 2) { - UInt32 v1 = Get32(p + 12); - int index = FindPairIndex(sid_32_Names, ARRAY_SIZE(sid_32_Names), v1); + const UInt32 v1 = Get32(p + 12); + const int index = FindPairIndex(sid_32_Names, Z7_ARRAY_SIZE(sid_32_Names), v1); if (index >= 0) { s += sid_32_Names[(unsigned)index].sz; @@ -423,7 +423,7 @@ if (v0 == 21 && num == 5) { UInt32 v4 = Get32(p + 8 + 4 * 4); - int index = FindPairIndex(sid_21_Names, ARRAY_SIZE(sid_21_Names), v4); + const int index = FindPairIndex(sid_21_Names, Z7_ARRAY_SIZE(sid_21_Names), v4); if (index >= 0) { s += sid_21_Names[(unsigned)index].sz; @@ -432,7 +432,7 @@ } if (v0 == 80 && num == 6) { - for (unsigned i = 0; i < ARRAY_SIZE(services_to_name); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(services_to_name); i++) { const CServicesToName &sn = services_to_name[i]; int j; @@ -457,7 +457,7 @@ } for (UInt32 i = 0; i < num; i++) { - s += '-'; + s.Add_Minus(); s.Add_UInt32(Get32(p + 8 + i * 4)); } } @@ -475,10 +475,10 @@ static void ParseAcl(AString &s, const Byte *p, UInt32 size, const char *strName, UInt32 flags, UInt32 offset) { - UInt32 control = Get16(p + 2); + const UInt32 control = Get16(p + 2); if ((flags & control) == 0) return; - UInt32 pos = Get32(p + offset); + const UInt32 pos = Get32(p + offset); s.Add_Space(); s += strName; if (pos >= size) @@ -489,7 +489,7 @@ return; if (Get16(p) != 2) // revision return; - UInt32 num = Get32(p + 4); + const UInt32 num = Get32(p + 4); s.Add_UInt32(num); /* @@ -580,26 +580,26 @@ size -= pos; if (size < 8) return false; - UInt32 rev = data[pos]; + const UInt32 rev = data[pos]; if (rev != 1) return false; - UInt32 num = data[pos + 1]; + const UInt32 num = data[pos + 1]; return (8 + num * 4 <= size); } static bool CheckAcl(const Byte *p, UInt32 size, UInt32 flags, UInt32 offset) throw() { - UInt32 control = Get16(p + 2); + const UInt32 control = Get16(p + 2); if ((flags & control) == 0) return true; - UInt32 pos = Get32(p + offset); + const UInt32 pos = Get32(p + offset); if (pos >= size) return false; p += pos; size -= pos; if (size < 8) return false; - UInt32 aclSize = Get16(p + 2); + const UInt32 aclSize = Get16(p + 2); return (aclSize <= size); } @@ -686,22 +686,22 @@ if (size < 8) return false; - UInt32 tag = Get32(data); - UInt32 len = Get16(data + 4); + const UInt32 tag = Get32(data); + const UInt32 len = Get16(data + 4); if (len + 8 > size) return false; if (Get16(data + 6) != 0) // padding return false; /* - #define _my_IO_REPARSE_TAG_DEDUP (0x80000013L) - if (tag == _my_IO_REPARSE_TAG_DEDUP) + #define my_IO_REPARSE_TAG_DEDUP (0x80000013L) + if (tag == my_IO_REPARSE_TAG_DEDUP) { } */ { - int index = FindPairIndex(k_ReparseTags, ARRAY_SIZE(k_ReparseTags), tag); + const int index = FindPairIndex(k_ReparseTags, Z7_ARRAY_SIZE(k_ReparseTags), tag); if (index >= 0) s += k_ReparseTags[(unsigned)index].sz; else @@ -729,7 +729,7 @@ s += "..."; break; } - unsigned b = data[i]; + const unsigned b = data[i]; s += (char)GetHex((b >> 4) & 0xF); s += (char)GetHex(b & 0xF); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/PropIDUtils.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/PropIDUtils.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/PropIDUtils.h 2017-02-25 11:49:34.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/PropIDUtils.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // PropIDUtils.h -#ifndef __PROPID_UTILS_H -#define __PROPID_UTILS_H +#ifndef ZIP7_INC_PROPID_UTILS_H +#define ZIP7_INC_PROPID_UTILS_H #include "../../../Common/MyString.h" @@ -11,7 +11,7 @@ bool ConvertNtReparseToString(const Byte *data, UInt32 size, UString &s); void ConvertNtSecureToString(const Byte *data, UInt32 size, AString &s); -bool CheckNtSecure(const Byte *data, UInt32 size) throw();; +bool CheckNtSecure(const Byte *data, UInt32 size) throw(); void ConvertWinAttribToString(char *s, UInt32 wa) throw(); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/SetProperties.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/SetProperties.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/SetProperties.cpp 2019-08-24 11:23:56.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/SetProperties.cpp 2023-04-05 20:00:00.000000000 +0000 @@ -18,7 +18,7 @@ static void ParseNumberString(const UString &s, NCOM::CPropVariant &prop) { const wchar_t *end; - UInt64 result = ConvertStringToUInt64(s, &end); + const UInt64 result = ConvertStringToUInt64(s, &end); if (*end != 0 || s.IsEmpty()) prop = s; else if (result <= (UInt32)0xFFFFFFFF) @@ -46,8 +46,9 @@ { if (properties.IsEmpty()) return S_OK; - CMyComPtr setProperties; - unknown->QueryInterface(IID_ISetProperties, (void **)&setProperties); + Z7_DECL_CMyComPtr_QI_FROM( + ISetProperties, + setProperties, unknown) if (!setProperties) return S_OK; @@ -64,7 +65,7 @@ { if (!name.IsEmpty()) { - wchar_t c = name.Back(); + const wchar_t c = name.Back(); if (c == L'-') propVariant = false; else if (c == L'+') diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/SetProperties.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/SetProperties.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/SetProperties.h 2006-02-19 12:09:12.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/SetProperties.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // SetProperties.h -#ifndef __SETPROPERTIES_H -#define __SETPROPERTIES_H +#ifndef ZIP7_INC_SETPROPERTIES_H +#define ZIP7_INC_SETPROPERTIES_H #include "Property.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/SortUtils.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/SortUtils.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/SortUtils.h 2014-01-17 07:05:35.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/SortUtils.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // SortUtils.h -#ifndef __SORT_UTLS_H -#define __SORT_UTLS_H +#ifndef ZIP7_INC_SORT_UTLS_H +#define ZIP7_INC_SORT_UTLS_H #include "../../../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/StdAfx.h 2013-01-25 07:40:27.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/TempFiles.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/TempFiles.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/TempFiles.h 2013-01-17 09:54:35.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/TempFiles.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // TempFiles.h -#ifndef __TEMP_FILES_H -#define __TEMP_FILES_H +#ifndef ZIP7_INC_TEMP_FILES_H +#define ZIP7_INC_TEMP_FILES_H #include "../../../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/UpdateAction.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/UpdateAction.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/UpdateAction.h 2015-08-01 08:55:37.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/UpdateAction.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // UpdateAction.h -#ifndef __UPDATE_ACTION_H -#define __UPDATE_ACTION_H +#ifndef ZIP7_INC_UPDATE_ACTION_H +#define ZIP7_INC_UPDATE_ACTION_H namespace NUpdateArchive { diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/UpdateCallback.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/UpdateCallback.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/UpdateCallback.cpp 2022-07-12 14:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/UpdateCallback.cpp 2023-05-03 12:00:00.000000000 +0000 @@ -7,17 +7,23 @@ #ifndef _WIN32 // #include // #include - +/* +inclusion of by is deprecated since glibc 2.25. +Since glibc 2.3.3, macros have been aliases for three GNU-specific +functions: gnu_dev_makedev(), gnu_dev_major(), and gnu_dev_minor() +*/ // for major()/minor(): -#if defined(__FreeBSD__) || defined(BSD) #include +#if defined(__FreeBSD__) || defined(BSD) || defined(__APPLE__) #else +#ifndef major #include #endif - #endif -#ifndef _7ZIP_ST +#endif // _WIN32 + +#ifndef Z7_ST #include "../../../Windows/Synchronization.h" #endif @@ -36,14 +42,14 @@ #include "UpdateCallback.h" #if defined(_WIN32) && !defined(UNDER_CE) -#define _USE_SECURITY_CODE +#define Z7_USE_SECURITY_CODE #include "../../../Windows/SecurityUtils.h" #endif using namespace NWindows; using namespace NFile; -#ifndef _7ZIP_ST +#ifndef Z7_ST static NSynchronization::CCriticalSection g_CriticalSection; #define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection); #else @@ -51,25 +57,11 @@ #endif -#ifdef _USE_SECURITY_CODE +#ifdef Z7_USE_SECURITY_CODE bool InitLocalPrivileges(); #endif CArchiveUpdateCallback::CArchiveUpdateCallback(): - _hardIndex_From((UInt32)(Int32)-1), - - Callback(NULL), - - DirItems(NULL), - ParentDirItem(NULL), - - Arc(NULL), - ArcItems(NULL), - UpdatePairs(NULL), - NewNames(NULL), - CommentIndex(-1), - Comment(NULL), - PreserveATime(false), ShareForWrite(false), StopAfterOpenError(false), @@ -92,29 +84,42 @@ Need_LatestMTime(false), LatestMTime_Defined(false), - ProcessedItemsStatuses(NULL) + Callback(NULL), + + DirItems(NULL), + ParentDirItem(NULL), + + Arc(NULL), + ArcItems(NULL), + UpdatePairs(NULL), + NewNames(NULL), + Comment(NULL), + CommentIndex(-1), + + ProcessedItemsStatuses(NULL), + _hardIndex_From((UInt32)(Int32)-1) { - #ifdef _USE_SECURITY_CODE + #ifdef Z7_USE_SECURITY_CODE _saclEnabled = InitLocalPrivileges(); #endif } -STDMETHODIMP CArchiveUpdateCallback::SetTotal(UInt64 size) +Z7_COM7F_IMF(CArchiveUpdateCallback::SetTotal(UInt64 size)) { COM_TRY_BEGIN return Callback->SetTotal(size); COM_TRY_END } -STDMETHODIMP CArchiveUpdateCallback::SetCompleted(const UInt64 *completeValue) +Z7_COM7F_IMF(CArchiveUpdateCallback::SetCompleted(const UInt64 *completeValue)) { COM_TRY_BEGIN return Callback->SetCompleted(completeValue); COM_TRY_END } -STDMETHODIMP CArchiveUpdateCallback::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) +Z7_COM7F_IMF(CArchiveUpdateCallback::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize)) { COM_TRY_BEGIN return Callback->SetRatioInfo(inSize, outSize); @@ -135,17 +140,17 @@ { NULL, kpidIsAnti, VT_BOOL} }; -STDMETHODIMP CArchiveUpdateCallback::EnumProperties(IEnumSTATPROPSTG **) +Z7_COM7F_IMF(CArchiveUpdateCallback::EnumProperties(IEnumSTATPROPSTG **) { - return CStatPropEnumerator::CreateEnumerator(kProps, ARRAY_SIZE(kProps), enumerator); + return CStatPropEnumerator::CreateEnumerator(kProps, Z7_ARRAY_SIZE(kProps), enumerator); } */ -STDMETHODIMP CArchiveUpdateCallback::GetUpdateItemInfo(UInt32 index, - Int32 *newData, Int32 *newProps, UInt32 *indexInArchive) +Z7_COM7F_IMF(CArchiveUpdateCallback::GetUpdateItemInfo(UInt32 index, + Int32 *newData, Int32 *newProps, UInt32 *indexInArchive)) { COM_TRY_BEGIN - RINOK(Callback->CheckBreak()); + RINOK(Callback->CheckBreak()) const CUpdatePair2 &up = (*UpdatePairs)[index]; if (newData) *newData = BoolToInt(up.NewData); if (newProps) *newProps = BoolToInt(up.NewProps); @@ -160,7 +165,7 @@ } -STDMETHODIMP CArchiveUpdateCallback::GetRootProp(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CArchiveUpdateCallback::GetRootProp(PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; switch (propID) @@ -176,14 +181,14 @@ return S_OK; } -STDMETHODIMP CArchiveUpdateCallback::GetParent(UInt32 /* index */, UInt32 *parent, UInt32 *parentType) +Z7_COM7F_IMF(CArchiveUpdateCallback::GetParent(UInt32 /* index */, UInt32 *parent, UInt32 *parentType)) { *parentType = NParentType::kDir; *parent = (UInt32)(Int32)-1; return S_OK; } -STDMETHODIMP CArchiveUpdateCallback::GetNumRawProps(UInt32 *numProps) +Z7_COM7F_IMF(CArchiveUpdateCallback::GetNumRawProps(UInt32 *numProps)) { *numProps = 0; if (StoreNtSecurity) @@ -191,25 +196,27 @@ return S_OK; } -STDMETHODIMP CArchiveUpdateCallback::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID) +Z7_COM7F_IMF(CArchiveUpdateCallback::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID)) { *name = NULL; *propID = kpidNtSecure; return S_OK; } -STDMETHODIMP CArchiveUpdateCallback::GetRootRawProp(PROPID - #ifdef _USE_SECURITY_CODE +Z7_COM7F_IMF(CArchiveUpdateCallback::GetRootRawProp(PROPID propID - #endif - , const void **data, UInt32 *dataSize, UInt32 *propType) + , const void **data, UInt32 *dataSize, UInt32 *propType)) { - *data = 0; + #ifndef Z7_USE_SECURITY_CODE + UNUSED_VAR(propID) + #endif + + *data = NULL; *dataSize = 0; *propType = 0; if (!StoreNtSecurity) return S_OK; - #ifdef _USE_SECURITY_CODE + #ifdef Z7_USE_SECURITY_CODE if (propID == kpidNtSecure) { if (StdInMode) @@ -233,12 +240,10 @@ return S_OK; } -// #ifdef _USE_SECURITY_CODE -// #endif -STDMETHODIMP CArchiveUpdateCallback::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) +Z7_COM7F_IMF(CArchiveUpdateCallback::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType)) { - *data = 0; + *data = NULL; *dataSize = 0; *propType = 0; @@ -265,7 +270,7 @@ const CDirItem &di = DirItems->Items[(unsigned)up.DirIndex]; #endif - #ifdef _USE_SECURITY_CODE + #ifdef Z7_USE_SECURITY_CODE if (propID == kpidNtSecure) { if (!StoreNtSecurity) @@ -349,7 +354,7 @@ #endif -STDMETHODIMP CArchiveUpdateCallback::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CArchiveUpdateCallback::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN const CUpdatePair2 &up = (*UpdatePairs)[index]; @@ -385,7 +390,7 @@ CReparseAttr attr; if (attr.Parse(di.ReparseData, di.ReparseData.Size())) { - UString simpleName = attr.GetPath(); + const UString simpleName = attr.GetPath(); if (!attr.IsSymLink_WSL() && attr.IsRelative_Win()) prop = simpleName; else @@ -484,6 +489,11 @@ // case kpidShortName: prop = di.ShortName; break; #else + #if defined(__APPLE__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wsign-conversion" + #endif + case kpidDeviceMajor: /* printf("\ndi.mode = %o\n", di.mode); @@ -499,6 +509,10 @@ prop = (UInt32)minor(di.rdev); break; + #if defined(__APPLE__) + #pragma GCC diagnostic pop + #endif + // case kpidDevice: if (S_ISCHR(di.mode) || S_ISBLK(di.mode)) prop = (UInt64)(di.rdev); break; case kpidUserId: if (StoreOwnerId) prop = (UInt32)di.uid; break; @@ -519,22 +533,22 @@ COM_TRY_END } -#ifndef _7ZIP_ST -static NSynchronization::CCriticalSection CS; +#ifndef Z7_ST +static NSynchronization::CCriticalSection g_CS; #endif void CArchiveUpdateCallback::UpdateProcessedItemStatus(unsigned dirIndex) { if (ProcessedItemsStatuses) { - #ifndef _7ZIP_ST - NSynchronization::CCriticalSectionLock lock(CS); + #ifndef Z7_ST + NSynchronization::CCriticalSectionLock lock(g_CS); #endif ProcessedItemsStatuses[dirIndex] = 1; } } -STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStream **inStream, UInt32 mode) +Z7_COM7F_IMF(CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStream **inStream, UInt32 mode)) { COM_TRY_BEGIN *inStream = NULL; @@ -542,7 +556,7 @@ if (!up.NewData) return E_FAIL; - RINOK(Callback->CheckBreak()); + RINOK(Callback->CheckBreak()) // RINOK(Callback->Finalize()); bool isDir = IsDir(up); @@ -554,7 +568,7 @@ name = (*ArcItems)[(unsigned)up.ArcIndex].Name; else if (up.DirIndex >= 0) name = DirItems->GetLogPath((unsigned)up.DirIndex); - RINOK(Callback->GetStream(name, isDir, true, mode)); + RINOK(Callback->GetStream(name, isDir, true, mode)) /* 9.33: fixed. Handlers expect real stream object for files, even for anti-file. so we return empty stream */ @@ -569,7 +583,7 @@ return S_OK; } - RINOK(Callback->GetStream(DirItems->GetLogPath((unsigned)up.DirIndex), isDir, false, mode)); + RINOK(Callback->GetStream(DirItems->GetLogPath((unsigned)up.DirIndex), isDir, false, mode)) if (isDir) return S_OK; @@ -640,8 +654,9 @@ #endif inStreamSpec->SupportHardLinks = StoreHardLinks; - inStreamSpec->Set_PreserveATime(PreserveATime - || mode == NUpdateNotifyOp::kAnalyze); // 22.00 : we don't change access time in Analyze pass. + const bool preserveATime = (PreserveATime + || mode == NUpdateNotifyOp::kAnalyze); // 22.00 : we don't change access time in Analyze pass. + inStreamSpec->Set_PreserveATime(preserveATime); const FString path = DirItems->GetPhyPath((unsigned)up.DirIndex); _openFiles_Indexes.Add(index); @@ -655,12 +670,32 @@ if (!inStreamSpec->OpenShared(path, ShareForWrite)) { - const DWORD error = ::GetLastError(); - const HRESULT hres = Callback->OpenFileError(path, error); - if (StopAfterOpenError) + bool isOpen = false; + if (preserveATime) + { + inStreamSpec->Set_PreserveATime(false); + isOpen = inStreamSpec->OpenShared(path, ShareForWrite); + } + if (!isOpen) + { + const DWORD error = ::GetLastError(); + const HRESULT hres = Callback->OpenFileError(path, error); if (hres == S_OK || hres == S_FALSE) + if (StopAfterOpenError || + // v23: we check also for some critical errors: + #ifdef _WIN32 + error == ERROR_NO_SYSTEM_RESOURCES + #else + error == EMFILE + #endif + ) + { + if (error == 0) + return E_FAIL; return HRESULT_FROM_WIN32(error); - return hres; + } + return hres; + } } /* @@ -679,7 +714,7 @@ inStreamSpec->ReloadProps(); } - // #if defined(USE_WIN_FILE) || !defined(_WIN32) + // #if defined(Z7_FILE_STREAMS_USE_WIN_FILE) || !defined(_WIN32) if (StoreHardLinks) { CStreamFileProps props; @@ -691,8 +726,8 @@ pair.Key1 = props.VolID; pair.Key2 = props.FileID_Low; pair.Value = index; - unsigned numItems = _map.Size(); - unsigned pairIndex = _map.AddToUniqueSorted2(pair); + const unsigned numItems = _map.Size(); + const unsigned pairIndex = _map.AddToUniqueSorted2(pair); if (numItems == _map.Size()) { // const CKeyKeyValPair &pair2 = _map.Pairs[pairIndex]; @@ -714,14 +749,14 @@ COM_TRY_END } -STDMETHODIMP CArchiveUpdateCallback::SetOperationResult(Int32 opRes) +Z7_COM7F_IMF(CArchiveUpdateCallback::SetOperationResult(Int32 opRes)) { COM_TRY_BEGIN return Callback->SetOperationResult(opRes); COM_TRY_END } -STDMETHODIMP CArchiveUpdateCallback::GetStream(UInt32 index, ISequentialInStream **inStream) +Z7_COM7F_IMF(CArchiveUpdateCallback::GetStream(UInt32 index, ISequentialInStream **inStream)) { COM_TRY_BEGIN return GetStream2(index, inStream, @@ -731,7 +766,7 @@ COM_TRY_END } -STDMETHODIMP CArchiveUpdateCallback::ReportOperation(UInt32 indexType, UInt32 index, UInt32 op) +Z7_COM7F_IMF(CArchiveUpdateCallback::ReportOperation(UInt32 indexType, UInt32 index, UInt32 op)) { COM_TRY_BEGIN @@ -770,9 +805,9 @@ } else if (Arc) { - RINOK(Arc->GetItem_Path(index, s2)); + RINOK(Arc->GetItem_Path(index, s2)) s = s2; - RINOK(Archive_IsItem_Dir(Arc->Archive, index, isDir)); + RINOK(Archive_IsItem_Dir(Arc->Archive, index, isDir)) } } } @@ -791,7 +826,7 @@ COM_TRY_END } -STDMETHODIMP CArchiveUpdateCallback::ReportExtractResult(UInt32 indexType, UInt32 index, Int32 opRes) +Z7_COM7F_IMF(CArchiveUpdateCallback::ReportExtractResult(UInt32 indexType, UInt32 index, Int32 opRes)) { COM_TRY_BEGIN @@ -825,12 +860,12 @@ s = (*ArcItems)[index].Name; else if (Arc) { - RINOK(Arc->GetItem_Path(index, s2)); + RINOK(Arc->GetItem_Path(index, s2)) s = s2; } if (Archive) { - RINOK(Archive_GetItemBoolProp(Archive, index, kpidEncrypted, isEncrypted)); + RINOK(Archive_GetItemBoolProp(Archive, index, kpidEncrypted, isEncrypted)) } } } @@ -848,7 +883,7 @@ /* -STDMETHODIMP CArchiveUpdateCallback::DoNeedArcProp(PROPID propID, Int32 *answer) +Z7_COM7F_IMF(CArchiveUpdateCallback::DoNeedArcProp(PROPID propID, Int32 *answer)) { *answer = 0; if (Need_ArcMTime_Report && propID == kpidComboMTime) @@ -856,7 +891,7 @@ return S_OK; } -STDMETHODIMP CArchiveUpdateCallback::ReportProp(UInt32 indexType, UInt32 index, PROPID propID, const PROPVARIANT *value) +Z7_COM7F_IMF(CArchiveUpdateCallback::ReportProp(UInt32 indexType, UInt32 index, PROPID propID, const PROPVARIANT *value)) { if (indexType == NArchive::NEventIndexType::kArcProp) { @@ -879,19 +914,19 @@ return Callback->ReportProp(indexType, index, propID, value); } -STDMETHODIMP CArchiveUpdateCallback::ReportRawProp(UInt32 indexType, UInt32 index, - PROPID propID, const void *data, UInt32 dataSize, UInt32 propType) +Z7_COM7F_IMF(CArchiveUpdateCallback::ReportRawProp(UInt32 indexType, UInt32 index, + PROPID propID, const void *data, UInt32 dataSize, UInt32 propType)) { return Callback->ReportRawProp(indexType, index, propID, data, dataSize, propType); } -STDMETHODIMP CArchiveUpdateCallback::ReportFinished(UInt32 indexType, UInt32 index, Int32 opRes) +Z7_COM7F_IMF(CArchiveUpdateCallback::ReportFinished(UInt32 indexType, UInt32 index, Int32 opRes)) { return Callback->ReportFinished(indexType, index, opRes); } */ -STDMETHODIMP CArchiveUpdateCallback::GetVolumeSize(UInt32 index, UInt64 *size) +Z7_COM7F_IMF(CArchiveUpdateCallback::GetVolumeSize(UInt32 index, UInt64 *size)) { if (VolumesSizes.Size() == 0) return S_FALSE; @@ -901,7 +936,7 @@ return S_OK; } -STDMETHODIMP CArchiveUpdateCallback::GetVolumeStream(UInt32 index, ISequentialOutStream **volumeStream) +Z7_COM7F_IMF(CArchiveUpdateCallback::GetVolumeStream(UInt32 index, ISequentialOutStream **volumeStream)) { COM_TRY_BEGIN char temp[16]; @@ -910,7 +945,7 @@ while (res.Len() < 2) res.InsertAtFront(FTEXT('0')); FString fileName = VolName; - fileName += '.'; + fileName.Add_Dot(); fileName += res; fileName += VolExt; COutFileStream *streamSpec = new COutFileStream; @@ -922,14 +957,14 @@ COM_TRY_END } -STDMETHODIMP CArchiveUpdateCallback::CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password) +Z7_COM7F_IMF(CArchiveUpdateCallback::CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password)) { COM_TRY_BEGIN return Callback->CryptoGetTextPassword2(passwordIsDefined, password); COM_TRY_END } -STDMETHODIMP CArchiveUpdateCallback::CryptoGetTextPassword(BSTR *password) +Z7_COM7F_IMF(CArchiveUpdateCallback::CryptoGetTextPassword(BSTR *password)) { COM_TRY_BEGIN return Callback->CryptoGetTextPassword(password); @@ -949,7 +984,7 @@ { if (_openFiles_Indexes[i] == index) { - RINOK(Callback->ReadingFileError(_openFiles_Paths[i], error)); + RINOK(Callback->ReadingFileError(_openFiles_Paths[i], error)) break; } } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/UpdateCallback.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/UpdateCallback.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/UpdateCallback.h 2022-04-09 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/UpdateCallback.h 2023-04-06 05:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // UpdateCallback.h -#ifndef __UPDATE_CALLBACK_H -#define __UPDATE_CALLBACK_H +#ifndef ZIP7_INC_UPDATE_CALLBACK_H +#define ZIP7_INC_UPDATE_CALLBACK_H #include "../../../Common/MyCom.h" @@ -27,37 +27,38 @@ } }; -#define INTERFACE_IUpdateCallbackUI(x) \ - virtual HRESULT WriteSfx(const wchar_t *name, UInt64 size) x; \ - virtual HRESULT SetTotal(UInt64 size) x; \ - virtual HRESULT SetCompleted(const UInt64 *completeValue) x; \ - virtual HRESULT SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) x; \ - virtual HRESULT CheckBreak() x; \ - /* virtual HRESULT Finalize() x; */ \ - virtual HRESULT SetNumItems(const CArcToDoStat &stat) x; \ - virtual HRESULT GetStream(const wchar_t *name, bool isDir, bool isAnti, UInt32 mode) x; \ - virtual HRESULT OpenFileError(const FString &path, DWORD systemError) x; \ - virtual HRESULT ReadingFileError(const FString &path, DWORD systemError) x; \ - virtual HRESULT SetOperationResult(Int32 opRes) x; \ - virtual HRESULT ReportExtractResult(Int32 opRes, Int32 isEncrypted, const wchar_t *name) x; \ - virtual HRESULT ReportUpdateOperation(UInt32 op, const wchar_t *name, bool isDir) x; \ - /* virtual HRESULT SetPassword(const UString &password) x; */ \ - virtual HRESULT CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password) x; \ - virtual HRESULT CryptoGetTextPassword(BSTR *password) x; \ - virtual HRESULT ShowDeleteFile(const wchar_t *name, bool isDir) x; \ + +Z7_PURE_INTERFACES_BEGIN + +#define Z7_IFACEN_IUpdateCallbackUI(x) \ + virtual HRESULT WriteSfx(const wchar_t *name, UInt64 size) x \ + virtual HRESULT SetTotal(UInt64 size) x \ + virtual HRESULT SetCompleted(const UInt64 *completeValue) x \ + virtual HRESULT SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) x \ + virtual HRESULT CheckBreak() x \ + /* virtual HRESULT Finalize() x */ \ + virtual HRESULT SetNumItems(const CArcToDoStat &stat) x \ + virtual HRESULT GetStream(const wchar_t *name, bool isDir, bool isAnti, UInt32 mode) x \ + virtual HRESULT OpenFileError(const FString &path, DWORD systemError) x \ + virtual HRESULT ReadingFileError(const FString &path, DWORD systemError) x \ + virtual HRESULT SetOperationResult(Int32 opRes) x \ + virtual HRESULT ReportExtractResult(Int32 opRes, Int32 isEncrypted, const wchar_t *name) x \ + virtual HRESULT ReportUpdateOperation(UInt32 op, const wchar_t *name, bool isDir) x \ + /* virtual HRESULT SetPassword(const UString &password) x */ \ + virtual HRESULT CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password) x \ + virtual HRESULT CryptoGetTextPassword(BSTR *password) x \ + virtual HRESULT ShowDeleteFile(const wchar_t *name, bool isDir) x \ /* - virtual HRESULT ReportProp(UInt32 indexType, UInt32 index, PROPID propID, const PROPVARIANT *value) x; \ - virtual HRESULT ReportRawProp(UInt32 indexType, UInt32 index, PROPID propID, const void *data, UInt32 dataSize, UInt32 propType) x; \ - virtual HRESULT ReportFinished(UInt32 indexType, UInt32 index, Int32 opRes) x; \ + virtual HRESULT ReportProp(UInt32 indexType, UInt32 index, PROPID propID, const PROPVARIANT *value) x \ + virtual HRESULT ReportRawProp(UInt32 indexType, UInt32 index, PROPID propID, const void *data, UInt32 dataSize, UInt32 propType) x \ + virtual HRESULT ReportFinished(UInt32 indexType, UInt32 index, Int32 opRes) x \ */ /* virtual HRESULT CloseProgress() { return S_OK; } */ -struct IUpdateCallbackUI -{ - INTERFACE_IUpdateCallbackUI(=0) -}; +Z7_IFACE_DECL_PURE(IUpdateCallbackUI) +Z7_PURE_INTERFACES_END struct CKeyKeyValPair { @@ -74,11 +75,11 @@ }; -class CArchiveUpdateCallback: +class CArchiveUpdateCallback Z7_final: public IArchiveUpdateCallback2, public IArchiveUpdateCallbackFile, // public IArchiveUpdateCallbackArcProp, - public IArchiveExtractCallbackMessage, + public IArchiveExtractCallbackMessage2, public IArchiveGetRawProps, public IArchiveGetRootProps, public ICryptoGetTextPassword2, @@ -87,54 +88,63 @@ public IInFileStream_Callback, public CMyUnknownImp { - #if defined(_WIN32) && !defined(UNDER_CE) - bool _saclEnabled; - #endif - CRecordVector _map; + Z7_COM_QI_BEGIN2(IArchiveUpdateCallback2) + Z7_COM_QI_ENTRY(IArchiveUpdateCallbackFile) + // Z7_COM_QI_ENTRY(IArchiveUpdateCallbackArcProp) + Z7_COM_QI_ENTRY(IArchiveExtractCallbackMessage2) + Z7_COM_QI_ENTRY(IArchiveGetRawProps) + Z7_COM_QI_ENTRY(IArchiveGetRootProps) + Z7_COM_QI_ENTRY(ICryptoGetTextPassword2) + Z7_COM_QI_ENTRY(ICryptoGetTextPassword) + Z7_COM_QI_ENTRY(ICompressProgressInfo) + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(ICompressProgressInfo) + + Z7_IFACE_COM7_IMP(IProgress) + Z7_IFACE_COM7_IMP(IArchiveUpdateCallback) + Z7_IFACE_COM7_IMP(IArchiveUpdateCallback2) + Z7_IFACE_COM7_IMP(IArchiveUpdateCallbackFile) + // Z7_IFACE_COM7_IMP(IArchiveUpdateCallbackArcProp) + Z7_IFACE_COM7_IMP(IArchiveExtractCallbackMessage2) + Z7_IFACE_COM7_IMP(IArchiveGetRawProps) + Z7_IFACE_COM7_IMP(IArchiveGetRootProps) + Z7_IFACE_COM7_IMP(ICryptoGetTextPassword2) + Z7_IFACE_COM7_IMP(ICryptoGetTextPassword) - UInt32 _hardIndex_From; - UInt32 _hardIndex_To; void UpdateProcessedItemStatus(unsigned dirIndex); public: - MY_QUERYINTERFACE_BEGIN2(IArchiveUpdateCallback2) - MY_QUERYINTERFACE_ENTRY(IArchiveUpdateCallbackFile) - // MY_QUERYINTERFACE_ENTRY(IArchiveUpdateCallbackArcProp) - MY_QUERYINTERFACE_ENTRY(IArchiveExtractCallbackMessage) - MY_QUERYINTERFACE_ENTRY(IArchiveGetRawProps) - MY_QUERYINTERFACE_ENTRY(IArchiveGetRootProps) - MY_QUERYINTERFACE_ENTRY(ICryptoGetTextPassword2) - MY_QUERYINTERFACE_ENTRY(ICryptoGetTextPassword) - MY_QUERYINTERFACE_ENTRY(ICompressProgressInfo) - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); - - INTERFACE_IArchiveUpdateCallback2(;) - INTERFACE_IArchiveUpdateCallbackFile(;) - // INTERFACE_IArchiveUpdateCallbackArcProp(;) - INTERFACE_IArchiveExtractCallbackMessage(;) - INTERFACE_IArchiveGetRawProps(;) - INTERFACE_IArchiveGetRootProps(;) + bool PreserveATime; + bool ShareForWrite; + bool StopAfterOpenError; + bool StdInMode; + + bool KeepOriginalItemNames; + bool StoreNtSecurity; + bool StoreHardLinks; + bool StoreSymLinks; - STDMETHOD(CryptoGetTextPassword2)(Int32 *passwordIsDefined, BSTR *password); - STDMETHOD(CryptoGetTextPassword)(BSTR *password); + bool StoreOwnerId; + bool StoreOwnerName; + + bool Need_LatestMTime; + bool LatestMTime_Defined; + + /* + bool Need_ArcMTime_Report; + bool ArcMTime_WasReported; + */ CRecordVector _openFiles_Indexes; FStringVector _openFiles_Paths; // CRecordVector< CInFileStream* > _openFiles_Streams; bool AreAllFilesClosed() const { return _openFiles_Indexes.IsEmpty(); } - virtual HRESULT InFileStream_On_Error(UINT_PTR val, DWORD error); - virtual void InFileStream_On_Destroy(CInFileStream *stream, UINT_PTR val); - - CRecordVector VolumesSizes; - FString VolName; - FString VolExt; - UString ArcFileName; // without path prefix + virtual HRESULT InFileStream_On_Error(UINT_PTR val, DWORD error) Z7_override; + virtual void InFileStream_On_Destroy(CInFileStream *stream, UINT_PTR val) Z7_override; IUpdateCallbackUI *Callback; @@ -145,36 +155,24 @@ CMyComPtr Archive; const CObjectVector *ArcItems; const CRecordVector *UpdatePairs; - const UStringVector *NewNames; - int CommentIndex; - const UString *Comment; - bool PreserveATime; - bool ShareForWrite; - bool StopAfterOpenError; - bool StdInMode; - - bool KeepOriginalItemNames; - bool StoreNtSecurity; - bool StoreHardLinks; - bool StoreSymLinks; + CRecordVector VolumesSizes; + FString VolName; + FString VolExt; + UString ArcFileName; // without path prefix - bool StoreOwnerId; - bool StoreOwnerName; + const UStringVector *NewNames; + const UString *Comment; + int CommentIndex; /* - bool Need_ArcMTime_Report; - bool ArcMTime_WasReported; CArcTime Reported_ArcMTime; */ - bool Need_LatestMTime; - bool LatestMTime_Defined; CFiTime LatestMTime; Byte *ProcessedItemsStatuses; - CArchiveUpdateCallback(); bool IsDir(const CUpdatePair2 &up) const @@ -185,6 +183,15 @@ return (*ArcItems)[(unsigned)up.ArcIndex].IsDir; return false; } + +private: + #if defined(_WIN32) && !defined(UNDER_CE) + bool _saclEnabled; + #endif + CRecordVector _map; + + UInt32 _hardIndex_From; + UInt32 _hardIndex_To; }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/Update.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/Update.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/Update.cpp 2022-04-09 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/Update.cpp 2023-03-22 10:00:00.000000000 +0000 @@ -18,6 +18,8 @@ #include "../../Common/FileStreams.h" #include "../../Common/LimitedStreams.h" +#include "../../Common/MultiOutStream.h" +#include "../../Common/StreamUtils.h" #include "../../Compress/CopyCoder.h" @@ -71,203 +73,44 @@ using namespace NUpdateArchive; -class COutMultiVolStream: - public IOutStream, - public CMyUnknownImp -{ - unsigned _streamIndex; // required stream - UInt64 _offsetPos; // offset from start of _streamIndex index - UInt64 _absPos; - UInt64 _length; - - struct CAltStreamInfo - { - COutFileStream *StreamSpec; - CMyComPtr Stream; - FString Name; - UInt64 Pos; - UInt64 RealSize; - }; - CObjectVector Streams; -public: - // CMyComPtr VolumeCallback; - CRecordVector Sizes; - FString Prefix; - CTempFiles *TempFiles; - - void Init() - { - _streamIndex = 0; - _offsetPos = 0; - _absPos = 0; - _length = 0; - } - - bool SetMTime(const CFiTime *mTime); - HRESULT Close(); - - UInt64 GetSize() const { return _length; } - - MY_UNKNOWN_IMP1(IOutStream) - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); - STDMETHOD(SetSize)(UInt64 newSize); +struct CMultiOutStream_Rec +{ + CMultiOutStream *Spec; + CMyComPtr Ref; }; -// static NSynchronization::CCriticalSection g_TempPathsCS; - -HRESULT COutMultiVolStream::Close() +struct CMultiOutStream_Bunch { - HRESULT res = S_OK; - FOR_VECTOR (i, Streams) + CObjectVector Items; + + HRESULT Destruct() { - COutFileStream *s = Streams[i].StreamSpec; - if (s) + HRESULT hres = S_OK; + FOR_VECTOR (i, Items) { - HRESULT res2 = s->Close(); - if (res2 != S_OK) - res = res2; + CMultiOutStream_Rec &rec = Items[i]; + if (rec.Ref) + { + const HRESULT hres2 = rec.Spec->Destruct(); + if (hres == S_OK) + hres = hres2; + } } + Items.Clear(); + return hres; } - return res; -} -bool COutMultiVolStream::SetMTime(const CFiTime *mTime) -{ - bool res = true; - FOR_VECTOR (i, Streams) + void DisableDeletion() { - COutFileStream *s = Streams[i].StreamSpec; - if (s) - if (!s->SetMTime(mTime)) - res = false; - } - return res; -} - -STDMETHODIMP COutMultiVolStream::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - if (processedSize) - *processedSize = 0; - while (size > 0) - { - if (_streamIndex >= Streams.Size()) - { - CAltStreamInfo altStream; - - FString name; - name.Add_UInt32(_streamIndex + 1); - while (name.Len() < 3) - name.InsertAtFront(FTEXT('0')); - name.Insert(0, Prefix); - altStream.StreamSpec = new COutFileStream; - altStream.Stream = altStream.StreamSpec; - if (!altStream.StreamSpec->Create(name, false)) - return GetLastError_noZero_HRESULT(); - { - // NSynchronization::CCriticalSectionLock lock(g_TempPathsCS); - TempFiles->Paths.Add(name); - } - - altStream.Pos = 0; - altStream.RealSize = 0; - altStream.Name = name; - Streams.Add(altStream); - continue; - } - CAltStreamInfo &altStream = Streams[_streamIndex]; - - unsigned index = _streamIndex; - if (index >= Sizes.Size()) - index = Sizes.Size() - 1; - UInt64 volSize = Sizes[index]; - - if (_offsetPos >= volSize) - { - _offsetPos -= volSize; - _streamIndex++; - continue; - } - if (_offsetPos != altStream.Pos) - { - // CMyComPtr outStream; - // RINOK(altStream.Stream.QueryInterface(IID_IOutStream, &outStream)); - RINOK(altStream.Stream->Seek((Int64)_offsetPos, STREAM_SEEK_SET, NULL)); - altStream.Pos = _offsetPos; - } - - UInt32 curSize = (UInt32)MyMin((UInt64)size, volSize - altStream.Pos); - UInt32 realProcessed; - RINOK(altStream.Stream->Write(data, curSize, &realProcessed)); - data = (const void *)((const Byte *)data + realProcessed); - size -= realProcessed; - altStream.Pos += realProcessed; - _offsetPos += realProcessed; - _absPos += realProcessed; - if (_absPos > _length) - _length = _absPos; - if (_offsetPos > altStream.RealSize) - altStream.RealSize = _offsetPos; - if (processedSize) - *processedSize += realProcessed; - if (altStream.Pos == volSize) + FOR_VECTOR (i, Items) { - _streamIndex++; - _offsetPos = 0; + CMultiOutStream_Rec &rec = Items[i]; + if (rec.Ref) + rec.Spec->NeedDelete = false; } - if (realProcessed == 0 && curSize != 0) - return E_FAIL; - break; } - return S_OK; -} +}; -STDMETHODIMP COutMultiVolStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) -{ - if (seekOrigin >= 3) - return STG_E_INVALIDFUNCTION; - switch (seekOrigin) - { - case STREAM_SEEK_SET: _absPos = (UInt64)offset; break; - case STREAM_SEEK_CUR: _absPos = (UInt64)((Int64)_absPos + offset); break; - case STREAM_SEEK_END: _absPos = (UInt64)((Int64)_length + offset); break; - } - _offsetPos = _absPos; - if (newPosition) - *newPosition = _absPos; - _streamIndex = 0; - return S_OK; -} - -STDMETHODIMP COutMultiVolStream::SetSize(UInt64 newSize) -{ - unsigned i = 0; - while (i < Streams.Size()) - { - CAltStreamInfo &altStream = Streams[i++]; - if ((UInt64)newSize < altStream.RealSize) - { - RINOK(altStream.Stream->SetSize(newSize)); - altStream.RealSize = newSize; - break; - } - newSize -= altStream.RealSize; - } - while (i < Streams.Size()) - { - { - CAltStreamInfo &altStream = Streams.Back(); - altStream.Stream.Release(); - DeleteFileAlways(altStream.Name); - } - Streams.DeleteBack(); - } - _offsetPos = _absPos; - _streamIndex = 0; - _length = newSize; - return S_OK; -} void CArchivePath::ParseFromPath(const UString &path, EArcNameMode mode) { @@ -305,7 +148,7 @@ UString path = GetPathWithoutExt(); if (!BaseExtension.IsEmpty()) { - path += '.'; + path.Add_Dot(); path += BaseExtension; } return path; @@ -317,7 +160,7 @@ // if BaseExtension is empty, we must ignore VolExtension also. if (!BaseExtension.IsEmpty()) { - path += '.'; + path.Add_Dot(); path += VolExtension; } return path; @@ -329,7 +172,7 @@ path += us2fs(Name); if (!BaseExtension.IsEmpty()) { - path += '.'; + path.Add_Dot(); path += us2fs(BaseExtension); } path += ".tmp"; @@ -403,7 +246,7 @@ } -struct CUpdateProduceCallbackImp: public IUpdateProduceCallback +struct CUpdateProduceCallbackImp Z7_final: public IUpdateProduceCallback { const CObjectVector *_arcItems; CDirItemsStat *_stat; @@ -417,7 +260,7 @@ _stat(stat), _callback(callback) {} - virtual HRESULT ShowDeleteFile(unsigned arcIndex); + virtual HRESULT ShowDeleteFile(unsigned arcIndex) Z7_override; }; @@ -499,6 +342,8 @@ int FindAltStreamColon_in_Path(const wchar_t *path); #endif + + static HRESULT Compress( const CUpdateOptions &options, bool isUpdatingItself, @@ -511,6 +356,7 @@ const CDirItems &dirItems, const CDirItem *parentDirItem, CTempFiles &tempFiles, + CMultiOutStream_Bunch &multiStreams, CUpdateErrorInfo &errorInfo, IUpdateCallbackUI *callback, CFinishArchiveStat &st) @@ -530,15 +376,15 @@ } else { - RINOK(codecs->CreateOutArchive((unsigned)formatIndex, outArchive)); + RINOK(codecs->CreateOutArchive((unsigned)formatIndex, outArchive)) - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS { CMyComPtr setCompressCodecsInfo; outArchive.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo); if (setCompressCodecsInfo) { - RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(codecs)); + RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(codecs)) } } #endif @@ -548,7 +394,7 @@ throw kUpdateIsNotSupoorted; // we need to set properties to get fileTimeType. - RINOK(SetProperties(outArchive, options.MethodMode.Properties)); + RINOK(SetProperties(outArchive, options.MethodMode.Properties)) NFileTimeType::EEnum fileTimeType; { @@ -580,7 +426,7 @@ */ UInt32 value; - RINOK(outArchive->GetFileTimeType(&value)); + RINOK(outArchive->GetFileTimeType(&value)) // we support any future fileType here. fileTimeType = (NFileTimeType::EEnum)value; @@ -676,7 +522,7 @@ if (needRename) { up2.NewProps = true; - RINOK(arc->IsItem_Anti(i, up2.IsAnti)); + RINOK(arc->IsItem_Anti(i, up2.IsAnti)) up2.NewNameIndex = (int)newNames.Add(dest); } updatePairs2.Add(up2); @@ -768,7 +614,7 @@ } } } - RINOK(callback->SetNumItems(stat2)); + RINOK(callback->SetNumItems(stat2)) } CArchiveUpdateCallback *updateCallbackSpec = new CArchiveUpdateCallback; @@ -828,7 +674,7 @@ COutFileStream *outStreamSpec = NULL; CStdOutFileStream *stdOutFileStreamSpec = NULL; - COutMultiVolStream *volStreamSpec = NULL; + CMultiOutStream *volStreamSpec = NULL; if (options.VolumesSizes.Size() == 0) { @@ -881,14 +727,17 @@ if (arc && arc->GetGlobalOffset() > 0) return E_NOTIMPL; - volStreamSpec = new COutMultiVolStream; + volStreamSpec = new CMultiOutStream(); outSeekStream = volStreamSpec; outStream = outSeekStream; - volStreamSpec->Sizes = options.VolumesSizes; volStreamSpec->Prefix = us2fs(archivePath.GetFinalVolPath()); - volStreamSpec->Prefix += '.'; - volStreamSpec->TempFiles = &tempFiles; - volStreamSpec->Init(); + volStreamSpec->Prefix.Add_Dot(); + volStreamSpec->Init(options.VolumesSizes); + { + CMultiOutStream_Rec &rec = multiStreams.Items.AddNew(); + rec.Spec = volStreamSpec; + rec.Ref = rec.Spec; + } /* updateCallbackSpec->VolumesSizes = volumesSizes; @@ -913,22 +762,22 @@ { outStreamSpec2 = new COutFileStream; sfxOutStream = outStreamSpec2; - FString realPath = us2fs(archivePath.GetFinalPath()); + const FString realPath = us2fs(archivePath.GetFinalPath()); if (!outStreamSpec2->Create(realPath, false)) return errorInfo.SetFromLastError("cannot open file", realPath); } { UInt64 sfxSize; - RINOK(sfxStreamSpec->GetSize(&sfxSize)); - RINOK(callback->WriteSfx(fs2us(options.SfxModule), sfxSize)); + RINOK(sfxStreamSpec->GetSize(&sfxSize)) + RINOK(callback->WriteSfx(fs2us(options.SfxModule), sfxSize)) } - RINOK(NCompress::CopyStream(sfxStream, sfxOutStream, NULL)); + RINOK(NCompress::CopyStream(sfxStream, sfxOutStream, NULL)) if (outStreamSpec2) { - RINOK(outStreamSpec2->Close()); + RINOK(outStreamSpec2->Close()) } } @@ -939,8 +788,8 @@ else { // Int64 globalOffset = arc->GetGlobalOffset(); - RINOK(arc->InStream->Seek(0, STREAM_SEEK_SET, NULL)); - RINOK(NCompress::CopyStream_ExactSize(arc->InStream, outStream, arc->ArcStreamOffset, NULL)); + RINOK(InStream_SeekToBegin(arc->InStream)) + RINOK(NCompress::CopyStream_ExactSize(arc->InStream, outStream, arc->ArcStreamOffset, NULL)) if (options.StdOutMode) tailStream = outStream; else @@ -953,10 +802,57 @@ } } + CFiTime ft; + FiTime_Clear(ft); + bool ft_Defined = false; + { + FOR_VECTOR (i, updatePairs2) + { + const CUpdatePair2 &pair2 = updatePairs2[i]; + CFiTime ft2; + FiTime_Clear(ft2); + bool ft2_Defined = false; + /* we use full precision of dirItem, if dirItem is defined + and (dirItem will be used or dirItem is sameTime in dir and arc */ + if (pair2.DirIndex >= 0 && + (pair2.NewProps || pair2.IsSameTime)) + { + ft2 = dirItems.Items[(unsigned)pair2.DirIndex].MTime; + ft2_Defined = true; + } + else if (pair2.UseArcProps && pair2.ArcIndex >= 0) + { + const CArcItem &arcItem = arcItems[(unsigned)pair2.ArcIndex]; + if (arcItem.MTime.Def) + { + arcItem.MTime.Write_To_FiTime(ft2); + ft2_Defined = true; + } + } + if (ft2_Defined) + { + if (!ft_Defined || Compare_FiTime(&ft, &ft2) < 0) + { + ft = ft2; + ft_Defined = true; + } + } + } + /* + if (fileTimeType != NFileTimeType::kNotDefined) + FiTime_Normalize_With_Prec(ft, fileTimeType); + */ + } + + if (volStreamSpec && options.SetArcMTime && ft_Defined) + { + volStreamSpec->MTime = ft; + volStreamSpec->MTime_Defined = true; + } HRESULT result = outArchive->UpdateItems(tailStream, updatePairs2.Size(), updateCallback); // callback->Finalize(); - RINOK(result); + RINOK(result) if (!updateCallbackSpec->AreAllFilesClosed()) { @@ -967,10 +863,6 @@ if (options.SetArcMTime) { - CFiTime ft; - FiTime_Clear(ft); - bool isDefined = false; - // bool needNormalizeAfterStream; // needParse; /* @@ -990,40 +882,9 @@ // CArcTime at = StreamCallback_ArcMTime; // updateCallbackSpec->StreamCallback_ArcMTime.Write_To_FiTime(ft); // we must normalize with precision from archive; - ft = updateCallbackSpec->LatestMTime; - isDefined = true; - } - - FOR_VECTOR (i, updatePairs2) - { - const CUpdatePair2 &pair2 = updatePairs2[i]; - CFiTime ft2; - bool ft2_Defined = false; - /* we use full precision of dirItem, if dirItem is defined - and (dirItem will be used or dirItem is sameTime in dir and arc */ - if (pair2.DirIndex >= 0 && - (pair2.NewProps || pair2.IsSameTime)) - { - ft2 = dirItems.Items[(unsigned)pair2.DirIndex].MTime; - ft2_Defined = true; - } - else if (pair2.UseArcProps && pair2.ArcIndex >= 0) - { - const CArcItem &arcItem = arcItems[(unsigned)pair2.ArcIndex]; - if (arcItem.MTime.Def) - { - arcItem.MTime.Write_To_FiTime(ft2); - ft2_Defined = true; - } - } - if (ft2_Defined) - { - if (Compare_FiTime(&ft, &ft2) < 0) - { - ft = ft2; - isDefined = true; - } - } + if (!ft_Defined || Compare_FiTime(&ft, &updateCallbackSpec->LatestMTime) < 0) + ft = updateCallbackSpec->LatestMTime; + ft_Defined = true; } /* if (fileTimeType != NFileTimeType::kNotDefined) @@ -1031,12 +892,14 @@ */ } // if (ft.dwLowDateTime != 0 || ft.dwHighDateTime != 0) - if (isDefined) + if (ft_Defined) { + // we ignore set time errors here. + // note that user could move some finished volumes to another folder. if (outStreamSpec) outStreamSpec->SetMTime(&ft); else if (volStreamSpec) - volStreamSpec->SetMTime(&ft); + volStreamSpec->SetMTime_Final(ft); } } @@ -1056,7 +919,10 @@ if (outStreamSpec) result = outStreamSpec->Close(); else if (volStreamSpec) - result = volStreamSpec->Close(); + { + result = volStreamSpec->FinalFlush_and_CloseFiles(st.NumVolumes); + st.IsMultiVolMode = true; + } RINOK(result) @@ -1121,7 +987,7 @@ arcItems.Clear(); UInt32 numItems; IInArchive *archive = arc.Archive; - RINOK(archive->GetNumberOfItems(&numItems)); + RINOK(archive->GetNumberOfItems(&numItems)) arcItems.ClearAndReserve(numItems); CReadArcItem item; @@ -1132,7 +998,7 @@ { CArcItem ai; - RINOK(arc.GetItem(i, item)); + RINOK(arc.GetItem(i, item)) ai.Name = item.Path; ai.IsDir = item.IsDir; ai.IsAltStream = @@ -1152,8 +1018,8 @@ ai.Censored = Censor_CheckPath(censor, item); // ai.MTime will be set to archive MTime, if not present in archive item - RINOK(arc.GetItem_MTime(i, ai.MTime)); - RINOK(arc.GetItem_Size(i, ai.Size, ai.Size_Defined)); + RINOK(arc.GetItem_MTime(i, ai.MTime)) + RINOK(arc.GetItem_Size(i, ai.Size, ai.Size_Defined)) ai.IndexInServer = i; arcItems.AddInReserved(ai); @@ -1163,10 +1029,73 @@ #if defined(_WIN32) && !defined(UNDER_CE) +#if defined(__MINGW32__) || defined(__MINGW64__) +#include +#else #include - #endif +extern "C" { + +#ifdef MAPI_FORCE_UNICODE + +#define Z7_WIN_LPMAPISENDMAILW LPMAPISENDMAILW +#define Z7_WIN_MapiFileDescW MapiFileDescW +#define Z7_WIN_MapiMessageW MapiMessageW +#define Z7_WIN_MapiRecipDescW MapiRecipDescW + +#else + +typedef struct +{ + ULONG ulReserved; + ULONG ulRecipClass; + PWSTR lpszName; + PWSTR lpszAddress; + ULONG ulEIDSize; + PVOID lpEntryID; +} Z7_WIN_MapiRecipDescW, *Z7_WIN_lpMapiRecipDescW; + +typedef struct +{ + ULONG ulReserved; + ULONG flFlags; + ULONG nPosition; + PWSTR lpszPathName; + PWSTR lpszFileName; + PVOID lpFileType; +} Z7_WIN_MapiFileDescW, *Z7_WIN_lpMapiFileDescW; + +typedef struct +{ + ULONG ulReserved; + PWSTR lpszSubject; + PWSTR lpszNoteText; + PWSTR lpszMessageType; + PWSTR lpszDateReceived; + PWSTR lpszConversationID; + FLAGS flFlags; + Z7_WIN_lpMapiRecipDescW lpOriginator; + ULONG nRecipCount; + Z7_WIN_lpMapiRecipDescW lpRecips; + ULONG nFileCount; + Z7_WIN_lpMapiFileDescW lpFiles; +} Z7_WIN_MapiMessageW, *Z7_WIN_lpMapiMessageW; + +typedef ULONG (FAR PASCAL Z7_WIN_MAPISENDMAILW)( + LHANDLE lhSession, + ULONG_PTR ulUIParam, + Z7_WIN_lpMapiMessageW lpMessage, + FLAGS flFlags, + ULONG ulReserved +); +typedef Z7_WIN_MAPISENDMAILW FAR *Z7_WIN_LPMAPISENDMAILW; + +#endif // MAPI_FORCE_UNICODE +} +#endif // _WIN32 + + HRESULT UpdateArchive( CCodecs *codecs, const CObjectVector &types, @@ -1253,8 +1182,7 @@ if (!options.VolumesSizes.IsEmpty()) { arcPath = options.ArchivePath.GetFinalVolPath(); - arcPath += '.'; - arcPath += "001"; + arcPath += ".001"; } if (cmdArcPath2.IsEmpty()) @@ -1268,7 +1196,7 @@ if (!fi.Find_FollowLink(us2fs(arcPath))) { if (renameMode) - throw "can't find archive";; + throw "can't find archive"; if (options.MethodMode.Type.FormatIndex < 0) { if (!options.SetArcPath(codecs, cmdArcPath2)) @@ -1319,7 +1247,7 @@ CIntVector excl; COpenOptions op; - #ifndef _SFX + #ifndef Z7_SFX op.props = &options.MethodMode.Properties; #endif op.codecs = codecs; @@ -1329,7 +1257,7 @@ op.stream = NULL; op.filePath = arcPath; - RINOK(callback->StartOpenArchive(arcPath)); + RINOK(callback->StartOpenArchive(arcPath)) HRESULT result = arcLink.Open_Strict(op, openCallback); @@ -1341,8 +1269,8 @@ if (result == S_FALSE) return E_FAIL; */ - RINOK(res2); - RINOK(result); + RINOK(res2) + RINOK(result) if (arcLink.VolumePaths.Size() > 1) { @@ -1422,7 +1350,7 @@ if (needScanning) { - RINOK(callback->StartScanning()); + RINOK(callback->StartScanning()) dirItems.SymLinks = options.SymLinks.Val; @@ -1452,7 +1380,7 @@ return res; } - RINOK(callback->FinishScanning(dirItems.Stat)); + RINOK(callback->FinishScanning(dirItems.Stat)) // 22.00: we don't need parent folder, if absolute path mode if (options.PathMode != NWildcard::k_AbsPath) @@ -1460,7 +1388,7 @@ { NFind::CFileInfo fi; FString prefix = us2fs(censor.Pairs[0].Prefix); - prefix += '.'; + prefix.Add_Dot(); // UString prefix = censor.Pairs[0].Prefix; /* if (prefix.Back() == WCHAR_PATH_SEPARATOR) @@ -1576,7 +1504,7 @@ { RINOK(EnumerateInArchiveItems( // options.StoreAltStreams, - censor, arcLink.Arcs.Back(), arcItems)); + censor, arcLink.Arcs.Back(), arcItems)) } /* @@ -1595,8 +1523,10 @@ processedItems[i] = 0; } + CMultiOutStream_Bunch multiStreams; + /* - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO if (arcLink.PasswordWasAsked) { // We set password, if open have requested password @@ -1640,18 +1570,22 @@ parentDirItem_Ptr, tempFiles, - errorInfo, callback, st)); + multiStreams, + errorInfo, callback, st)) - RINOK(callback->FinishArchive(st)); + RINOK(callback->FinishArchive(st)) } if (thereIsInArchive) { - RINOK(arcLink.Close()); + RINOK(arcLink.Close()) arcLink.Release(); } + multiStreams.DisableDeletion(); + RINOK(multiStreams.Destruct()) + tempFiles.Paths.Clear(); if (createTempFile) { @@ -1702,6 +1636,19 @@ return errorInfo.Get_HRESULT_Error(); } + FStringVector fullPaths; + unsigned i; + + for (i = 0; i < options.Commands.Size(); i++) + { + CArchivePath &ap = options.Commands[i].ArchivePath; + const FString finalPath = us2fs(ap.GetFinalPath()); + FString arcPath2; + if (!MyGetFullPathName(finalPath, arcPath2)) + return errorInfo.SetFromLastError("GetFullPathName error", finalPath); + fullPaths.Add(arcPath2); + } + /* LPMAPISENDDOCUMENTS fnSend = (LPMAPISENDDOCUMENTS)mapiLib.GetProc("MAPISendDocuments"); if (fnSend == 0) @@ -1710,25 +1657,70 @@ return errorInfo.Get_HRESULT_Error(); } */ + const + Z7_WIN_LPMAPISENDMAILW sendMailW = Z7_GET_PROC_ADDRESS( + Z7_WIN_LPMAPISENDMAILW, mapiLib.Get_HMODULE(), + "MAPISendMailW"); + if (sendMailW) + { + + CCurrentDirRestorer curDirRestorer; + + UStringVector paths; + UStringVector names; - LPMAPISENDMAIL sendMail = (LPMAPISENDMAIL)(void *)mapiLib.GetProc("MAPISendMail"); - if (sendMail == 0) + for (i = 0; i < fullPaths.Size(); i++) { - errorInfo.SetFromLastError("7-Zip cannot find MAPISendMail function"); - return errorInfo.Get_HRESULT_Error();; + const UString arcPath2 = fs2us(fullPaths[i]); + const UString fileName = ExtractFileNameFromPath(arcPath2); + paths.Add(arcPath2); + names.Add(fileName); + // Warning!!! MAPISendDocuments function changes Current directory + // fnSend(0, ";", (LPSTR)(LPCSTR)path, (LPSTR)(LPCSTR)name, 0); } - FStringVector fullPaths; - unsigned i; + CRecordVector files; + files.ClearAndSetSize(paths.Size()); - for (i = 0; i < options.Commands.Size(); i++) + for (i = 0; i < paths.Size(); i++) { - CArchivePath &ap = options.Commands[i].ArchivePath; - FString finalPath = us2fs(ap.GetFinalPath()); - FString arcPath2; - if (!MyGetFullPathName(finalPath, arcPath2)) - return errorInfo.SetFromLastError("GetFullPathName error", finalPath); - fullPaths.Add(arcPath2); + Z7_WIN_MapiFileDescW &f = files[i]; + memset(&f, 0, sizeof(f)); + f.nPosition = 0xFFFFFFFF; + f.lpszPathName = paths[i].Ptr_non_const(); + f.lpszFileName = names[i].Ptr_non_const(); + } + + { + Z7_WIN_MapiMessageW m; + memset(&m, 0, sizeof(m)); + m.nFileCount = files.Size(); + m.lpFiles = &files.Front(); + + const UString addr (options.EMailAddress); + Z7_WIN_MapiRecipDescW rec; + if (!addr.IsEmpty()) + { + memset(&rec, 0, sizeof(rec)); + rec.ulRecipClass = MAPI_TO; + rec.lpszAddress = addr.Ptr_non_const(); + m.nRecipCount = 1; + m.lpRecips = &rec; + } + + sendMailW((LHANDLE)0, 0, &m, MAPI_DIALOG, 0); + } + } + else + { + const + LPMAPISENDMAIL sendMail = Z7_GET_PROC_ADDRESS( + LPMAPISENDMAIL, mapiLib.Get_HMODULE(), + "MAPISendMail"); + if (!sendMail) + { + errorInfo.SetFromLastError("7-Zip cannot find MAPISendMail function"); + return errorInfo.Get_HRESULT_Error(); } CCurrentDirRestorer curDirRestorer; @@ -1779,6 +1771,7 @@ sendMail((LHANDLE)0, 0, &m, MAPI_DIALOG, 0); } + } } #endif @@ -1827,7 +1820,7 @@ && Compare_FiTime(&fileInfo.MTime, &dirItem.MTime) == 0 && Compare_FiTime(&fileInfo.CTime, &dirItem.CTime) == 0) { - RINOK(callback->DeletingAfterArchiving(phyPath, false)); + RINOK(callback->DeletingAfterArchiving(phyPath, false)) DeleteFileAlways(phyPath); } } @@ -1852,12 +1845,12 @@ const FString phyPath = dirItems.GetPhyPath(pairs[i].Index); if (NFind::DoesDirExist(phyPath)) { - RINOK(callback->DeletingAfterArchiving(phyPath, true)); + RINOK(callback->DeletingAfterArchiving(phyPath, true)) RemoveDir(phyPath); } } - RINOK(callback->FinishDeletingAfterArchiving()); + RINOK(callback->FinishDeletingAfterArchiving()) } return S_OK; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/Update.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/Update.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/Update.h 2022-02-24 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/Update.h 2023-04-05 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Update.h -#ifndef __COMMON_UPDATE_H -#define __COMMON_UPDATE_H +#ifndef ZIP7_INC_COMMON_UPDATE_H +#define ZIP7_INC_COMMON_UPDATE_H #include "../../../Common/Wildcard.h" @@ -34,7 +34,7 @@ FString TempPrefix; // path(folder) for temp location FString TempPostfix; - CArchivePath(): Temp(false) {}; + CArchivePath(): Temp(false) {} void ParseFromPath(const UString &path, EArcNameMode mode); UString GetPathWithoutExt() const { return Prefix + Name; } @@ -81,31 +81,21 @@ struct CUpdateOptions { - CCompressionMethodMode MethodMode; - - CObjectVector Commands; bool UpdateArchiveItself; - CArchivePath ArchivePath; - EArcNameMode ArcNameMode; - bool SfxMode; - FString SfxModule; - + bool PreserveATime; bool OpenShareForWrite; bool StopAfterOpenError; bool StdInMode; - UString StdInFileName; bool StdOutMode; - + bool EMailMode; bool EMailRemoveAfter; - UString EMailAddress; - FString WorkingDir; - NWildcard::ECensorPathMode PathMode; - // UString AddPathPrefix; + bool DeleteAfterCompressing; + bool SetArcMTime; CBoolPair NtSecurity; CBoolPair AltStreams; @@ -115,19 +105,28 @@ CBoolPair StoreOwnerId; CBoolPair StoreOwnerName; - bool DeleteAfterCompressing; + EArcNameMode ArcNameMode; + NWildcard::ECensorPathMode PathMode; - bool SetArcMTime; + CCompressionMethodMode MethodMode; + + CObjectVector Commands; + CArchivePath ArchivePath; + + FString SfxModule; + UString StdInFileName; + UString EMailAddress; + FString WorkingDir; + // UString AddPathPrefix; CObjectVector RenamePairs; + CRecordVector VolumesSizes; bool InitFormatIndex(const CCodecs *codecs, const CObjectVector &types, const UString &arcPath); bool SetArcPath(const CCodecs *codecs, const UString &arcPath); CUpdateOptions(): UpdateArchiveItself(true), - ArcNameMode(k_ArcNameMode_Smart), - SfxMode(false), PreserveATime(false), @@ -140,12 +139,13 @@ EMailMode(false), EMailRemoveAfter(false), - PathMode(NWildcard::k_RelatPath), - DeleteAfterCompressing(false), - SetArcMTime(false) + SetArcMTime(false), - {}; + ArcNameMode(k_ArcNameMode_Smart), + PathMode(NWildcard::k_RelatPath) + + {} void SetActionCommand_Add() { @@ -154,10 +154,9 @@ c.ActionSet = NUpdateArchive::k_ActionSet_Add; Commands.Add(c); } - - CRecordVector VolumesSizes; }; + struct CUpdateErrorInfo { DWORD SystemError; // it's DWORD (WRes) only; @@ -170,32 +169,40 @@ HRESULT SetFromLastError(const char *message, const FString &fileName); HRESULT SetFromError_DWORD(const char *message, const FString &fileName, DWORD error); - CUpdateErrorInfo(): SystemError(0) {}; + CUpdateErrorInfo(): SystemError(0) {} }; struct CFinishArchiveStat { UInt64 OutArcFileSize; + unsigned NumVolumes; + bool IsMultiVolMode; - CFinishArchiveStat(): OutArcFileSize(0) {} + CFinishArchiveStat(): OutArcFileSize(0), NumVolumes(0), IsMultiVolMode(false) {} }; -#define INTERFACE_IUpdateCallbackUI2(x) \ - INTERFACE_IUpdateCallbackUI(x) \ - INTERFACE_IDirItemsCallback(x) \ - virtual HRESULT OpenResult(const CCodecs *codecs, const CArchiveLink &arcLink, const wchar_t *name, HRESULT result) x; \ - virtual HRESULT StartScanning() x; \ - virtual HRESULT FinishScanning(const CDirItemsStat &st) x; \ - virtual HRESULT StartOpenArchive(const wchar_t *name) x; \ - virtual HRESULT StartArchive(const wchar_t *name, bool updating) x; \ - virtual HRESULT FinishArchive(const CFinishArchiveStat &st) x; \ - virtual HRESULT DeletingAfterArchiving(const FString &path, bool isDir) x; \ - virtual HRESULT FinishDeletingAfterArchiving() x; \ +Z7_PURE_INTERFACES_BEGIN + +// INTERFACE_IUpdateCallbackUI(x) +// INTERFACE_IDirItemsCallback(x) + +#define Z7_IFACEN_IUpdateCallbackUI2(x) \ + virtual HRESULT OpenResult(const CCodecs *codecs, const CArchiveLink &arcLink, const wchar_t *name, HRESULT result) x \ + virtual HRESULT StartScanning() x \ + virtual HRESULT FinishScanning(const CDirItemsStat &st) x \ + virtual HRESULT StartOpenArchive(const wchar_t *name) x \ + virtual HRESULT StartArchive(const wchar_t *name, bool updating) x \ + virtual HRESULT FinishArchive(const CFinishArchiveStat &st) x \ + virtual HRESULT DeletingAfterArchiving(const FString &path, bool isDir) x \ + virtual HRESULT FinishDeletingAfterArchiving() x \ -struct IUpdateCallbackUI2: public IUpdateCallbackUI, public IDirItemsCallback +DECLARE_INTERFACE(IUpdateCallbackUI2): + public IUpdateCallbackUI, + public IDirItemsCallback { - INTERFACE_IUpdateCallbackUI2(=0) + Z7_IFACE_PURE(IUpdateCallbackUI2) }; +Z7_PURE_INTERFACES_END HRESULT UpdateArchive( CCodecs *codecs, diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/UpdatePair.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/UpdatePair.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/UpdatePair.cpp 2022-04-06 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/UpdatePair.cpp 2023-04-06 05:00:00.000000000 +0000 @@ -103,7 +103,7 @@ static const char * const k_Duplicate_inDir_Message = "Duplicate filename on disk:"; static const char * const k_NotCensoredCollision_Message = "Internal file name collision (file on disk, file in archive):"; -MY_ATTR_NORETURN +Z7_ATTR_NORETURN static void ThrowError(const char *message, const UString &s1, const UString &s2) { @@ -115,7 +115,7 @@ static int CompareArcItemsBase(const CArcItem &ai1, const CArcItem &ai2) { - int res = CompareFileNames(ai1.Name, ai2.Name); + const int res = CompareFileNames(ai1.Name, ai2.Name); if (res != 0) return res; if (ai1.IsDir != ai2.IsDir) @@ -128,7 +128,7 @@ const unsigned i1 = *p1; const unsigned i2 = *p2; const CObjectVector &arcItems = *(const CObjectVector *)param; - int res = CompareArcItemsBase(arcItems[i1], arcItems[i2]); + const int res = CompareArcItemsBase(arcItems[i1], arcItems[i2]); if (res != 0) return res; return MyCompare(i1, i2); @@ -259,7 +259,7 @@ int compResult = 0; if (ai->MTime.Def) { - compResult = MyCompareTime(fileTimeType, di->MTime, ai->MTime); + compResult = MyCompareTime((unsigned)fileTimeType, di->MTime, ai->MTime); } switch (compResult) { @@ -283,7 +283,7 @@ { if (prevHostName) { - unsigned hostLen = prevHostName->Len(); + const unsigned hostLen = prevHostName->Len(); if (name->Len() > hostLen) if ((*name)[hostLen] == ':' && CompareFileNames(*prevHostName, name->Left(hostLen)) == 0) pair.HostIndex = prevHostFile; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/UpdatePair.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/UpdatePair.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/UpdatePair.h 2014-05-03 11:49:25.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/UpdatePair.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // UpdatePair.h -#ifndef __UPDATE_PAIR_H -#define __UPDATE_PAIR_H +#ifndef ZIP7_INC_UPDATE_PAIR_H +#define ZIP7_INC_UPDATE_PAIR_H #include "DirItem.h" #include "UpdateAction.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/UpdateProduce.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/UpdateProduce.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/UpdateProduce.h 2022-02-08 16:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/UpdateProduce.h 2023-02-01 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // UpdateProduce.h -#ifndef __UPDATE_PRODUCE_H -#define __UPDATE_PRODUCE_H +#ifndef ZIP7_INC_UPDATE_PRODUCE_H +#define ZIP7_INC_UPDATE_PRODUCE_H #include "UpdatePair.h" @@ -43,10 +43,13 @@ {} }; -struct IUpdateProduceCallback +Z7_PURE_INTERFACES_BEGIN + +DECLARE_INTERFACE(IUpdateProduceCallback) { virtual HRESULT ShowDeleteFile(unsigned arcIndex) = 0; }; +Z7_PURE_INTERFACES_END void UpdateProduce( const CRecordVector &updatePairs, diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/WorkDir.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/WorkDir.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/WorkDir.cpp 2021-01-25 19:32:34.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/WorkDir.cpp 2023-04-06 05:00:00.000000000 +0000 @@ -2,11 +2,8 @@ #include "StdAfx.h" -#include "../../../Common/StringConvert.h" -#include "../../../Common/Wildcard.h" - -#include "../../../Windows/FileFind.h" #include "../../../Windows/FileName.h" +#include "../../../Windows/FileSystem.h" #include "WorkDir.h" @@ -22,10 +19,10 @@ if (workDirInfo.ForRemovableOnly) { mode = NWorkDir::NMode::kCurrent; - FString prefix = path.Left(3); - if (prefix[1] == FTEXT(':') && prefix[2] == FTEXT('\\')) + const FString prefix = path.Left(3); + if (NName::IsDrivePath(prefix)) { - UINT driveType = GetDriveType(GetSystemString(prefix, ::AreFileApisANSI() ? CP_ACP : CP_OEMCP)); + const UINT driveType = NSystem::MyGetDriveType(prefix); if (driveType == DRIVE_CDROM || driveType == DRIVE_REMOVABLE) mode = workDirInfo.Mode; } @@ -39,29 +36,26 @@ } #endif - int pos = path.ReverseFind_PathSepar() + 1; + const int pos = path.ReverseFind_PathSepar() + 1; fileName = path.Ptr((unsigned)pos); - switch (mode) + FString tempDir; + switch ((int)mode) { case NWorkDir::NMode::kCurrent: - { - return path.Left((unsigned)pos); - } + tempDir = path.Left((unsigned)pos); + break; case NWorkDir::NMode::kSpecified: - { - FString tempDir = workDirInfo.Path; - NName::NormalizeDirPathPrefix(tempDir); - return tempDir; - } + tempDir = workDirInfo.Path; + break; + // case NWorkDir::NMode::kSystem: default: - { - FString tempDir; if (!MyGetTempPath(tempDir)) throw 141717; - return tempDir; - } + break; } + NName::NormalizeDirPathPrefix(tempDir); + return tempDir; } HRESULT CWorkDirTempFile::CreateTempFile(const FString &originalPath) @@ -69,9 +63,8 @@ NWorkDir::CInfo workDirInfo; workDirInfo.Load(); FString namePart; - FString workDir = GetWorkDir(workDirInfo, originalPath, namePart); + const FString workDir = GetWorkDir(workDirInfo, originalPath, namePart); CreateComplexDir(workDir); - CTempFile tempFile; _outStreamSpec = new COutFileStream; OutStream = _outStreamSpec; if (!_tempFile.Create(workDir + namePart, &_outStreamSpec->File)) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/WorkDir.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/WorkDir.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/WorkDir.h 2013-02-18 08:11:20.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/WorkDir.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // WorkDir.h -#ifndef __WORK_DIR_H -#define __WORK_DIR_H +#ifndef ZIP7_INC_WORK_DIR_H +#define ZIP7_INC_WORK_DIR_H #include "../../../Windows/FileDir.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/ZipRegistry.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Common/ZipRegistry.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/ZipRegistry.cpp 2022-06-03 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/ZipRegistry.cpp 2023-04-06 05:00:00.000000000 +0000 @@ -11,6 +11,7 @@ #include "../../../Windows/Registry.h" #include "../../../Windows/Synchronization.h" +// #include "../Explorer/ContextMenuFlags.h" #include "ZipRegistry.h" using namespace NWindows; @@ -191,6 +192,7 @@ static LPCTSTR const kLevel = TEXT("Level"); static LPCTSTR const kDictionary = TEXT("Dictionary"); +// static LPCTSTR const kDictionaryChain = TEXT("DictionaryChain"); static LPCTSTR const kOrder = TEXT("Order"); static LPCTSTR const kBlockSize = TEXT("BlockSize"); static LPCTSTR const kNumThreads = TEXT("NumThreads"); @@ -269,6 +271,7 @@ Key_Set_UInt32(fk, kLevel, fo.Level); Key_Set_UInt32(fk, kDictionary, fo.Dictionary); + // Key_Set_UInt32(fk, kDictionaryChain, fo.DictionaryChain); Key_Set_UInt32(fk, kOrder, fo.Order); Key_Set_UInt32(fk, kBlockSize, fo.BlockLogSize); Key_Set_UInt32(fk, kNumThreads, fo.NumThreads); @@ -326,6 +329,7 @@ Key_Get_UInt32(fk, kLevel, fo.Level); Key_Get_UInt32(fk, kDictionary, fo.Dictionary); + // Key_Get_UInt32(fk, kDictionaryChain, fo.DictionaryChain); Key_Get_UInt32(fk, kOrder, fo.Order); Key_Get_UInt32(fk, kBlockSize, fo.BlockLogSize); Key_Get_UInt32(fk, kNumThreads, fo.NumThreads); @@ -549,7 +553,15 @@ WriteZone = (UInt32)(Int32)-1; - Flags = (UInt32)(Int32)-1; + /* we can disable email items by default, + because email code doesn't work in some systems */ + Flags = (UInt32)(Int32)-1 + /* + & ~NContextMenuFlags::kCompressEmail + & ~NContextMenuFlags::kCompressTo7zEmail + & ~NContextMenuFlags::kCompressToZipEmail + */ + ; Flags_Def = false; CS_LOCK diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Common/ZipRegistry.h 7zip-23.01+dfsg/CPP/7zip/UI/Common/ZipRegistry.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Common/ZipRegistry.h 2022-06-03 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Common/ZipRegistry.h 2023-04-06 05:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ZipRegistry.h -#ifndef __ZIP_REGISTRY_H -#define __ZIP_REGISTRY_H +#ifndef ZIP7_INC_ZIP_REGISTRY_H +#define ZIP7_INC_ZIP_REGISTRY_H #include "../../../Common/MyTypes.h" #include "../../../Common/MyString.h" @@ -81,6 +81,7 @@ { UInt32 Level; UInt32 Dictionary; + // UInt32 DictionaryChain; UInt32 Order; UInt32 BlockLogSize; UInt32 NumThreads; @@ -116,6 +117,7 @@ void ResetForLevelChange() { BlockLogSize = NumThreads = Level = Dictionary = Order = (UInt32)(Int32)-1; + // DictionaryChain = (UInt32)(Int32)-1; Method.Empty(); // Options.Empty(); // EncryptionMethod.Empty(); @@ -133,10 +135,6 @@ UInt32 Level; bool ShowPassword; bool EncryptHeaders; - UString ArcType; - UStringVector ArcPaths; - - CObjectVector Formats; CBoolPair NtSecurity; CBoolPair AltStreams; @@ -145,6 +143,11 @@ CBoolPair PreserveATime; + UString ArcType; + UStringVector ArcPaths; + + CObjectVector Formats; + void Save() const; void Load(); }; @@ -164,8 +167,8 @@ struct CInfo { NMode::EEnum Mode; - FString Path; bool ForRemovableOnly; + FString Path; void SetForRemovableOnlyDefault() { ForRemovableOnly = true; } void SetDefault() diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/BenchCon.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Console/BenchCon.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/BenchCon.cpp 2015-03-10 16:19:21.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/BenchCon.cpp 2023-04-01 19:00:00.000000000 +0000 @@ -7,13 +7,13 @@ #include "BenchCon.h" #include "ConsoleClose.h" -struct CPrintBenchCallback: public IBenchPrintCallback +struct CPrintBenchCallback Z7_final: public IBenchPrintCallback { FILE *_file; - void Print(const char *s); - void NewLine(); - HRESULT CheckBreak(); + void Print(const char *s) Z7_override; + void NewLine() Z7_override; + HRESULT CheckBreak() Z7_override; }; void CPrintBenchCallback::Print(const char *s) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/BenchCon.h 7zip-23.01+dfsg/CPP/7zip/UI/Console/BenchCon.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/BenchCon.h 2012-12-06 08:03:03.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/BenchCon.h 2023-04-01 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // BenchCon.h -#ifndef __BENCH_CON_H -#define __BENCH_CON_H +#ifndef ZIP7_INC_BENCH_CON_H +#define ZIP7_INC_BENCH_CON_H #include diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/ConsoleClose.h 7zip-23.01+dfsg/CPP/7zip/UI/Console/ConsoleClose.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/ConsoleClose.h 2021-01-05 15:48:43.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/ConsoleClose.h 2023-04-03 07:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ConsoleClose.h -#ifndef __CONSOLE_CLOSE_H -#define __CONSOLE_CLOSE_H +#ifndef ZIP7_INC_CONSOLE_CLOSE_H +#define ZIP7_INC_CONSOLE_CLOSE_H namespace NConsoleClose { @@ -21,7 +21,7 @@ return (g_BreakCounter != 0); } -class CCtrlHandlerSetter +class CCtrlHandlerSetter Z7_final { #ifndef _WIN32 void (*memo_sig_int)(int); @@ -29,7 +29,7 @@ #endif public: CCtrlHandlerSetter(); - virtual ~CCtrlHandlerSetter(); + ~CCtrlHandlerSetter(); }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/Console.dsp 7zip-23.01+dfsg/CPP/7zip/UI/Console/Console.dsp --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/Console.dsp 2022-07-14 06:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/Console.dsp 2023-04-02 08:00:00.000000000 +0000 @@ -44,7 +44,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /Gr /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_MBCS" /D "WIN32" /D "_CONSOLE" /D "WIN_LONG_PATH" /D "EXTERNAL_CODECS" /D "_7ZIP_LARGE_PAGES" /D "SUPPORT_DEVICE_FILE" /FAcs /Yu"StdAfx.h" /FD /GF /c +# ADD CPP /nologo /Gr /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_MBCS" /D "WIN32" /D "_CONSOLE" /D "Z7_LONG_PATH" /D "Z7_EXTERNAL_CODECS" /D "Z7_LARGE_PAGES" /D "Z7_DEVICE_FILE" /FAcs /Yu"StdAfx.h" /FD /GF /c # ADD BASE RSC /l 0x419 /d "NDEBUG" # ADD RSC /l 0x419 /d "NDEBUG" BSC32=bscmake.exe @@ -69,7 +69,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /Gr /MTd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_MBCS" /D "WIN32" /D "_CONSOLE" /D "WIN_LONG_PATH" /D "EXTERNAL_CODECS" /D "_7ZIP_LARGE_PAGES" /D "SUPPORT_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gr /MTd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_MBCS" /D "WIN32" /D "_CONSOLE" /D "Z7_LONG_PATH" /D "Z7_EXTERNAL_CODECS" /D "Z7_LARGE_PAGES" /D "Z7_DEVICE_FILE" /FAcs /Yu"StdAfx.h" /FD /GZ /c # ADD BASE RSC /l 0x419 /d "_DEBUG" # ADD RSC /l 0x419 /d "_DEBUG" BSC32=bscmake.exe @@ -95,7 +95,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /Gz /MD /W3 /GX /O1 /I "../../../" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"StdAfx.h" /FD /c -# ADD CPP /nologo /Gr /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_UNICODE" /D "UNICODE" /D "WIN32" /D "_CONSOLE" /D "WIN_LONG_PATH" /D "EXTERNAL_CODECS" /D "_7ZIP_LARGE_PAGES" /D "SUPPORT_DEVICE_FILE" /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gr /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_UNICODE" /D "UNICODE" /D "WIN32" /D "_CONSOLE" /D "Z7_LONG_PATH" /D "Z7_EXTERNAL_CODECS" /D "Z7_LARGE_PAGES" /D "Z7_DEVICE_FILE" /Yu"StdAfx.h" /FD /c # ADD BASE RSC /l 0x419 /d "NDEBUG" # ADD RSC /l 0x419 /d "NDEBUG" BSC32=bscmake.exe @@ -121,7 +121,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /Gz /W3 /Gm /GX /ZI /Od /I "../../../" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"StdAfx.h" /FD /GZ /c -# ADD CPP /nologo /Gr /MTd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_UNICODE" /D "UNICODE" /D "WIN32" /D "_CONSOLE" /D "WIN_LONG_PATH" /D "EXTERNAL_CODECS" /D "_7ZIP_LARGE_PAGES" /D "SUPPORT_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gr /MTd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_UNICODE" /D "UNICODE" /D "WIN32" /D "_CONSOLE" /D "Z7_LONG_PATH" /D "Z7_EXTERNAL_CODECS" /D "Z7_LARGE_PAGES" /D "Z7_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c # ADD BASE RSC /l 0x419 /d "_DEBUG" # ADD RSC /l 0x419 /d "_DEBUG" BSC32=bscmake.exe @@ -445,6 +445,14 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyGuidDef.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\Common\MyInitGuid.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\MyString.cpp # End Source File # Begin Source File @@ -465,6 +473,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\NewHandler.cpp # End Source File # Begin Source File @@ -761,6 +773,14 @@ # End Source File # Begin Source File +SOURCE=..\..\Common\MultiOutStream.cpp +# End Source File +# Begin Source File + +SOURCE=..\..\Common\MultiOutStream.h +# End Source File +# Begin Source File + SOURCE=..\..\Common\ProgressUtils.cpp # End Source File # Begin Source File @@ -849,6 +869,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\7zWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\Alloc.c # SUBTRACT CPP /YX /Yc /Yu # End Source File @@ -858,6 +882,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\Compiler.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\CpuArch.c # SUBTRACT CPP /YX /Yc /Yu # End Source File diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/Console.mak 7zip-23.01+dfsg/CPP/7zip/UI/Console/Console.mak --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/Console.mak 2019-02-19 10:52:35.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/Console.mak 2023-06-20 07:00:00.000000000 +0000 @@ -1,7 +1,7 @@ MY_CONSOLE = 1 !IFNDEF UNDER_CE -CFLAGS = $(CFLAGS) -DWIN_LONG_PATH -D_7ZIP_LARGE_PAGES -DSUPPORT_DEVICE_FILE +CFLAGS = $(CFLAGS) -DZ7_LONG_PATH -DZ7_LARGE_PAGES -DZ7_DEVICE_FILE !ENDIF CONSOLE_OBJS = \ @@ -41,3 +41,5 @@ C_OBJS = $(C_OBJS) \ $O\DllSecur.obj \ + +# we need empty line after last line above diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/Console.manifest 7zip-23.01+dfsg/CPP/7zip/UI/Console/Console.manifest --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/Console.manifest 2018-04-04 13:36:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/Console.manifest 2023-04-02 08:00:00.000000000 +0000 @@ -10,4 +10,7 @@ + + +true \ No newline at end of file diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/ExtractCallbackConsole.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Console/ExtractCallbackConsole.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/ExtractCallbackConsole.cpp 2022-04-29 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/ExtractCallbackConsole.cpp 2023-04-01 14:00:00.000000000 +0000 @@ -11,7 +11,7 @@ #include "../../../Windows/ErrorMsg.h" #include "../../../Windows/PropVariantConv.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "../../../Windows/Synchronization.h" #endif @@ -183,7 +183,7 @@ -#ifndef _7ZIP_ST +#ifndef Z7_ST static NSynchronization::CCriticalSection g_CriticalSection; #define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection); #else @@ -235,7 +235,7 @@ , "CRC Error" }; -STDMETHODIMP CExtractCallbackConsole::SetTotal(UInt64 size) +Z7_COM7F_IMF(CExtractCallbackConsole::SetTotal(UInt64 size)) { MT_LOCK @@ -247,7 +247,7 @@ return CheckBreak2(); } -STDMETHODIMP CExtractCallbackConsole::SetCompleted(const UInt64 *completeValue) +Z7_COM7F_IMF(CExtractCallbackConsole::SetCompleted(const UInt64 *completeValue)) { MT_LOCK @@ -281,14 +281,14 @@ } } -STDMETHODIMP CExtractCallbackConsole::AskOverwrite( +Z7_COM7F_IMF(CExtractCallbackConsole::AskOverwrite( const wchar_t *existName, const FILETIME *existTime, const UInt64 *existSize, const wchar_t *newName, const FILETIME *newTime, const UInt64 *newSize, - Int32 *answer) + Int32 *answer)) { MT_LOCK - RINOK(CheckBreak2()); + RINOK(CheckBreak2()) ClosePercentsAndFlush(); @@ -302,7 +302,7 @@ NUserAnswerMode::EEnum overwriteAnswer = ScanUserYesNoAllQuit(_so); - switch (overwriteAnswer) + switch ((int)overwriteAnswer) { case NUserAnswerMode::kQuit: return E_ABORT; case NUserAnswerMode::kNo: *answer = NOverwriteAnswer::kNo; break; @@ -325,7 +325,7 @@ return CheckBreak2(); } -STDMETHODIMP CExtractCallbackConsole::PrepareOperation(const wchar_t *name, Int32 isFolder, Int32 askExtractMode, const UInt64 *position) +Z7_COM7F_IMF(CExtractCallbackConsole::PrepareOperation(const wchar_t *name, Int32 isFolder, Int32 askExtractMode, const UInt64 *position)) { MT_LOCK @@ -341,7 +341,7 @@ case NArchive::NExtract::NAskMode::kSkip: s = kSkipString; requiredLevel = 2; break; case NArchive::NExtract::NAskMode::kReadExternal: s = kReadString; requiredLevel = 0; break; default: s = "???"; requiredLevel = 2; - }; + } bool show2 = (LogLevel >= requiredLevel && _so); @@ -394,11 +394,11 @@ return CheckBreak2(); } -STDMETHODIMP CExtractCallbackConsole::MessageError(const wchar_t *message) +Z7_COM7F_IMF(CExtractCallbackConsole::MessageError(const wchar_t *message)) { MT_LOCK - RINOK(CheckBreak2()); + RINOK(CheckBreak2()) NumFileErrors_in_Current++; NumFileErrors++; @@ -460,7 +460,7 @@ } } -STDMETHODIMP CExtractCallbackConsole::SetOperationResult(Int32 opRes, Int32 encrypted) +Z7_COM7F_IMF(CExtractCallbackConsole::SetOperationResult(Int32 opRes, Int32 encrypted)) { MT_LOCK @@ -499,7 +499,7 @@ return CheckBreak2(); } -STDMETHODIMP CExtractCallbackConsole::ReportExtractResult(Int32 opRes, Int32 encrypted, const wchar_t *name) +Z7_COM7F_IMF(CExtractCallbackConsole::ReportExtractResult(Int32 opRes, Int32 encrypted, const wchar_t *name)) { if (opRes != NArchive::NExtract::NOperationResult::kOK) { @@ -512,7 +512,7 @@ -#ifndef _NO_CRYPTO +#ifndef Z7_NO_CRYPTO HRESULT CExtractCallbackConsole::SetPassword(const UString &password) { @@ -521,7 +521,7 @@ return S_OK; } -STDMETHODIMP CExtractCallbackConsole::CryptoGetTextPassword(BSTR *password) +Z7_COM7F_IMF(CExtractCallbackConsole::CryptoGetTextPassword(BSTR *password)) { COM_TRY_BEGIN MT_LOCK @@ -533,7 +533,7 @@ HRESULT CExtractCallbackConsole::BeforeOpen(const wchar_t *name, bool testMode) { - RINOK(CheckBreak2()); + RINOK(CheckBreak2()) NumTryArcs++; ThereIsError_in_Current = false; @@ -560,7 +560,7 @@ { AString s; - for (unsigned i = 0; i < ARRAY_SIZE(k_ErrorFlagsMessages); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_ErrorFlagsMessages); i++) { UInt32 f = (1 << i); if ((errorFlags & f) == 0) @@ -739,7 +739,7 @@ { if (_so) { - RINOK(Print_OpenArchive_Props(*_so, codecs, arcLink)); + RINOK(Print_OpenArchive_Props(*_so, codecs, arcLink)) *_so << endl; } } @@ -753,8 +753,8 @@ *_se << kError; _se->NormalizePrint_wstr(name); *_se << endl; - HRESULT res = Print_OpenArchive_Error(*_se, codecs, arcLink); - RINOK(res); + const HRESULT res = Print_OpenArchive_Error(*_se, codecs, arcLink); + RINOK(res) if (result == S_FALSE) { } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/ExtractCallbackConsole.h 7zip-23.01+dfsg/CPP/7zip/UI/Console/ExtractCallbackConsole.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/ExtractCallbackConsole.h 2022-04-29 17:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/ExtractCallbackConsole.h 2023-04-03 07:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ExtractCallbackConsole.h -#ifndef __EXTRACT_CALLBACK_CONSOLE_H -#define __EXTRACT_CALLBACK_CONSOLE_H +#ifndef ZIP7_INC_EXTRACT_CALLBACK_CONSOLE_H +#define ZIP7_INC_EXTRACT_CALLBACK_CONSOLE_H #include "../../../Common/StdOutStream.h" @@ -34,8 +34,10 @@ }; */ -class CExtractScanConsole: public IDirItemsCallback +class CExtractScanConsole Z7_final: public IDirItemsCallback { + Z7_IFACE_IMP(IDirItemsCallback) + CStdOutStream *_so; CStdOutStream *_se; CPercentPrinter _percent; @@ -54,8 +56,6 @@ public: - virtual ~CExtractScanConsole() {} - void Init(CStdOutStream *outStream, CStdOutStream *errorStream, CStdOutStream *percentStream) { _so = outStream; @@ -67,8 +67,6 @@ void StartScanning(); - INTERFACE_IDirItemsCallback(;) - void CloseScanning() { if (NeedPercents()) @@ -81,16 +79,36 @@ -class CExtractCallbackConsole: +class CExtractCallbackConsole Z7_final: + public IFolderArchiveExtractCallback, public IExtractCallbackUI, // public IArchiveExtractCallbackMessage, public IFolderArchiveExtractCallback2, - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO public ICryptoGetTextPassword, - #endif + #endif public COpenCallbackConsole, public CMyUnknownImp { + Z7_COM_QI_BEGIN2(IFolderArchiveExtractCallback) + // Z7_COM_QI_ENTRY(IArchiveExtractCallbackMessage) + Z7_COM_QI_ENTRY(IFolderArchiveExtractCallback2) + #ifndef Z7_NO_CRYPTO + Z7_COM_QI_ENTRY(ICryptoGetTextPassword) + #endif + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(IProgress) + Z7_IFACE_COM7_IMP(IFolderArchiveExtractCallback) + Z7_IFACE_IMP(IExtractCallbackUI) + // Z7_IFACE_COM7_IMP(IArchiveExtractCallbackMessage) + Z7_IFACE_COM7_IMP(IFolderArchiveExtractCallback2) + #ifndef Z7_NO_CRYPTO + Z7_IFACE_COM7_IMP(ICryptoGetTextPassword) + #endif + + AString _tempA; UString _tempU; @@ -109,32 +127,7 @@ if (_so) _so->Flush(); } - public: - MY_QUERYINTERFACE_BEGIN2(IFolderArchiveExtractCallback) - // MY_QUERYINTERFACE_ENTRY(IArchiveExtractCallbackMessage) - MY_QUERYINTERFACE_ENTRY(IFolderArchiveExtractCallback2) - #ifndef _NO_CRYPTO - MY_QUERYINTERFACE_ENTRY(ICryptoGetTextPassword) - #endif - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - STDMETHOD(SetTotal)(UInt64 total); - STDMETHOD(SetCompleted)(const UInt64 *completeValue); - - INTERFACE_IFolderArchiveExtractCallback(;) - - INTERFACE_IExtractCallbackUI(;) - // INTERFACE_IArchiveExtractCallbackMessage(;) - INTERFACE_IFolderArchiveExtractCallback2(;) - - #ifndef _NO_CRYPTO - - STDMETHOD(CryptoGetTextPassword)(BSTR *password); - - #endif - UInt64 NumTryArcs; bool ThereIsError_in_Current; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/HashCon.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Console/HashCon.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/HashCon.cpp 2021-12-16 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/HashCon.cpp 2022-12-18 19:00:00.000000000 +0000 @@ -99,7 +99,7 @@ static void AddMinuses(AString &s, unsigned num) { for (unsigned i = 0; i < num; i++) - s += '-'; + s.Add_Minus(); } static void AddSpaces_if_Positive(AString &s, int num) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/HashCon.h 7zip-23.01+dfsg/CPP/7zip/UI/Console/HashCon.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/HashCon.h 2021-10-24 13:58:18.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/HashCon.h 2023-04-03 07:00:00.000000000 +0000 @@ -1,14 +1,19 @@ // HashCon.h -#ifndef __HASH_CON_H -#define __HASH_CON_H +#ifndef ZIP7_INC_HASH_CON_H +#define ZIP7_INC_HASH_CON_H #include "../Common/HashCalc.h" #include "UpdateCallbackConsole.h" -class CHashCallbackConsole: public IHashCallbackUI, public CCallbackConsoleBase +class CHashCallbackConsole Z7_final: + public IHashCallbackUI, + public CCallbackConsoleBase { + Z7_IFACE_IMP(IDirItemsCallback) + Z7_IFACE_IMP(IHashCallbackUI) + UString _fileName; AString _s; @@ -33,9 +38,7 @@ public: bool PrintNameInPercents; - bool PrintHeaders; - // bool PrintSize; // bool PrintNewLine; // set it too (false), if you need only hash for single file without LF char. AString PrintFields; @@ -48,10 +51,6 @@ // , PrintSize(true), // , PrintNewLine(true) {} - - virtual ~CHashCallbackConsole() {} - - INTERFACE_IHashCallbackUI(;) }; void PrintHashStat(CStdOutStream &so, const CHashBundle &hb); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/List.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Console/List.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/List.cpp 2022-05-18 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/List.cpp 2023-03-06 16:00:00.000000000 +0000 @@ -131,6 +131,8 @@ , "Group ID" , "Device Major" , "Device Minor" + , "Dev Major" + , "Dev Minor" }; static const char kEmptyAttribChar = '.'; @@ -405,13 +407,13 @@ for (k = 0; k < fii.PrefixSpacesWidth; k++) LinesString.Add_Space(); for (k = 0; k < fii.Width; k++) - LinesString += '-'; + LinesString.Add_Minus(); } } static void GetPropName(PROPID propID, const wchar_t *name, AString &nameA, UString &nameU) { - if (propID < ARRAY_SIZE(kPropIdToName)) + if (propID < Z7_ARRAY_SIZE(kPropIdToName)) { nameA = kPropIdToName[propID]; return; @@ -455,13 +457,13 @@ HRESULT CFieldPrinter::AddMainProps(IInArchive *archive) { UInt32 numProps; - RINOK(archive->GetNumberOfProperties(&numProps)); + RINOK(archive->GetNumberOfProperties(&numProps)) for (UInt32 i = 0; i < numProps; i++) { CMyComBSTR name; PROPID propID; VARTYPE vt; - RINOK(archive->GetPropertyInfo(i, &name, &propID, &vt)); + RINOK(archive->GetPropertyInfo(i, &name, &propID, &vt)) AddProp(name, propID, false); } return S_OK; @@ -470,12 +472,12 @@ HRESULT CFieldPrinter::AddRawProps(IArchiveGetRawProps *getRawProps) { UInt32 numProps; - RINOK(getRawProps->GetNumRawProps(&numProps)); + RINOK(getRawProps->GetNumRawProps(&numProps)) for (UInt32 i = 0; i < numProps; i++) { CMyComBSTR name; PROPID propID; - RINOK(getRawProps->GetRawPropInfo(i, &name, &propID)); + RINOK(getRawProps->GetRawPropInfo(i, &name, &propID)) AddProp(name, propID, true); } return S_OK; @@ -516,7 +518,7 @@ ConvertUtcFileTimeToString2(t.FT, t.Ns100, dest, prec); } -#ifndef _SFX +#ifndef Z7_SFX static inline char GetHex(Byte value) { @@ -585,12 +587,12 @@ if (f.IsRawProp) { - #ifndef _SFX + #ifndef Z7_SFX const void *data; UInt32 dataSize; UInt32 propType; - RINOK(Arc->GetRawProps->GetRawProp(index, f.PropID, &data, &dataSize, &propType)); + RINOK(Arc->GetRawProps->GetRawProp(index, f.PropID, &data, &dataSize, &propType)) if (dataSize != 0) { @@ -600,7 +602,7 @@ { if (propType != NPropDataType::kRaw) return E_FAIL; - #ifndef _SFX + #ifndef Z7_SFX ConvertNtSecureToString((const Byte *)data, dataSize, TempAString); g_StdOut << TempAString; needPrint = false; @@ -654,7 +656,7 @@ break; } default: - RINOK(Arc->Archive->GetProperty(index, f.PropID, &prop)); + RINOK(Arc->Archive->GetProperty(index, f.PropID, &prop)) } if (f.PropID == kpidAttrib && (prop.vt == VT_EMPTY || prop.vt == VT_UI4)) { @@ -786,7 +788,7 @@ value.Val = 0; value.Def = false; CPropVariant prop; - RINOK(archive->GetProperty(index, propID, &prop)); + RINOK(archive->GetProperty(index, propID, &prop)) value.Def = ConvertPropVariantToUInt64(prop, value.Val); return S_OK; } @@ -798,7 +800,7 @@ t.Clear(); // t.Def = false; CPropVariant prop; - RINOK(archive->GetProperty(index, kpidMTime, &prop)); + RINOK(archive->GetProperty(index, kpidMTime, &prop)) if (prop.vt == VT_FILETIME) t.Set_From_Prop(prop); else if (prop.vt != VT_EMPTY) @@ -815,7 +817,7 @@ { const char *s; char temp[16]; - if (propID < ARRAY_SIZE(kPropIdToName)) + if (propID < Z7_ARRAY_SIZE(kPropIdToName)) s = kPropIdToName[propID]; else { @@ -868,7 +870,7 @@ so << "{"; so << endl; UString_Replace_CRLF_to_LF(s); - so.Normalize_UString__LF_Allowed(s); + so.Normalize_UString_LF_Allowed(s); so << s; so << endl; so << "}"; @@ -919,7 +921,7 @@ static HRESULT PrintArcProp(CStdOutStream &so, IInArchive *archive, PROPID propID, const wchar_t *name) { CPropVariant prop; - RINOK(archive->GetArchiveProperty(propID, &prop)); + RINOK(archive->GetArchiveProperty(propID, &prop)) PrintPropertyPair2(so, propID, name, prop); return S_OK; } @@ -973,20 +975,20 @@ if (offset != 0) PrintPropNameAndNumber_Signed(so, kpidOffset, offset); IInArchive *archive = arc.Archive; - RINOK(PrintArcProp(so, archive, kpidPhySize, NULL)); + RINOK(PrintArcProp(so, archive, kpidPhySize, NULL)) if (er.TailSize != 0) PrintPropNameAndNumber(so, kpidTailSize, er.TailSize); { UInt32 numProps; - RINOK(archive->GetNumberOfArchiveProperties(&numProps)); + RINOK(archive->GetNumberOfArchiveProperties(&numProps)) for (UInt32 j = 0; j < numProps; j++) { CMyComBSTR name; PROPID propID; VARTYPE vt; - RINOK(archive->GetArchivePropertyInfo(j, &name, &propID, &vt)); - RINOK(PrintArcProp(so, archive, propID, name)); + RINOK(archive->GetArchivePropertyInfo(j, &name, &propID, &vt)) + RINOK(PrintArcProp(so, archive, propID, name)) } } @@ -1002,9 +1004,9 @@ CMyComBSTR name; PROPID propID; VARTYPE vt; - RINOK(archive->GetPropertyInfo(j, &name, &propID, &vt)); + RINOK(archive->GetPropertyInfo(j, &name, &propID, &vt)) CPropVariant prop; - RINOK(archive->GetProperty(mainIndex, propID, &prop)); + RINOK(archive->GetProperty(mainIndex, propID, &prop)) PrintPropertyPair2(so, propID, name, prop); } } @@ -1016,7 +1018,7 @@ HRESULT Print_OpenArchive_Error(CStdOutStream &so, const CCodecs *codecs, const CArchiveLink &arcLink); HRESULT Print_OpenArchive_Error(CStdOutStream &so, const CCodecs *codecs, const CArchiveLink &arcLink) { - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO if (arcLink.PasswordWasAsked) so << "Cannot open encrypted archive. Wrong password?"; else @@ -1051,10 +1053,10 @@ bool processAltStreams, bool showAltStreams, const NWildcard::CCensorNode &wildcardCensor, bool enableHeaders, bool techMode, - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO bool &passwordEnabled, UString &password, #endif - #ifndef _SFX + #ifndef Z7_SFX const CObjectVector *props, #endif UInt64 &numErrors, @@ -1067,7 +1069,7 @@ CFieldPrinter fp; if (!techMode) - fp.Init(kStandardFieldTable, ARRAY_SIZE(kStandardFieldTable)); + fp.Init(kStandardFieldTable, Z7_ARRAY_SIZE(kStandardFieldTable)); CListStat2 stat2total; @@ -1128,7 +1130,7 @@ COpenCallbackConsole openCallback; openCallback.Init(&g_StdOut, g_ErrStream, NULL); - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO openCallback.PasswordIsDefined = passwordEnabled; openCallback.Password = password; @@ -1142,7 +1144,7 @@ */ COpenOptions options; - #ifndef _SFX + #ifndef Z7_SFX options.props = props; #endif options.codecs = codecs; @@ -1229,7 +1231,7 @@ if (enableHeaders) { - RINOK(Print_OpenArchive_Props(g_StdOut, codecs, arcLink)); + RINOK(Print_OpenArchive_Props(g_StdOut, codecs, arcLink)) g_StdOut << endl; if (techMode) @@ -1251,17 +1253,17 @@ if (techMode) { fp.Clear(); - RINOK(fp.AddMainProps(archive)); + RINOK(fp.AddMainProps(archive)) if (arc.GetRawProps) { - RINOK(fp.AddRawProps(arc.GetRawProps)); + RINOK(fp.AddRawProps(arc.GetRawProps)) } } CListStat2 stat2; UInt32 numItems; - RINOK(archive->GetNumberOfItems(&numItems)); + RINOK(archive->GetNumberOfItems(&numItems)) CReadArcItem item; UStringVector pathParts; @@ -1275,12 +1277,12 @@ if (stdInMode && res == E_INVALIDARG) break; - RINOK(res); + RINOK(res) if (arc.Ask_Aux) { bool isAux; - RINOK(Archive_IsItem_Aux(archive, i, isAux)); + RINOK(Archive_IsItem_Aux(archive, i, isAux)) if (isAux) continue; } @@ -1288,12 +1290,12 @@ bool isAltStream = false; if (arc.Ask_AltStream) { - RINOK(Archive_IsItem_AltStream(archive, i, isAltStream)); + RINOK(Archive_IsItem_AltStream(archive, i, isAltStream)) if (isAltStream && !processAltStreams) continue; } - RINOK(Archive_IsItem_Dir(archive, i, fp.IsDir)); + RINOK(Archive_IsItem_Dir(archive, i, fp.IsDir)) if (fp.IsDir ? listOptions.ExcludeDirItems : listOptions.ExcludeFileItems) continue; @@ -1302,7 +1304,7 @@ { if (isAltStream) { - RINOK(arc.GetItem(i, item)); + RINOK(arc.GetItem(i, item)) if (!CensorNode_CheckPath(wildcardCensor, item)) continue; } @@ -1319,9 +1321,9 @@ CListStat st; - RINOK(GetUInt64Value(archive, i, kpidSize, st.Size)); - RINOK(GetUInt64Value(archive, i, kpidPackSize, st.PackSize)); - RINOK(GetItemMTime(archive, i, st.MTime)); + RINOK(GetUInt64Value(archive, i, kpidSize, st.Size)) + RINOK(GetUInt64Value(archive, i, kpidPackSize, st.PackSize)) + RINOK(GetItemMTime(archive, i, st.MTime)) if (fp.IsDir) stat2.NumDirs++; @@ -1331,7 +1333,7 @@ if (isAltStream && !showAltStreams) continue; - RINOK(fp.PrintItemInfo(i, st)); + RINOK(fp.PrintItemInfo(i, st)) } UInt64 numStreams = stat2.GetNumStreams(); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/List.h 7zip-23.01+dfsg/CPP/7zip/UI/Console/List.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/List.h 2021-09-27 12:59:28.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/List.h 2023-01-29 16:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // List.h -#ifndef __LIST_H -#define __LIST_H +#ifndef ZIP7_INC_LIST_H +#define ZIP7_INC_LIST_H #include "../../../Common/Wildcard.h" @@ -28,10 +28,10 @@ bool processAltStreams, bool showAltStreams, const NWildcard::CCensorNode &wildcardCensor, bool enableHeaders, bool techMode, - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO bool &passwordEnabled, UString &password, #endif - #ifndef _SFX + #ifndef Z7_SFX const CObjectVector *props, #endif UInt64 &errors, diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/MainAr.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Console/MainAr.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/MainAr.cpp 2021-02-09 19:48:29.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/MainAr.cpp 2023-04-01 19:00:00.000000000 +0000 @@ -5,6 +5,7 @@ #ifdef _WIN32 #include "../../../../C/DllSecur.h" #endif +#include "../../../../C/CpuArch.h" #include "../../../Common/MyException.h" #include "../../../Common/StdOutStream.h" @@ -56,7 +57,44 @@ #define NT_CHECK_FAIL_ACTION *g_StdStream << "Unsupported Windows version"; return NExitCode::kFatalError; #endif -int MY_CDECL main +static inline bool CheckIsa() +{ + // __try + { + #if defined(__AVX2__) + if (!CPU_IsSupported_AVX2()) + return false; + #elif defined(__AVX__) + if (!CPU_IsSupported_AVX()) + return false; + #elif defined(__SSE2__) && !defined(MY_CPU_AMD64) || defined(_M_IX86_FP) && (_M_IX86_FP >= 2) + if (!CPU_IsSupported_SSE2()) + return false; + #elif defined(__SSE__) && !defined(MY_CPU_AMD64) || defined(_M_IX86_FP) && (_M_IX86_FP >= 1) + if (!CPU_IsSupported_SSE() || + !CPU_IsSupported_CMOV()) + return false; + #endif + /* + __asm + { + _emit 0fH + _emit 038H + _emit 0cbH + _emit (0c0H + 0 * 8 + 0) + } + */ + return true; + } + /* + __except (EXCEPTION_EXECUTE_HANDLER) + { + return false; + } + */ +} + +int Z7_CDECL main ( #ifndef _WIN32 int numArgs, char *args[] @@ -66,6 +104,14 @@ g_ErrStream = &g_StdErr; g_StdStream = &g_StdOut; + // #if (defined(_MSC_VER) && defined(_M_IX86)) + if (!CheckIsa()) + { + PrintError("ERROR: processor doesn't support required ISA extension"); + return NExitCode::kFatalError; + } + // #endif + NT_CHECK NConsoleClose::CCtrlHandlerSetter ctrlHandlerSetter; @@ -119,7 +165,7 @@ } return (NExitCode::kFatalError); } - catch(NExitCode::EEnum &exitCode) + catch(NExitCode::EEnum exitCode) { FlushStreams(); if (g_ErrStream) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/Main.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Console/Main.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/Main.cpp 2022-04-29 18:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/Main.cpp 2023-04-07 18:00:00.000000000 +0000 @@ -5,13 +5,39 @@ #include "../../../Common/MyWindows.h" #ifdef _WIN32 -#include + +#ifndef Z7_OLD_WIN_SDK + +#if defined(__MINGW32__) || defined(__MINGW64__) +#include #else +#include +#endif + +#else // Z7_OLD_WIN_SDK + +typedef struct _PROCESS_MEMORY_COUNTERS { + DWORD cb; + DWORD PageFaultCount; + SIZE_T PeakWorkingSetSize; + SIZE_T WorkingSetSize; + SIZE_T QuotaPeakPagedPoolUsage; + SIZE_T QuotaPagedPoolUsage; + SIZE_T QuotaPeakNonPagedPoolUsage; + SIZE_T QuotaNonPagedPoolUsage; + SIZE_T PagefileUsage; + SIZE_T PeakPagefileUsage; +} PROCESS_MEMORY_COUNTERS; +typedef PROCESS_MEMORY_COUNTERS *PPROCESS_MEMORY_COUNTERS; + +#endif // Z7_OLD_WIN_SDK + +#else // _WIN32 #include #include #include #include -#endif +#endif // _WIN32 #include "../../../../C/CpuArch.h" @@ -28,13 +54,14 @@ #include "../../../Windows/ErrorMsg.h" #include "../../../Windows/TimeUtils.h" +#include "../../../Windows/FileDir.h" #include "../Common/ArchiveCommandLine.h" #include "../Common/Bench.h" #include "../Common/ExitCode.h" #include "../Common/Extract.h" -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS #include "../Common/LoadCodecs.h" #endif @@ -48,7 +75,7 @@ #include "OpenCallbackConsole.h" #include "UpdateCallbackConsole.h" -#ifdef PROG_VARIANT_R +#ifdef Z7_PROG_VARIANT_R #include "../../../../C/7zVersion.h" #else #include "../../MyVersion.h" @@ -59,7 +86,9 @@ using namespace NCommandLineParser; #ifdef _WIN32 -HINSTANCE g_hInstance = 0; +extern +HINSTANCE g_hInstance; +HINSTANCE g_hInstance = NULL; #endif extern CStdOutStream *g_StdStream; @@ -71,19 +100,21 @@ extern unsigned g_NumHashers; extern const CHasherInfo *g_Hashers[]; -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS +extern +const CExternalCodecs *g_ExternalCodecs_Ptr; const CExternalCodecs *g_ExternalCodecs_Ptr; #endif DECLARE_AND_SET_CLIENT_VERSION_VAR -#if defined(PROG_VARIANT_Z) +#if defined(Z7_PROG_VARIANT_Z) #define PROG_POSTFIX "z" #define PROG_POSTFIX_2 " (z)" -#elif defined(PROG_VARIANT_R) +#elif defined(Z7_PROG_VARIANT_R) #define PROG_POSTFIX "r" #define PROG_POSTFIX_2 " (r)" -#elif !defined(EXTERNAL_CODECS) +#elif !defined(Z7_EXTERNAL_CODECS) #define PROG_POSTFIX "a" #define PROG_POSTFIX_2 " (a)" #else @@ -130,12 +161,12 @@ " -mmt[N] : set number of CPU threads\n" " -mx[N] : set compression level: -mx1 (fastest) ... -mx9 (ultra)\n" " -o{Directory} : set Output directory\n" - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO " -p{Password} : set Password\n" #endif " -r[-|0] : Recurse subdirectories for name search\n" " -sa{a|e|s} : set Archive name mode\n" - " -scc{UTF-8|WIN|DOS} : set charset for for console input/output\n" + " -scc{UTF-8|WIN|DOS} : set charset for console input/output\n" " -scs{UTF-8|UTF-16LE|UTF-16BE|WIN|DOS|{id}} : set charset for list files\n" " -scrc[CRC32|CRC64|SHA1|SHA256|*] : set hash function for x, e, h commands\n" " -sdel : delete files after compression\n" @@ -151,7 +182,7 @@ " -so : write data to stdout\n" " -spd : disable wildcard matching for file names\n" " -spe : eliminate duplication of root folder for extract command\n" - " -spf : use fully qualified file paths\n" + " -spf[2] : use fully qualified file paths\n" " -ssc[-] : set sensitive case mode\n" " -sse : stop archive creating, if it can't open some input file\n" " -ssp : do not change Last Access Time of source files while archiving\n" @@ -177,7 +208,7 @@ #define kDefaultSfxModule "7zCon.sfx" -MY_ATTR_NORETURN +Z7_ATTR_NORETURN static void ShowMessageAndThrowException(LPCSTR message, NExitCode::EEnum code) { if (g_ErrStream) @@ -247,9 +278,17 @@ { const UInt32 numCpus = NWindows::NSystem::GetNumberOfProcessors(); *so << " Threads:" << numCpus; + const UInt64 openMAX= NWindows::NSystem::Get_File_OPEN_MAX(); + *so << " OPEN_MAX:" << openMAX; + { + FString temp; + NDir::MyGetTempPath(temp); + if (!temp.IsEqualTo(STRING_PATH_SEPARATOR "tmp" STRING_PATH_SEPARATOR)) + *so << " temp_path:" << temp; + } } - #ifdef _7ZIP_ASM + #ifdef Z7_7ZIP_ASM *so << ", ASM"; #endif @@ -313,6 +352,17 @@ PrintStringRight(so, s, size); } +#ifdef Z7_EXTERNAL_CODECS +static void PrintNumber(CStdOutStream &so, UInt32 val, unsigned numDigits) +{ + AString s; + s.Add_UInt32(val); + while (s.Len() < numDigits) + s.InsertAtFront('0'); + so << s; +} +#endif + static void PrintLibIndex(CStdOutStream &so, int libIndex) { if (libIndex >= 0) @@ -480,8 +530,12 @@ *g_StdStream << " " << s << " Memory ="; PrintNum(SHIFT_SIZE_VALUE(val, 20), 7); *g_StdStream << " MB"; - - #ifdef _7ZIP_LARGE_PAGES + /* + *g_StdStream << " ="; + PrintNum(SHIFT_SIZE_VALUE(val, 10), 9); + *g_StdStream << " KB"; + */ + #ifdef Z7_LARGE_PAGES AString lp; Add_LargePages_String(lp); if (!lp.IsEmpty()) @@ -530,22 +584,27 @@ The program with K32GetProcessMemoryInfo will not work on systems before Win7 // memDefined = GetProcessMemoryInfo(GetCurrentProcess(), &m, sizeof(m)); */ - - HMODULE kern = ::GetModuleHandleW(L"kernel32.dll"); - Func_GetProcessMemoryInfo my_GetProcessMemoryInfo = (Func_GetProcessMemoryInfo) - (void *)::GetProcAddress(kern, "K32GetProcessMemoryInfo"); + const HMODULE kern = ::GetModuleHandleW(L"kernel32.dll"); + Func_GetProcessMemoryInfo + my_GetProcessMemoryInfo = Z7_GET_PROC_ADDRESS( + Func_GetProcessMemoryInfo, kern, + "K32GetProcessMemoryInfo"); if (!my_GetProcessMemoryInfo) { - HMODULE lib = LoadLibraryW(L"Psapi.dll"); + const HMODULE lib = LoadLibraryW(L"Psapi.dll"); if (lib) - my_GetProcessMemoryInfo = (Func_GetProcessMemoryInfo)(void *)::GetProcAddress(lib, "GetProcessMemoryInfo"); + my_GetProcessMemoryInfo = Z7_GET_PROC_ADDRESS( + Func_GetProcessMemoryInfo, lib, + "GetProcessMemoryInfo"); } if (my_GetProcessMemoryInfo) memDefined = my_GetProcessMemoryInfo(GetCurrentProcess(), &m, sizeof(m)); // FreeLibrary(lib); - - Func_QueryProcessCycleTime my_QueryProcessCycleTime = (Func_QueryProcessCycleTime) - (void *)::GetProcAddress(kern, "QueryProcessCycleTime"); + const + Func_QueryProcessCycleTime + my_QueryProcessCycleTime = Z7_GET_PROC_ADDRESS( + Func_QueryProcessCycleTime, kern, + "QueryProcessCycleTime"); if (my_QueryProcessCycleTime) cycleDefined = my_QueryProcessCycleTime(GetCurrentProcess(), &cycleTime); } @@ -595,6 +654,7 @@ #ifndef UNDER_CE if (memDefined) PrintMemUsage("Physical", m.PeakWorkingSetSize); #endif + *g_StdStream << endl; } @@ -603,7 +663,7 @@ static UInt64 Get_timeofday_us() { struct timeval now; - if (gettimeofday(&now, 0 ) == 0) + if (gettimeofday(&now, NULL) == 0) return (UInt64)now.tv_sec * 1000000 + (UInt64)now.tv_usec; return 0; } @@ -666,7 +726,7 @@ *g_StdStream << '%'; } -static void PrintStat(UInt64 startTime) +static void PrintStat(const UInt64 startTime) { tms t; /* clock_t res = */ times(&t); @@ -722,9 +782,23 @@ #endif #ifndef _WIN32 - UInt64 startTime = Get_timeofday_us(); + const UInt64 startTime = Get_timeofday_us(); #endif + /* + { + g_StdOut << "DWORD:" << (unsigned)sizeof(DWORD); + g_StdOut << " LONG:" << (unsigned)sizeof(LONG); + g_StdOut << " long:" << (unsigned)sizeof(long); + #ifdef _WIN64 + // g_StdOut << " long long:" << (unsigned)sizeof(long long); + #endif + g_StdOut << " int:" << (unsigned)sizeof(int); + g_StdOut << " void*:" << (unsigned)sizeof(void *); + g_StdOut << endl; + } + */ + UStringVector commandStrings; #ifdef _WIN32 @@ -778,7 +852,7 @@ CStdOutStream *percentsStream = NULL; if (options.Number_for_Percents != k_OutStream_disabled) - percentsStream = (options.Number_for_Percents == k_OutStream_stderr) ? &g_StdErr : &g_StdOut;; + percentsStream = (options.Number_for_Percents == k_OutStream_stderr) ? &g_StdErr : &g_StdOut; if (options.HelpMode) { @@ -866,9 +940,9 @@ ThrowException_if_Error(codecs->Load()); Codecs_AddHashArcHandler(codecs); - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS { - g_ExternalCodecs_Ptr = &__externalCodecs; + g_ExternalCodecs_Ptr = &_externalCodecs; UString s; codecs->GetCodecsErrorMessage(s); if (!s.IsEmpty()) @@ -886,7 +960,7 @@ || options.Command.CommandType == NCommandType::kList || options.Command.IsFromUpdateGroup())) { - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS if (!codecs->MainDll_ErrorPath.IsEmpty()) { UString s ("Can't load module: "); @@ -918,12 +992,12 @@ // excludedFormats.Sort(); } - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS if (isExtractGroupCommand || options.Command.IsFromUpdateGroup() || options.Command.CommandType == NCommandType::kHash || options.Command.CommandType == NCommandType::kBenchmark) - ThrowException_if_Error(__externalCodecs.Load()); + ThrowException_if_Error(_externalCodecs.Load()); #endif int retCode = NExitCode::kSuccess; @@ -943,12 +1017,16 @@ CStdOutStream &so = (g_StdStream ? *g_StdStream : g_StdOut); unsigned i; - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS so << endl << "Libs:" << endl; for (i = 0; i < codecs->Libs.Size(); i++) { PrintLibIndex(so, (int)i); - so << ' ' << codecs->Libs[i].Path << endl; + const CCodecLib &lib = codecs->Libs[i]; + // if (lib.Version != 0) + so << ": " << (lib.Version >> 16) << "."; + PrintNumber(so, lib.Version & 0xffff, 2); + so << " : " << lib.Path << endl; } #endif @@ -963,7 +1041,7 @@ { const CArcInfoEx &arc = codecs->Formats[i]; - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS PrintLibIndex(so, arc.LibIndex); #else so << " "; @@ -1063,10 +1141,10 @@ } - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS UInt32 numMethods; - if (codecs->GetNumMethods(&numMethods) == S_OK) + if (_externalCodecs.GetCodecs->GetNumMethods(&numMethods) == S_OK) for (UInt32 j = 0; j < numMethods; j++) { PrintLibIndex(so, codecs->GetCodec_LibIndex(j)); @@ -1110,9 +1188,9 @@ so << ' ' << codec.Name << endl; } - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS - numMethods = codecs->GetNumHashers(); + numMethods = _externalCodecs.GetHashers->GetNumHashers(); for (UInt32 j = 0; j < numMethods; j++) { PrintLibIndex(so, codecs->GetHasherLibIndex(j)); @@ -1198,7 +1276,7 @@ CExtractCallbackConsole *ecs = new CExtractCallbackConsole; CMyComPtr extractCallback = ecs; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO ecs->PasswordIsDefined = options.PasswordEnabled; ecs->Password = options.Password; #endif @@ -1216,7 +1294,7 @@ COpenCallbackConsole openCallback; openCallback.Init(g_StdStream, g_ErrStream); - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO openCallback.PasswordIsDefined = options.PasswordEnabled; openCallback.Password = options.Password; #endif @@ -1230,7 +1308,7 @@ eo.YesToAll = options.YesToAll; eo.TestMode = options.Command.IsTestCommand(); - #ifndef _SFX + #ifndef Z7_SFX eo.Properties = options.Properties; #endif @@ -1254,7 +1332,9 @@ ArchivePathsSorted, ArchivePathsFullSorted, options.Censor.Pairs.Front().Head, - eo, ecs, ecs, hashCalc, errorMessage, stat); + eo, + ecs, ecs, ecs, + hashCalc, errorMessage, stat); ecs->ClosePercents(); @@ -1379,7 +1459,7 @@ options.Censor.Pairs.Front().Head, options.EnableHeaders, options.TechMode, - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO options.PasswordEnabled, options.Password, #endif @@ -1408,7 +1488,7 @@ COpenCallbackConsole openCallback; openCallback.Init(g_StdStream, g_ErrStream, percentsStream); - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO bool passwordIsDefined = (options.PasswordEnabled && !options.Password.IsEmpty()); openCallback.PasswordIsDefined = passwordIsDefined; @@ -1422,7 +1502,7 @@ if (percentsStream) callback.SetWindowWidth(consoleWidth); - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO callback.PasswordIsDefined = passwordIsDefined; callback.AskPassword = (options.PasswordEnabled && options.Password.IsEmpty()); callback.Password = options.Password; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/makefile 7zip-23.01+dfsg/CPP/7zip/UI/Console/makefile --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/makefile 2021-10-07 18:27:16.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/makefile 2023-01-29 17:00:00.000000000 +0000 @@ -1,6 +1,6 @@ PROG = 7z.exe CFLAGS = $(CFLAGS) \ - -DEXTERNAL_CODECS \ + -DZ7_EXTERNAL_CODECS \ COMMON_OBJS = \ $O\CommandLineParser.obj \ @@ -42,6 +42,7 @@ $O\FilterCoder.obj \ $O\LimitedStreams.obj \ $O\MethodProps.obj \ + $O\MultiOutStream.obj \ $O\ProgressUtils.obj \ $O\PropId.obj \ $O\StreamObjects.obj \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/makefile.gcc 7zip-23.01+dfsg/CPP/7zip/UI/Console/makefile.gcc --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/makefile.gcc 2022-07-14 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/makefile.gcc 2023-01-30 18:00:00.000000000 +0000 @@ -20,7 +20,7 @@ ifdef ST_MODE -LOCAL_FLAGS_ST = -D_7ZIP_ST +LOCAL_FLAGS_ST = -DZ7_ST ifdef IS_MINGW MT_OBJS = \ @@ -43,9 +43,9 @@ ifdef IS_MINGW LOCAL_FLAGS_WIN = \ - -D_7ZIP_LARGE_PAGES \ - -DWIN_LONG_PATH \ - -DSUPPORT_DEVICE_FILE \ + -DZ7_LARGE_PAGES \ + -DZ7_LONG_PATH \ + -DZ7_DEVICE_FILE \ SYS_OBJS = \ $O/FileSystem.o \ @@ -66,7 +66,7 @@ LOCAL_FLAGS = \ $(LOCAL_FLAGS_WIN) \ $(LOCAL_FLAGS_ST) \ - -DEXTERNAL_CODECS \ + -DZ7_EXTERNAL_CODECS \ @@ -147,6 +147,7 @@ $O/LimitedStreams.o \ $O/MethodId.o \ $O/MethodProps.o \ + $O/MultiOutStream.o \ $O/OffsetStream.o \ $O/OutBuffer.o \ $O/ProgressUtils.o \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/OpenCallbackConsole.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Console/OpenCallbackConsole.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/OpenCallbackConsole.cpp 2017-02-17 23:42:14.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/OpenCallbackConsole.cpp 2023-01-29 16:00:00.000000000 +0000 @@ -77,17 +77,17 @@ } -#ifndef _NO_CRYPTO +#ifndef Z7_NO_CRYPTO HRESULT COpenCallbackConsole::Open_CryptoGetTextPassword(BSTR *password) { *password = NULL; - RINOK(CheckBreak2()); + RINOK(CheckBreak2()) if (!PasswordIsDefined) { ClosePercents(); - RINOK(GetPassword_HRESULT(_so, Password)); + RINOK(GetPassword_HRESULT(_so, Password)) PasswordIsDefined = true; } return StringToBstr(Password, password); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/OpenCallbackConsole.h 7zip-23.01+dfsg/CPP/7zip/UI/Console/OpenCallbackConsole.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/OpenCallbackConsole.h 2019-08-24 11:15:53.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/OpenCallbackConsole.h 2023-04-01 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // OpenCallbackConsole.h -#ifndef __OPEN_CALLBACK_CONSOLE_H -#define __OPEN_CALLBACK_CONSOLE_H +#ifndef ZIP7_INC_OPEN_CALLBACK_CONSOLE_H +#define ZIP7_INC_OPEN_CALLBACK_CONSOLE_H #include "../../../Common/StdOutStream.h" @@ -17,10 +17,10 @@ CStdOutStream *_so; CStdOutStream *_se; - bool _totalFilesDefined; - // bool _totalBytesDefined; // UInt64 _totalFiles; UInt64 _totalBytes; + bool _totalFilesDefined; + // bool _totalBytesDefined; bool NeedPercents() const { return _percent._so != NULL; } @@ -35,12 +35,12 @@ } COpenCallbackConsole(): + _totalBytes(0), _totalFilesDefined(false), // _totalBytesDefined(false), - _totalBytes(0), MultiArcMode(false) - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO , PasswordIsDefined(false) // , PasswordWasAsked(false) #endif @@ -56,9 +56,9 @@ _percent._so = percentStream; } - INTERFACE_IOpenCallbackUI(;) + Z7_IFACE_IMP(IOpenCallbackUI) - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO bool PasswordIsDefined; // bool PasswordWasAsked; UString Password; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/PercentPrinter.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Console/PercentPrinter.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/PercentPrinter.cpp 2022-04-13 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/PercentPrinter.cpp 2022-12-15 09:00:00.000000000 +0000 @@ -79,7 +79,7 @@ while (size < kPercentsSize) { - _s += ' '; + _s.Add_Space(); size++; } @@ -125,8 +125,8 @@ char s[32]; ConvertUInt64ToString(Files, s); // unsigned size = (unsigned)strlen(s); - // for (; size < 3; size++) _s += ' '; - _s += ' '; + // for (; size < 3; size++) _s.Add_Space(); + _s.Add_Space(); _s += s; // _s += "f"; } @@ -134,13 +134,13 @@ if (!Command.IsEmpty()) { - _s += ' '; + _s.Add_Space(); _s += Command; } if (!FileName.IsEmpty() && _s.Len() < MaxLen) { - _s += ' '; + _s.Add_Space(); _tempU = FileName; _so->Normalize_UString(_tempU); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/PercentPrinter.h 7zip-23.01+dfsg/CPP/7zip/UI/Console/PercentPrinter.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/PercentPrinter.h 2014-12-20 13:23:15.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/PercentPrinter.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // PercentPrinter.h -#ifndef __PERCENT_PRINTER_H -#define __PERCENT_PRINTER_H +#ifndef ZIP7_INC_PERCENT_PRINTER_H +#define ZIP7_INC_PERCENT_PRINTER_H #include "../../../Common/StdOutStream.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/UI/Console/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/StdAfx.h 2014-04-25 10:55:08.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/UpdateCallbackConsole.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Console/UpdateCallbackConsole.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/UpdateCallbackConsole.cpp 2022-04-29 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/UpdateCallbackConsole.cpp 2023-04-01 19:00:00.000000000 +0000 @@ -7,7 +7,7 @@ #include "../../../Windows/ErrorMsg.h" #include "../../../Windows/FileName.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "../../../Windows/Synchronization.h" #endif @@ -19,7 +19,7 @@ using namespace NWindows; -#ifndef _7ZIP_ST +#ifndef Z7_ST static NSynchronization::CCriticalSection g_CriticalSection; #define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection); #else @@ -136,7 +136,7 @@ { if (_so) { - RINOK(Print_OpenArchive_Props(*_so, codecs, arcLink)); + RINOK(Print_OpenArchive_Props(*_so, codecs, arcLink)) *_so << endl; } } @@ -150,7 +150,7 @@ _se->NormalizePrint_wstr(name); *_se << endl; HRESULT res = Print_OpenArchive_Error(*_se, codecs, arcLink); - RINOK(res); + RINOK(res) _se->Flush(); } } @@ -333,6 +333,12 @@ s += "Archive size: "; PrintSize_bytes_Smart(s, st.OutArcFileSize); s.Add_LF(); + if (st.IsMultiVolMode) + { + s += "Volumes: "; + s.Add_UInt32(st.NumVolumes); + s.Add_LF(); + } *_so << endl; *_so << s; // *_so << endl; @@ -681,12 +687,12 @@ /* HRESULT CUpdateCallbackConsole::SetPassword(const UString & - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO password #endif ) { - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO PasswordIsDefined = true; Password = password; #endif @@ -700,7 +706,7 @@ *password = NULL; - #ifdef _NO_CRYPTO + #ifdef Z7_NO_CRYPTO *passwordIsDefined = false; return S_OK; @@ -711,7 +717,7 @@ { if (AskPassword) { - RINOK(GetPassword_HRESULT(_so, Password)); + RINOK(GetPassword_HRESULT(_so, Password)) PasswordIsDefined = true; } } @@ -729,7 +735,7 @@ *password = NULL; - #ifdef _NO_CRYPTO + #ifdef Z7_NO_CRYPTO return E_NOTIMPL; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/UpdateCallbackConsole.h 7zip-23.01+dfsg/CPP/7zip/UI/Console/UpdateCallbackConsole.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/UpdateCallbackConsole.h 2022-04-29 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/UpdateCallbackConsole.h 2023-04-01 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // UpdateCallbackConsole.h -#ifndef __UPDATE_CALLBACK_CONSOLE_H -#define __UPDATE_CALLBACK_CONSOLE_H +#ifndef ZIP7_INC_UPDATE_CALLBACK_CONSOLE_H +#define ZIP7_INC_UPDATE_CALLBACK_CONSOLE_H #include "../../../Common/StdOutStream.h" @@ -26,6 +26,7 @@ } }; + class CCallbackConsoleBase { protected: @@ -42,7 +43,7 @@ HRESULT ReadingFileError_Base(const FString &name, DWORD systemError); public: - bool NeedPercents() const { return _percent._so != NULL; }; + bool NeedPercents() const { return _percent._so != NULL; } bool StdOutMode; @@ -94,29 +95,32 @@ // void PrintPropInfo(UString &s, PROPID propID, const PROPVARIANT *value); }; -class CUpdateCallbackConsole: public IUpdateCallbackUI2, public CCallbackConsoleBase + +class CUpdateCallbackConsole Z7_final: + public IUpdateCallbackUI2, + public CCallbackConsoleBase { // void PrintPropPair(const char *name, const wchar_t *val); - + Z7_IFACE_IMP(IUpdateCallbackUI) + Z7_IFACE_IMP(IDirItemsCallback) + Z7_IFACE_IMP(IUpdateCallbackUI2) public: bool DeleteMessageWasShown; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO bool PasswordIsDefined; - UString Password; bool AskPassword; + UString Password; #endif CUpdateCallbackConsole(): DeleteMessageWasShown(false) - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO , PasswordIsDefined(false) , AskPassword(false) #endif {} - virtual ~CUpdateCallbackConsole() {} - /* void Init(CStdOutStream *outStream) { @@ -124,7 +128,6 @@ } */ // ~CUpdateCallbackConsole() { if (NeedPercents()) _percent.ClosePrint(); } - INTERFACE_IUpdateCallbackUI2(;) }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/UserInputUtils.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Console/UserInputUtils.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/UserInputUtils.cpp 2021-01-25 09:25:39.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/UserInputUtils.cpp 2023-03-25 16:00:00.000000000 +0000 @@ -73,19 +73,26 @@ #ifdef MY_DISABLE_ECHO - HANDLE console = GetStdHandle(STD_INPUT_HANDLE); + const HANDLE console = GetStdHandle(STD_INPUT_HANDLE); + + /* + GetStdHandle() returns + INVALID_HANDLE_VALUE: If the function fails. + NULL : If an application does not have associated standard handles, + such as a service running on an interactive desktop, + and has not redirected them. */ bool wasChanged = false; DWORD mode = 0; - if (console != INVALID_HANDLE_VALUE && console != 0) + if (console != INVALID_HANDLE_VALUE && console != NULL) if (GetConsoleMode(console, &mode)) wasChanged = (SetConsoleMode(console, mode & ~(DWORD)ENABLE_ECHO_INPUT) != 0); - bool res = g_StdIn.ScanUStringUntilNewLine(psw); + const bool res = g_StdIn.ScanUStringUntilNewLine(psw); if (wasChanged) SetConsoleMode(console, mode); #else - bool res = g_StdIn.ScanUStringUntilNewLine(psw); + const bool res = g_StdIn.ScanUStringUntilNewLine(psw); #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Console/UserInputUtils.h 7zip-23.01+dfsg/CPP/7zip/UI/Console/UserInputUtils.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Console/UserInputUtils.h 2017-02-17 23:43:48.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Console/UserInputUtils.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // UserInputUtils.h -#ifndef __USER_INPUT_UTILS_H -#define __USER_INPUT_UTILS_H +#ifndef ZIP7_INC_USER_INPUT_UTILS_H +#define ZIP7_INC_USER_INPUT_UTILS_H #include "../../../Common/StdOutStream.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/ContextMenu.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/ContextMenu.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/ContextMenu.cpp 2022-05-26 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/ContextMenu.cpp 2023-04-07 09:00:00.000000000 +0000 @@ -9,12 +9,12 @@ #include "../../../Windows/COM.h" #include "../../../Windows/DLL.h" #include "../../../Windows/FileDir.h" -#include "../../../Windows/FileFind.h" #include "../../../Windows/FileName.h" -#include "../../../Windows/MemoryGlobal.h" #include "../../../Windows/Menu.h" #include "../../../Windows/ProcessUtils.h" -#include "../../../Windows/Shell.h" + +// for IS_INTRESOURCE(): +#include "../../../Windows/Window.h" #include "../../PropID.h" @@ -24,11 +24,8 @@ #include "../Common/ZipRegistry.h" #include "../FileManager/FormatUtils.h" -#include "../FileManager/PropertyName.h" - -#ifdef LANG #include "../FileManager/LangUtils.h" -#endif +#include "../FileManager/PropertyName.h" #include "ContextMenu.h" #include "ContextMenuFlags.h" @@ -36,6 +33,7 @@ #include "resource.h" + // #define SHOW_DEBUG_CTX_MENU #ifdef SHOW_DEBUG_CTX_MENU @@ -56,50 +54,117 @@ extern HINSTANCE g_hInstance; #endif +#ifdef UNDER_CE + #define MY_IS_INTRESOURCE(_r) ((((ULONG_PTR)(_r)) >> 16) == 0) +#else + #define MY_IS_INTRESOURCE(_r) IS_INTRESOURCE(_r) +#endif + + #ifdef SHOW_DEBUG_CTX_MENU -void Print_Ptr(void *p, char *s) +static void PrintStringA(const char *name, LPCSTR ptr) { - char temp[64]; - ConvertUInt64ToHex((UInt64)(void *)p, temp); - AString s2; - s2 += temp; - s2.Add_Space(); - s2 += s; - OutputDebugStringA(s2); -} - -void Print_Number(UInt32 number, char *s) -{ - char temp[64]; - ConvertUInt64ToString(number, temp); - AString s2; - s2 += temp; - s2.Add_Space(); - s2 += s; - OutputDebugStringA(s2); -} - -#define ODS(sz) Print_Ptr(this, sz) -#define ODS_U(s) OutputDebugStringW(s); -// #define ODS(sz) -// #define ODS_U(s) + AString m; + m += name; + m += ": "; + char s[32]; + sprintf(s, "%p", (const void *)ptr); + m += s; + if (!MY_IS_INTRESOURCE(ptr)) + { + m += ": \""; + m += ptr; + m += "\""; + } + OutputDebugStringA(m); +} -#define ODS2(sz) Print_Ptr(this, sz) +#if !defined(UNDER_CE) +static void PrintStringW(const char *name, LPCWSTR ptr) +{ + UString m; + m += name; + m += ": "; + char s[32]; + sprintf(s, "%p", (const void *)ptr); + m += s; + if (!MY_IS_INTRESOURCE(ptr)) + { + m += ": \""; + m += ptr; + m += "\""; + } + OutputDebugStringW(m); +} +#endif + +static void Print_Ptr(const void *p, const char *s) +{ + char temp[32]; + sprintf(temp, "%p", (const void *)p); + AString m; + m += temp; + m.Add_Space(); + m += s; + OutputDebugStringA(m); +} + +static void Print_Number(UInt32 number, const char *s) +{ + AString m; + m.Add_UInt32(number); + m.Add_Space(); + m += s; + OutputDebugStringA(m); +} + +#define ODS(sz) { Print_Ptr(this, sz); } +#define ODS_U(s) { OutputDebugStringW(s); } +#define ODS_(op) { op; } +#define ODS_SPRF_s(x) { char s[256]; x; OutputDebugStringA(s); } #else -#define Print_Number(number, s) #define ODS(sz) #define ODS_U(s) -#define ODS2(sz) +#define ODS_(op) +#define ODS_SPRF_s(x) #endif +/* +DOCs: In Windows 7 and later, the number of items passed to + a verb is limited to 16 when a shortcut menu is queried. + The verb is then re-created and re-initialized with the full + selection when that verb is invoked. +win10 tests: + if (the number of selected file/dir objects > 16) + { + Explorer does the following actions: + - it creates ctx_menu_1 IContextMenu object + - it calls ctx_menu_1->Initialize() with list of only up to 16 items + - it calls ctx_menu_1->QueryContextMenu(menu_1) + - if (some menu command is pressed) + { + - it gets shown string from selected menu item : shown_menu_1_string + - it creates another ctx_menu_2 IContextMenu object + - it calls ctx_menu_2->Initialize() with list of all items + - it calls ctx_menu_2->QueryContextMenu(menu_2) + - if there is menu item with shown_menu_1_string string in menu_2, + Explorer calls ctx_menu_2->InvokeCommand() for that item. + Explorer probably doesn't use VERB from first object ctx_menu_1. + So we must provide same shown menu strings for both objects: + ctx_menu_1 and ctx_menu_2. + } + } +*/ + CZipContextMenu::CZipContextMenu(): - _isMenuForFM(false), + _isMenuForFM(true), + _fileNames_WereReduced(true), _dropMode(false), _bitmap(NULL), _writeZone((UInt32)(Int32)-1), @@ -107,87 +172,81 @@ IsRoot(true), CurrentSubCommand(0) { - ODS("-- CZipContextMenu()"); - + ODS("== CZipContextMenu()"); InterlockedIncrement(&g_DllRefCount); - _bitmap = ::LoadBitmap(g_hInstance, MAKEINTRESOURCE(IDB_MENU_LOGO)); } CZipContextMenu::~CZipContextMenu() { ODS("== ~CZipContextMenu"); - if (_bitmap != NULL) + if (_bitmap) DeleteObject(_bitmap); InterlockedDecrement(&g_DllRefCount); } -HRESULT CZipContextMenu::GetFileNames(LPDATAOBJECT dataObject, UStringVector &fileNames) -{ - fileNames.Clear(); - if (!dataObject) - return E_INVALIDARG; - - #ifndef UNDER_CE - - FORMATETC fmte = {CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL}; - NCOM::CStgMedium stgMedium; - HRESULT result = dataObject->GetData(&fmte, &stgMedium); - if (result != S_OK) - return result; - stgMedium._mustBeReleased = true; - - NShell::CDrop drop(false); - NMemory::CGlobalLock globalLock(stgMedium->hGlobal); - drop.Attach((HDROP)globalLock.GetPointer()); - drop.QueryFileNames(fileNames); - - #endif - - return S_OK; -} - // IShellExtInit -STDMETHODIMP CZipContextMenu::Initialize(LPCITEMIDLIST pidlFolder, LPDATAOBJECT dataObject, HKEY /* hkeyProgID */) +/* +IShellExtInit::Initialize() + pidlFolder: + - for property sheet extension: + NULL + - for shortcut menu extensions: + pidl of folder that contains the item whose shortcut menu is being displayed: + - for nondefault drag-and-drop menu extensions: + pidl of target folder: for nondefault drag-and-drop menu extensions + pidlFolder == NULL in (win10): for context menu +*/ + +Z7_COMWF_B CZipContextMenu::Initialize(LPCITEMIDLIST pidlFolder, LPDATAOBJECT dataObject, HKEY /* hkeyProgID */) { - // OutputDebugString(TEXT("::Initialize\r\n")); + COM_TRY_BEGIN + ODS("==== CZipContextMenu::Initialize START") + _isMenuForFM = false; + _fileNames_WereReduced = true; _dropMode = false; + _attribs.Clear(); + _fileNames.Clear(); _dropPath.Empty(); - if (pidlFolder != 0) + + if (pidlFolder) { - #ifndef UNDER_CE + ODS("==== CZipContextMenu::Initialize (pidlFolder != 0)") + #ifndef UNDER_CE if (NShell::GetPathFromIDList(pidlFolder, _dropPath)) { - // OutputDebugString(path); - // OutputDebugString(TEXT("\r\n")); + ODS("==== CZipContextMenu::Initialize path from (pidl):") + ODS_U(_dropPath); + /* win10 : path with "\\\\?\\\" prefix is returned by GetPathFromIDList, if path is long + we can remove super prefix here. But probably prefix + is not problem for following 7-zip code. + so we don't remove super prefix */ + NFile::NName::If_IsSuperPath_RemoveSuperPrefix(_dropPath); NName::NormalizeDirPathPrefix(_dropPath); _dropMode = !_dropPath.IsEmpty(); } else - #endif + #endif _dropPath.Empty(); } - /* - m_IsFolder = false; - if (pidlFolder == 0) - */ - // pidlFolder is NULL :( - return GetFileNames(dataObject, _fileNames); -} + if (!dataObject) + return E_INVALIDARG; + + #ifndef UNDER_CE + + RINOK(NShell::DataObject_GetData_HDROP_or_IDLIST_Names(dataObject, _fileNames)) + // for (unsigned y = 0; y < 10000; y++) + if (NShell::DataObject_GetData_FILE_ATTRS(dataObject, _attribs) != S_OK) + _attribs.Clear(); + + #endif + + ODS_SPRF_s(sprintf(s, "==== CZipContextMenu::Initialize END _files=%d", + _fileNames.Size())) -HRESULT CZipContextMenu::InitContextMenu(const wchar_t * /* folder */, const wchar_t * const *names, unsigned numFiles) -{ - _isMenuForFM = true; - _fileNames.Clear(); - for (UInt32 i = 0; i < numFiles; i++) - { - // MessageBoxW(0, names[i], NULL, 0); - // OutputDebugStringW(names[i]); - _fileNames.Add(names[i]); - } - _dropMode = false; return S_OK; + COM_TRY_END } @@ -202,7 +261,7 @@ struct CContextMenuCommand { UInt32 flag; - CZipContextMenu::ECommandInternalID CommandInternalID; + CZipContextMenu::enum_CommandInternalID CommandInternalID; LPCSTR Verb; UINT ResourceID; }; @@ -227,7 +286,7 @@ struct CHashCommand { - CZipContextMenu::ECommandInternalID CommandInternalID; + CZipContextMenu::enum_CommandInternalID CommandInternalID; LPCSTR UserName; LPCSTR MethodName; }; @@ -244,19 +303,19 @@ }; -static int FindCommand(CZipContextMenu::ECommandInternalID &id) +static int FindCommand(CZipContextMenu::enum_CommandInternalID &id) { - for (unsigned i = 0; i < ARRAY_SIZE(g_Commands); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Commands); i++) if (g_Commands[i].CommandInternalID == id) - return i; + return (int)i; return -1; } -void CZipContextMenu::FillCommand(ECommandInternalID id, UString &mainString, CCommandMapItem &cmi) +void CZipContextMenu::FillCommand(enum_CommandInternalID id, UString &mainString, CCommandMapItem &cmi) const { mainString.Empty(); - int i = FindCommand(id); + const int i = FindCommand(id); if (i < 0) throw 201908; const CContextMenuCommand &command = g_Commands[(unsigned)i]; @@ -266,7 +325,6 @@ // cmi.HelpString = cmi.Verb; LangString(command.ResourceID, mainString); cmi.UserString = mainString; - // return true; } @@ -279,14 +337,39 @@ } -void CZipContextMenu::AddCommand(ECommandInternalID id, UString &mainString, CCommandMapItem &cmi) +void CZipContextMenu::AddCommand(enum_CommandInternalID id, UString &mainString, CCommandMapItem &cmi) { FillCommand(id, mainString, cmi); _commandMap.Add(cmi); } -static void MyInsertMenu(CMenu &menu, int pos, UINT id, const UString &s, HBITMAP bitmap) + +/* +note: old msdn article: +Duplicate Menu Items In the File Menu For a Shell Context Menu Extension (214477) +---------- + On systems with Shell32.dll version 4.71 or higher, a context menu extension + for a file folder that inserts one or more pop-up menus results in duplicates + of these menu items. + This occurs when the file menu is activated more than once for the selected object. + +CAUSE + In a context menu extension, if pop-up menus are inserted using InsertMenu + or AppendMenu, then the ID for the pop-up menu item cannot be specified. + Instead, this field should take in the HMENU of the pop-up menu. + Because the ID is not specified for the pop-up menu item, the Shell does + not keep track of the menu item if the file menu is pulled down multiple times. + As a result, the pop-up menu items are added multiple times in the context menu. + + This problem occurs only when the file menu is pulled down, and does not happen + when the context menu is invoked by using the right button or the context menu key. +RESOLUTION + To work around this problem, use InsertMenuItem and specify the ID of the + pop-up menu item in the wID member of the MENUITEMINFO structure. +*/ + +static void MyInsertMenu(CMenu &menu, unsigned pos, UINT id, const UString &s, HBITMAP bitmap) { if (!menu) return; @@ -310,7 +393,7 @@ static void MyAddSubMenu( CObjectVector &_commandMap, const char *verb, - CMenu &menu, int pos, UINT id, const UString &s, HMENU hSubMenu, HBITMAP bitmap) + CMenu &menu, unsigned pos, UINT id, const UString &s, HMENU hSubMenu, HBITMAP bitmap) { CZipContextMenu::CCommandMapItem cmi; cmi.CommandInternalID = CZipContextMenu::kCommandNULL; @@ -349,7 +432,7 @@ static bool IsItArcExt(const UString &ext) { - for (unsigned i = 0; i < ARRAY_SIZE(kArcExts); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(kArcExts); i++) if (ext.IsEqualTo_Ascii_NoCase(kArcExts[i])) return true; return false; @@ -444,39 +527,21 @@ , "rar" }; -static bool FindExt(const char *p, const FString &name) + +bool FindExt(const char *p, const UString &name, CStringFinder &finder); +bool FindExt(const char *p, const UString &name, CStringFinder &finder) { - int dotPos = name.ReverseFind_Dot(); + const int dotPos = name.ReverseFind_Dot(); if (dotPos < 0 || dotPos == (int)name.Len() - 1) return false; - - AString s; - - for (unsigned pos = dotPos + 1;; pos++) - { - wchar_t c = name[pos]; - if (c == 0) - break; - if (c >= 0x80) - return false; - s += (char)MyCharLower_Ascii((char)c); - } - - for (unsigned i = 0; p[i] != 0;) - { - unsigned j; - for (j = i; p[j] != ' '; j++); - if (s.Len() == j - i && memcmp(p + i, (const char *)s, s.Len()) == 0) - return true; - i = j + 1; - } - - return false; + return finder.FindWord_In_LowCaseAsciiList_NoCase(p, name.Ptr(dotPos + 1)); } -static bool DoNeedExtract(const FString &name) +/* returns false, if extraction of that file extension is not expected */ +static bool DoNeedExtract(const UString &name, CStringFinder &finder) { - return !FindExt(kExtractExcludeExtensions, name); + // for (int y = 0; y < 1000; y++) FindExt(kExtractExcludeExtensions, name); + return !FindExt(kExtractExcludeExtensions, name, finder); } // we must use diferent Verbs for Popup subMenu. @@ -510,28 +575,24 @@ */ - -STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, +Z7_COMWF_B CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, UINT commandIDFirst, UINT commandIDLast, UINT flags) { - ODS("+ QueryContextMenu()"); + ODS("+ QueryContextMenu()") COM_TRY_BEGIN try { - #ifdef SHOW_DEBUG_CTX_MENU - { char s[256]; sprintf(s, "QueryContextMenu: index=%d first=%d last=%d flags=%x _files=%d", - indexMenu, commandIDFirst, commandIDLast, flags, _fileNames.Size()); OutputDebugStringA(s); } + _commandMap.Clear(); + ODS_SPRF_s(sprintf(s, "QueryContextMenu: index=%u first=%u last=%u flags=%x _files=%u", + indexMenu, commandIDFirst, commandIDLast, flags, _fileNames.Size())) /* for (UInt32 i = 0; i < _fileNames.Size(); i++) { - OutputDebugStringW(_fileNames[i]); + ODS_U(_fileNames[i]) } */ - #endif - LoadLangOneTime(); - if (_fileNames.Size() == 0) { return MAKE_HRESULT(SEVERITY_SUCCESS, 0, 0); @@ -541,7 +602,6 @@ if (commandIDFirst > commandIDLast) return E_INVALIDARG; - UINT currentCommandID = commandIDFirst; if ((flags & 0x000F) != CMF_NORMAL @@ -552,24 +612,33 @@ // 19.01 : we changed from (currentCommandID) to (currentCommandID - commandIDFirst) // why it was so before? - _commandMap.Clear(); +#ifdef Z7_LANG + LoadLangOneTime(); +#endif CMenu popupMenu; CMenuDestroyer menuDestroyer; + ODS("### 40") CContextMenuInfo ci; ci.Load(); + ODS("### 44") _elimDup = ci.ElimDup; _writeZone = ci.WriteZone; HBITMAP bitmap = NULL; if (ci.MenuIcons.Val) + { + ODS("### 45") + if (!_bitmap) + _bitmap = ::LoadBitmap(g_hInstance, MAKEINTRESOURCE(IDB_MENU_LOGO)); bitmap = _bitmap; + } UINT subIndex = indexMenu; - ODS("### 50"); + ODS("### 50") if (ci.Cascaded.Val) { @@ -596,7 +665,7 @@ popupMenu.InsertItem(subIndex++, true, mi); } - UInt32 contextMenuFlags = ci.Flags; + const UInt32 contextMenuFlags = ci.Flags; NFind::CFileInfo fi0; FString folderPrefix; @@ -610,7 +679,7 @@ { // CFileInfo::Find can be slow for device files. So we don't call it. // we need only name here. - fi0.Name = us2fs(fileName.Ptr(NName::kDevicePathPrefixSize)); // change it 4 - must be constant + fi0.Name = us2fs(fileName.Ptr(NName::kDevicePathPrefixSize)); folderPrefix = #ifdef UNDER_CE "\\"; @@ -630,16 +699,42 @@ } } - ODS("### 100"); + ODS("### 100") UString mainString; + CStringFinder finder; + UStringVector fileNames_Reduced; + const unsigned k_Explorer_NumReducedItems = 16; + const bool needReduce = !_isMenuForFM && (_fileNames.Size() >= k_Explorer_NumReducedItems); + _fileNames_WereReduced = needReduce; + // _fileNames_WereReduced = true; // for debug; + const UStringVector *fileNames = &_fileNames; + if (needReduce) + { + for (unsigned i = 0; i < k_Explorer_NumReducedItems + && i < _fileNames.Size(); i++) + fileNames_Reduced.Add(_fileNames[i]); + fileNames = &fileNames_Reduced; + } + /* + if (_fileNames.Size() == k_Explorer_NumReducedItems) // for debug + { + for (int i = 0; i < 10; i++) + { + CCommandMapItem cmi; + AddCommand(kCompressToZipEmail, mainString, cmi); + MyInsertMenu(popupMenu, subIndex++, currentCommandID++, mainString, bitmap); + } + } + */ + if (_fileNames.Size() == 1 && currentCommandID + 14 <= commandIDLast) { - if (!fi0.IsDir() && DoNeedExtract(fi0.Name)) + if (!fi0.IsDir() && DoNeedExtract(fs2us(fi0.Name), finder)) { // Open - bool thereIsMainOpenItem = ((contextMenuFlags & NContextMenuFlags::kOpen) != 0); + const bool thereIsMainOpenItem = ((contextMenuFlags & NContextMenuFlags::kOpen) != 0); if (thereIsMainOpenItem) { CCommandMapItem cmi; @@ -658,7 +753,7 @@ _commandMap.Back().CtxCommandType = CtxCommandType_OpenRoot; UINT subIndex2 = 0; - for (unsigned i = (thereIsMainOpenItem ? 1 : 0); i < ARRAY_SIZE(kOpenTypes); i++) + for (unsigned i = (thereIsMainOpenItem ? 1 : 0); i < Z7_ARRAY_SIZE(kOpenTypes); i++) { CCommandMapItem cmi; if (i == 0) @@ -685,29 +780,40 @@ } } + ODS("### 150") + if (_fileNames.Size() > 0 && currentCommandID + 10 <= commandIDLast) { - bool needExtract = (!fi0.IsDir() && DoNeedExtract(fi0.Name)); - - if (!needExtract) + ODS("### needExtract list START") + const bool needExtendedVerbs = ((flags & Z7_WIN_CMF_EXTENDEDVERBS) != 0); + // || _isMenuForFM; + bool needExtract = true; + bool areDirs = fi0.IsDir() || (unsigned)_attribs.FirstDirIndex < k_Explorer_NumReducedItems; + if (!needReduce) + areDirs = areDirs || (_attribs.FirstDirIndex != -1); + if (areDirs) + needExtract = false; + + if (!needExtendedVerbs) + if (needExtract) { - for (unsigned i = 1; i < _fileNames.Size(); i++) + UString name; + const unsigned numItemsCheck = fileNames->Size(); + for (unsigned i = 0; i < numItemsCheck; i++) { - NFind::CFileInfo fi; - if (!fi.Find(us2fs(_fileNames[i]))) - { - throw 20190821; - // return RETURN_WIN32_LastError_AS_HRESULT(); - } - if (!fi.IsDir() && DoNeedExtract(fi.Name)) + const UString &a = (*fileNames)[i]; + const int slash = a.ReverseFind_PathSepar(); + name = a.Ptr(slash + 1); + // for (int y = 0; y < 600; y++) // for debug + const bool needExtr2 = DoNeedExtract(name, finder); + if (!needExtr2) { - needExtract = true; + needExtract = needExtr2; break; } } } - - // const UString &fileName = _fileNames.Front(); + ODS("### needExtract list END") if (needExtract) { @@ -757,16 +863,46 @@ // Test CCommandMapItem cmi; AddCommand(kTest, mainString, cmi); + // if (_fileNames.Size() == 16) mainString += "_[16]"; // for debug MyInsertMenu(popupMenu, subIndex++, currentCommandID++, mainString, bitmap); } } - - const UString arcName = CreateArchiveName(_fileNames, _fileNames.Size() == 1 ? &fi0 : NULL); - UString arcName7z = arcName; - arcName7z += ".7z"; - UString arcNameZip = arcName; - arcNameZip += ".zip"; + ODS("### CreateArchiveName START") + UString arcName_base; + const UString arcName = CreateArchiveName( + *fileNames, + false, // isHash + fileNames->Size() == 1 ? &fi0 : NULL, + arcName_base); + ODS("### CreateArchiveName END") + UString arcName_Show = arcName; + if (needReduce) + { + /* we need same arcName_Show for two calls from Explorer: + 1) reduced call (only first 16 items) + 2) full call with all items (can be >= 16 items) + (fileNames) array was reduced to 16 items. + So we will have same (arcName) in both reduced and full calls. + If caller (Explorer) uses (reduce_to_first_16_items) scheme, + we can use (arcName) here instead of (arcName_base). + (arcName_base) has no number in name. + */ + arcName_Show = arcName_base; // we can comment that line + /* we use "_" in archive name as sign to user + that shows that final archive name can be changed. */ + arcName_Show += "_"; + } + + UString arcName_7z = arcName; + arcName_7z += ".7z"; + UString arcName_7z_Show = arcName_Show; + arcName_7z_Show += ".7z"; + UString arcName_zip = arcName; + arcName_zip += ".zip"; + UString arcName_zip_Show = arcName_Show; + arcName_zip_Show += ".zip"; + // Compress if ((contextMenuFlags & NContextMenuFlags::kCompress) != 0) @@ -794,7 +930,7 @@ // CompressTo7z if (contextMenuFlags & NContextMenuFlags::kCompressTo7z && - !arcName7z.IsEqualTo_NoCase(fs2us(fi0.Name))) + !arcName_7z.IsEqualTo_NoCase(fs2us(fi0.Name))) { CCommandMapItem cmi; UString s; @@ -802,10 +938,10 @@ cmi.Folder = _dropPath; else cmi.Folder = fs2us(folderPrefix); - cmi.ArcName = arcName7z; + cmi.ArcName = arcName_7z; cmi.ArcType = "7z"; AddCommand(kCompressTo7z, s, cmi); - MyFormatNew_ReducedName(s, arcName7z); + MyFormatNew_ReducedName(s, arcName_7z_Show); Set_UserString_in_LastCommand(s); MyInsertMenu(popupMenu, subIndex++, currentCommandID++, s, bitmap); } @@ -816,10 +952,10 @@ { CCommandMapItem cmi; UString s; - cmi.ArcName = arcName7z; + cmi.ArcName = arcName_7z; cmi.ArcType = "7z"; AddCommand(kCompressTo7zEmail, s, cmi); - MyFormatNew_ReducedName(s, arcName7z); + MyFormatNew_ReducedName(s, arcName_7z_Show); Set_UserString_in_LastCommand(s); MyInsertMenu(popupMenu, subIndex++, currentCommandID++, s, bitmap); } @@ -827,7 +963,7 @@ // CompressToZip if (contextMenuFlags & NContextMenuFlags::kCompressToZip && - !arcNameZip.IsEqualTo_NoCase(fs2us(fi0.Name))) + !arcName_zip.IsEqualTo_NoCase(fs2us(fi0.Name))) { CCommandMapItem cmi; UString s; @@ -835,10 +971,10 @@ cmi.Folder = _dropPath; else cmi.Folder = fs2us(folderPrefix); - cmi.ArcName = arcNameZip; + cmi.ArcName = arcName_zip; cmi.ArcType = "zip"; AddCommand(kCompressToZip, s, cmi); - MyFormatNew_ReducedName(s, arcNameZip); + MyFormatNew_ReducedName(s, arcName_zip_Show); Set_UserString_in_LastCommand(s); MyInsertMenu(popupMenu, subIndex++, currentCommandID++, s, bitmap); } @@ -849,16 +985,17 @@ { CCommandMapItem cmi; UString s; - cmi.ArcName = arcNameZip; + cmi.ArcName = arcName_zip; cmi.ArcType = "zip"; AddCommand(kCompressToZipEmail, s, cmi); - MyFormatNew_ReducedName(s, arcNameZip); + MyFormatNew_ReducedName(s, arcName_zip_Show); Set_UserString_in_LastCommand(s); MyInsertMenu(popupMenu, subIndex++, currentCommandID++, s, bitmap); } #endif } + ODS("### 300") // don't use InsertMenu: See MSDN: // PRB: Duplicate Menu Items In the File Menu For a Shell Context Menu Extension @@ -879,6 +1016,8 @@ indexMenu = subIndex; } + ODS("### 350") + const bool needCrc = ((contextMenuFlags & (NContextMenuFlags::kCRC | NContextMenuFlags::kCRC_Cascaded)) != 0); @@ -901,7 +1040,7 @@ CMenu menu; { - int indexInParent; + unsigned indexInParent; if (insertHashMenuTo7zipMenu) { indexInParent = subIndex; @@ -920,7 +1059,9 @@ indexMenu = indexInParent; } - for (unsigned i = 0; i < ARRAY_SIZE(g_HashCommands); i++) + ODS("### HashCommands") + + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_HashCommands); i++) { if (currentCommandID >= commandIDLast) break; @@ -928,13 +1069,13 @@ CCommandMapItem cmi; cmi.CommandInternalID = hc.CommandInternalID; cmi.Verb = kCheckSumCascadedVerb; - cmi.Verb += '.'; - cmi.Verb += hc.MethodName; + cmi.Verb.Add_Dot(); UString s; s += hc.UserName; if (hc.CommandInternalID == kHash_Generate_SHA256) { + cmi.Verb += "Generate"; { popupMenu.Attach(hMenu); CMenuItem mi; @@ -944,28 +1085,47 @@ } UString name; - if (_fileNames.Size() > 1) - name = CreateArchiveName(_fileNames, _fileNames.Size() == 1 ? &fi0 : NULL); + UString showName; + ODS("### Hash CreateArchiveName Start") + // for (int y = 0; y < 10000; y++) // for debug + // if (fileNames->Size() == 1) name = fs2us(fi0.Name); else + name = CreateArchiveName( + *fileNames, + true, // isHash + fileNames->Size() == 1 ? &fi0 : NULL, + showName); + if (needReduce) + showName += "_"; else - name = fs2us(fi0.Name); + showName = name; + + ODS("### Hash CreateArchiveName END") name += ".sha256"; + showName += ".sha256"; cmi.Folder = fs2us(folderPrefix); cmi.ArcName = name; s = "SHA-256 -> "; - s += name; + s += showName; } else if (hc.CommandInternalID == kHash_TestArc) { + cmi.Verb += "Test"; s = LangStringAlt(IDS_CONTEXT_TEST, "Test archive"); s += " : "; s += GetNameOfProperty(kpidChecksum, UString("Checksum")); } + else + cmi.Verb += "Calc"; + + cmi.Verb.Add_Dot(); + cmi.Verb += hc.MethodName; // cmi.HelpString = cmi.Verb; cmi.UserString = s; cmi.CtxCommandType = CtxCommandType_CrcChild; _commandMap.Add(cmi); MyInsertMenu(subMenu, subIndex_CRC++, currentCommandID++, s, bitmap); + ODS("### 380") } subMenu.Detach(); @@ -973,49 +1133,45 @@ } popupMenu.Detach(); - /* if (!ci.Cascaded.Val) indexMenu = subIndex; */ - - ODS("### 400"); - - #ifdef SHOW_DEBUG_CTX_MENU - { char s[256]; sprintf(s, "Commands=%d currentCommandID - commandIDFirst = %d", - _commandMap.Size(), currentCommandID - commandIDFirst); OutputDebugStringA(s); } - #endif - - if (_commandMap.Size() != currentCommandID - commandIDFirst) + const unsigned numCommands = currentCommandID - commandIDFirst; + ODS("+ QueryContextMenu() END") + ODS_SPRF_s(sprintf(s, "Commands=%u currentCommandID - commandIDFirst = %u", + _commandMap.Size(), numCommands)) + if (_commandMap.Size() != numCommands) throw 20190818; - return MAKE_HRESULT(SEVERITY_SUCCESS, 0, currentCommandID - commandIDFirst); - + /* + FOR_VECTOR (k, _commandMap) + { + ODS_U(_commandMap[k].Verb); + } + */ } catch(...) { + ODS_SPRF_s(sprintf(s, "catch() exception: Commands=%u", _commandMap.Size())) + if (_commandMap.Size() == 0) + throw; + } /* we added some menu items already : num_added_menu_items, So we MUST return (number_of_defined_ids), where (number_of_defined_ids >= num_added_menu_items) This will prevent incorrect menu working, when same IDs can be assigned in multiple menu items from different subhandlers. And we must add items to _commandMap before adding to menu. */ - #ifdef SHOW_DEBUG_CTX_MENU - { char s[256]; sprintf(s, "catch() exception: Commands=%d", - _commandMap.Size()); OutputDebugStringA(s); } - #endif - // if (_commandMap.Size() != 0) - return MAKE_HRESULT(SEVERITY_SUCCESS, 0, _commandMap.Size()); - // throw; - } + return MAKE_HRESULT(SEVERITY_SUCCESS, 0, _commandMap.Size()); COM_TRY_END } -int CZipContextMenu::FindVerb(const UString &verb) +int CZipContextMenu::FindVerb(const UString &verb) const { FOR_VECTOR (i, _commandMap) if (_commandMap[i].Verb == verb) - return i; + return (int)i; return -1; } @@ -1025,66 +1181,16 @@ } -#ifdef UNDER_CE - #define MY__IS_INTRESOURCE(_r) ((((ULONG_PTR)(_r)) >> 16) == 0) -#else - #define MY__IS_INTRESOURCE(_r) IS_INTRESOURCE(_r) -#endif - - -#ifdef SHOW_DEBUG_CTX_MENU -static void PrintStringA(const char *name, LPCSTR ptr) -{ - AString m; - m += name; - m += ": "; - char s[32]; - sprintf(s, "%p", ptr); - m += s; - if (!MY__IS_INTRESOURCE(ptr)) - { - m += ": \""; - m += ptr; - m += "\""; - } - OutputDebugStringA(m); -} - -#if !defined(UNDER_CE) -static void PrintStringW(const char *name, LPCWSTR ptr) -{ - UString m; - m += name; - m += ": "; - char s[32]; - sprintf(s, "%p", ptr); - m += s; - if (!MY__IS_INTRESOURCE(ptr)) - { - m += ": \""; - m += ptr; - m += "\""; - } - OutputDebugStringW(m); -} -#endif -#endif - - -STDMETHODIMP CZipContextMenu::InvokeCommand(LPCMINVOKECOMMANDINFO commandInfo) +Z7_COMWF_B CZipContextMenu::InvokeCommand(LPCMINVOKECOMMANDINFO commandInfo) { COM_TRY_BEGIN + ODS("==== CZipContextMenu::InvokeCommand()") + #ifdef SHOW_DEBUG_CTX_MENU - { char s[1280]; sprintf(s, - #ifdef _WIN64 - "64" - #else - "32" - #endif - ": InvokeCommand: cbSize=%d flags=%x " - , commandInfo->cbSize, commandInfo->fMask); OutputDebugStringA(s); } + ODS_SPRF_s(sprintf(s, ": InvokeCommand: cbSize=%u flags=%x ", + (unsigned)commandInfo->cbSize, (unsigned)commandInfo->fMask)) PrintStringA("Verb", commandInfo->lpVerb); PrintStringA("Parameters", commandInfo->lpParameters); @@ -1094,16 +1200,16 @@ int commandOffset = -1; // xp64 / Win10 : explorer.exe sends 0 in lpVerbW - // MSDN: if (IS_INTRESOURCE(lpVerbW)), we must use LOWORD(lpVerb) as sommand offset + // MSDN: if (IS_INTRESOURCE(lpVerbW)), we must use LOWORD(lpVerb) as command offset - // FIXME: MINGW doesn't define CMINVOKECOMMANDINFOEX - #if !defined(UNDER_CE) /* && defined(_MSC_VER) */ + // FIXME: old MINGW doesn't define CMINVOKECOMMANDINFOEX / CMIC_MASK_UNICODE + #if !defined(UNDER_CE) && defined(CMIC_MASK_UNICODE) bool unicodeVerb = false; if (commandInfo->cbSize == sizeof(CMINVOKECOMMANDINFOEX) && (commandInfo->fMask & CMIC_MASK_UNICODE) != 0) { LPCMINVOKECOMMANDINFOEX commandInfoEx = (LPCMINVOKECOMMANDINFOEX)commandInfo; - if (!MY__IS_INTRESOURCE(commandInfoEx->lpVerbW)) + if (!MY_IS_INTRESOURCE(commandInfoEx->lpVerbW)) { unicodeVerb = true; commandOffset = FindVerb(commandInfoEx->lpVerbW); @@ -1120,22 +1226,17 @@ if (!unicodeVerb) #endif { - #ifdef SHOW_DEBUG_CTX_MENU - OutputDebugStringA("use non-UNICODE verb"); - #endif + ODS("use non-UNICODE verb") // if (HIWORD(commandInfo->lpVerb) == 0) - if (MY__IS_INTRESOURCE(commandInfo->lpVerb)) + if (MY_IS_INTRESOURCE(commandInfo->lpVerb)) commandOffset = LOWORD(commandInfo->lpVerb); else commandOffset = FindVerb(GetUnicodeString(commandInfo->lpVerb)); } - #ifdef SHOW_DEBUG_CTX_MENU - { char s[128]; sprintf(s, "commandOffset=%d", - commandOffset); OutputDebugStringA(s); } - #endif + ODS_SPRF_s(sprintf(s, "commandOffset=%d", commandOffset)) - if (commandOffset < 0 || (unsigned)commandOffset >= _commandMap.Size()) + if (/* commandOffset < 0 || */ (unsigned)commandOffset >= _commandMap.Size()) return E_INVALIDARG; const CCommandMapItem &cmi = _commandMap[(unsigned)commandOffset]; return InvokeCommandCommon(cmi); @@ -1145,7 +1246,7 @@ HRESULT CZipContextMenu::InvokeCommandCommon(const CCommandMapItem &cmi) { - const ECommandInternalID cmdID = cmi.CommandInternalID; + const enum_CommandInternalID cmdID = cmi.CommandInternalID; try { @@ -1167,6 +1268,11 @@ case kExtractHere: case kExtractTo: { + if (_attribs.FirstDirIndex != -1) + { + ShowErrorMessageRes(IDS_SELECT_FILES); + break; + } ExtractArchives(_fileNames, cmi.Folder, (cmdID == kExtract), // showDialog (cmdID == kExtractTo) && _elimDup.Val, // elimDup @@ -1186,16 +1292,37 @@ case kCompressToZip: case kCompressToZipEmail: { + UString arcName = cmi.ArcName; + if (_fileNames_WereReduced) + { + UString arcName_base; + arcName = CreateArchiveName( + _fileNames, + false, // isHash + NULL, // fi0 + arcName_base); + const char *postfix = NULL; + if (cmdID == kCompressTo7z || + cmdID == kCompressTo7zEmail) + postfix = ".7z"; + else if ( + cmdID == kCompressToZip || + cmdID == kCompressToZipEmail) + postfix = ".zip"; + if (postfix) + arcName += postfix; + } + const bool email = - (cmdID == kCompressEmail) || - (cmdID == kCompressTo7zEmail) || - (cmdID == kCompressToZipEmail); + cmdID == kCompressEmail || + cmdID == kCompressTo7zEmail || + cmdID == kCompressToZipEmail; const bool showDialog = - (cmdID == kCompress) || - (cmdID == kCompressEmail); - const bool addExtension = (cmdID == kCompress || cmdID == kCompressEmail); + cmdID == kCompress || + cmdID == kCompressEmail; + const bool addExtension = showDialog; CompressFiles(cmi.Folder, - cmi.ArcName, cmi.ArcType, + arcName, cmi.ArcType, addExtension, _fileNames, email, showDialog, false // waitFinish @@ -1211,7 +1338,7 @@ case kHash_Generate_SHA256: case kHash_TestArc: { - for (unsigned i = 0; i < ARRAY_SIZE(g_HashCommands); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_HashCommands); i++) { const CHashCommand &hc = g_HashCommands[i]; if (hc.CommandInternalID == cmdID) @@ -1223,7 +1350,18 @@ } UString generateName; if (cmdID == kHash_Generate_SHA256) + { generateName = cmi.ArcName; + if (_fileNames_WereReduced) + { + UString arcName_base; + generateName = CreateArchiveName(_fileNames, + true, // isHash + NULL, // fi0 + arcName_base); + generateName += ".sha256"; + } + } CalcChecksum(_fileNames, (UString)hc.MethodName, cmi.Folder, generateName); break; @@ -1237,14 +1375,14 @@ } catch(...) { - ::MessageBoxW(0, L"Error", L"7-Zip", MB_ICONERROR); + ShowErrorMessage(NULL, L"Error"); } return S_OK; } -static void MyCopyString(void *dest, const UString &src, bool writeInUnicode, UINT size) +static void MyCopyString_isUnicode(void *dest, UINT size, const UString &src, bool writeInUnicode) { if (size != 0) size--; @@ -1253,6 +1391,7 @@ UString s = src; s.DeleteFrom(size); MyStringCopy((wchar_t *)dest, s); + ODS_U(s) } else { @@ -1263,50 +1402,48 @@ } -STDMETHODIMP CZipContextMenu::GetCommandString(UINT_PTR commandOffset, UINT uType, +Z7_COMWF_B CZipContextMenu::GetCommandString( + #ifdef Z7_OLD_WIN_SDK + UINT + #else + UINT_PTR + #endif + commandOffset, + UINT uType, UINT * /* pwReserved */ , LPSTR pszName, UINT cchMax) { COM_TRY_BEGIN + ODS("GetCommandString") + const int cmdOffset = (int)commandOffset; - #ifdef SHOW_DEBUG_CTX_MENU - { char s[256]; sprintf(s, "GetCommandString: cmdOffset=%d uType=%d cchMax = %d", - cmdOffset, uType, cchMax); OutputDebugStringA(s); } - #endif + ODS_SPRF_s(sprintf(s, "GetCommandString: cmdOffset=%d uType=%d cchMax = %d", + cmdOffset, uType, cchMax)) - if (uType == GCS_VALIDATEA || uType == GCS_VALIDATEW) + if ((uType | GCS_UNICODE) == GCS_VALIDATEW) { - if (cmdOffset < 0 || (unsigned)cmdOffset >= _commandMap.Size()) + if (/* cmdOffset < 0 || */ (unsigned)cmdOffset >= _commandMap.Size()) return S_FALSE; - else - return S_OK; + return S_OK; } - if (cmdOffset < 0 || (unsigned)cmdOffset >= _commandMap.Size()) + if (/* cmdOffset < 0 || */ (unsigned)cmdOffset >= _commandMap.Size()) { - #ifdef SHOW_DEBUG_CTX_MENU - OutputDebugStringA("---------------- cmdOffset: E_INVALIDARG"); - #endif + ODS("------ cmdOffset: E_INVALIDARG") return E_INVALIDARG; } - const CCommandMapItem &cmi = _commandMap[(unsigned)cmdOffset]; - - if (uType == GCS_HELPTEXTA || uType == GCS_HELPTEXTW) - { - // we can return "Verb" here for debug purposes. - // HelpString; - MyCopyString(pszName, cmi.Verb, uType == GCS_HELPTEXTW, cchMax); - return S_OK; - } - - if (uType == GCS_VERBA || uType == GCS_VERBW) + // we use Verb as HelpString + if (cchMax != 0) + if ((uType | GCS_UNICODE) == GCS_VERBW || + (uType | GCS_UNICODE) == GCS_HELPTEXTW) { - MyCopyString(pszName, cmi.Verb, uType == GCS_VERBW, cchMax); + const CCommandMapItem &cmi = _commandMap[(unsigned)cmdOffset]; + MyCopyString_isUnicode(pszName, cchMax, cmi.Verb, (uType & GCS_UNICODE) != 0); return S_OK; } - + return E_INVALIDARG; COM_TRY_END @@ -1339,7 +1476,7 @@ class CCoTaskWSTR { LPWSTR m_str; - CLASS_NO_COPY(CCoTaskWSTR) + Z7_CLASS_NO_COPY(CCoTaskWSTR) public: CCoTaskWSTR(): m_str(NULL) {} ~CCoTaskWSTR() { ::CoTaskMemFree(m_str); } @@ -1380,41 +1517,47 @@ */ }; -static void LoadPaths(IShellItemArray *psiItemArray, UStringVector &paths) +static HRESULT LoadPaths(IShellItemArray *psiItemArray, UStringVector &paths) { if (psiItemArray) { DWORD numItems = 0; - if (psiItemArray->GetCount(&numItems) == S_OK) + RINOK(psiItemArray->GetCount(&numItems)) { + ODS_(Print_Number(numItems, " ==== LoadPaths START === ")) for (DWORD i = 0; i < numItems; i++) { CMyComPtr item; - if (psiItemArray->GetItemAt(i, &item) == S_OK && item) + RINOK(psiItemArray->GetItemAt(i, &item)) + if (item) { CCoTaskWSTR displayName; if (item->GetDisplayName(SIGDN_FILESYSPATH, &displayName) == S_OK && (bool)displayName) { - OutputDebugStringW(displayName); + ODS_U(displayName) paths.Add((LPCWSTR)displayName); } } } + ODS_(Print_Number(numItems, " ==== LoadPaths END === ")) } } + return S_OK; } void CZipExplorerCommand::LoadItems(IShellItemArray *psiItemArray) { SubCommands.Clear(); - - UStringVector paths; - LoadPaths(psiItemArray, paths); - _fileNames = paths; - - HRESULT res = QueryContextMenu( + _fileNames.Clear(); + { + UStringVector paths; + if (LoadPaths(psiItemArray, paths) != S_OK) + return; + _fileNames = paths; + } + const HRESULT res = QueryContextMenu( NULL, // hMenu, 0, // indexMenu, 0, // commandIDFirst, @@ -1424,7 +1567,6 @@ if (FAILED(res)) return /* res */; - CZipExplorerCommand *crcHandler = NULL; CZipExplorerCommand *openHandler = NULL; @@ -1435,7 +1577,6 @@ { const CCommandMapItem &cmi = _commandMap[i]; - if (cmi.IsPopup) if (!cmi.IsSubMenu()) continue; @@ -1459,22 +1600,22 @@ shellExt->_commandMap_Cur.Add(cmi); - ODS_U(cmi.UserString); + ODS_U(cmi.UserString) if (cmi.CtxCommandType == CtxCommandType_CrcRoot && useCascadedCrc) crcHandler = shellExt; if (cmi.CtxCommandType == CtxCommandType_OpenRoot && useCascadedOpen) { - // ODS2("cmi.CtxCommandType == CtxCommandType_OpenRoot"); + // ODS("cmi.CtxCommandType == CtxCommandType_OpenRoot"); openHandler = shellExt; } } } -STDMETHODIMP CZipExplorerCommand::GetTitle(IShellItemArray *psiItemArray, LPWSTR *ppszName) +Z7_COMWF_B CZipExplorerCommand::GetTitle(IShellItemArray *psiItemArray, LPWSTR *ppszName) { - ODS("- GetTitle()"); + ODS("- GetTitle()") // COM_TRY_BEGIN if (IsSeparator) { @@ -1505,9 +1646,9 @@ } -STDMETHODIMP CZipExplorerCommand::GetIcon(IShellItemArray * /* psiItemArray */, LPWSTR *ppszIcon) +Z7_COMWF_B CZipExplorerCommand::GetIcon(IShellItemArray * /* psiItemArray */, LPWSTR *ppszIcon) { - ODS("- GetIcon()"); + ODS("- GetIcon()") // COM_TRY_BEGIN *ppszIcon = NULL; // return E_NOTIMPL; @@ -1520,30 +1661,30 @@ } -STDMETHODIMP CZipExplorerCommand::GetToolTip (IShellItemArray * /* psiItemArray */, LPWSTR *ppszInfotip) +Z7_COMWF_B CZipExplorerCommand::GetToolTip (IShellItemArray * /* psiItemArray */, LPWSTR *ppszInfotip) { // COM_TRY_BEGIN - ODS("- GetToolTip()"); + ODS("- GetToolTip()") *ppszInfotip = NULL; return E_NOTIMPL; // COM_TRY_END } -STDMETHODIMP CZipExplorerCommand::GetCanonicalName(GUID *pguidCommandName) +Z7_COMWF_B CZipExplorerCommand::GetCanonicalName(GUID *pguidCommandName) { // COM_TRY_BEGIN - ODS("- GetCanonicalName()"); + ODS("- GetCanonicalName()") *pguidCommandName = GUID_NULL; return E_NOTIMPL; // COM_TRY_END } -STDMETHODIMP CZipExplorerCommand::GetState(IShellItemArray * /* psiItemArray */, BOOL /* fOkToBeSlow */, EXPCMDSTATE *pCmdState) +Z7_COMWF_B CZipExplorerCommand::GetState(IShellItemArray * /* psiItemArray */, BOOL /* fOkToBeSlow */, EXPCMDSTATE *pCmdState) { // COM_TRY_BEGIN - ODS("- GetState()"); + ODS("- GetState()") *pCmdState = ECS_ENABLED; return S_OK; // COM_TRY_END @@ -1552,16 +1693,17 @@ -STDMETHODIMP CZipExplorerCommand::Invoke(IShellItemArray *psiItemArray, IBindCtx * /* pbc */) +Z7_COMWF_B CZipExplorerCommand::Invoke(IShellItemArray *psiItemArray, IBindCtx * /* pbc */) { COM_TRY_BEGIN if (_commandMap_Cur.IsEmpty()) return E_INVALIDARG; - ODS("- Invoke()"); + ODS("- Invoke()") + _fileNames.Clear(); UStringVector paths; - LoadPaths(psiItemArray, paths); + RINOK(LoadPaths(psiItemArray, paths)) _fileNames = paths; return InvokeCommandCommon(_commandMap_Cur[0]); @@ -1569,9 +1711,9 @@ } -STDMETHODIMP CZipExplorerCommand::GetFlags(EXPCMDFLAGS *pFlags) +Z7_COMWF_B CZipExplorerCommand::GetFlags(EXPCMDFLAGS *pFlags) { - ODS("- GetFlags()"); + ODS("- GetFlags()") // COM_TRY_BEGIN EXPCMDFLAGS f = ECF_DEFAULT; if (IsSeparator) @@ -1585,7 +1727,7 @@ // const CCommandMapItem &cmi = ; if (_commandMap_Cur[0].IsSubMenu()) { - // ODS("ECF_HASSUBCOMMANDS"); + // ODS("ECF_HASSUBCOMMANDS") f = ECF_HASSUBCOMMANDS; } } @@ -1596,9 +1738,9 @@ } -STDMETHODIMP CZipExplorerCommand::EnumSubCommands(IEnumExplorerCommand **ppEnum) +Z7_COMWF_B CZipExplorerCommand::EnumSubCommands(IEnumExplorerCommand **ppEnum) { - ODS("- EnumSubCommands()"); + ODS("- EnumSubCommands()") // COM_TRY_BEGIN *ppEnum = NULL; @@ -1623,12 +1765,12 @@ } -STDMETHODIMP CZipContextMenu::Next(ULONG celt, IExplorerCommand **pUICommand, ULONG *pceltFetched) +Z7_COMWF_B CZipContextMenu::Next(ULONG celt, IExplorerCommand **pUICommand, ULONG *pceltFetched) { - ODS("CZipContextMenu::Next()"); - Print_Number(celt, "celt"); - Print_Number(CurrentSubCommand, "CurrentSubCommand"); - Print_Number(SubCommands.Size(), "SubCommands.Size()"); + ODS("CZipContextMenu::Next()") + ODS_(Print_Number(celt, "celt")) + ODS_(Print_Number(CurrentSubCommand, "CurrentSubCommand")) + ODS_(Print_Number(SubCommands.Size(), "SubCommands.Size()")) COM_TRY_BEGIN ULONG fetched = 0; @@ -1649,7 +1791,7 @@ if (pceltFetched) *pceltFetched = fetched; - ODS(fetched == celt ? " === OK === " : "=== ERROR ==="); + ODS(fetched == celt ? " === OK === " : "=== ERROR ===") // we return S_FALSE for (fetched == 0) return (fetched == celt) ? S_OK : S_FALSE; @@ -1657,25 +1799,24 @@ } -STDMETHODIMP CZipContextMenu::Skip(ULONG celt) +Z7_COMWF_B CZipContextMenu::Skip(ULONG /* celt */) { - ODS("CZipContextMenu::Skip()"); - celt = celt; + ODS("CZipContextMenu::Skip()") return E_NOTIMPL; } -STDMETHODIMP CZipContextMenu::Reset(void) +Z7_COMWF_B CZipContextMenu::Reset(void) { - ODS("CZipContextMenu::Reset()"); + ODS("CZipContextMenu::Reset()") CurrentSubCommand = 0; return S_OK; } -STDMETHODIMP CZipContextMenu::Clone(IEnumExplorerCommand **ppenum) +Z7_COMWF_B CZipContextMenu::Clone(IEnumExplorerCommand **ppenum) { - ODS("CZipContextMenu::Clone()"); + ODS("CZipContextMenu::Clone()") *ppenum = NULL; return E_NOTIMPL; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/ContextMenuFlags.h 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/ContextMenuFlags.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/ContextMenuFlags.h 2021-09-29 17:53:12.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/ContextMenuFlags.h 2023-01-10 18:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ContextMenuFlags.h -#ifndef __CONTEXT_MENU_FLAGS_H -#define __CONTEXT_MENU_FLAGS_H +#ifndef ZIP7_INC_CONTEXT_MENU_FLAGS_H +#define ZIP7_INC_CONTEXT_MENU_FLAGS_H namespace NContextMenuFlags { diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/ContextMenu.h 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/ContextMenu.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/ContextMenu.h 2022-06-06 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/ContextMenu.h 2023-04-07 09:00:00.000000000 +0000 @@ -1,38 +1,77 @@ // ContextMenu.h -#ifndef __CONTEXT_MENU_H -#define __CONTEXT_MENU_H +#ifndef ZIP7_INC_CONTEXT_MENU_H +#define ZIP7_INC_CONTEXT_MENU_H -#include "../../../Common/MyWindows.h" - -#include +#include "../../../Windows/Shell.h" #include "MyExplorerCommand.h" -#include "../../../Common/MyString.h" - #include "../FileManager/MyCom2.h" -enum ECtxCommandType +#ifdef CMF_EXTENDEDVERBS +#define Z7_WIN_CMF_EXTENDEDVERBS CMF_EXTENDEDVERBS +#else +#define Z7_WIN_CMF_EXTENDEDVERBS 0x00000100 +#endif + +enum enum_CtxCommandType { CtxCommandType_Normal, CtxCommandType_OpenRoot, CtxCommandType_OpenChild, CtxCommandType_CrcRoot, - CtxCommandType_CrcChild, + CtxCommandType_CrcChild }; -class CZipContextMenu: +class CZipContextMenu Z7_final: public IContextMenu, public IShellExtInit, public IExplorerCommand, public IEnumExplorerCommand, public CMyUnknownImp { + Z7_COM_UNKNOWN_IMP_4_MT( + IContextMenu, + IShellExtInit, + IExplorerCommand, + IEnumExplorerCommand + ) + + // IShellExtInit + STDMETHOD(Initialize)(LPCITEMIDLIST pidlFolder, LPDATAOBJECT dataObject, HKEY hkeyProgID) Z7_override; + + // IContextMenu + STDMETHOD(QueryContextMenu)(HMENU hmenu, UINT indexMenu, UINT idCmdFirst, UINT idCmdLast, UINT uFlags) Z7_override; + STDMETHOD(InvokeCommand)(LPCMINVOKECOMMANDINFO lpici) Z7_override; + STDMETHOD(GetCommandString)( + #ifdef Z7_OLD_WIN_SDK + UINT + #else + UINT_PTR + #endif + idCmd, UINT uType, UINT *pwReserved, LPSTR pszName, UINT cchMax) Z7_override; + + // IExplorerCommand + STDMETHOD (GetTitle) (IShellItemArray *psiItemArray, LPWSTR *ppszName) Z7_override; + STDMETHOD (GetIcon) (IShellItemArray *psiItemArray, LPWSTR *ppszIcon) Z7_override; + STDMETHOD (GetToolTip) (IShellItemArray *psiItemArray, LPWSTR *ppszInfotip) Z7_override; + STDMETHOD (GetCanonicalName) (GUID *pguidCommandName) Z7_override; + STDMETHOD (GetState) (IShellItemArray *psiItemArray, BOOL fOkToBeSlow, EXPCMDSTATE *pCmdState) Z7_override; + STDMETHOD (Invoke) (IShellItemArray *psiItemArray, IBindCtx *pbc) Z7_override; + STDMETHOD (GetFlags) (EXPCMDFLAGS *pFlags) Z7_override; + STDMETHOD (EnumSubCommands) (IEnumExplorerCommand **ppEnum) Z7_override; + + // IEnumExplorerCommand + STDMETHOD (Next) (ULONG celt, IExplorerCommand **pUICommand, ULONG *pceltFetched) Z7_override; + STDMETHOD (Skip) (ULONG celt) Z7_override; + STDMETHOD (Reset) (void) Z7_override; + STDMETHOD (Clone) (IEnumExplorerCommand **ppenum) Z7_override; + public: - enum ECommandInternalID + enum enum_CommandInternalID { kCommandNULL, kOpen, @@ -54,48 +93,22 @@ kHash_Generate_SHA256, kHash_TestArc }; - - MY_UNKNOWN_IMP4_MT( - IContextMenu, - IShellExtInit, - IExplorerCommand, - IEnumExplorerCommand - ) - - // IShellExtInit - STDMETHOD(Initialize)(LPCITEMIDLIST pidlFolder, LPDATAOBJECT dataObject, HKEY hkeyProgID); - - // IContextMenu - STDMETHOD(QueryContextMenu)(HMENU hmenu, UINT indexMenu, UINT idCmdFirst, UINT idCmdLast, UINT uFlags); - STDMETHOD(InvokeCommand)(LPCMINVOKECOMMANDINFO lpici); - STDMETHOD(GetCommandString)(UINT_PTR idCmd, UINT uType, UINT *pwReserved, LPSTR pszName, UINT cchMax); - HRESULT InitContextMenu(const wchar_t *folder, const wchar_t * const *names, unsigned numFiles); +public: + void Init_For_7zFM() + { + // _isMenuForFM = true; + // _fileNames_WereReduced = false; + } void LoadItems(IShellItemArray *psiItemArray); - // IExplorerCommand - STDMETHOD (GetTitle) (IShellItemArray *psiItemArray, LPWSTR *ppszName); - STDMETHOD (GetIcon) (IShellItemArray *psiItemArray, LPWSTR *ppszIcon); - STDMETHOD (GetToolTip) (IShellItemArray *psiItemArray, LPWSTR *ppszInfotip); - STDMETHOD (GetCanonicalName) (GUID *pguidCommandName); - STDMETHOD (GetState) (IShellItemArray *psiItemArray, BOOL fOkToBeSlow, EXPCMDSTATE *pCmdState); - STDMETHOD (Invoke) (IShellItemArray *psiItemArray, IBindCtx *pbc); - STDMETHOD (GetFlags) (EXPCMDFLAGS *pFlags); - STDMETHOD (EnumSubCommands) (IEnumExplorerCommand **ppEnum); - - // IEnumExplorerCommand - STDMETHOD (Next) (ULONG celt, IExplorerCommand **pUICommand, ULONG *pceltFetched); - STDMETHOD (Skip) (ULONG celt); - STDMETHOD (Reset) (void); - STDMETHOD (Clone) (IEnumExplorerCommand **ppenum); - CZipContextMenu(); ~CZipContextMenu(); struct CCommandMapItem { - ECommandInternalID CommandInternalID; + enum_CommandInternalID CommandInternalID; UString Verb; UString UserString; // UString HelpString; @@ -103,7 +116,7 @@ UString ArcName; UString ArcType; bool IsPopup; - ECtxCommandType CtxCommandType; + enum_CtxCommandType CtxCommandType; CCommandMapItem(): IsPopup(false), @@ -118,33 +131,34 @@ } }; -private: + UStringVector _fileNames; + NWindows::NShell::CFileAttribs _attribs; +private: bool _isMenuForFM; - UStringVector _fileNames; + bool _fileNames_WereReduced; // = true, if only first 16 items were used in QueryContextMenu() bool _dropMode; UString _dropPath; CObjectVector _commandMap; CObjectVector _commandMap_Cur; HBITMAP _bitmap; - CBoolPair _elimDup; UInt32 _writeZone; + CBoolPair _elimDup; bool IsSeparator; bool IsRoot; CObjectVector< CMyComPtr > SubCommands; - ULONG CurrentSubCommand; + unsigned CurrentSubCommand; void Set_UserString_in_LastCommand(const UString &s) { _commandMap.Back().UserString = s; } - HRESULT GetFileNames(LPDATAOBJECT dataObject, UStringVector &fileNames); - int FindVerb(const UString &verb); - void FillCommand(ECommandInternalID id, UString &mainString, CCommandMapItem &cmi); - void AddCommand(ECommandInternalID id, UString &mainString, CCommandMapItem &cmi); + int FindVerb(const UString &verb) const; + void FillCommand(enum_CommandInternalID id, UString &mainString, CCommandMapItem &cmi) const; + void AddCommand(enum_CommandInternalID id, UString &mainString, CCommandMapItem &cmi); void AddMapItem_ForSubMenu(const char *ver); HRESULT InvokeCommandCommon(const CCommandMapItem &cmi); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/DllExportsExplorer.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/DllExportsExplorer.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/DllExportsExplorer.cpp 2021-10-24 11:41:05.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/DllExportsExplorer.cpp 2023-04-07 10:00:00.000000000 +0000 @@ -1,4 +1,4 @@ -// DLLExports.cpp +// DLLExportsExplorer.cpp // // Notes: // Win2000: @@ -9,9 +9,23 @@ #include "StdAfx.h" #include "../../../Common/MyWindows.h" -// #include "../../../Common/IntToString.h" +#if defined(__clang__) && __clang_major__ >= 4 +#pragma GCC diagnostic ignored "-Wnonportable-system-include-path" +#endif +// : in new Windows Kit 10.0.2**** (NTDDI_WIN10_MN is defined) +// : in another Windows Kit versions +#if defined(NTDDI_WIN10_MN) || defined(__MINGW32__) || defined(__MINGW64__) +#include +#else #include +#endif + +#if defined(__MINGW32__) || defined(__MINGW64__) +#include +#else +#include +#endif #include "../../../Common/MyInitGuid.h" @@ -32,7 +46,7 @@ // {23170F69-40C1-278A-1000-000100020000} static LPCTSTR const k_Clsid = TEXT("{23170F69-40C1-278A-1000-000100020000}"); -DEFINE_GUID(CLSID_CZipContextMenu, +Z7_DEFINE_GUID(CLSID_CZipContextMenu, k_7zip_GUID_Data1, k_7zip_GUID_Data2, k_7zip_GUID_Data3_Common, @@ -42,11 +56,11 @@ extern HINSTANCE g_hInstance; -HINSTANCE g_hInstance = 0; +HINSTANCE g_hInstance = NULL; extern HWND g_HWND; -HWND g_HWND = 0; +HWND g_HWND = NULL; extern LONG g_DllRefCount; @@ -56,21 +70,20 @@ // #define ODS(sz) OutputDebugStringW(L#sz) #define ODS(sz) -class CShellExtClassFactory: +class CShellExtClassFactory Z7_final: public IClassFactory, public CMyUnknownImp { + Z7_COM_UNKNOWN_IMP_1_MT(IClassFactory) + + STDMETHOD(CreateInstance)(LPUNKNOWN, REFIID, void**) Z7_override Z7_final; + STDMETHOD(LockServer)(BOOL) Z7_override Z7_final; public: - CShellExtClassFactory() { InterlockedIncrement(&g_DllRefCount); } + CShellExtClassFactory() { InterlockedIncrement(&g_DllRefCount); } ~CShellExtClassFactory() { InterlockedDecrement(&g_DllRefCount); } - - MY_UNKNOWN_IMP1_MT(IClassFactory) - - STDMETHODIMP CreateInstance(LPUNKNOWN, REFIID, void**); - STDMETHODIMP LockServer(BOOL); }; -STDMETHODIMP CShellExtClassFactory::CreateInstance(LPUNKNOWN pUnkOuter, +Z7_COMWF_B CShellExtClassFactory::CreateInstance(LPUNKNOWN pUnkOuter, REFIID riid, void **ppvObj) { ODS("CShellExtClassFactory::CreateInstance()\r\n"); @@ -92,14 +105,15 @@ if (!shellExt) return E_OUTOFMEMORY; - HRESULT res = shellExt->QueryInterface(riid, ppvObj); + IContextMenu *ctxm = shellExt; + const HRESULT res = ctxm->QueryInterface(riid, ppvObj); if (res != S_OK) delete shellExt; return res; } -STDMETHODIMP CShellExtClassFactory::LockServer(BOOL /* fLock */) +Z7_COMWF_B CShellExtClassFactory::LockServer(BOOL /* fLock */) { return S_OK; // Check it } @@ -169,7 +183,8 @@ catch(...) { return E_OUTOFMEMORY; } if (!cf) return E_OUTOFMEMORY; - HRESULT res = cf->QueryInterface(riid, ppv); + IClassFactory *cf2 = cf; + const HRESULT res = cf2->QueryInterface(riid, ppv); if (res != S_OK) delete cf; return res; @@ -217,7 +232,7 @@ STDAPI DllRegisterServer(void) { - return RegisterServer() ? S_OK: SELFREG_E_CLASS; + return RegisterServer() ? S_OK: SELFREG_E_CLASS; } static BOOL UnregisterServer() diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/Explorer.dsp 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/Explorer.dsp --- 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/Explorer.dsp 2021-10-24 12:01:16.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/Explorer.dsp 2023-04-06 11:00:00.000000000 +0000 @@ -45,7 +45,7 @@ # PROP Ignore_Export_Lib 1 # PROP Target_Dir "" # ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXPLORER_EXPORTS" /YX /FD /c -# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_MBCS" /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "EXPLORER_EXPORTS" /D "LANG" /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_MBCS" /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "EXPLORER_EXPORTS" /D "Z7_LANG" /D "Z7_LONG_PATH" /FAcs /Yu"StdAfx.h" /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "NDEBUG" @@ -72,7 +72,7 @@ # PROP Ignore_Export_Lib 1 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXPLORER_EXPORTS" /YX /FD /GZ /c -# ADD CPP /nologo /Gz /MTd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_MBCS" /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "EXPLORER_EXPORTS" /D "LANG" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gz /MTd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_MBCS" /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "EXPLORER_EXPORTS" /D "Z7_LANG" /D "Z7_LONG_PATH" /Yu"StdAfx.h" /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "_DEBUG" @@ -98,8 +98,8 @@ # PROP Intermediate_Dir "ReleaseU" # PROP Ignore_Export_Lib 1 # PROP Target_Dir "" -# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "EXPLORER_EXPORTS" /D "LANG" /D "_MBCS" /Yu"StdAfx.h" /FD /c -# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_UNICODE" /D "UNICODE" /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "EXPLORER_EXPORTS" /D "LANG" /Yu"StdAfx.h" /FD /c +# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "EXPLORER_EXPORTS" /D "Z7_LANG" /D "_MBCS" /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_UNICODE" /D "UNICODE" /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "EXPLORER_EXPORTS" /D "Z7_LANG" /D "Z7_LONG_PATH" /Yu"StdAfx.h" /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "NDEBUG" @@ -127,8 +127,8 @@ # PROP Intermediate_Dir "DebugU" # PROP Ignore_Export_Lib 1 # PROP Target_Dir "" -# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "EXPLORER_EXPORTS" /D "LANG" /D "_MBCS" /Yu"StdAfx.h" /FD /GZ /c -# ADD CPP /nologo /Gz /MTd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_UNICODE" /D "UNICODE" /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "EXPLORER_EXPORTS" /D "LANG" /Yu"StdAfx.h" /FD /GZ /c +# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "EXPLORER_EXPORTS" /D "Z7_LANG" /D "_MBCS" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gz /MTd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_UNICODE" /D "UNICODE" /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "EXPLORER_EXPORTS" /D "Z7_LANG" /D "Z7_LONG_PATH" /Yu"StdAfx.h" /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "_DEBUG" @@ -270,6 +270,10 @@ # End Source File # Begin Source File +SOURCE=..\FileManager\MyCom2.h +# End Source File +# Begin Source File + SOURCE=..\FileManager\ProgramLocation.cpp # End Source File # Begin Source File @@ -298,6 +302,18 @@ # PROP Default_Filter "" # Begin Source File +SOURCE=..\..\..\..\C\7zTypes.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\7zWindows.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\Compiler.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\CpuArch.c # SUBTRACT CPP /YX /Yc /Yu # End Source File @@ -307,6 +323,15 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\Sort.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\Sort.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\Threads.c # SUBTRACT CPP /YX /Yc /Yu # End Source File @@ -320,6 +345,10 @@ # PROP Default_Filter "" # Begin Source File +SOURCE=..\..\..\Common\Common.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\IntToString.cpp # End Source File # Begin Source File @@ -356,6 +385,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\NewHandler.cpp # End Source File # Begin Source File @@ -440,6 +473,10 @@ # End Group # Begin Source File +SOURCE=..\..\..\Windows\COM.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Windows\DLL.cpp # End Source File # Begin Source File @@ -567,5 +604,9 @@ SOURCE=.\ContextMenuFlags.h # End Source File +# Begin Source File + +SOURCE=..\FileManager\FM.ico +# End Source File # End Target # End Project diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/makefile 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/makefile --- 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/makefile 2021-10-08 12:29:18.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/makefile 2023-01-29 20:00:00.000000000 +0000 @@ -1,13 +1,13 @@ PROG = 7-zip.dll DEF_FILE = Explorer.def CFLAGS = $(CFLAGS) \ - -DLANG \ + -DZ7_LANG \ !IFDEF UNDER_CE LIBS = $(LIBS) Commctrl.lib !ELSE LIBS = $(LIBS) htmlhelp.lib comdlg32.lib Mpr.lib Gdi32.lib -CFLAGS = $(CFLAGS) -DWIN_LONG_PATH +CFLAGS = $(CFLAGS) -DZ7_LONG_PATH !ENDIF EXPLORER_OBJS = \ @@ -70,6 +70,7 @@ C_OBJS = \ $O\CpuArch.obj \ + $O\Sort.obj \ $O\Threads.obj \ !include "../../7zip.mak" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/MyExplorerCommand.h 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/MyExplorerCommand.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/MyExplorerCommand.h 2021-12-25 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/MyExplorerCommand.h 2023-04-07 07:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // MyExplorerCommand.h -#ifndef __MY_EXPLORER_COMMAND_H -#define __MY_EXPLORER_COMMAND_H +#ifndef ZIP7_INC_MY_EXPLORER_COMMAND_H +#define ZIP7_INC_MY_EXPLORER_COMMAND_H #if _MSC_VER >= 1910 #define USE_SYS_shobjidl_core @@ -17,7 +17,9 @@ ShObjIdl.h : old Windows SDK ShObjIdl_core.h : new Windows 10 SDK */ +#ifndef Z7_OLD_WIN_SDK #include +#endif #ifndef __IShellItem_INTERFACE_DEFINED__ #define __IShellItem_INTERFACE_DEFINED__ diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/MyMessages.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/MyMessages.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/MyMessages.cpp 2021-01-22 20:33:29.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/MyMessages.cpp 2023-01-04 20:00:00.000000000 +0000 @@ -18,12 +18,15 @@ void ShowErrorMessageHwndRes(HWND window, UINT resID) { - ShowErrorMessage(window, LangString(resID)); + UString s = LangString(resID); + if (s.IsEmpty()) + s.Add_UInt32(resID); + ShowErrorMessage(window, s); } void ShowErrorMessageRes(UINT resID) { - ShowErrorMessageHwndRes(0, resID); + ShowErrorMessageHwndRes(NULL, resID); } static void ShowErrorMessageDWORD(HWND window, DWORD errorCode) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/MyMessages.h 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/MyMessages.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/MyMessages.h 2013-01-17 10:33:38.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/MyMessages.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,16 +1,16 @@ // MyMessages.h -#ifndef __MY_MESSAGES_H -#define __MY_MESSAGES_H +#ifndef ZIP7_INC_MY_MESSAGES_H +#define ZIP7_INC_MY_MESSAGES_H #include "../../../Common/MyString.h" void ShowErrorMessage(HWND window, LPCWSTR message); -inline void ShowErrorMessage(LPCWSTR message) { ShowErrorMessage(0, message); } +inline void ShowErrorMessage(LPCWSTR message) { ShowErrorMessage(NULL, message); } void ShowErrorMessageHwndRes(HWND window, UInt32 langID); void ShowErrorMessageRes(UInt32 langID); -void ShowLastErrorMessage(HWND window = 0); +void ShowLastErrorMessage(HWND window = NULL); #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/RegistryContextMenu.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/RegistryContextMenu.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/RegistryContextMenu.cpp 2021-02-10 17:38:20.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/RegistryContextMenu.cpp 2023-03-06 18:00:00.000000000 +0000 @@ -67,8 +67,9 @@ static void Init_RegDeleteKeyExW() { if (!func_RegDeleteKeyExW) - func_RegDeleteKeyExW = (Func_RegDeleteKeyExW) - (void *)GetProcAddress(GetModuleHandleW(L"advapi32.dll"), "RegDeleteKeyExW"); + func_RegDeleteKeyExW = Z7_GET_PROC_ADDRESS( + Func_RegDeleteKeyExW, GetModuleHandleW(L"advapi32.dll"), + "RegDeleteKeyExW"); } #define INIT_REG_WOW if (wow != 0) Init_RegDeleteKeyExW(); @@ -205,7 +206,7 @@ if (setMode) for (unsigned i = 0; i < 2; i++) { - for (unsigned k = 0; k < ARRAY_SIZE(k_shellex_Prefixes); k++) + for (unsigned k = 0; k < Z7_ARRAY_SIZE(k_shellex_Prefixes); k++) { CSysString s (k_shellex_Prefixes[k]); s += (i == 0 ? k_KeyPostfix_ContextMenu : k_KeyPostfix_DragDrop); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/RegistryContextMenu.h 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/RegistryContextMenu.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/RegistryContextMenu.h 2015-12-08 07:26:40.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/RegistryContextMenu.h 2023-01-10 18:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // RegistryContextMenu.h -#ifndef __REGISTRY_CONTEXT_MENU_H -#define __REGISTRY_CONTEXT_MENU_H +#ifndef ZIP7_INC_REGISTRY_CONTEXT_MENU_H +#define ZIP7_INC_REGISTRY_CONTEXT_MENU_H #ifndef UNDER_CE diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/resource2.rc 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/resource2.rc --- 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/resource2.rc 2013-12-30 08:37:01.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/resource2.rc 2023-01-04 20:00:00.000000000 +0000 @@ -13,6 +13,7 @@ IDS_CONTEXT_COMPRESS_TO "Add to {0}" IDS_CONTEXT_COMPRESS_EMAIL "Compress and email..." IDS_CONTEXT_COMPRESS_TO_EMAIL "Compress to {0} and email" + IDS_SELECT_FILES "You must select one or more files" END IDB_MENU_LOGO BITMAP "../../UI/Explorer/MenuLogo.bmp" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/resource.h 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/resource.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/resource.h 2014-04-23 07:52:29.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/resource.h 2023-01-04 20:00:00.000000000 +0000 @@ -10,4 +10,6 @@ #define IDS_CONTEXT_COMPRESS_EMAIL 2329 #define IDS_CONTEXT_COMPRESS_TO_EMAIL 2330 +#define IDS_SELECT_FILES 3015 + #define IDB_MENU_LOGO 190 diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Explorer/StdAfx.h 2014-04-23 08:53:56.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Explorer/StdAfx.h 2023-03-06 18:00:00.000000000 +0000 @@ -1,14 +1,6 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H - -// #define _WIN32_WINNT 0x0400 -#define _WIN32_WINNT 0x0500 -#define WINVER _WIN32_WINNT - -#include "../../../Common/Common.h" - -#include - +#if _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' #endif +#include "../FileManager/StdAfx.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/ExtractEngine.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Far/ExtractEngine.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/ExtractEngine.cpp 2021-10-21 18:19:13.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/ExtractEngine.cpp 2023-03-20 17:00:00.000000000 +0000 @@ -2,7 +2,7 @@ #include "StdAfx.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "../../../Windows/Synchronization.h" #endif @@ -16,7 +16,7 @@ using namespace NWindows; using namespace NFar; -#ifndef _7ZIP_ST +#ifndef Z7_ST static NSynchronization::CCriticalSection g_CriticalSection; #define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection); #else @@ -31,10 +31,6 @@ extern void PrintMessage(const char *message); -CExtractCallbackImp::~CExtractCallbackImp() -{ -} - void CExtractCallbackImp::Init( UINT codePage, CProgressBox *progressBox, @@ -47,7 +43,7 @@ _percent = progressBox; } -STDMETHODIMP CExtractCallbackImp::SetTotal(UInt64 size) +Z7_COM7F_IMF(CExtractCallbackImp::SetTotal(UInt64 size)) { MT_LOCK @@ -59,7 +55,7 @@ return CheckBreak2(); } -STDMETHODIMP CExtractCallbackImp::SetCompleted(const UInt64 *completeValue) +Z7_COM7F_IMF(CExtractCallbackImp::SetCompleted(const UInt64 *completeValue)) { MT_LOCK @@ -72,15 +68,15 @@ return CheckBreak2(); } -STDMETHODIMP CExtractCallbackImp::AskOverwrite( +Z7_COM7F_IMF(CExtractCallbackImp::AskOverwrite( const wchar_t *existName, const FILETIME *existTime, const UInt64 *existSize, const wchar_t *newName, const FILETIME *newTime, const UInt64 *newSize, - Int32 *answer) + Int32 *answer)) { MT_LOCK NOverwriteDialog::CFileInfo oldFileInfo, newFileInfo; - oldFileInfo.TimeIsDefined = (existTime != 0); + oldFileInfo.TimeIsDefined = (existTime != NULL); if (oldFileInfo.TimeIsDefined) oldFileInfo.Time = *existTime; oldFileInfo.SizeIsDefined = (existSize != NULL); @@ -88,7 +84,7 @@ oldFileInfo.Size = *existSize; oldFileInfo.Name = existName; - newFileInfo.TimeIsDefined = (newTime != 0); + newFileInfo.TimeIsDefined = (newTime != NULL); if (newFileInfo.TimeIsDefined) newFileInfo.Time = *newTime; newFileInfo.SizeIsDefined = (newSize != NULL); @@ -99,7 +95,7 @@ NOverwriteDialog::NResult::EEnum result = NOverwriteDialog::Execute(oldFileInfo, newFileInfo); - switch (result) + switch ((int)result) { case NOverwriteDialog::NResult::kCancel: // *answer = NOverwriteAnswer::kCancel; @@ -132,7 +128,7 @@ static const char * const kSkipString = "Skipping"; static const char * const kReadString = "Reading"; -STDMETHODIMP CExtractCallbackImp::PrepareOperation(const wchar_t *name, Int32 /* isFolder */, Int32 askExtractMode, const UInt64 * /* position */) +Z7_COM7F_IMF(CExtractCallbackImp::PrepareOperation(const wchar_t *name, Int32 /* isFolder */, Int32 askExtractMode, const UInt64 * /* position */)) { MT_LOCK @@ -146,7 +142,7 @@ case NArchive::NExtract::NAskMode::kSkip: s = kSkipString; break; case NArchive::NExtract::NAskMode::kReadExternal: s = kReadString; break; default: s = "???"; // return E_FAIL; - }; + } if (_percent) { @@ -158,7 +154,7 @@ return CheckBreak2(); } -STDMETHODIMP CExtractCallbackImp::MessageError(const wchar_t *message) +Z7_COM7F_IMF(CExtractCallbackImp::MessageError(const wchar_t *message)) { MT_LOCK @@ -199,7 +195,7 @@ } if (messageID != 0) { - s = g_StartupInfo.GetMsgString(messageID); + s = g_StartupInfo.GetMsgString((int)messageID); s.Replace((AString)" '%s'", AString()); } else if (opRes == NArchive::NExtract::NOperationResult::kUnavailable) @@ -217,13 +213,13 @@ else { s = "Error #"; - s.Add_UInt32(opRes); + s.Add_UInt32((UInt32)opRes); } } } } -STDMETHODIMP CExtractCallbackImp::SetOperationResult(Int32 opRes, Int32 encrypted) +Z7_COM7F_IMF(CExtractCallbackImp::SetOperationResult(Int32 opRes, Int32 encrypted)) { MT_LOCK @@ -248,7 +244,7 @@ } -STDMETHODIMP CExtractCallbackImp::ReportExtractResult(Int32 opRes, Int32 encrypted, const wchar_t *name) +Z7_COM7F_IMF(CExtractCallbackImp::ReportExtractResult(Int32 opRes, Int32 encrypted, const wchar_t *name)) { MT_LOCK @@ -265,13 +261,13 @@ extern HRESULT GetPassword(UString &password); -STDMETHODIMP CExtractCallbackImp::CryptoGetTextPassword(BSTR *password) +Z7_COM7F_IMF(CExtractCallbackImp::CryptoGetTextPassword(BSTR *password)) { MT_LOCK if (!m_PasswordIsDefined) { - RINOK(GetPassword(m_Password)); + RINOK(GetPassword(m_Password)) m_PasswordIsDefined = true; } return StringToBstr(m_Password, password); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/ExtractEngine.h 7zip-23.01+dfsg/CPP/7zip/UI/Far/ExtractEngine.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/ExtractEngine.h 2015-03-19 11:47:59.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/ExtractEngine.h 2023-03-19 09:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ExtractEngine.h -#ifndef __EXTRACT_ENGINE_H -#define __EXTRACT_ENGINE_H +#ifndef ZIP7_INC_EXTRACT_ENGINE_H +#define ZIP7_INC_EXTRACT_ENGINE_H #include "../../../Common/MyCom.h" #include "../../../Common/MyString.h" @@ -11,26 +11,14 @@ #include "ProgressBox.h" -class CExtractCallbackImp: - public IFolderArchiveExtractCallback, - public IFolderArchiveExtractCallback2, - public ICryptoGetTextPassword, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP2(ICryptoGetTextPassword, IFolderArchiveExtractCallback2) - - // IProgress - STDMETHOD(SetTotal)(UInt64 size); - STDMETHOD(SetCompleted)(const UInt64 *completeValue); - - INTERFACE_IFolderArchiveExtractCallback(;) - INTERFACE_IFolderArchiveExtractCallback2(;) - - // ICryptoGetTextPassword - STDMETHOD(CryptoGetTextPassword)(BSTR *password); +Z7_CLASS_IMP_COM_3( + CExtractCallbackImp + , IFolderArchiveExtractCallback + , IFolderArchiveExtractCallback2 + , ICryptoGetTextPassword +) + Z7_IFACE_COM7_IMP(IProgress) -private: UString m_CurrentFilePath; CProgressBox *_percent; @@ -47,8 +35,6 @@ */ void AddErrorMessage(LPCTSTR message); public: - // CExtractCallbackImp() {} - ~CExtractCallbackImp(); void Init(UINT codePage, CProgressBox *progressBox, bool passwordIsDefined, const UString &password); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/Far.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Far/Far.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/Far.cpp 2021-03-05 19:07:55.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/Far.cpp 2023-03-23 17:00:00.000000000 +0000 @@ -3,12 +3,7 @@ #include "StdAfx.h" -#ifdef __clang__ - #pragma clang diagnostic ignored "-Wmissing-prototypes" -#endif - #include "../../../Common/MyWindows.h" - #include "../../../Common/MyInitGuid.h" #include "../../../Common/StringConvert.h" @@ -35,10 +30,14 @@ static const char * const kHelpTopicConfig = "Config"; static bool kPluginEnabledDefault = true; +extern +HINSTANCE g_hInstance; HINSTANCE g_hInstance; namespace NFar { +extern +const char *g_PluginName_for_Error; const char *g_PluginName_for_Error = "7-Zip"; } @@ -49,9 +48,16 @@ BOOL WINAPI DllMain( #ifdef UNDER_CE - HANDLE + HANDLE #else - HINSTANCE + HINSTANCE + #endif + hInstance, DWORD dwReason, LPVOID); +BOOL WINAPI DllMain( + #ifdef UNDER_CE + HANDLE + #else + HINSTANCE #endif hInstance, DWORD dwReason, LPVOID) { @@ -89,7 +95,7 @@ EXTERN_C void WINAPI SetStartupInfo(const PluginStartupInfo *info) { - MY_TRY_BEGIN; + MY_TRY_BEGIN g_StartupInfo.Init(*info, kPliginNameForRegistry); g_Options.Enabled = g_StartupInfo.QueryRegKeyValue( HKEY_CURRENT_USER, kRegisrtryMainKeyName, @@ -98,18 +104,16 @@ // OutputDebugStringA("SetStartupInfo"); // LoadGlobalCodecs(); - MY_TRY_END1("SetStartupInfo"); + MY_TRY_END1("SetStartupInfo") } -class COpenArchiveCallback: - public IArchiveOpenCallback, - public IArchiveOpenVolumeCallback, - public IArchiveOpenSetSubArchiveName, - public IProgress, - public ICryptoGetTextPassword, - public CMyUnknownImp -{ - DWORD m_StartTickValue; +Z7_CLASS_IMP_COM_3( + COpenArchiveCallback + , IArchiveOpenCallback + , IProgress + , ICryptoGetTextPassword +) + // DWORD m_StartTickValue; bool m_MessageBoxIsShown; CProgressBox _progressBox; @@ -117,53 +121,17 @@ bool _numFilesTotalDefined; bool _numBytesTotalDefined; - NFind::CFileInfo _fileInfo; - bool _subArchiveMode; - UString _subArchiveName; public: bool PasswordIsDefined; UString Password; - FString _folderPrefix; - -public: - MY_UNKNOWN_IMP4( - IArchiveOpenVolumeCallback, - IArchiveOpenSetSubArchiveName, - IProgress, - ICryptoGetTextPassword - ) - - // IProgress - STDMETHOD(SetTotal)(UInt64 total); - STDMETHOD(SetCompleted)(const UInt64 *aCompleteValue); - - // IArchiveOpenCallback - STDMETHOD(SetTotal)(const UInt64 *numFiles, const UInt64 *numBytes); - STDMETHOD(SetCompleted)(const UInt64 *numFiles, const UInt64 *numBytes); - - // IArchiveOpenVolumeCallback - STDMETHOD(GetProperty)(PROPID propID, PROPVARIANT *value); - STDMETHOD(GetStream)(const wchar_t *name, IInStream **inStream); - - STDMETHOD(SetSubArchiveName(const wchar_t *name)) - { - _subArchiveMode = true; - _subArchiveName = name; - return S_OK; - } - - // ICryptoGetTextPassword - STDMETHOD(CryptoGetTextPassword)(BSTR *password); - - COpenArchiveCallback(): _subArchiveMode(false) {} + COpenArchiveCallback() + {} void Init() { PasswordIsDefined = false; - _subArchiveMode = false; - _numFilesTotalDefined = false; _numBytesTotalDefined = false; @@ -174,13 +142,6 @@ g_StartupInfo.GetMsgString(NMessageID::kReading)); } void ShowMessage(); - - void LoadFileInfo(const FString &folderPrefix, const FString &fileName) - { - _folderPrefix = folderPrefix; - if (!_fileInfo.Find(_folderPrefix + fileName)) - throw 1; - } }; static HRESULT CheckBreak2() @@ -202,7 +163,7 @@ _progressBox.Print(); } -STDMETHODIMP COpenArchiveCallback::SetTotal(const UInt64 *numFiles, const UInt64 *numBytes) +Z7_COM7F_IMF(COpenArchiveCallback::SetTotal(const UInt64 *numFiles, const UInt64 *numBytes)) { _numFilesTotalDefined = (numFiles != NULL); if (_numFilesTotalDefined) @@ -215,7 +176,7 @@ return CheckBreak2(); } -STDMETHODIMP COpenArchiveCallback::SetCompleted(const UInt64 *numFiles, const UInt64 *numBytes) +Z7_COM7F_IMF(COpenArchiveCallback::SetCompleted(const UInt64 *numFiles, const UInt64 *numBytes)) { if (numFiles) _progressBox.Files = *numFiles; @@ -228,63 +189,18 @@ } -STDMETHODIMP COpenArchiveCallback::SetTotal(const UInt64 /* total */) +Z7_COM7F_IMF(COpenArchiveCallback::SetTotal(const UInt64 /* total */)) { return CheckBreak2(); } -STDMETHODIMP COpenArchiveCallback::SetCompleted(const UInt64 * /* completed */) +Z7_COM7F_IMF(COpenArchiveCallback::SetCompleted(const UInt64 * /* completed */)) { ShowMessage(); return CheckBreak2(); } -STDMETHODIMP COpenArchiveCallback::GetStream(const wchar_t *name, IInStream **inStream) -{ - if (WasEscPressed()) - return E_ABORT; - if (_subArchiveMode) - return S_FALSE; - *inStream = NULL; - FString fullPath = _folderPrefix + us2fs(name); - if (!_fileInfo.Find(fullPath)) - return S_FALSE; - if (_fileInfo.IsDir()) - return S_FALSE; - CInFileStream *inFile = new CInFileStream; - CMyComPtr inStreamTemp = inFile; - if (!inFile->Open(fullPath)) - return ::GetLastError(); - *inStream = inStreamTemp.Detach(); - return S_OK; -} - - -STDMETHODIMP COpenArchiveCallback::GetProperty(PROPID propID, PROPVARIANT *value) -{ - NCOM::CPropVariant prop; - if (_subArchiveMode) - { - switch (propID) - { - case kpidName: prop = _subArchiveName; break; - } - } - else - switch (propID) - { - case kpidName: prop = GetUnicodeString(_fileInfo.Name, CP_OEMCP); break; - case kpidIsDir: prop = _fileInfo.IsDir(); break; - case kpidSize: prop = _fileInfo.Size; break; - case kpidAttrib: prop = (UInt32)_fileInfo.Attrib; break; - case kpidCTime: prop = _fileInfo.CTime; break; - case kpidATime: prop = _fileInfo.ATime; break; - case kpidMTime: prop = _fileInfo.MTime; break; - } - prop.Detach(value); - return S_OK; -} - +HRESULT GetPassword(UString &password); HRESULT GetPassword(UString &password) { if (WasEscPressed()) @@ -297,7 +213,7 @@ { DI_PSWEDIT, 5, 3, 70, 3, true, false, 0, true, -1, "", NULL } }; - const int kNumItems = ARRAY_SIZE(initItems); + const int kNumItems = Z7_ARRAY_SIZE(initItems); FarDialogItem dialogItems[kNumItems]; g_StartupInfo.InitDialogItems(initItems, dialogItems, kNumItems); @@ -309,11 +225,11 @@ return S_OK; } -STDMETHODIMP COpenArchiveCallback::CryptoGetTextPassword(BSTR *password) +Z7_COM7F_IMF(COpenArchiveCallback::CryptoGetTextPassword(BSTR *password)) { if (!PasswordIsDefined) { - RINOK(GetPassword(Password)); + RINOK(GetPassword(Password)) PasswordIsDefined = true; } return StringToBstr(Password, password); @@ -357,14 +273,19 @@ } COpenArchiveCallback *openArchiveCallbackSpec = new COpenArchiveCallback; - CMyComPtr openArchiveCallback = openArchiveCallbackSpec; + CMyComPtr uiCallback = openArchiveCallbackSpec; + + /* COpenCallbackImp object will exist after Open stage for multivolume archioves */ + COpenCallbackImp *impSpec = new COpenCallbackImp; + CMyComPtr impCallback = impSpec; + impSpec->ReOpenCallback = openArchiveCallbackSpec; // we set pointer without reference counter // if ((opMode & OPM_SILENT) == 0 && (opMode & OPM_FIND ) == 0) openArchiveCallbackSpec->Init(); { FString dirPrefix, fileName; GetFullPathAndSplit(fullName, dirPrefix, fileName); - openArchiveCallbackSpec->LoadFileInfo(dirPrefix, fileName); + impSpec->Init2(dirPrefix, fileName); } // ::OutputDebugStringA("before OpenArchive\n"); @@ -373,7 +294,7 @@ archiveHandler = agent; CMyComBSTR archiveType; HRESULT result = archiveHandler->Open(NULL, - GetUnicodeString(fullName, CP_OEMCP), UString(), &archiveType, openArchiveCallback); + GetUnicodeString(fullName, CP_OEMCP), UString(), &archiveType, impCallback); /* HRESULT result = ::OpenArchive(fullName, &archiveHandler, archiverInfoResult, defaultName, openArchiveCallback); @@ -427,7 +348,7 @@ EXTERN_C HANDLE WINAPI OpenFilePlugin(char *name, const unsigned char * /* data */, int /* dataSize */) { - MY_TRY_BEGIN; + MY_TRY_BEGIN // OutputDebugStringA("--- OpenFilePlugin"); if (name == NULL || (!g_Options.Enabled)) { @@ -435,13 +356,13 @@ return(INVALID_HANDLE_VALUE); } return MyOpenFilePlugin(name, true); // isAbortCodeSupported - MY_TRY_END2("OpenFilePlugin", INVALID_HANDLE_VALUE); + MY_TRY_END2("OpenFilePlugin", INVALID_HANDLE_VALUE) } /* EXTERN_C HANDLE WINAPI OpenFilePluginW(const wchar_t *name,const unsigned char *Data,int DataSize,int OpMode) { - MY_TRY_BEGIN; + MY_TRY_BEGIN if (name == NULL || (!g_Options.Enabled)) { // if (!Opt.ProcessShiftF1) @@ -455,7 +376,7 @@ EXTERN_C HANDLE WINAPI OpenPlugin(int openFrom, INT_PTR item) { - MY_TRY_BEGIN; + MY_TRY_BEGIN if (openFrom == OPEN_COMMANDLINE) { @@ -511,13 +432,13 @@ } return INVALID_HANDLE_VALUE; - MY_TRY_END2("OpenPlugin", INVALID_HANDLE_VALUE); + MY_TRY_END2("OpenPlugin", INVALID_HANDLE_VALUE) } EXTERN_C void WINAPI ClosePlugin(HANDLE plugin) { // OutputDebugStringA("-- ClosePlugin --- START"); - // MY_TRY_BEGIN; + // MY_TRY_BEGIN delete (CPlugin *)plugin; // OutputDebugStringA("-- ClosePlugin --- END"); // MY_TRY_END1("ClosePlugin"); @@ -525,14 +446,14 @@ EXTERN_C int WINAPI GetFindData(HANDLE plugin, struct PluginPanelItem **panelItems, int *itemsNumber, int opMode) { - MY_TRY_BEGIN; + MY_TRY_BEGIN return(((CPlugin *)plugin)->GetFindData(panelItems, itemsNumber, opMode)); - MY_TRY_END2("GetFindData", FALSE); + MY_TRY_END2("GetFindData", FALSE) } EXTERN_C void WINAPI FreeFindData(HANDLE plugin, struct PluginPanelItem *panelItems, int itemsNumber) { - // MY_TRY_BEGIN; + // MY_TRY_BEGIN ((CPlugin *)plugin)->FreeFindData(panelItems, itemsNumber); // MY_TRY_END1("FreeFindData"); } @@ -540,43 +461,43 @@ EXTERN_C int WINAPI GetFiles(HANDLE plugin, struct PluginPanelItem *panelItems, int itemsNumber, int move, char *destPath, int opMode) { - MY_TRY_BEGIN; - return(((CPlugin *)plugin)->GetFiles(panelItems, itemsNumber, move, destPath, opMode)); - MY_TRY_END2("GetFiles", NFileOperationReturnCode::kError); + MY_TRY_BEGIN + return(((CPlugin *)plugin)->GetFiles(panelItems, (unsigned)itemsNumber, move, destPath, opMode)); + MY_TRY_END2("GetFiles", NFileOperationReturnCode::kError) } EXTERN_C int WINAPI SetDirectory(HANDLE plugin, const char *dir, int opMode) { - MY_TRY_BEGIN; + MY_TRY_BEGIN return(((CPlugin *)plugin)->SetDirectory(dir, opMode)); - MY_TRY_END2("SetDirectory", FALSE); + MY_TRY_END2("SetDirectory", FALSE) } EXTERN_C void WINAPI GetPluginInfo(struct PluginInfo *info) { - MY_TRY_BEGIN; + MY_TRY_BEGIN info->StructSize = sizeof(*info); info->Flags = 0; info->DiskMenuStrings = NULL; info->DiskMenuNumbers = NULL; info->DiskMenuStringsNumber = 0; - static const char *pluginMenuStrings[2]; - pluginMenuStrings[0] = g_StartupInfo.GetMsgString(NMessageID::kOpenArchiveMenuString); - pluginMenuStrings[1] = g_StartupInfo.GetMsgString(NMessageID::kCreateArchiveMenuString); + static char *pluginMenuStrings[2]; + pluginMenuStrings[0] = const_cast(g_StartupInfo.GetMsgString(NMessageID::kOpenArchiveMenuString)); + pluginMenuStrings[1] = const_cast(g_StartupInfo.GetMsgString(NMessageID::kCreateArchiveMenuString)); info->PluginMenuStrings = (char **)pluginMenuStrings; info->PluginMenuStringsNumber = 2; - static const char *pluginCfgStrings[1]; - pluginCfgStrings[0] = g_StartupInfo.GetMsgString(NMessageID::kOpenArchiveMenuString); + static char *pluginCfgStrings[1]; + pluginCfgStrings[0] = const_cast(g_StartupInfo.GetMsgString(NMessageID::kOpenArchiveMenuString)); info->PluginConfigStrings = (char **)pluginCfgStrings; - info->PluginConfigStringsNumber = ARRAY_SIZE(pluginCfgStrings); - info->CommandPrefix = (char *)kCommandPrefix; - MY_TRY_END1("GetPluginInfo"); + info->PluginConfigStringsNumber = Z7_ARRAY_SIZE(pluginCfgStrings); + info->CommandPrefix = const_cast(kCommandPrefix); + MY_TRY_END1("GetPluginInfo") } EXTERN_C int WINAPI Configure(int /* itemNumber */) { - MY_TRY_BEGIN; + MY_TRY_BEGIN const int kEnabledCheckBoxIndex = 1; @@ -591,7 +512,7 @@ { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kCancel, NULL, NULL }, }; - const int kNumDialogItems = ARRAY_SIZE(initItems); + const int kNumDialogItems = Z7_ARRAY_SIZE(initItems); const int kOkButtonIndex = kNumDialogItems - 2; FarDialogItem dialogItems[kNumDialogItems]; @@ -608,33 +529,59 @@ g_StartupInfo.SetRegKeyValue(HKEY_CURRENT_USER, kRegisrtryMainKeyName, kRegisrtryValueNameEnabled, g_Options.Enabled); return(TRUE); - MY_TRY_END2("Configure", FALSE); + MY_TRY_END2("Configure", FALSE) } EXTERN_C void WINAPI GetOpenPluginInfo(HANDLE plugin,struct OpenPluginInfo *info) { - MY_TRY_BEGIN; + MY_TRY_BEGIN ((CPlugin *)plugin)->GetOpenPluginInfo(info); - MY_TRY_END1("GetOpenPluginInfo"); + MY_TRY_END1("GetOpenPluginInfo") } EXTERN_C int WINAPI PutFiles(HANDLE plugin, struct PluginPanelItem *panelItems, int itemsNumber, int move, int opMode) { - MY_TRY_BEGIN; - return (((CPlugin *)plugin)->PutFiles(panelItems, itemsNumber, move, opMode)); - MY_TRY_END2("PutFiles", NFileOperationReturnCode::kError); + MY_TRY_BEGIN + return (((CPlugin *)plugin)->PutFiles(panelItems, (unsigned)itemsNumber, move, opMode)); + MY_TRY_END2("PutFiles", NFileOperationReturnCode::kError) } EXTERN_C int WINAPI DeleteFiles(HANDLE plugin, PluginPanelItem *panelItems, int itemsNumber, int opMode) { - MY_TRY_BEGIN; - return (((CPlugin *)plugin)->DeleteFiles(panelItems, itemsNumber, opMode)); - MY_TRY_END2("DeleteFiles", FALSE); + MY_TRY_BEGIN + return (((CPlugin *)plugin)->DeleteFiles(panelItems, (unsigned)itemsNumber, opMode)); + MY_TRY_END2("DeleteFiles", FALSE) } EXTERN_C int WINAPI ProcessKey(HANDLE plugin, int key, unsigned int controlState) { - MY_TRY_BEGIN; + MY_TRY_BEGIN + /* FIXME: after folder creation with F7, it doesn't reload new file list + We need some to reload it */ return (((CPlugin *)plugin)->ProcessKey(key, controlState)); - MY_TRY_END2("ProcessKey", FALSE); + MY_TRY_END2("ProcessKey", FALSE) } + +/* +struct MakeDirectoryInfo +{ + size_t StructSize; + HANDLE hPanel; + const wchar_t *Name; + OPERATION_MODES OpMode; + void* Instance; +}; + +typedef INT_PTR MY_intptr_t; + +MY_intptr_t WINAPI MakeDirectoryW(struct MakeDirectoryInfo *Info) +{ + MY_TRY_BEGIN + if (Info->StructSize < sizeof(MakeDirectoryInfo)) + { + return 0; + } + return 0; + MY_TRY_END2("MakeDirectoryW", FALSE); +} +*/ diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/Far.dsp 7zip-23.01+dfsg/CPP/7zip/UI/Far/Far.dsp --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/Far.dsp 2021-10-07 18:28:11.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/Far.dsp 2023-03-25 16:00:00.000000000 +0000 @@ -43,7 +43,7 @@ # PROP Ignore_Export_Lib 1 # PROP Target_Dir "" # ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FAR_EXPORTS" /YX /FD /c -# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FAR_EXPORTS" /D "EXTERNAL_CODECS" /D "NEW_FOLDER_INTERFACE" /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FAR_EXPORTS" /D "Z7_EXTERNAL_CODECS" /Yu"StdAfx.h" /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "NDEBUG" @@ -70,7 +70,7 @@ # PROP Ignore_Export_Lib 1 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FAR_EXPORTS" /YX /FD /GZ /c -# ADD CPP /nologo /Gz /MTd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FAR_EXPORTS" /D "EXTERNAL_CODECS" /D "NEW_FOLDER_INTERFACE" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gz /MTd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FAR_EXPORTS" /D "Z7_EXTERNAL_CODECS" /Yu"StdAfx.h" /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "_DEBUG" @@ -114,6 +114,10 @@ # PROP Default_Filter "" # Begin Source File +SOURCE=..\..\..\Common\Common.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\CRC.cpp # End Source File # Begin Source File @@ -134,6 +138,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyCom.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\MyString.cpp # End Source File # Begin Source File @@ -142,6 +150,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyTypes.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\MyVector.cpp # End Source File # Begin Source File @@ -150,6 +162,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\NewHandler.cpp # End Source File # Begin Source File @@ -334,6 +350,14 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Windows\FileSystem.cpp +# End Source File +# Begin Source File + +SOURCE=..\..\..\Windows\FileSystem.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Windows\PropVariant.cpp # End Source File # Begin Source File @@ -374,6 +398,14 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Windows\System.cpp +# End Source File +# Begin Source File + +SOURCE=..\..\..\Windows\System.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Windows\TimeUtils.cpp # End Source File # Begin Source File @@ -562,10 +594,6 @@ # End Source File # Begin Source File -SOURCE=..\Agent\ArchiveFolderOpen.cpp -# End Source File -# Begin Source File - SOURCE=..\Agent\ArchiveFolderOut.cpp # End Source File # Begin Source File @@ -700,6 +728,14 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\7zTypes.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\7zWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\Alloc.c # SUBTRACT CPP /YX /Yc /Yu # End Source File @@ -709,6 +745,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\Compiler.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\CpuArch.c # SUBTRACT CPP /YX /Yc /Yu # End Source File diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/FarPlugin.h 7zip-23.01+dfsg/CPP/7zip/UI/Far/FarPlugin.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/FarPlugin.h 2015-03-21 12:27:41.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/FarPlugin.h 2023-03-25 13:00:00.000000000 +0000 @@ -16,8 +16,8 @@ } CHAR_INFO, *PCHAR_INFO; #endif -#ifndef __FAR_PLUGIN_H -#define __FAR_PLUGIN_H +#ifndef ZIP7_INC_FAR_PLUGIN_H +#define ZIP7_INC_FAR_PLUGIN_H #ifndef _WIN64 #if defined(__BORLANDC__) && (__BORLANDC <= 0x520) @@ -525,5 +525,36 @@ EXTERN_C_END */ +EXTERN_C_BEGIN + + void WINAPI _export ClosePlugin(HANDLE hPlugin); + int WINAPI _export Compare(HANDLE hPlugin,const struct PluginPanelItem *Item1,const struct PluginPanelItem *Item2,unsigned int Mode); + int WINAPI _export Configure(int ItemNumber); + int WINAPI _export DeleteFiles(HANDLE hPlugin,struct PluginPanelItem *PanelItem,int ItemsNumber,int OpMode); + void WINAPI _export ExitFAR(void); + void WINAPI _export FreeFindData(HANDLE hPlugin,struct PluginPanelItem *PanelItem,int ItemsNumber); + void WINAPI _export FreeVirtualFindData(HANDLE hPlugin,struct PluginPanelItem *PanelItem,int ItemsNumber); + int WINAPI _export GetFiles(HANDLE hPlugin,struct PluginPanelItem *PanelItem,int ItemsNumber,int Move,char *DestPath,int OpMode); + int WINAPI _export GetFindData(HANDLE hPlugin,struct PluginPanelItem **pPanelItem,int *pItemsNumber,int OpMode); + int WINAPI _export GetMinFarVersion(void); + void WINAPI _export GetOpenPluginInfo(HANDLE hPlugin,struct OpenPluginInfo *Info); + void WINAPI _export GetPluginInfo(struct PluginInfo *Info); + int WINAPI _export GetVirtualFindData(HANDLE hPlugin,struct PluginPanelItem **pPanelItem,int *pItemsNumber,const char *Path); + int WINAPI _export MakeDirectory(HANDLE hPlugin,char *Name,int OpMode); + HANDLE WINAPI _export OpenFilePlugin(char *Name,const unsigned char *Data,int DataSize); + HANDLE WINAPI _export OpenPlugin(int OpenFrom,INT_PTR Item); + int WINAPI _export ProcessDialogEvent(int Event,void *Param); + int WINAPI _export ProcessEditorEvent(int Event,void *Param); + int WINAPI _export ProcessEditorInput(const INPUT_RECORD *Rec); + int WINAPI _export ProcessEvent(HANDLE hPlugin,int Event,void *Param); + int WINAPI _export ProcessHostFile(HANDLE hPlugin,struct PluginPanelItem *PanelItem,int ItemsNumber,int OpMode); + int WINAPI _export ProcessKey(HANDLE hPlugin,int Key,unsigned int ControlState); + int WINAPI _export ProcessViewerEvent(int Event,void *Param); + int WINAPI _export PutFiles(HANDLE hPlugin,struct PluginPanelItem *PanelItem,int ItemsNumber,int Move,int OpMode); + int WINAPI _export SetDirectory(HANDLE hPlugin,const char *Dir,int OpMode); + int WINAPI _export SetFindList(HANDLE hPlugin,const struct PluginPanelItem *PanelItem,int ItemsNumber); + void WINAPI _export SetStartupInfo(const struct PluginStartupInfo *Info); + +EXTERN_C_END #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/FarUtils.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Far/FarUtils.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/FarUtils.cpp 2021-12-15 19:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/FarUtils.cpp 2023-03-19 09:00:00.000000000 +0000 @@ -36,10 +36,10 @@ } int CStartupInfo::ShowMessage(unsigned int flags, - const char *helpTopic, const char **items, int numItems, int numButtons) + const char *helpTopic, const char **items, unsigned numItems, int numButtons) { return m_Data.Message(m_Data.ModuleNumber, flags, helpTopic, - items, numItems, numButtons); + items, (int)numItems, numButtons); } namespace NMessageID @@ -53,7 +53,7 @@ }; } -int CStartupInfo::ShowWarningWithOk(const char **items, int numItems) +int CStartupInfo::ShowWarningWithOk(const char **items, unsigned numItems) { return ShowMessage(FMSG_WARNING | FMSG_MB_OK, NULL, items, numItems, 0); } @@ -76,7 +76,7 @@ AString s; SetErrorTitle(s); const char *items[]= { s, message }; - return ShowWarningWithOk(items, ARRAY_SIZE(items)); + return ShowWarningWithOk(items, Z7_ARRAY_SIZE(items)); } */ @@ -85,7 +85,7 @@ AString s; SetErrorTitle(s); const char *items[]= { s, m1, m2 }; - return ShowWarningWithOk(items, ARRAY_SIZE(items)); + return ShowWarningWithOk(items, Z7_ARRAY_SIZE(items)); } static void SplitString(const AString &src, AStringVector &destStrings) @@ -145,14 +145,14 @@ } int CStartupInfo::ShowDialog(int X1, int Y1, int X2, int Y2, - const char *helpTopic, struct FarDialogItem *items, int numItems) + const char *helpTopic, struct FarDialogItem *items, unsigned numItems) { - return m_Data.Dialog(m_Data.ModuleNumber, X1, Y1, X2, Y2, (char *)helpTopic, - items, numItems); + return m_Data.Dialog(m_Data.ModuleNumber, X1, Y1, X2, Y2, const_cast(helpTopic), + items, (int)numItems); } int CStartupInfo::ShowDialog(int sizeX, int sizeY, - const char *helpTopic, struct FarDialogItem *items, int numItems) + const char *helpTopic, struct FarDialogItem *items, unsigned numItems) { return ShowDialog(-1, -1, sizeX, sizeY, helpTopic, items, numItems); } @@ -160,9 +160,9 @@ inline static BOOL GetBOOLValue(bool v) { return (v? TRUE: FALSE); } void CStartupInfo::InitDialogItems(const CInitDialogItem *srcItems, - FarDialogItem *destItems, int numItems) + FarDialogItem *destItems, unsigned numItems) { - for (int i = 0; i < numItems; i++) + for (unsigned i = 0; i < numItems; i++) { const CInitDialogItem &srcItem = srcItems[i]; FarDialogItem &destItem = destItems[i]; @@ -356,7 +356,7 @@ if (!ControlGetActivePanelInfo(panelInfo)) return false; for (int i = 0; i < panelInfo.ItemsNumber; i++) - panelInfo.PanelItems[i].Flags &= ~PPIF_SELECTED; + panelInfo.PanelItems[i].Flags &= ~(DWORD)PPIF_SELECTED; return ControlSetSelection(panelInfo); } @@ -374,10 +374,13 @@ int *breakKeys, int *breakCode, struct FarMenuItem *items, - int numItems) + unsigned numItems) { - return m_Data.Menu(m_Data.ModuleNumber, x, y, maxHeight, flags, (char *)title, - (char *)aBottom, (char *)helpTopic, breakKeys, breakCode, items, numItems); + return m_Data.Menu(m_Data.ModuleNumber, x, y, maxHeight, flags, + const_cast(title), + const_cast(aBottom), + const_cast(helpTopic), + breakKeys, breakCode, items, (int)numItems); } int CStartupInfo::Menu( @@ -385,7 +388,7 @@ const char *title, const char *helpTopic, struct FarMenuItem *items, - int numItems) + unsigned numItems) { return Menu(-1, -1, 0, flags, title, NULL, helpTopic, NULL, NULL, items, numItems); @@ -405,7 +408,7 @@ item.Checked = 0; item.Separator = 0; item.Selected = ((int)i == selectedItem); - const AString reducedString (items[i].Left(ARRAY_SIZE(item.Text) - 1)); + const AString reducedString (items[i].Left(Z7_ARRAY_SIZE(item.Text) - 1)); MyStringCopy(item.Text, reducedString); farMenuItems.Add(item); } @@ -435,7 +438,7 @@ g_StartupInfo.RestoreScreen(m_HANDLE); m_Saved = false; } -}; +} int PrintErrorMessage(const char *message, unsigned code) { @@ -471,7 +474,7 @@ int ShowSysErrorMessage(DWORD errorCode) { - UString message = NError::MyFormatMessage(errorCode); + const UString message = NError::MyFormatMessage(errorCode); return g_StartupInfo.ShowErrorMessage(UnicodeStringToMultiByte(message, CP_OEMCP)); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/FarUtils.h 7zip-23.01+dfsg/CPP/7zip/UI/Far/FarUtils.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/FarUtils.h 2017-03-26 10:32:33.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/FarUtils.h 2023-01-22 21:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // FarUtils.h -#ifndef __FAR_UTILS_H -#define __FAR_UTILS_H +#ifndef ZIP7_INC_FAR_UTILS_H +#define ZIP7_INC_FAR_UTILS_H #include "FarPlugin.h" @@ -61,8 +61,8 @@ const char *GetMsgString(int messageId); int ShowMessage(unsigned int flags, const char *helpTopic, - const char **items, int numItems, int numButtons); - int ShowWarningWithOk(const char **items, int numItems); + const char **items, unsigned numItems, int numButtons); + int ShowWarningWithOk(const char **items, unsigned numItems); void SetErrorTitle(AString &s); int ShowErrorMessage(const char *message); @@ -71,12 +71,12 @@ int ShowMessage(int messageId); int ShowDialog(int X1, int Y1, int X2, int Y2, - const char *helpTopic, struct FarDialogItem *items, int numItems); + const char *helpTopic, struct FarDialogItem *items, unsigned numItems); int ShowDialog(int sizeX, int sizeY, - const char *helpTopic, struct FarDialogItem *items, int numItems); + const char *helpTopic, struct FarDialogItem *items, unsigned numItems); void InitDialogItems(const CInitDialogItem *srcItems, - FarDialogItem *destItems, int numItems); + FarDialogItem *destItems, unsigned numItems); HANDLE SaveScreen(int X1, int Y1, int X2, int Y2); HANDLE SaveScreen(); @@ -119,13 +119,13 @@ int *breakKeys, int *breakCode, FarMenuItem *items, - int numItems); + unsigned numItems); int Menu( unsigned int flags, const char *title, const char *helpTopic, FarMenuItem *items, - int numItems); + unsigned numItems); int Menu( unsigned int flags, @@ -136,14 +136,14 @@ int Editor(const char *fileName, const char *title, int X1, int Y1, int X2, int Y2, DWORD flags, int startLine, int startChar) - { return m_Data.Editor((char *)fileName, (char *)title, X1, Y1, X2, Y2, + { return m_Data.Editor(const_cast(fileName), const_cast(title), X1, Y1, X2, Y2, flags, startLine, startChar); } int Editor(const char *fileName) { return Editor(fileName, NULL, 0, 0, -1, -1, 0, -1, -1); } int Viewer(const char *fileName, const char *title, int X1, int Y1, int X2, int Y2, DWORD flags) - { return m_Data.Viewer((char *)fileName, (char *)title, X1, Y1, X2, Y2, flags); } + { return m_Data.Viewer(const_cast(fileName), const_cast(title), X1, Y1, X2, Y2, flags); } int Viewer(const char *fileName) { return Viewer(fileName, NULL, 0, 0, -1, -1, VF_NONMODAL); } @@ -154,7 +154,7 @@ bool m_Saved; HANDLE m_HANDLE; public: - CScreenRestorer(): m_Saved(false){}; + CScreenRestorer(): m_Saved(false) {} ~CScreenRestorer(); void Save(); void Restore(); @@ -184,10 +184,16 @@ catch(const wchar_t *s) { PrintErrorMessage(x, s); return y; }\ catch(...) { g_StartupInfo.ShowErrorMessage(x); return y; } + int ShowSysErrorMessage(DWORD errorCode); int ShowSysErrorMessage(DWORD errorCode, const wchar_t *name); int ShowLastErrorMessage(); +inline int ShowSysErrorMessage(HRESULT errorCode) + { return ShowSysErrorMessage((DWORD)errorCode); } +inline int ShowSysErrorMessage(HRESULT errorCode, const wchar_t *name) + { return ShowSysErrorMessage((DWORD)errorCode, name); } + bool WasEscPressed(); void ReduceString(UString &s, unsigned size); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/makefile 7zip-23.01+dfsg/CPP/7zip/UI/Far/makefile --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/makefile 2021-10-08 12:31:25.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/makefile 2023-04-01 13:00:00.000000000 +0000 @@ -1,11 +1,10 @@ PROG = 7-ZipFar.dll DEF_FILE = Far.def CFLAGS = $(CFLAGS) \ - -DEXTERNAL_CODECS \ - -DNEW_FOLDER_INTERFACE + -DZ7_EXTERNAL_CODECS \ !IFNDEF UNDER_CE -CFLAGS = $(CFLAGS) -DWIN_LONG_PATH +CFLAGS = $(CFLAGS) -DZ7_LONG_PATH !ENDIF CURRENT_OBJS = \ @@ -40,11 +39,13 @@ $O\FileIO.obj \ $O\FileLink.obj \ $O\FileName.obj \ + $O\FileSystem.obj \ $O\PropVariant.obj \ $O\PropVariantConv.obj \ $O\Registry.obj \ $O\ResourceString.obj \ $O\Synchronization.obj \ + $O\System.obj \ $O\TimeUtils.obj \ 7ZIP_COMMON_OBJS = \ @@ -88,7 +89,6 @@ $O\AgentOut.obj \ $O\AgentProxy.obj \ $O\ArchiveFolder.obj \ - $O\ArchiveFolderOpen.obj \ $O\ArchiveFolderOut.obj \ $O\UpdateCallbackAgent.obj \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/Messages.h 7zip-23.01+dfsg/CPP/7zip/UI/Far/Messages.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/Messages.h 2017-05-05 09:10:41.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/Messages.h 2023-03-25 13:00:00.000000000 +0000 @@ -1,13 +1,13 @@ // Far/Messages.h -#ifndef __7ZIP_FAR_MESSAGES_H -#define __7ZIP_FAR_MESSAGES_H +#ifndef ZIP7_INC_FAR_MESSAGES_H +#define ZIP7_INC_FAR_MESSAGES_H #include "../../PropID.h" namespace NMessageID { -const unsigned k_Last_PropId_supported_by_plugin = kpidCopyLink; +const unsigned k_Last_PropId_supported_by_plugin = kpidDevMinor; enum EEnum { diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/OverwriteDialogFar.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Far/OverwriteDialogFar.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/OverwriteDialogFar.cpp 2021-02-10 17:49:28.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/OverwriteDialogFar.cpp 2023-03-25 13:00:00.000000000 +0000 @@ -35,7 +35,7 @@ { ConvertUInt64ToString(fileInfo.Size, buffer); fileInfoStrings.Size = buffer; - fileInfoStrings.Size += ' '; + fileInfoStrings.Size.Add_Space(); fileInfoStrings.Size += g_StartupInfo.GetMsgString(NMessageID::kOverwriteBytes); } else @@ -49,7 +49,7 @@ char timeString[32]; ConvertUtcFileTimeToString(fileInfo.Time, timeString); fileInfoStrings.Time = g_StartupInfo.GetMsgString(NMessageID::kOverwriteModifiedOn); - fileInfoStrings.Time += ' '; + fileInfoStrings.Time.Add_Space(); fileInfoStrings.Time += timeString; } } @@ -96,12 +96,12 @@ ReduceString2(name2, maxNameLen - kNameOffset); } - AString pref1A (UnicodeStringToMultiByte(pref1, CP_OEMCP)); - AString pref2A (UnicodeStringToMultiByte(pref2, CP_OEMCP)); - AString name1A (UnicodeStringToMultiByte(name1, CP_OEMCP)); - AString name2A (UnicodeStringToMultiByte(name2, CP_OEMCP)); + const AString pref1A (UnicodeStringToMultiByte(pref1, CP_OEMCP)); + const AString pref2A (UnicodeStringToMultiByte(pref2, CP_OEMCP)); + const AString name1A (UnicodeStringToMultiByte(name1, CP_OEMCP)); + const AString name2A (UnicodeStringToMultiByte(name2, CP_OEMCP)); - struct CInitDialogItem initItems[]={ + const struct CInitDialogItem initItems[]={ { DI_DOUBLEBOX, 3, 1, kXSize - 4, kYSize - 2, false, false, 0, false, NMessageID::kOverwriteTitle, NULL, NULL }, { DI_TEXT, 5, 2, 0, 0, false, false, 0, false, NMessageID::kOverwriteMessage1, NULL, NULL }, @@ -131,10 +131,10 @@ { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kOverwriteCancel, NULL, NULL } }; - const int kNumDialogItems = ARRAY_SIZE(initItems); + const int kNumDialogItems = Z7_ARRAY_SIZE(initItems); FarDialogItem aDialogItems[kNumDialogItems]; g_StartupInfo.InitDialogItems(initItems, aDialogItems, kNumDialogItems); - int anAskCode = g_StartupInfo.ShowDialog(kXSize, kYSize, + const int anAskCode = g_StartupInfo.ShowDialog(kXSize, kYSize, NULL, aDialogItems, kNumDialogItems); const int kButtonStartPos = kNumDialogItems - 6; if (anAskCode >= kButtonStartPos && anAskCode < kNumDialogItems) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/OverwriteDialogFar.h 7zip-23.01+dfsg/CPP/7zip/UI/Far/OverwriteDialogFar.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/OverwriteDialogFar.h 2013-01-25 07:27:28.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/OverwriteDialogFar.h 2023-01-22 20:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // OverwriteDialogFar.h -#ifndef __OVERWRITE_DIALOG_FAR_H -#define __OVERWRITE_DIALOG_FAR_H +#ifndef ZIP7_INC_OVERWRITE_DIALOG_FAR_H +#define ZIP7_INC_OVERWRITE_DIALOG_FAR_H #include "../../../Common/MyString.h" #include "../../../Common/MyTypes.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/Plugin.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Far/Plugin.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/Plugin.cpp 2021-10-21 18:31:59.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/Plugin.cpp 2023-03-06 17:00:00.000000000 +0000 @@ -20,13 +20,13 @@ using namespace NDir; using namespace NFar; -// This function is unused +// This function is used by CAgentFolder +int CompareFileNames_ForFolderList(const wchar_t *s1, const wchar_t *s2); int CompareFileNames_ForFolderList(const wchar_t *s1, const wchar_t *s2) { return MyStringCompareNoCase(s1, s2); } - CPlugin::CPlugin(const FString &fileName, CAgent *agent, UString archiveTypeName): _agent(agent), m_FileName(fileName), @@ -72,7 +72,7 @@ dest[len] = 0; } -#define COPY_STR_LIMITED(dest, src) CopyStrLimited(dest, src, ARRAY_SIZE(dest)) +#define COPY_STR_LIMITED(dest, src) CopyStrLimited(dest, src, Z7_ARRAY_SIZE(dest)) void CPlugin::ReadPluginPanelItem(PluginPanelItem &panelItem, UInt32 itemIndex) { @@ -156,7 +156,7 @@ g_StartupInfo.GetMsgString(NMessageID::kWaitTitle), g_StartupInfo.GetMsgString(NMessageID::kReadingList) }; - g_StartupInfo.ShowMessage(0, NULL, msgItems, ARRAY_SIZE(msgItems), 0); + g_StartupInfo.ShowMessage(0, NULL, msgItems, Z7_ARRAY_SIZE(msgItems), 0); */ } @@ -177,7 +177,7 @@ delete [](*panelItems); throw; } - *itemsNumber = numItems; + *itemsNumber = (int)numItems; return(TRUE); } @@ -291,7 +291,7 @@ { if (propID > NMessageID::k_Last_PropId_supported_by_plugin) return -1; - return NMessageID::kNoProperty + propID; + return NMessageID::kNoProperty + (int)propID; } /* @@ -324,7 +324,7 @@ // { kpidType, L"Type" } }; -static const int kNumPropertyIDInfos = ARRAY_SIZE(kPropertyIDInfos); +static const int kNumPropertyIDInfos = Z7_ARRAY_SIZE(kPropertyIDInfos); static int FindPropertyInfo(PROPID propID) { @@ -395,7 +395,7 @@ char s[32]; ConvertUInt64ToString(value, s); unsigned i = MyStringLen(s); - unsigned pos = ARRAY_SIZE(s); + unsigned pos = Z7_ARRAY_SIZE(s); s[--pos] = 0; while (i > 3) { @@ -597,7 +597,7 @@ case -2: propID = kpidType; break; case -1: propID = kpidError; break; default: - if (getProps->GetArcPropInfo(level, i, &name, &propID, &vt) != S_OK) + if (getProps->GetArcPropInfo(level, (UInt32)i, &name, &propID, &vt) != S_OK) continue; } NCOM::CPropVariant prop; @@ -619,7 +619,7 @@ CMyComBSTR name; PROPID propID; VARTYPE vt; - if (getProps->GetArcPropInfo2(level, i, &name, &propID, &vt) != S_OK) + if (getProps->GetArcPropInfo2(level, (UInt32)i, &name, &propID, &vt) != S_OK) continue; NCOM::CPropVariant prop; if (getProps->GetArcProp2(level, propID, &prop) != S_OK) @@ -636,7 +636,7 @@ //m_InfoLines[1].Separator = 0; info->InfoLines = m_InfoLines; - info->InfoLinesNumber = numItems; + info->InfoLinesNumber = (int)numItems; info->DescrFiles = NULL; @@ -654,19 +654,19 @@ AddColumn(kpidATime); AddColumn(kpidAttrib); - _PanelMode.ColumnTypes = (char *)(const char *)PanelModeColumnTypes; - _PanelMode.ColumnWidths = (char *)(const char *)PanelModeColumnWidths; - _PanelMode.ColumnTitles = NULL; - _PanelMode.FullScreen = TRUE; - _PanelMode.DetailedStatus = FALSE; - _PanelMode.AlignExtensions = FALSE; - _PanelMode.CaseConversion = FALSE; - _PanelMode.StatusColumnTypes = "N"; - _PanelMode.StatusColumnWidths = "0"; - _PanelMode.Reserved[0] = 0; - _PanelMode.Reserved[1] = 0; + _panelMode.ColumnTypes = (char *)(const char *)PanelModeColumnTypes; + _panelMode.ColumnWidths = (char *)(const char *)PanelModeColumnWidths; + _panelMode.ColumnTitles = NULL; + _panelMode.FullScreen = TRUE; + _panelMode.DetailedStatus = FALSE; + _panelMode.AlignExtensions = FALSE; + _panelMode.CaseConversion = FALSE; + _panelMode.StatusColumnTypes = "N"; + _panelMode.StatusColumnWidths = "0"; + _panelMode.Reserved[0] = 0; + _panelMode.Reserved[1] = 0; - info->PanelModesArray = &_PanelMode; + info->PanelModesArray = &_panelMode; info->PanelModesNumber = 1; */ @@ -704,18 +704,18 @@ if (strcmp(pluginPanelItem.FindData.cFileName, "..") == 0 && NFind::NAttributes::IsDir(pluginPanelItem.FindData.dwFileAttributes)) return S_FALSE; - int itemIndex = (int)pluginPanelItem.UserData; + const UInt32 itemIndex = (UInt32)pluginPanelItem.UserData; CObjectVector properties; UInt32 numProps; - RINOK(_folder->GetNumberOfProperties(&numProps)); + RINOK(_folder->GetNumberOfProperties(&numProps)) unsigned i; for (i = 0; i < numProps; i++) { CMyComBSTR name; PROPID propID; VARTYPE vt; - RINOK(_folder->GetPropertyInfo(i, &name, &propID, &vt)); + RINOK(_folder->GetPropertyInfo(i, &name, &propID, &vt)) CArchiveItemProperty prop; prop.Type = vt; prop.ID = propID; @@ -743,7 +743,7 @@ { const CArchiveItemProperty &property = properties[i]; - int startY = kStartY + values.Size(); + const int startY = kStartY + (int)values.Size(); { CInitDialogItem idi = @@ -755,7 +755,7 @@ } NCOM::CPropVariant prop; - RINOK(_folder->GetProperty(itemIndex, property.ID, &prop)); + RINOK(_folder->GetProperty(itemIndex, property.ID, &prop)) values.Add(PropToString(prop, property.ID)); { @@ -834,7 +834,7 @@ } } - int startY = kStartY + values.Size(); + const int startY = kStartY + (int)values.Size(); { CInitDialogItem idi = @@ -856,14 +856,14 @@ } } - unsigned numLines = values.Size(); + const unsigned numLines = values.Size(); for (i = 0; i < numLines; i++) { CInitDialogItem &idi = initDialogItems[1 + i * 2 + 1]; idi.DataString = values[i]; } - unsigned numDialogItems = initDialogItems.Size(); + const unsigned numDialogItems = initDialogItems.Size(); CObjArray dialogItems(numDialogItems); g_StartupInfo.InitDialogItems(&initDialogItems.Front(), dialogItems, numDialogItems); @@ -884,14 +884,14 @@ for (i = 0; i < numLines; i++) { FarDialogItem &dialogItem = dialogItems[1 + i * 2 + 1]; - unsigned len = (int)strlen(dialogItem.Data); + const unsigned len = (unsigned)strlen(dialogItem.Data); if (len > maxLen2) maxLen2 = len; - dialogItem.X1 = maxLen + kSpace; + dialogItem.X1 = (int)(maxLen + kSpace); } - size = numLines + 6; - xSize = maxLen + kSpace + maxLen2 + 5; + size = (int)numLines + 6; + xSize = (int)(maxLen + kSpace + maxLen2 + 5); FarDialogItem &firstDialogItem = dialogItems[0]; firstDialogItem.Y2 = size - 2; firstDialogItem.X2 = xSize - 4; @@ -926,7 +926,7 @@ PanelInfo panelInfo; g_StartupInfo.ControlGetActivePanelInfo(panelInfo); GetFilesReal(panelInfo.SelectedItems, - panelInfo.SelectedItemsNumber, FALSE, + (unsigned)panelInfo.SelectedItemsNumber, FALSE, UnicodeStringToMultiByte(fs2us(folderPath), CP_OEMCP), OPM_SILENT, true); g_StartupInfo.Control(this, FCTL_UPDATEPANEL, NULL); g_StartupInfo.Control(this, FCTL_REDRAWPANEL, NULL); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/PluginDelete.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Far/PluginDelete.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/PluginDelete.cpp 2021-10-27 12:20:37.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/PluginDelete.cpp 2023-03-19 09:00:00.000000000 +0000 @@ -13,7 +13,7 @@ using namespace NFar; -int CPlugin::DeleteFiles(PluginPanelItem *panelItems, int numItems, int opMode) +int CPlugin::DeleteFiles(PluginPanelItem *panelItems, unsigned numItems, int opMode) { if (numItems == 0) return FALSE; @@ -63,7 +63,7 @@ // sprintf(msg, g_StartupInfo.GetMsgString(NMessageID::kDeleteNumberOfFiles), numItems); // msgItems[1] = msg; } - if (g_StartupInfo.ShowMessage(FMSG_WARNING, NULL, msgItems, ARRAY_SIZE(msgItems), 2) != 0) + if (g_StartupInfo.ShowMessage(FMSG_WARNING, NULL, msgItems, Z7_ARRAY_SIZE(msgItems), 2) != 0) return (FALSE); } @@ -87,7 +87,7 @@ */ CObjArray indices(numItems); - int i; + unsigned i; for (i = 0; i < numItems; i++) indices[i] = (UInt32)panelItems[i].UserData; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/Plugin.h 7zip-23.01+dfsg/CPP/7zip/UI/Far/Plugin.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/Plugin.h 2015-06-09 07:59:22.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/Plugin.h 2023-01-22 21:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // 7zip/Far/Plugin.h -#ifndef __7ZIP_FAR_PLUGIN_H -#define __7ZIP_FAR_PLUGIN_H +#ifndef ZIP7_INC_7ZIP_FAR_PLUGIN_H +#define ZIP7_INC_7ZIP_FAR_PLUGIN_H #include "../../../Common/MyCom.h" @@ -40,7 +40,7 @@ AString PanelModeColumnTypes; AString PanelModeColumnWidths; - // PanelMode _PanelMode; + // PanelMode _panelMode; void AddColumn(PROPID aPropID); void EnterToDirectory(const UString &dirName); @@ -62,7 +62,7 @@ void FreeFindData(PluginPanelItem *panelItem,int ItemsNumber); int SetDirectory(const char *aszDir, int opMode); void GetOpenPluginInfo(struct OpenPluginInfo *info); - int DeleteFiles(PluginPanelItem *panelItems, int itemsNumber, int opMode); + int DeleteFiles(PluginPanelItem *panelItems, unsigned itemsNumber, int opMode); HRESULT ExtractFiles( bool decompressAllItems, @@ -74,13 +74,13 @@ const UString &destPath, bool passwordIsDefined, const UString &password); - NFar::NFileOperationReturnCode::EEnum GetFiles(struct PluginPanelItem *panelItem, int itemsNumber, + NFar::NFileOperationReturnCode::EEnum GetFiles(struct PluginPanelItem *panelItem, unsigned itemsNumber, int move, char *destPath, int opMode); NFar::NFileOperationReturnCode::EEnum GetFilesReal(struct PluginPanelItem *panelItems, - int itemsNumber, int move, const char *_aDestPath, int opMode, bool showBox); + unsigned itemsNumber, int move, const char *_aDestPath, int opMode, bool showBox); - NFar::NFileOperationReturnCode::EEnum PutFiles(struct PluginPanelItem *panelItems, int itemsNumber, + NFar::NFileOperationReturnCode::EEnum PutFiles(struct PluginPanelItem *panelItems, unsigned itemsNumber, int move, int opMode); HRESULT CreateFolder(); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/PluginRead.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Far/PluginRead.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/PluginRead.cpp 2021-10-22 10:38:30.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/PluginRead.cpp 2023-03-19 09:00:00.000000000 +0000 @@ -86,14 +86,14 @@ } NFileOperationReturnCode::EEnum CPlugin::GetFiles(struct PluginPanelItem *panelItems, - int itemsNumber, int move, char *destPath, int opMode) + unsigned itemsNumber, int move, char *destPath, int opMode) { return GetFilesReal(panelItems, itemsNumber, move, destPath, opMode, (opMode & OPM_SILENT) == 0); } NFileOperationReturnCode::EEnum CPlugin::GetFilesReal(struct PluginPanelItem *panelItems, - int itemsNumber, int move, const char *destPathLoc, int opMode, bool showBox) + unsigned itemsNumber, int move, const char *destPathLoc, int opMode, bool showBox) { if (move != 0) { @@ -112,7 +112,7 @@ extractionInfo.PathMode = NExtract::NPathMode::kCurPaths; extractionInfo.OverwriteMode = NExtract::NOverwriteMode::kOverwrite; - bool silent = (opMode & OPM_SILENT) != 0; + const bool silent = (opMode & OPM_SILENT) != 0; bool decompressAllItems = false; UString password = Password; bool passwordIsDefined = PasswordIsDefined; @@ -184,9 +184,9 @@ { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kExtractCancel, NULL, NULL } }; - const int kNumDialogItems = ARRAY_SIZE(initItems); - const int kOkButtonIndex = kNumDialogItems - 2; - const int kPasswordIndex = kNumDialogItems - 4; + const unsigned kNumDialogItems = Z7_ARRAY_SIZE(initItems); + const unsigned kOkButtonIndex = kNumDialogItems - 2; + const unsigned kPasswordIndex = kNumDialogItems - 4; FarDialogItem dialogItems[kNumDialogItems]; g_StartupInfo.InitDialogItems(initItems, dialogItems, kNumDialogItems); @@ -275,10 +275,10 @@ GetRealIndexes(panelItems, itemsNumber, realIndices); */ CObjArray indices(itemsNumber); - for (int i = 0; i < itemsNumber; i++) + for (unsigned i = 0; i < itemsNumber; i++) indices[i] = (UInt32)panelItems[i].UserData; - HRESULT result = ExtractFiles(decompressAllItems, indices, itemsNumber, + const HRESULT result = ExtractFiles(decompressAllItems, indices, itemsNumber, !showBox, extractionInfo.PathMode, extractionInfo.OverwriteMode, destPathU, passwordIsDefined, password); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/PluginWrite.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Far/PluginWrite.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/PluginWrite.cpp 2021-10-27 12:20:57.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/PluginWrite.cpp 2023-04-01 13:00:00.000000000 +0000 @@ -49,7 +49,7 @@ */ NCOM::CPropVariant value = (UInt32)method; const wchar_t *name = L"x"; - RINOK(setProperties->SetProperties(&name, &value, 1)); + RINOK(setProperties->SetProperties(&name, &value, 1)) } return S_OK; } @@ -78,7 +78,7 @@ */ NFileOperationReturnCode::EEnum CPlugin::PutFiles( - struct PluginPanelItem *panelItems, int numItems, + struct PluginPanelItem *panelItems, unsigned numItems, int moveMode, int opMode) { if (moveMode != 0 @@ -106,7 +106,7 @@ unsigned methodIndex = 0; unsigned i; - for (i = ARRAY_SIZE(g_MethodMap); i != 0;) + for (i = Z7_ARRAY_SIZE(g_MethodMap); i != 0;) { i--; if (compressionInfo.Level >= g_MethodMap[i]) @@ -144,17 +144,17 @@ { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kCancel, NULL, NULL } }; - const int kNumDialogItems = ARRAY_SIZE(initItems); + const int kNumDialogItems = Z7_ARRAY_SIZE(initItems); const int kOkButtonIndex = kNumDialogItems - 2; FarDialogItem dialogItems[kNumDialogItems]; g_StartupInfo.InitDialogItems(initItems, dialogItems, kNumDialogItems); - int askCode = g_StartupInfo.ShowDialog(76, kYSize, + const int askCode = g_StartupInfo.ShowDialog(76, kYSize, kHelpTopic, dialogItems, kNumDialogItems); if (askCode != kOkButtonIndex) return NFileOperationReturnCode::kInterruptedByUser; compressionInfo.Level = g_MethodMap[0]; - for (i = 0; i < ARRAY_SIZE(g_MethodMap); i++) + for (i = 0; i < Z7_ARRAY_SIZE(g_MethodMap); i++) if (dialogItems[kMethodRadioIndex + i].Selected) compressionInfo.Level = g_MethodMap[i]; @@ -168,7 +168,7 @@ compressionInfo.Save(); - CWorkDirTempFile tempFile;; + CWorkDirTempFile tempFile; if (tempFile.CreateTempFile(m_FileName) != S_OK) return NFileOperationReturnCode::kError; @@ -337,7 +337,7 @@ // the bug was fixed: curPos = path.Find((wchar_t)kDirDelimiter, 2); if (curPos < 0) - curPos = path.Len(); + curPos = (int)path.Len(); else curPos++; } @@ -368,7 +368,7 @@ if (dotPos > slashPos + 1) arcName.DeleteFrom(dotPos); } - arcName += '.'; + arcName.Add_Dot(); arcName += arcInfo.GetMainExt(); } @@ -420,9 +420,9 @@ if (arcInfo.UpdateEnabled) { if (archiverIndex == -1) - archiverIndex = i; + archiverIndex = (int)i; if (MyStringCompareNoCase(arcInfo.Name, compressionInfo.ArcType) == 0) - archiverIndex = i; + archiverIndex = (int)i; } } } @@ -480,7 +480,7 @@ unsigned methodIndex = 0; unsigned i; - for (i = ARRAY_SIZE(g_MethodMap); i != 0;) + for (i = Z7_ARRAY_SIZE(g_MethodMap); i != 0;) { i--; if (compressionInfo.Level >= g_MethodMap[i]) @@ -522,7 +522,7 @@ { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kCancel, NULL, NULL } }; - const int kNumDialogItems = ARRAY_SIZE(initItems); + const int kNumDialogItems = Z7_ARRAY_SIZE(initItems); const int kOkButtonIndex = kNumDialogItems - 3; const int kSelectarchiverButtonIndex = kNumDialogItems - 2; @@ -537,7 +537,7 @@ MultiByteToUnicodeString2(arcName, archiveNameA, CP_OEMCP); compressionInfo.Level = g_MethodMap[0]; - for (i = 0; i < ARRAY_SIZE(g_MethodMap); i++) + for (i = 0; i < Z7_ARRAY_SIZE(g_MethodMap); i++) if (dialogItems[kMethodRadioIndex + i].Selected) compressionInfo.Level = g_MethodMap[i]; @@ -549,7 +549,7 @@ if (askCode == kSelectarchiverButtonIndex) { - CIntVector indices; + CUIntVector indices; AStringVector archiverNames; FOR_VECTOR (k, codecs->Formats) { @@ -561,7 +561,7 @@ } } - int index = g_StartupInfo.Menu(FMENU_AUTOHIGHLIGHT, + const int index = g_StartupInfo.Menu(FMENU_AUTOHIGHLIGHT, g_StartupInfo.GetMsgString(NMessageID::kUpdateSelectArchiverMenuTitle), NULL, archiverNames, archiverIndex); if (index >= 0) @@ -574,7 +574,7 @@ if (arcName.Len() >= prevExtensionLen && MyStringCompareNoCase(arcName.RightPtr(prevExtensionLen), prevExtension) == 0) { - int pos = arcName.Len() - prevExtensionLen; + const unsigned pos = arcName.Len() - prevExtensionLen; if (pos > 2) { if (arcName[pos - 1] == '.') @@ -583,7 +583,7 @@ } } - archiverIndex = indices[index]; + archiverIndex = (int)indices[index]; const CArcInfoEx &arcInfo = codecs->Formats[archiverIndex]; prevFormat = archiverIndex; @@ -612,8 +612,7 @@ return E_FAIL; CWorkDirTempFile tempFile; - RINOK(tempFile.CreateTempFile(fullArcName)); - + RINOK(tempFile.CreateTempFile(fullArcName)) CScreenRestorer screenRestorer; CProgressBox progressBox; CProgressBox *progressBoxPointer = NULL; @@ -640,15 +639,15 @@ archiveHandler = agentSpec; // CLSID realClassID; CMyComBSTR archiveType; - RINOK(agentSpec->Open(NULL, + RINOK(archiveHandler->Open(NULL, GetUnicodeString(fullArcName, CP_OEMCP), UString(), // &realClassID, &archiveType, - NULL)); + NULL)) if (MyStringCompareNoCase(archiverInfoFinal.Name, (const wchar_t *)archiveType) != 0) throw "Type of existing archive differs from specified type"; - HRESULT result = archiveHandler.QueryInterface( + const HRESULT result = archiveHandler.QueryInterface( IID_IOutFolderArchive, &outArchive); if (result != S_OK) { @@ -690,7 +689,7 @@ updateCallbackSpec->Init(/* archiveHandler, */ progressBoxPointer); - RINOK(SetOutProperties(outArchive, compressionInfo.Level)); + RINOK(SetOutProperties(outArchive, compressionInfo.Level)) // FStringVector requestedPaths; // FStringVector processedPaths; @@ -754,7 +753,7 @@ { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kCancel, NULL, NULL } }; - const int kNumDialogItems = ARRAY_SIZE(initItems); + const int kNumDialogItems = Z7_ARRAY_SIZE(initItems); const int kOkButtonIndex = kNumDialogItems - 2; FarDialogItem dialogItems[kNumDialogItems]; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/ProgressBox.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Far/ProgressBox.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/ProgressBox.cpp 2017-02-08 08:44:43.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/ProgressBox.cpp 2023-03-06 17:00:00.000000000 +0000 @@ -67,9 +67,9 @@ static void GetTimeString(UInt64 timeValue, char *s) { - UInt64 hours = timeValue / 3600; + const UInt64 hours = timeValue / 3600; UInt32 seconds = (UInt32)(timeValue - hours * 3600); - UInt32 minutes = seconds / 60; + const UInt32 minutes = seconds / 60; seconds %= 60; if (hours > 99) { @@ -78,11 +78,11 @@ } else { - UInt32 hours32 = (UInt32)hours; - UINT_TO_STR_2(hours32); + const UInt32 hours32 = (UInt32)hours; + UINT_TO_STR_2(hours32) } - *s++ = ':'; UINT_TO_STR_2(minutes); - *s++ = ':'; UINT_TO_STR_2(seconds); + *s++ = ':'; UINT_TO_STR_2(minutes) + *s++ = ':'; UINT_TO_STR_2(seconds) *s = 0; } @@ -280,10 +280,10 @@ else */ { - int slashPos = FileName.ReverseFind_PathSepar(); + const int slashPos = FileName.ReverseFind_PathSepar(); if (slashPos >= 0) { - _name1U.SetFrom(FileName, slashPos + 1); + _name1U.SetFrom(FileName, (unsigned)(slashPos + 1)); _name2U = FileName.Ptr(slashPos + 1); } else @@ -295,7 +295,7 @@ { const char *strings[] = { _title, _timeStr, _files, _sizesStr, Command, _name1, _name2, _perc }; - NFar::g_StartupInfo.ShowMessage(FMSG_LEFTALIGN, NULL, strings, ARRAY_SIZE(strings), 0); + NFar::g_StartupInfo.ShowMessage(FMSG_LEFTALIGN, NULL, strings, Z7_ARRAY_SIZE(strings), 0); } _wasPrinted = true; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/ProgressBox.h 7zip-23.01+dfsg/CPP/7zip/UI/Far/ProgressBox.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/ProgressBox.h 2017-02-08 08:44:43.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/ProgressBox.h 2023-01-22 20:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ProgressBox.h -#ifndef __PROGRESS_BOX_H -#define __PROGRESS_BOX_H +#ifndef ZIP7_INC_PROGRESS_BOX_H +#define ZIP7_INC_PROGRESS_BOX_H #include "../../../Common/MyString.h" #include "../../../Common/MyTypes.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/UI/Far/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/StdAfx.h 2014-04-25 10:55:08.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/UpdateCallbackFar.cpp 7zip-23.01+dfsg/CPP/7zip/UI/Far/UpdateCallbackFar.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/UpdateCallbackFar.cpp 2017-04-08 12:17:23.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/UpdateCallbackFar.cpp 2023-01-30 18:00:00.000000000 +0000 @@ -2,7 +2,7 @@ #include "StdAfx.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "../../../Windows/Synchronization.h" #endif @@ -14,7 +14,7 @@ using namespace NWindows; using namespace NFar; -#ifndef _7ZIP_ST +#ifndef Z7_ST static NSynchronization::CCriticalSection g_CriticalSection; #define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection); #else @@ -27,7 +27,7 @@ } -STDMETHODIMP CUpdateCallback100Imp::ScanProgress(UInt64 numFolders, UInt64 numFiles, UInt64 totalSize, const wchar_t *path, Int32 /* isDir */) +Z7_COM7F_IMF(CUpdateCallback100Imp::ScanProgress(UInt64 numFolders, UInt64 numFiles, UInt64 totalSize, const wchar_t *path, Int32 /* isDir */)) { MT_LOCK @@ -43,14 +43,14 @@ return CheckBreak2(); } -STDMETHODIMP CUpdateCallback100Imp::ScanError(const wchar_t *path, HRESULT errorCode) +Z7_COM7F_IMF(CUpdateCallback100Imp::ScanError(const wchar_t *path, HRESULT errorCode)) { if (ShowSysErrorMessage(errorCode, path) == -1) return E_ABORT; return CheckBreak2(); } -STDMETHODIMP CUpdateCallback100Imp::SetNumFiles(UInt64 numFiles) +Z7_COM7F_IMF(CUpdateCallback100Imp::SetNumFiles(UInt64 numFiles)) { MT_LOCK @@ -63,12 +63,12 @@ } -STDMETHODIMP CUpdateCallback100Imp::SetTotal(const UInt64 * /* files */, const UInt64 * /* bytes */) +Z7_COM7F_IMF(CUpdateCallback100Imp::SetTotal(const UInt64 * /* files */, const UInt64 * /* bytes */)) { return S_OK; } -STDMETHODIMP CUpdateCallback100Imp::SetCompleted(const UInt64 * /* files */, const UInt64 * /* bytes */) +Z7_COM7F_IMF(CUpdateCallback100Imp::SetCompleted(const UInt64 * /* files */, const UInt64 * /* bytes */)) { MT_LOCK return CheckBreak2(); @@ -76,7 +76,7 @@ -STDMETHODIMP CUpdateCallback100Imp::SetTotal(UInt64 size) +Z7_COM7F_IMF(CUpdateCallback100Imp::SetTotal(UInt64 size)) { MT_LOCK @@ -88,7 +88,7 @@ return CheckBreak2(); } -STDMETHODIMP CUpdateCallback100Imp::SetCompleted(const UInt64 *completeValue) +Z7_COM7F_IMF(CUpdateCallback100Imp::SetCompleted(const UInt64 *completeValue)) { MT_LOCK @@ -101,7 +101,7 @@ return CheckBreak2(); } -STDMETHODIMP CUpdateCallback100Imp::CompressOperation(const wchar_t *name) +Z7_COM7F_IMF(CUpdateCallback100Imp::CompressOperation(const wchar_t *name)) { MT_LOCK @@ -111,10 +111,10 @@ _percent->FileName = name; _percent->Print(); } - return CheckBreak2();; + return CheckBreak2(); } -STDMETHODIMP CUpdateCallback100Imp::DeleteOperation(const wchar_t *name) +Z7_COM7F_IMF(CUpdateCallback100Imp::DeleteOperation(const wchar_t *name)) { MT_LOCK @@ -124,10 +124,10 @@ _percent->FileName = name; _percent->Print(); } - return CheckBreak2();; + return CheckBreak2(); } -STDMETHODIMP CUpdateCallback100Imp::OperationResult(Int32 /* opRes */) +Z7_COM7F_IMF(CUpdateCallback100Imp::OperationResult(Int32 /* opRes */)) { MT_LOCK @@ -138,7 +138,7 @@ return CheckBreak2(); } -STDMETHODIMP CUpdateCallback100Imp::UpdateErrorMessage(const wchar_t *message) +Z7_COM7F_IMF(CUpdateCallback100Imp::UpdateErrorMessage(const wchar_t *message)) { MT_LOCK @@ -147,14 +147,14 @@ return CheckBreak2(); } -HRESULT CUpdateCallback100Imp::OpenFileError(const wchar_t *path, HRESULT errorCode) +Z7_COM7F_IMF(CUpdateCallback100Imp::OpenFileError(const wchar_t *path, HRESULT errorCode)) { if (ShowSysErrorMessage(errorCode, path) == -1) return E_ABORT; return CheckBreak2(); } -STDMETHODIMP CUpdateCallback100Imp::ReadingFileError(const wchar_t *path, HRESULT errorCode) +Z7_COM7F_IMF(CUpdateCallback100Imp::ReadingFileError(const wchar_t *path, HRESULT errorCode)) { if (ShowSysErrorMessage(errorCode, path) == -1) return E_ABORT; @@ -163,7 +163,7 @@ void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, AString &s); -STDMETHODIMP CUpdateCallback100Imp::ReportExtractResult(Int32 opRes, Int32 isEncrypted, const wchar_t *name) +Z7_COM7F_IMF(CUpdateCallback100Imp::ReportExtractResult(Int32 opRes, Int32 isEncrypted, const wchar_t *name)) { MT_LOCK @@ -179,7 +179,7 @@ } -STDMETHODIMP CUpdateCallback100Imp::ReportUpdateOperation(UInt32 op, const wchar_t *name, Int32 /* isDir */) +Z7_COM7F_IMF(CUpdateCallback100Imp::ReportUpdateOperation(UInt32 op, const wchar_t *name, Int32 /* isDir */)) { const char *s; switch (op) @@ -206,26 +206,26 @@ _percent->Print(); } - return CheckBreak2();; + return CheckBreak2(); } extern HRESULT GetPassword(UString &password); -STDMETHODIMP CUpdateCallback100Imp::CryptoGetTextPassword(BSTR *password) +Z7_COM7F_IMF(CUpdateCallback100Imp::CryptoGetTextPassword(BSTR *password)) { MT_LOCK *password = NULL; if (!PasswordIsDefined) { - RINOK(GetPassword(Password)); + RINOK(GetPassword(Password)) PasswordIsDefined = true; } return StringToBstr(Password, password); } -STDMETHODIMP CUpdateCallback100Imp::CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password) +Z7_COM7F_IMF(CUpdateCallback100Imp::CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password)) { MT_LOCK diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/Far/UpdateCallbackFar.h 7zip-23.01+dfsg/CPP/7zip/UI/Far/UpdateCallbackFar.h --- 7zip-22.01+dfsg/CPP/7zip/UI/Far/UpdateCallbackFar.h 2017-04-08 12:30:56.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/Far/UpdateCallbackFar.h 2023-03-25 13:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // UpdateCallbackFar.h -#ifndef __UPDATE_CALLBACK_FAR_H -#define __UPDATE_CALLBACK_FAR_H +#ifndef ZIP7_INC_UPDATE_CALLBACK_FAR_H +#define ZIP7_INC_UPDATE_CALLBACK_FAR_H #include "../../../Common/MyCom.h" @@ -11,43 +11,27 @@ #include "ProgressBox.h" -class CUpdateCallback100Imp: - public IFolderArchiveUpdateCallback, - public IFolderArchiveUpdateCallback2, - public IFolderScanProgress, - public ICryptoGetTextPassword2, - public ICryptoGetTextPassword, - public IArchiveOpenCallback, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_6( + CUpdateCallback100Imp + , IFolderArchiveUpdateCallback + , IFolderArchiveUpdateCallback2 + , IFolderScanProgress + , ICryptoGetTextPassword2 + , ICryptoGetTextPassword + , IArchiveOpenCallback +) + Z7_IFACE_COM7_IMP(IProgress) + // CMyComPtr _archiveHandler; CProgressBox *_percent; - UInt64 _total; - + // UInt64 _total; public: - bool PasswordIsDefined; UString Password; - MY_UNKNOWN_IMP6( - IFolderArchiveUpdateCallback, - IFolderArchiveUpdateCallback2, - IFolderScanProgress, - ICryptoGetTextPassword2, - ICryptoGetTextPassword, - IArchiveOpenCallback - ) - - INTERFACE_IProgress(;) - INTERFACE_IFolderArchiveUpdateCallback(;) - INTERFACE_IFolderArchiveUpdateCallback2(;) - INTERFACE_IFolderScanProgress(;) - INTERFACE_IArchiveOpenCallback(;) - - STDMETHOD(CryptoGetTextPassword)(BSTR *password); - STDMETHOD(CryptoGetTextPassword2)(Int32 *passwordIsDefined, BSTR *password); - - CUpdateCallback100Imp(): _total(0) {} + CUpdateCallback100Imp() + // : _total(0) + {} void Init(/* IInFolderArchive *archiveHandler, */ CProgressBox *progressBox) { // _archiveHandler = archiveHandler; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/7zFM.exe.manifest 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/7zFM.exe.manifest --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/7zFM.exe.manifest 2018-04-25 11:15:28.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/7zFM.exe.manifest 2023-04-02 08:00:00.000000000 +0000 @@ -17,4 +17,7 @@ true + + +true diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/AboutDialog.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/AboutDialog.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/AboutDialog.cpp 2021-05-18 06:45:36.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/AboutDialog.cpp 2023-03-06 16:00:00.000000000 +0000 @@ -14,10 +14,12 @@ #include "HelpUtils.h" #include "LangUtils.h" +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { IDT_ABOUT_INFO }; +#endif #define kHomePageURL TEXT("https://www.7-zip.org/") #define kHelpTopic "start.htm" @@ -29,7 +31,7 @@ bool CAboutDialog::OnInit() { - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS if (g_CodecsObj) { UString s; @@ -39,11 +41,13 @@ } #endif - LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); + #ifdef Z7_LANG + LangSetWindowText(*this, IDD_ABOUT); + LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs)); + #endif SetItemText(IDT_ABOUT_VERSION, UString("7-Zip " MY_VERSION_CPU)); SetItemText(IDT_ABOUT_DATE, LLL(MY_DATE)); - LangSetWindowText(*this, IDD_ABOUT); NormalizePosition(); return CModalDialog::OnInit(); } @@ -53,7 +57,7 @@ ShowHelpWindow(kHelpTopic); } -bool CAboutDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CAboutDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { LPCTSTR url; switch (buttonID) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/AboutDialog.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/AboutDialog.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/AboutDialog.h 2013-01-17 10:21:21.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/AboutDialog.h 2023-01-28 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // AboutDialog.h -#ifndef __ABOUT_DIALOG_H -#define __ABOUT_DIALOG_H +#ifndef ZIP7_INC_ABOUT_DIALOG_H +#define ZIP7_INC_ABOUT_DIALOG_H #include "../../../Windows/Control/Dialog.h" @@ -10,10 +10,10 @@ class CAboutDialog: public NWindows::NControl::CModalDialog { public: - virtual bool OnInit(); - virtual void OnHelp(); - virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); - INT_PTR Create(HWND wndParent = 0) { return CModalDialog::Create(IDD_ABOUT, wndParent); } + virtual bool OnInit() Z7_override; + virtual void OnHelp() Z7_override; + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; + INT_PTR Create(HWND wndParent = NULL) { return CModalDialog::Create(IDD_ABOUT, wndParent); } }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/AltStreamsFolder.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/AltStreamsFolder.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/AltStreamsFolder.cpp 2021-02-11 08:53:59.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/AltStreamsFolder.cpp 2023-04-06 17:00:00.000000000 +0000 @@ -2,10 +2,32 @@ #include "StdAfx.h" +#ifdef __MINGW32_VERSION +// #if !defined(_MSC_VER) && (__GNUC__) && (__GNUC__ < 10) +// for old mingw +#include +#else +#ifndef Z7_OLD_WIN_SDK + #if !defined(_M_IA64) + #include + #endif +#else +typedef LONG NTSTATUS; +typedef struct _IO_STATUS_BLOCK { + union { + NTSTATUS Status; + PVOID Pointer; + }; + ULONG_PTR Information; +} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK; +#endif +#endif + #include "../../../Common/ComTry.h" #include "../../../Common/StringConvert.h" #include "../../../Common/Wildcard.h" +#include "../../../Windows/DLL.h" #include "../../../Windows/ErrorMsg.h" #include "../../../Windows/FileDir.h" #include "../../../Windows/FileIO.h" @@ -54,7 +76,7 @@ { if (IsNetworkShareRootPath(path)) return 0; - unsigned prefixSize = GetRootPrefixSize(path); + const unsigned prefixSize = GetRootPrefixSize(path); if (prefixSize == 0 || prefixSize >= path.Len()) return 0; FString parentPath = path; @@ -70,7 +92,7 @@ } if ((unsigned)pos + 1 < prefixSize) return 0; - return pos + 1; + return (unsigned)pos + 1; } HRESULT CAltStreamsFolder::Init(const FString &path /* , IFolderFolder *parentFolder */) @@ -115,7 +137,7 @@ return S_OK; } -STDMETHODIMP CAltStreamsFolder::LoadItems() +Z7_COM7F_IMF(CAltStreamsFolder::LoadItems()) { Int32 dummy; WasChanged(&dummy); @@ -152,7 +174,7 @@ return S_OK; } -STDMETHODIMP CAltStreamsFolder::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CAltStreamsFolder::GetNumberOfItems(UInt32 *numItems)) { *numItems = Streams.Size(); return S_OK; @@ -160,16 +182,16 @@ #ifdef USE_UNICODE_FSTRING -STDMETHODIMP CAltStreamsFolder::GetItemPrefix(UInt32 /* index */, const wchar_t **name, unsigned *len) +Z7_COM7F_IMF(CAltStreamsFolder::GetItemPrefix(UInt32 /* index */, const wchar_t **name, unsigned *len)) { - *name = 0; + *name = NULL; *len = 0; return S_OK; } -STDMETHODIMP CAltStreamsFolder::GetItemName(UInt32 index, const wchar_t **name, unsigned *len) +Z7_COM7F_IMF(CAltStreamsFolder::GetItemName(UInt32 index, const wchar_t **name, unsigned *len)) { - *name = 0; + *name = NULL; *len = 0; { const CAltStream &ss = Streams[index]; @@ -179,7 +201,7 @@ return S_OK; } -STDMETHODIMP_(UInt64) CAltStreamsFolder::GetItemSize(UInt32 index) +Z7_COM7F_IMF2(UInt64, CAltStreamsFolder::GetItemSize(UInt32 index)) { return Streams[index].Size; } @@ -187,7 +209,7 @@ #endif -STDMETHODIMP CAltStreamsFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CAltStreamsFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; { @@ -223,11 +245,11 @@ static inline const wchar_t *GetExtensionPtr(const UString &name) { - int dotPos = name.ReverseFind_Dot(); - return name.Ptr((dotPos < 0) ? name.Len() : dotPos); + const int dotPos = name.ReverseFind_Dot(); + return name.Ptr(dotPos < 0 ? name.Len() : (unsigned)dotPos); } -STDMETHODIMP_(Int32) CAltStreamsFolder::CompareItems(UInt32 index1, UInt32 index2, PROPID propID, Int32 /* propIsRaw */) +Z7_COM7F_IMF2(Int32, CAltStreamsFolder::CompareItems(UInt32 index1, UInt32 index2, PROPID propID, Int32 /* propIsRaw */)) { const CAltStream &ss1 = Streams[index1]; const CAltStream &ss2 = Streams[index2]; @@ -262,23 +284,23 @@ return 0; } -STDMETHODIMP CAltStreamsFolder::BindToFolder(UInt32 /* index */, IFolderFolder **resultFolder) +Z7_COM7F_IMF(CAltStreamsFolder::BindToFolder(UInt32 /* index */, IFolderFolder **resultFolder)) { - *resultFolder = 0; + *resultFolder = NULL; return E_INVALIDARG; } -STDMETHODIMP CAltStreamsFolder::BindToFolder(const wchar_t * /* name */, IFolderFolder **resultFolder) +Z7_COM7F_IMF(CAltStreamsFolder::BindToFolder(const wchar_t * /* name */, IFolderFolder **resultFolder)) { - *resultFolder = 0; + *resultFolder = NULL; return E_INVALIDARG; } // static CFSTR const kSuperPrefix = FTEXT("\\\\?\\"); -STDMETHODIMP CAltStreamsFolder::BindToParentFolder(IFolderFolder **resultFolder) +Z7_COM7F_IMF(CAltStreamsFolder::BindToParentFolder(IFolderFolder **resultFolder)) { - *resultFolder = 0; + *resultFolder = NULL; /* if (_parentFolder) { @@ -338,15 +360,9 @@ return S_OK; } -STDMETHODIMP CAltStreamsFolder::GetNumberOfProperties(UInt32 *numProperties) -{ - *numProperties = ARRAY_SIZE(kProps); - return S_OK; -} - -STDMETHODIMP CAltStreamsFolder::GetPropertyInfo IMP_IFolderFolder_GetProp(kProps) +IMP_IFolderFolder_Props(CAltStreamsFolder) -STDMETHODIMP CAltStreamsFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CAltStreamsFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -360,7 +376,7 @@ COM_TRY_END } -STDMETHODIMP CAltStreamsFolder::WasChanged(Int32 *wasChanged) +Z7_COM7F_IMF(CAltStreamsFolder::WasChanged(Int32 *wasChanged)) { bool wasChangedMain = false; for (;;) @@ -385,7 +401,7 @@ return S_OK; } -STDMETHODIMP CAltStreamsFolder::Clone(IFolderFolder **resultFolder) +Z7_COM7F_IMF(CAltStreamsFolder::Clone(IFolderFolder **resultFolder)) { CAltStreamsFolder *folderSpec = new CAltStreamsFolder; CMyComPtr folderNew = folderSpec; @@ -436,39 +452,31 @@ } */ -STDMETHODIMP CAltStreamsFolder::CreateFolder(const wchar_t * /* name */, IProgress * /* progress */) +Z7_COM7F_IMF(CAltStreamsFolder::CreateFolder(const wchar_t * /* name */, IProgress * /* progress */)) { return E_NOTIMPL; } -STDMETHODIMP CAltStreamsFolder::CreateFile(const wchar_t *name, IProgress * /* progress */) +Z7_COM7F_IMF(CAltStreamsFolder::CreateFile(const wchar_t *name, IProgress * /* progress */)) { FString absPath; GetAbsPath(name, absPath); NIO::COutFile outFile; if (!outFile.Create(absPath, false)) - return ::GetLastError(); + return GetLastError_noZero_HRESULT(); return S_OK; } -static DWORD Return_LastError_or_FAIL() -{ - DWORD errorCode = GetLastError(); - if (errorCode == 0) - errorCode = (DWORD)E_FAIL; - return errorCode; -} - static UString GetLastErrorMessage() { - return NError::MyFormatMessage(Return_LastError_or_FAIL()); + return NError::MyFormatMessage(GetLastError_noZero_HRESULT()); } static HRESULT UpdateFile(NFsFolder::CCopyStateIO &state, CFSTR inPath, CFSTR outPath, IFolderArchiveUpdateCallback *callback) { if (NFind::DoesFileOrDirExist(outPath)) { - RINOK(SendMessageError(callback, NError::MyFormatMessage(ERROR_ALREADY_EXISTS), FString(outPath))); + RINOK(SendMessageError(callback, NError::MyFormatMessage(ERROR_ALREADY_EXISTS), FString(outPath))) CFileInfo fi; if (fi.Find(inPath)) { @@ -480,8 +488,8 @@ { if (callback) - RINOK(callback->CompressOperation(fs2us(inPath))); - RINOK(state.MyCopyFile(inPath, outPath)); + RINOK(callback->CompressOperation(fs2us(inPath))) + RINOK(state.MyCopyFile(inPath, outPath)) if (state.ErrorFileIndex >= 0) { if (state.ErrorMessage.IsEmpty()) @@ -492,31 +500,136 @@ else errorName = outPath; if (callback) - RINOK(SendMessageError(callback, state.ErrorMessage, errorName)); + RINOK(SendMessageError(callback, state.ErrorMessage, errorName)) } if (callback) - RINOK(callback->OperationResult(0)); + RINOK(callback->OperationResult(0)) } return S_OK; } -STDMETHODIMP CAltStreamsFolder::Rename(UInt32 index, const wchar_t *newName, IProgress *progress) +EXTERN_C_BEGIN + +typedef enum { - CMyComPtr callback; - if (progress) + Z7_WIN_FileRenameInformation = 10 +} +Z7_WIN_FILE_INFORMATION_CLASS; + + +typedef struct +{ + // #if (_WIN32_WINNT >= _WIN32_WINNT_WIN10_RS1) + union { - RINOK(progress->QueryInterface(IID_IFolderArchiveUpdateCallback, (void **)&callback)); - } + BOOLEAN ReplaceIfExists; // FileRenameInformation + ULONG Flags; // FileRenameInformationEx + } DUMMYUNIONNAME; + // #else + // BOOLEAN ReplaceIfExists; + // #endif + HANDLE RootDirectory; + ULONG FileNameLength; + WCHAR FileName[1]; +} Z7_WIN_FILE_RENAME_INFORMATION; + +#if (_WIN32_WINNT >= 0x0500) && !defined(_M_IA64) +#define Z7_WIN_NTSTATUS NTSTATUS +#define Z7_WIN_IO_STATUS_BLOCK IO_STATUS_BLOCK +#else +typedef LONG Z7_WIN_NTSTATUS; +typedef struct +{ + union + { + Z7_WIN_NTSTATUS Status; + PVOID Pointer; + } DUMMYUNIONNAME; + ULONG_PTR Information; +} Z7_WIN_IO_STATUS_BLOCK; +#endif + +typedef Z7_WIN_NTSTATUS (WINAPI *Func_NtSetInformationFile)( + HANDLE FileHandle, + Z7_WIN_IO_STATUS_BLOCK *IoStatusBlock, + PVOID FileInformation, + ULONG Length, + Z7_WIN_FILE_INFORMATION_CLASS FileInformationClass); + +// NTAPI +typedef ULONG (WINAPI *Func_RtlNtStatusToDosError)(Z7_WIN_NTSTATUS Status); + +#define MY_STATUS_SUCCESS 0 + +EXTERN_C_END + +// static Func_NtSetInformationFile f_NtSetInformationFile; +// static bool g_NtSetInformationFile_WasRequested = false; - FString destPath = _pathPrefix + us2fs(newName); +Z7_COM7F_IMF(CAltStreamsFolder::Rename(UInt32 index, const wchar_t *newName, IProgress *progress)) +{ const CAltStream &ss = Streams[index]; + const FString srcPath = _pathPrefix + us2fs(ss.Name); + + const HMODULE ntdll = ::GetModuleHandleW(L"ntdll.dll"); + // if (!g_NtSetInformationFile_WasRequested) { + // g_NtSetInformationFile_WasRequested = true; + const + Func_NtSetInformationFile + f_NtSetInformationFile = Z7_GET_PROC_ADDRESS( + Func_NtSetInformationFile, ntdll, + "NtSetInformationFile"); + if (f_NtSetInformationFile) + { + NIO::CInFile inFile; + if (inFile.Open_for_FileRenameInformation(srcPath)) + { + UString destPath (':'); + destPath += newName; + const ULONG len = (ULONG)sizeof(wchar_t) * destPath.Len(); + CByteBuffer buffer(sizeof(Z7_WIN_FILE_RENAME_INFORMATION) + len); + // buffer is 4 bytes larger than required. + Z7_WIN_FILE_RENAME_INFORMATION *fri = (Z7_WIN_FILE_RENAME_INFORMATION *)(void *)(Byte *)buffer; + memset(fri, 0, sizeof(Z7_WIN_FILE_RENAME_INFORMATION)); + /* DOCS: If ReplaceIfExists is set to TRUE, the rename operation will succeed only + if a stream with the same name does not exist or is a zero-length data stream. */ + fri->ReplaceIfExists = FALSE; + fri->RootDirectory = NULL; + fri->FileNameLength = len; + memcpy(fri->FileName, destPath.Ptr(), len); + Z7_WIN_IO_STATUS_BLOCK iosb; + const Z7_WIN_NTSTATUS status = f_NtSetInformationFile (inFile.GetHandle(), + &iosb, fri, (ULONG)buffer.Size(), Z7_WIN_FileRenameInformation); + if (status != MY_STATUS_SUCCESS) + { + const + Func_RtlNtStatusToDosError + f_RtlNtStatusToDosError = Z7_GET_PROC_ADDRESS( + Func_RtlNtStatusToDosError, ntdll, + "RtlNtStatusToDosError"); + if (f_RtlNtStatusToDosError) + { + const ULONG res = f_RtlNtStatusToDosError(status); + if (res != ERROR_MR_MID_NOT_FOUND) + return HRESULT_FROM_WIN32(res); + } + } + return status; + } + } + + CMyComPtr callback; + if (progress) + { + RINOK(progress->QueryInterface(IID_IFolderArchiveUpdateCallback, (void **)&callback)) + } if (callback) { - RINOK(callback->SetNumFiles(1)); - RINOK(callback->SetTotal(ss.Size)); + RINOK(callback->SetNumFiles(1)) + RINOK(callback->SetTotal(ss.Size)) } NFsFolder::CCopyStateIO state; @@ -524,32 +637,33 @@ state.TotalSize = 0; state.DeleteSrcFile = true; - return UpdateFile(state, _pathPrefix + us2fs(ss.Name), destPath, callback); + const FString destPath = _pathPrefix + us2fs(newName); + return UpdateFile(state, srcPath, destPath, callback); } -STDMETHODIMP CAltStreamsFolder::Delete(const UInt32 *indices, UInt32 numItems,IProgress *progress) +Z7_COM7F_IMF(CAltStreamsFolder::Delete(const UInt32 *indices, UInt32 numItems,IProgress *progress)) { - RINOK(progress->SetTotal(numItems)); + RINOK(progress->SetTotal(numItems)) for (UInt32 i = 0; i < numItems; i++) { const CAltStream &ss = Streams[indices[i]]; const FString fullPath = _pathPrefix + us2fs(ss.Name); - bool result = DeleteFileAlways(fullPath); + const bool result = DeleteFileAlways(fullPath); if (!result) - return Return_LastError_or_FAIL(); - UInt64 completed = i; - RINOK(progress->SetCompleted(&completed)); + return GetLastError_noZero_HRESULT(); + const UInt64 completed = i; + RINOK(progress->SetCompleted(&completed)) } return S_OK; } -STDMETHODIMP CAltStreamsFolder::SetProperty(UInt32 /* index */, PROPID /* propID */, - const PROPVARIANT * /* value */, IProgress * /* progress */) +Z7_COM7F_IMF(CAltStreamsFolder::SetProperty(UInt32 /* index */, PROPID /* propID */, + const PROPVARIANT * /* value */, IProgress * /* progress */)) { return E_NOTIMPL; } -STDMETHODIMP CAltStreamsFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex) +Z7_COM7F_IMF(CAltStreamsFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex)) { const CAltStream &ss = Streams[index]; *iconIndex = 0; @@ -561,30 +675,28 @@ *iconIndex = iconIndexTemp; return S_OK; } - return Return_LastError_or_FAIL(); + return GetLastError_noZero_HRESULT(); } /* -class CGetProp: - public IGetProp, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CGetProp + , IGetProp +) public: // const CArc *Arc; // UInt32 IndexInArc; UString Name; // relative path UInt64 Size; - - MY_UNKNOWN_IMP1(IGetProp) - INTERFACE_IGetProp(;) }; -STDMETHODIMP CGetProp::GetProp(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CGetProp::GetProp(PROPID propID, PROPVARIANT *value)) { if (propID == kpidName) { COM_TRY_BEGIN - NCOM::CPropVariant prop = Name; + NCOM::CPropVariant prop; + prop = Name; prop.Detach(value); return S_OK; COM_TRY_END @@ -612,7 +724,7 @@ FString destPath = destPathSpec; if (CompareFileNames(destPath, srcPath) == 0) { - RINOK(SendMessageError(callback, "Cannot copy file onto itself", destPath)); + RINOK(SendMessageError(callback, "Cannot copy file onto itself", destPath)) return E_ABORT; } @@ -624,13 +736,13 @@ &srcFileInfo.MTime, &srcAltStream.Size, fs2us(destPath), &destPathResult, - &writeAskResult)); + &writeAskResult)) if (IntToBool(writeAskResult)) { - RINOK(callback->SetCurrentFilePath(fs2us(srcPath))); + RINOK(callback->SetCurrentFilePath(fs2us(srcPath))) FString destPathNew (us2fs((LPCOLESTR)destPathResult)); - RINOK(state.MyCopyFile(srcPath, destPathNew)); + RINOK(state.MyCopyFile(srcPath, destPathNew)) if (state.ErrorFileIndex >= 0) { if (state.ErrorMessage.IsEmpty()) @@ -640,7 +752,7 @@ errorName = srcPath; else errorName = destPathNew; - RINOK(SendMessageError(callback, state.ErrorMessage, errorName)); + RINOK(SendMessageError(callback, state.ErrorMessage, errorName)) return E_ABORT; } state.StartPos += state.CurrentSize; @@ -650,22 +762,23 @@ if (state.TotalSize >= srcAltStream.Size) { state.TotalSize -= srcAltStream.Size; - RINOK(state.Progress->SetTotal(state.TotalSize)); + RINOK(state.Progress->SetTotal(state.TotalSize)) } } return S_OK; } -STDMETHODIMP CAltStreamsFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems, +Z7_COM7F_IMF(CAltStreamsFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems, Int32 /* includeAltStreams */, Int32 /* replaceAltStreamColon */, - const wchar_t *path, IFolderOperationsExtractCallback *callback) + const wchar_t *path, IFolderOperationsExtractCallback *callback)) { if (numItems == 0) return S_OK; /* - CMyComPtr ExtractToStreamCallback; - RINOK(callback->QueryInterface(IID_IFolderExtractToStreamCallback, (void **)&ExtractToStreamCallback)); + Z7_DECL_CMyComPtr_QI_FROM( + IFolderExtractToStreamCallback, + ExtractToStreamCallback, callback) if (ExtractToStreamCallback) { Int32 useStreams = 0; @@ -683,8 +796,8 @@ { totalSize += Streams[indices[i]].Size; } - RINOK(callback->SetTotal(totalSize)); - RINOK(callback->SetNumFiles(numItems)); + RINOK(callback->SetTotal(totalSize)) + RINOK(callback->SetNumFiles(numItems)) } /* @@ -716,8 +829,8 @@ if (destPath.IsEmpty() /* && !ExtractToStreamCallback */) return E_INVALIDARG; - bool isAltDest = NName::IsAltPathPrefix(destPath); - bool isDirectPath = (!isAltDest && !IsPathSepar(destPath.Back())); + const bool isAltDest = NName::IsAltPathPrefix(destPath); + const bool isDirectPath = (!isAltDest && !IsPathSepar(destPath.Back())); if (isDirectPath) { @@ -727,7 +840,7 @@ CFileInfo fi; if (!fi.Find(_pathBaseFile)) - return GetLastError(); + return GetLastError_noZero_HRESULT(); NFsFolder::CCopyStateIO state; state.Progress = callback; @@ -736,21 +849,21 @@ for (UInt32 i = 0; i < numItems; i++) { - UInt32 index = indices[i]; + const UInt32 index = indices[i]; const CAltStream &ss = Streams[index]; FString destPath2 = destPath; if (!isDirectPath) destPath2 += us2fs(Get_Correct_FsFile_Name(ss.Name)); FString srcPath; GetFullPath(ss, srcPath); - RINOK(CopyStream(state, srcPath, fi, ss, destPath2, callback)); + RINOK(CopyStream(state, srcPath, fi, ss, destPath2, callback)) } return S_OK; } -STDMETHODIMP CAltStreamsFolder::CopyFrom(Int32 /* moveMode */, const wchar_t * /* fromFolderPath */, - const wchar_t * const * /* itemsPaths */, UInt32 /* numItems */, IProgress * /* progress */) +Z7_COM7F_IMF(CAltStreamsFolder::CopyFrom(Int32 /* moveMode */, const wchar_t * /* fromFolderPath */, + const wchar_t * const * /* itemsPaths */, UInt32 /* numItems */, IProgress * /* progress */)) { /* if (numItems == 0) @@ -831,7 +944,7 @@ return E_NOTIMPL; } -STDMETHODIMP CAltStreamsFolder::CopyFromFile(UInt32 /* index */, const wchar_t * /* fullFilePath */, IProgress * /* progress */) +Z7_COM7F_IMF(CAltStreamsFolder::CopyFromFile(UInt32 /* index */, const wchar_t * /* fullFilePath */, IProgress * /* progress */)) { return E_NOTIMPL; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/AltStreamsFolder.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/AltStreamsFolder.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/AltStreamsFolder.h 2014-09-01 09:45:46.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/AltStreamsFolder.h 2023-04-01 09:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // AltStreamsFolder.h -#ifndef __ALT_STREAMS_FOLDER_H -#define __ALT_STREAMS_FOLDER_H +#ifndef ZIP7_INC_ALT_STREAMS_FOLDER_H +#define ZIP7_INC_ALT_STREAMS_FOLDER_H #include "../../../Common/MyCom.h" @@ -24,12 +24,12 @@ }; -class CAltStreamsFolder: +class CAltStreamsFolder Z7_final: public IFolderFolder, public IFolderCompare, - #ifdef USE_UNICODE_FSTRING + #ifdef USE_UNICODE_FSTRING public IFolderGetItemName, - #endif + #endif public IFolderWasChanged, public IFolderOperations, // public IFolderOperationsDeleteToRecycleBin, @@ -37,35 +37,29 @@ public IFolderGetSystemIconIndex, public CMyUnknownImp { -public: - MY_QUERYINTERFACE_BEGIN2(IFolderFolder) - MY_QUERYINTERFACE_ENTRY(IFolderCompare) + Z7_COM_QI_BEGIN2(IFolderFolder) + Z7_COM_QI_ENTRY(IFolderCompare) #ifdef USE_UNICODE_FSTRING - MY_QUERYINTERFACE_ENTRY(IFolderGetItemName) + Z7_COM_QI_ENTRY(IFolderGetItemName) #endif - MY_QUERYINTERFACE_ENTRY(IFolderWasChanged) - // MY_QUERYINTERFACE_ENTRY(IFolderOperationsDeleteToRecycleBin) - MY_QUERYINTERFACE_ENTRY(IFolderOperations) - MY_QUERYINTERFACE_ENTRY(IFolderClone) - MY_QUERYINTERFACE_ENTRY(IFolderGetSystemIconIndex) - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - - INTERFACE_FolderFolder(;) - INTERFACE_FolderOperations(;) - - STDMETHOD_(Int32, CompareItems)(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw); + Z7_COM_QI_ENTRY(IFolderWasChanged) + // Z7_COM_QI_ENTRY(IFolderOperationsDeleteToRecycleBin) + Z7_COM_QI_ENTRY(IFolderOperations) + Z7_COM_QI_ENTRY(IFolderClone) + Z7_COM_QI_ENTRY(IFolderGetSystemIconIndex) + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(IFolderFolder) + Z7_IFACE_COM7_IMP(IFolderCompare) + #ifdef USE_UNICODE_FSTRING + Z7_IFACE_COM7_IMP(IFolderGetItemName) + #endif + Z7_IFACE_COM7_IMP(IFolderWasChanged) + Z7_IFACE_COM7_IMP(IFolderOperations) + Z7_IFACE_COM7_IMP(IFolderClone) + Z7_IFACE_COM7_IMP(IFolderGetSystemIconIndex) - #ifdef USE_UNICODE_FSTRING - INTERFACE_IFolderGetItemName(;) - #endif - STDMETHOD(WasChanged)(Int32 *wasChanged); - STDMETHOD(Clone)(IFolderFolder **resultFolder); - - STDMETHOD(GetSystemIconIndex)(UInt32 index, Int32 *iconIndex); - -private: FString _pathBaseFile; // folder FString _pathPrefix; // folder: @@ -81,8 +75,6 @@ // path must be with ':' at tail HRESULT Init(const FString &path /* , IFolderFolder *parentFolder */); - CAltStreamsFolder() {} - void GetFullPath(const CAltStream &item, FString &path) const { path = _pathPrefix; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/App.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/App.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/App.cpp 2021-01-24 14:20:48.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/App.cpp 2023-04-01 10:00:00.000000000 +0000 @@ -49,7 +49,7 @@ void CPanelCallbackImp::SetFocusToPath(unsigned index) { - int newPanelIndex = index; + unsigned newPanelIndex = index; if (g_App.NumPanels == 1) newPanelIndex = g_App.LastFocusedPanel; _app->RefreshTitle(); @@ -66,7 +66,7 @@ void CPanelCallbackImp::DragEnd() { _app->DragEnd(); } void CPanelCallbackImp::RefreshTitle(bool always) { _app->RefreshTitlePanel(_index, always); } -void CApp::ReloadLang() +void CApp::ReloadLangItems() { LangString(IDS_N_SELECTED_ITEMS, LangString_N_SELECTED_ITEMS); } @@ -101,11 +101,11 @@ panel._showRealFileIcons = st.ShowRealFileIcons; panel._exStyle = extendedStyle; - DWORD style = (DWORD)panel._listView.GetStyle(); + LONG_PTR style = panel._listView.GetStyle(); if (st.AlternativeSelection) style |= LVS_SINGLESEL; else - style &= ~LVS_SINGLESEL; + style &= ~(LONG_PTR)(DWORD)LVS_SINGLESEL; panel._listView.SetStyle(style); panel.SetExtendedStyle(); } @@ -115,7 +115,7 @@ #define ILC_COLOR32 0x0020 #endif -HRESULT CApp::CreateOnePanel(int panelIndex, const UString &mainPath, const UString &arcFormat, +HRESULT CApp::CreateOnePanel(unsigned panelIndex, const UString &mainPath, const UString &arcFormat, bool needOpenArc, COpenResult &openRes) { @@ -133,7 +133,7 @@ else path = mainPath; - int id = 1000 + 100 * panelIndex; + const unsigned id = 1000 + 100 * panelIndex; // check it return Panels[panelIndex].Create(_window, _window, id, path, arcFormat, &m_PanelCallbackImp[panelIndex], &AppState, @@ -214,9 +214,9 @@ static void SetButtonText(int commandID, UString &s) { - if (SetButtonText(commandID, g_StandardButtons, ARRAY_SIZE(g_StandardButtons), s)) + if (SetButtonText(commandID, g_StandardButtons, Z7_ARRAY_SIZE(g_StandardButtons), s)) return; - SetButtonText(commandID, g_ArchiveButtons, ARRAY_SIZE(g_ArchiveButtons), s); + SetButtonText(commandID, g_ArchiveButtons, Z7_ARRAY_SIZE(g_ArchiveButtons), s); } static void AddButton( @@ -241,7 +241,7 @@ large ? MAKEINTRESOURCE(butInfo.BitmapResID): MAKEINTRESOURCE(butInfo.Bitmap2ResID)); - if (b != 0) + if (b) { imageList.AddMasked(b, RGB(255, 0, 255)); ::DeleteObject(b); @@ -264,10 +264,10 @@ CreateToolbar(_window, _buttonsImageList, _toolBar, LargeButtons); unsigned i; if (ShowArchiveToolbar) - for (i = 0; i < ARRAY_SIZE(g_ArchiveButtons); i++) + for (i = 0; i < Z7_ARRAY_SIZE(g_ArchiveButtons); i++) AddButton(_buttonsImageList, _toolBar, g_ArchiveButtons[i], ShowButtonsLables, LargeButtons); if (ShowStandardToolbar) - for (i = 0; i < ARRAY_SIZE(g_StandardButtons); i++) + for (i = 0; i < Z7_ARRAY_SIZE(g_StandardButtons); i++) AddButton(_buttonsImageList, _toolBar, g_StandardButtons[i], ShowButtonsLables, LargeButtons); _toolBar.AutoSize(); @@ -290,7 +290,7 @@ _commandBar.Create(g_hInstance, hwnd, 1); #endif - MyLoadMenu(); + MyLoadMenu(false); // needResetMenu #ifdef UNDER_CE _commandBar.AutoSize(); @@ -317,7 +317,7 @@ for (i = 0; i < kNumPanelsMax; i++) { CPanel &panel = Panels[i]; - panel._ListViewMode = listMode.Panels[i]; + panel._listViewMode = listMode.Panels[i]; panel._xSize = xSizes[i]; panel._flatModeForArc = ReadFlatView(i); } @@ -342,7 +342,7 @@ RINOK(CreateOnePanel(panelIndex, path, arcFormat, isMainPanel && needOpenArc, - *(isMainPanel ? &openRes : &openRes2))); + *(isMainPanel ? &openRes : &openRes2))) if (isMainPanel) { @@ -366,7 +366,7 @@ COpenResult openRes; RINOK(CreateOnePanel(1 - LastFocusedPanel, UString(), UString(), false, // needOpenArc - openRes)); + openRes)) Panels[1 - LastFocusedPanel].Enable(true); Panels[1 - LastFocusedPanel].Show(SW_SHOWNORMAL); } @@ -479,7 +479,7 @@ s.Add_LF(); } -static void AddPropValueToSum(IFolderFolder *folder, int index, PROPID propID, UInt64 &sum) +static void AddPropValueToSum(IFolderFolder *folder, UInt32 index, PROPID propID, UInt64 &sum) { if (sum == (UInt64)(Int64)-1) return; @@ -501,7 +501,7 @@ unsigned i; for (i = 0; i < indices.Size(); i++) { - int index = indices[i]; + const UInt32 index = indices[i]; if (IsItem_Folder(index)) { AddPropValueToSum(_folder, index, kpidSize, foldersSize); @@ -528,7 +528,7 @@ { info.Add_LF(); info += " "; - int index = indices[i]; + const UInt32 index = indices[i]; info += GetItemRelPath(index); if (IsItem_Folder(index)) info.Add_PathSepar(); @@ -557,9 +557,9 @@ } */ -void CApp::OnCopy(bool move, bool copyToSame, int srcPanelIndex) +void CApp::OnCopy(bool move, bool copyToSame, unsigned srcPanelIndex) { - unsigned destPanelIndex = (NumPanels <= 1) ? srcPanelIndex : (1 - srcPanelIndex); + const unsigned destPanelIndex = (NumPanels <= 1) ? srcPanelIndex : (1 - srcPanelIndex); CPanel &srcPanel = Panels[srcPanelIndex]; CPanel &destPanel = Panels[destPanelIndex]; @@ -584,10 +584,10 @@ { if (copyToSame) { - int focusedItem = srcPanel._listView.GetFocusedItem(); + const int focusedItem = srcPanel._listView.GetFocusedItem(); if (focusedItem < 0) return; - int realIndex = srcPanel.GetRealItemIndex(focusedItem); + const unsigned realIndex = srcPanel.GetRealItemIndex(focusedItem); if (realIndex == kParentIndex) return; indices.Add(realIndex); @@ -595,7 +595,7 @@ } else { - srcPanel.GetOperatedIndicesSmart(indices); + srcPanel.Get_ItemIndices_OperSmart(indices); if (indices.Size() == 0) return; destPath = destPanel.GetFsPath(); @@ -607,7 +607,7 @@ UStringVector copyFolders; ReadCopyHistory(copyFolders); - bool useFullItemPaths = srcPanel.Is_IO_FS_Folder(); // maybe we need flat also here ?? + const bool useFullItemPaths = srcPanel.Is_IO_FS_Folder(); // maybe we need flat also here ?? { CCopyDialog copyDialog; @@ -722,7 +722,7 @@ UString prefix = destPath.Left(pos + 1); if (!CreateComplexDir(us2fs(prefix))) { - DWORD lastError = ::GetLastError(); + const HRESULT lastError = GetLastError_noZero_HRESULT(); srcPanel.MessageBox_Error_2Lines_Message_HRESULT(prefix, lastError); return; } @@ -734,7 +734,7 @@ NName::NormalizeDirPathPrefix(destPath); if (!CreateComplexDir(us2fs(destPath))) { - DWORD lastError = ::GetLastError(); + const HRESULT lastError = GetLastError_noZero_HRESULT(); srcPanel.MessageBox_Error_2Lines_Message_HRESULT(destPath, lastError); return; } @@ -815,7 +815,7 @@ filePaths.AddInReserved(s); } - result = destPanel.CopyFrom(move, folderPrefix, filePaths, true, 0); + result = destPanel.CopyFrom(move, folderPrefix, filePaths, true, NULL); } if (result != S_OK) @@ -849,7 +849,7 @@ srcPanel.SetFocusToList(); } -void CApp::OnSetSameFolder(int srcPanelIndex) +void CApp::OnSetSameFolder(unsigned srcPanelIndex) { if (NumPanels <= 1) return; @@ -858,17 +858,17 @@ destPanel.BindToPathAndRefresh(srcPanel._currentFolderPrefix); } -void CApp::OnSetSubFolder(int srcPanelIndex) +void CApp::OnSetSubFolder(unsigned srcPanelIndex) { if (NumPanels <= 1) return; const CPanel &srcPanel = Panels[srcPanelIndex]; CPanel &destPanel = Panels[1 - srcPanelIndex]; - int focusedItem = srcPanel._listView.GetFocusedItem(); + const int focusedItem = srcPanel._listView.GetFocusedItem(); if (focusedItem < 0) return; - int realIndex = srcPanel.GetRealItemIndex(focusedItem); + const unsigned realIndex = srcPanel.GetRealItemIndex(focusedItem); if (!srcPanel.IsItem_Folder(realIndex)) return; @@ -933,7 +933,7 @@ if (pnmh->code == TTN_GETDISPINFO) { LPNMTTDISPINFO info = (LPNMTTDISPINFO)pnmh; - info->hinst = 0; + info->hinst = NULL; g_ToolTipBuffer.Empty(); SetButtonText((int)info->hdr.idFrom, g_ToolTipBuffer); g_ToolTipBufferSys = GetSystemString(g_ToolTipBuffer); @@ -944,7 +944,7 @@ if (pnmh->code == TTN_GETDISPINFOW) { LPNMTTDISPINFOW info = (LPNMTTDISPINFOW)pnmh; - info->hinst = 0; + info->hinst = NULL; g_ToolTipBuffer.Empty(); SetButtonText((int)info->hdr.idFrom, g_ToolTipBuffer); info->lpszText = g_ToolTipBuffer.Ptr_non_const(); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/App.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/App.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/App.h 2021-11-22 15:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/App.h 2023-04-11 10:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // App.h -#ifndef __APP_H -#define __APP_H +#ifndef ZIP7_INC_APP_H +#define ZIP7_INC_APP_H #include "../../../Windows/Control/CommandBar.h" #include "../../../Windows/Control/ImageList.h" @@ -30,7 +30,7 @@ kMenuCmdID_Toolbar_End }; -class CPanelCallbackImp: public CPanelCallback +class CPanelCallbackImp Z7_final: public CPanelCallback { CApp *_app; unsigned _index; @@ -40,79 +40,26 @@ _app = app; _index = index; } - virtual void OnTab(); - virtual void SetFocusToPath(unsigned index); - virtual void OnCopy(bool move, bool copyToSame); - virtual void OnSetSameFolder(); - virtual void OnSetSubFolder(); - virtual void PanelWasFocused(); - virtual void DragBegin(); - virtual void DragEnd(); - virtual void RefreshTitle(bool always); + virtual void OnTab() Z7_override; + virtual void SetFocusToPath(unsigned index) Z7_override; + virtual void OnCopy(bool move, bool copyToSame) Z7_override; + virtual void OnSetSameFolder() Z7_override; + virtual void OnSetSubFolder() Z7_override; + virtual void PanelWasFocused() Z7_override; + virtual void DragBegin() Z7_override; + virtual void DragEnd() Z7_override; + virtual void RefreshTitle(bool always) Z7_override; }; -class CApp; - -class CDropTarget: - public IDropTarget, - public CMyUnknownImp -{ - CMyComPtr m_DataObject; - UStringVector m_SourcePaths; - int m_SelectionIndex; - bool m_DropIsAllowed; // = true, if data contain fillist - bool m_PanelDropIsAllowed; // = false, if current target_panel is source_panel. - // check it only if m_DropIsAllowed == true - int m_SubFolderIndex; - UString m_SubFolderName; - - CPanel *m_Panel; - bool m_IsAppTarget; // true, if we want to drop to app window (not to panel). - - bool m_SetPathIsOK; - - bool IsItSameDrive() const; - - void QueryGetData(IDataObject *dataObject); - bool IsFsFolderPath() const; - DWORD GetEffect(DWORD keyState, POINTL pt, DWORD allowedEffect); - void RemoveSelection(); - void PositionCursor(POINTL ptl); - UString GetTargetPath() const; - bool SetPath(bool enablePath) const; - bool SetPath(); - -public: - MY_UNKNOWN_IMP1_MT(IDropTarget) - STDMETHOD(DragEnter)(IDataObject * dataObject, DWORD keyState, POINTL pt, DWORD *effect); - STDMETHOD(DragOver)(DWORD keyState, POINTL pt, DWORD * effect); - STDMETHOD(DragLeave)(); - STDMETHOD(Drop)(IDataObject * dataObject, DWORD keyState, POINTL pt, DWORD *effect); - - CDropTarget(): - m_SelectionIndex(-1), - m_DropIsAllowed(false), - m_PanelDropIsAllowed(false), - m_SubFolderIndex(-1), - m_Panel(NULL), - m_IsAppTarget(false), - m_SetPathIsOK(false), - App(NULL), - SrcPanelIndex(-1), - TargetPanelIndex(-1) - {} - - CApp *App; - int SrcPanelIndex; // index of D&D source_panel - int TargetPanelIndex; // what panel to use as target_panel of Application -}; +class CDropTarget; class CApp { public: NWindows::CWindow _window; bool ShowSystemMenu; + bool AutoRefresh_Mode; // bool ShowDeletedFiles; unsigned NumPanels; unsigned LastFocusedPanel; @@ -138,45 +85,27 @@ UString LangString_N_SELECTED_ITEMS; - void ReloadLang(); + void ReloadLangItems(); - CApp(): _window(0), NumPanels(2), LastFocusedPanel(0), - AutoRefresh_Mode(true) + CApp(): + _window(NULL), + AutoRefresh_Mode(true), + NumPanels(2), + LastFocusedPanel(0) { SetPanels_AutoRefresh_Mode(); } - void CreateDragTarget() - { - _dropTargetSpec = new CDropTarget(); - _dropTarget = _dropTargetSpec; - _dropTargetSpec->App = (this); - } + void CreateDragTarget(); + void SetFocusedPanel(unsigned index); + void DragBegin(unsigned panelIndex); + void DragEnd(); + + void OnCopy(bool move, bool copyToSame, unsigned srcPanelIndex); + void OnSetSameFolder(unsigned srcPanelIndex); + void OnSetSubFolder(unsigned srcPanelIndex); - void SetFocusedPanel(unsigned index) - { - LastFocusedPanel = index; - _dropTargetSpec->TargetPanelIndex = LastFocusedPanel; - } - - void DragBegin(unsigned panelIndex) - { - _dropTargetSpec->TargetPanelIndex = (NumPanels > 1) ? 1 - panelIndex : panelIndex; - _dropTargetSpec->SrcPanelIndex = panelIndex; - } - - void DragEnd() - { - _dropTargetSpec->TargetPanelIndex = LastFocusedPanel; - _dropTargetSpec->SrcPanelIndex = -1; - } - - - void OnCopy(bool move, bool copyToSame, int srcPanelIndex); - void OnSetSameFolder(int srcPanelIndex); - void OnSetSubFolder(int srcPanelIndex); - - HRESULT CreateOnePanel(int panelIndex, const UString &mainPath, const UString &arcFormat, bool needOpenArc, COpenResult &openRes); + HRESULT CreateOnePanel(unsigned panelIndex, const UString &mainPath, const UString &arcFormat, bool needOpenArc, COpenResult &openRes); HRESULT Create(HWND hwnd, const UString &mainPath, const UString &arcFormat, int xSizes[2], bool needOpenArc, COpenResult &openRes); void Read(); void Save(); @@ -290,7 +219,6 @@ // void Change_ShowNtfsStrems_Mode() { Panels[LastFocusedPanel].Change_ShowNtfsStrems_Mode(); } // void Change_ShowDeleted() { ShowDeletedFiles = !ShowDeletedFiles; } - bool AutoRefresh_Mode; bool Get_AutoRefresh_Mode() { // return Panels[LastFocusedPanel].Get_ShowNtfsStrems_Mode(); @@ -307,13 +235,13 @@ Panels[i].Set_AutoRefresh_Mode(AutoRefresh_Mode); } - void OpenBookmark(int index) { GetFocusedPanel().OpenBookmark(index); } - void SetBookmark(int index) { GetFocusedPanel().SetBookmark(index); } + void OpenBookmark(unsigned index) { GetFocusedPanel().OpenBookmark(index); } + void SetBookmark(unsigned index) { GetFocusedPanel().SetBookmark(index); } void ReloadToolbars(); void ReadToolbar() { - UInt32 mask = ReadToolbarsMask(); + const UInt32 mask = ReadToolbarsMask(); if (mask & ((UInt32)1 << 31)) { ShowButtonsLables = !g_IsSmallScreen; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/AppState.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/AppState.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/AppState.h 2013-02-10 17:59:18.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/AppState.h 2023-01-10 18:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // AppState.h -#ifndef __APP_STATE_H -#define __APP_STATE_H +#ifndef ZIP7_INC_APP_STATE_H +#define ZIP7_INC_APP_STATE_H #include "../../../Windows/Synchronization.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/BrowseDialog.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/BrowseDialog.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/BrowseDialog.cpp 2021-02-11 08:53:59.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/BrowseDialog.cpp 2023-03-20 10:00:00.000000000 +0000 @@ -4,7 +4,7 @@ #include "../../../Common/MyWindows.h" -#include +#include "../../../Common/IntToString.h" #ifndef UNDER_CE #include "../../../Windows/CommonDialog.h" @@ -25,7 +25,6 @@ #ifdef USE_MY_BROWSE_DIALOG #include "../../../Common/Defs.h" -#include "../../../Common/IntToString.h" #include "../../../Common/Wildcard.h" #include "../../../Windows/FileDir.h" @@ -40,11 +39,11 @@ #include "PropertyNameRes.h" #include "SysIconUtils.h" -#ifndef _SFX +#ifndef Z7_SFX #include "RegistryUtils.h" #endif -#endif +#endif // USE_MY_BROWSE_DIALOG #include "ComboDialog.h" #include "LangUtils.h" @@ -56,6 +55,11 @@ using namespace NName; using namespace NFind; +static void MessageBox_Error_Global(HWND wnd, const wchar_t *message) +{ + ::MessageBoxW(wnd, message, L"7-Zip", MB_ICONERROR); +} + #ifdef USE_MY_BROWSE_DIALOG extern bool g_LVN_ITEMACTIVATE_Support; @@ -63,19 +67,8 @@ static const int kParentIndex = -1; static const UINT k_Message_RefreshPathEdit = WM_APP + 1; -static HRESULT GetNormalizedError() -{ - DWORD errorCode = GetLastError(); - return errorCode == 0 ? E_FAIL : errorCode; -} - extern UString HResultToMessage(HRESULT errorCode); -static void MessageBox_Error_Global(HWND wnd, const wchar_t *message) -{ - ::MessageBoxW(wnd, message, L"7-Zip", MB_ICONERROR); -} - static void MessageBox_HResError(HWND wnd, HRESULT errorCode, const wchar_t *name) { UString s = HResultToMessage(errorCode); @@ -98,17 +91,21 @@ CExtToIconMap _extToIconMap; int _sortIndex; bool _ascending; + #ifndef Z7_SFX bool _showDots; + #endif UString _topDirPrefix; // we don't open parent of that folder UString DirPrefix; - virtual bool OnInit(); - virtual bool OnSize(WPARAM wParam, int xSize, int ySize); - virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam); - virtual bool OnNotify(UINT controlID, LPNMHDR header); - virtual bool OnKeyDown(LPNMLVKEYDOWN keyDownInfo); - virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); - virtual void OnOK(); + virtual bool OnInit() Z7_override; + virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override; + virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam) Z7_override; + virtual bool OnNotify(UINT controlID, LPNMHDR header) Z7_override; + virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM lParam) Z7_override; + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; + virtual void OnOK() Z7_override; + + bool OnKeyDown(LPNMLVKEYDOWN keyDownInfo); void Post_RefreshPathEdit() { PostMsg(k_Message_RefreshPathEdit); } @@ -126,59 +123,37 @@ int GetRealItemIndex(int indexInListView) const { LPARAM param; - if (!_list.GetItemParam(indexInListView, param)) + if (!_list.GetItemParam((unsigned)indexInListView, param)) return (int)-1; return (int)param; } public: + + bool SaveMode; bool FolderMode; + int FilterIndex; // [in / out] + CObjectVector Filters; + + UString FilePath; // [in / out] UString Title; - UString FilePath; // input/ result path - bool ShowAllFiles; - UStringVector Filters; - UString FilterDescription; - - CBrowseDialog(): _showDots(false), FolderMode(false), ShowAllFiles(true) {} - void SetFilter(const UString &s); - INT_PTR Create(HWND parent = 0) { return CModalDialog::Create(IDD_BROWSE, parent); } - int CompareItems(LPARAM lParam1, LPARAM lParam2); + + CBrowseDialog(): + #ifndef Z7_SFX + _showDots(false), + #endif + SaveMode(false) + , FolderMode(false) + , FilterIndex(-1) + {} + INT_PTR Create(HWND parent = NULL) { return CModalDialog::Create(IDD_BROWSE, parent); } + int CompareItems(LPARAM lParam1, LPARAM lParam2) const; }; -void CBrowseDialog::SetFilter(const UString &s) -{ - Filters.Clear(); - UString mask; - unsigned i; - for (i = 0; i < s.Len(); i++) - { - wchar_t c = s[i]; - if (c == ';') - { - if (!mask.IsEmpty()) - Filters.Add(mask); - mask.Empty(); - } - else - mask += c; - } - if (!mask.IsEmpty()) - Filters.Add(mask); - ShowAllFiles = Filters.IsEmpty(); - for (i = 0; i < Filters.Size(); i++) - { - const UString &f = Filters[i]; - if (f == L"*.*" || f == L"*") - { - ShowAllFiles = true; - break; - } - } -} bool CBrowseDialog::OnInit() { - #ifdef LANG + #ifdef Z7_LANG LangSetDlgItems(*this, NULL, 0); #endif if (!Title.IsEmpty()) @@ -187,16 +162,11 @@ _filterCombo.Attach(GetItem(IDC_BROWSE_FILTER)); _pathEdit.Attach(GetItem(IDE_BROWSE_PATH)); - if (FolderMode) - HideItem(IDC_BROWSE_FILTER); - else - EnableItem(IDC_BROWSE_FILTER, false); - #ifndef UNDER_CE _list.SetUnicodeFormat(); #endif - #ifndef _SFX + #ifndef Z7_SFX CFmSettings st; st.Load(); if (st.SingleClick) @@ -205,22 +175,34 @@ #endif { - UString s; - if (!FilterDescription.IsEmpty()) - s = FilterDescription; - else if (ShowAllFiles) - s = "*.*"; - else + /* + Filters.Clear(); // for debug + if (Filters.IsEmpty() && !FolderMode) { - FOR_VECTOR (i, Filters) - { - if (i != 0) - s.Add_Space(); - s += Filters[i]; - } + CBrowseFilterInfo &f = Filters.AddNew(); + const UString mask("*.*"); + f.Masks.Add(mask); + // f.Description = "("; + f.Description += mask; + // f.Description += ")"; } - _filterCombo.AddString(s); - _filterCombo.SetCurSel(0); + */ + + FOR_VECTOR (i, Filters) + { + _filterCombo.AddString(Filters[i].Description); + } + + if (Filters.Size() <= 1) + { + if (FolderMode) + HideItem(IDC_BROWSE_FILTER); + else + EnableItem(IDC_BROWSE_FILTER, false); + } + + if (/* FilterIndex >= 0 && */ (unsigned)FilterIndex < Filters.Size()) + _filterCombo.SetCurSel(FilterIndex); } _list.SetImageList(GetSysImageList(true), LVSIL_SMALL); @@ -261,7 +243,7 @@ _topDirPrefix.Empty(); { - int rootSize = GetRootPrefixSize(FilePath); + unsigned rootSize = GetRootPrefixSize(FilePath); #if defined(_WIN32) && !defined(UNDER_CE) // We can go up from root folder to drives list if (IsDrivePath(FilePath)) @@ -301,7 +283,7 @@ #ifndef UNDER_CE /* If we clear UISF_HIDEFOCUS, the focus rectangle in ListView will be visible, even if we use mouse for pressing the button to open this dialog. */ - PostMsg(MY__WM_UPDATEUISTATE, MAKEWPARAM(MY__UIS_CLEAR, MY__UISF_HIDEFOCUS)); + PostMsg(Z7_WIN_WM_UPDATEUISTATE, MAKEWPARAM(Z7_WIN_UIS_CLEAR, Z7_WIN_UISF_HIDEFOCUS)); #endif return CModalDialog::OnInit(); @@ -368,6 +350,24 @@ return CModalDialog::OnMessage(message, wParam, lParam); } + +bool CBrowseDialog::OnCommand(unsigned code, unsigned itemID, LPARAM lParam) +{ + if (code == CBN_SELCHANGE) + { + switch (itemID) + { + case IDC_BROWSE_FILTER: + { + Reload(); + return true; + } + } + } + return CModalDialog::OnCommand(code, itemID, lParam); +} + + bool CBrowseDialog::OnNotify(UINT /* controlID */, LPNMHDR header) { if (header->hwndFrom != _list) @@ -385,7 +385,7 @@ break; case LVN_COLUMNCLICK: { - int index = LPNMLISTVIEW(header)->iSubItem; + const int index = LPNMLISTVIEW(header)->iSubItem; if (index == _sortIndex) _ascending = !_ascending; else @@ -413,7 +413,7 @@ bool CBrowseDialog::OnKeyDown(LPNMLVKEYDOWN keyDownInfo) { - bool ctrl = IsKeyDown(VK_CONTROL); + const bool ctrl = IsKeyDown(VK_CONTROL); switch (keyDownInfo->wVKey) { @@ -434,7 +434,8 @@ return false; } -bool CBrowseDialog::OnButtonClicked(int buttonID, HWND buttonHWND) + +bool CBrowseDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -474,21 +475,21 @@ return false; if (IS_PATH_SEPAR(s.Back())) return false; - int pos = s.ReverseFind_PathSepar(); - parentPrefix.SetFrom(s, pos + 1); - name = s.Ptr((unsigned)(pos + 1)); + const unsigned pos1 = (unsigned)(s.ReverseFind_PathSepar() + 1); + parentPrefix.SetFrom(s, pos1); + name = s.Ptr(pos1); return true; } -int CBrowseDialog::CompareItems(LPARAM lParam1, LPARAM lParam2) +int CBrowseDialog::CompareItems(LPARAM lParam1, LPARAM lParam2) const { if (lParam1 == kParentIndex) return -1; if (lParam2 == kParentIndex) return 1; const CFileInfo &f1 = _files[(int)lParam1]; const CFileInfo &f2 = _files[(int)lParam2]; - bool isDir1 = f1.IsDir(); - bool isDir2 = f2.IsDir(); + const bool isDir1 = f1.IsDir(); + const bool isDir2 = f2.IsDir(); if (isDir1 && !isDir2) return -1; if (isDir2 && !isDir1) return 1; @@ -509,16 +510,16 @@ static void ConvertSizeToString(UInt64 v, wchar_t *s) { - Byte c = 0; + char c = 0; if (v >= ((UInt64)10000 << 20)) { v >>= 30; c = 'G'; } else if (v >= ((UInt64)10000 << 10)) { v >>= 20; c = 'M'; } else if (v >= ((UInt64)10000 << 0)) { v >>= 10; c = 'K'; } - ConvertUInt64ToString(v, s); + s = ConvertUInt64ToString(v, s); if (c != 0) { - s += MyStringLen(s); *s++ = ' '; - *s++ = c; + *s++ = (wchar_t)c; + *s++ = 'B'; *s++ = 0; } } @@ -536,42 +537,57 @@ isDrive = true; FStringVector drives; if (!MyGetLogicalDriveStrings(drives)) - return GetNormalizedError(); + return GetLastError_noZero_HRESULT(); FOR_VECTOR (i, drives) { - FString d = drives[i]; - if (d.Len() < 3 || d.Back() != '\\') + const FString &d = drives[i]; + if (d.Len() < 2 || d.Back() != '\\') return E_FAIL; - d.DeleteBack(); CFileInfo &fi = files.AddNew(); fi.SetAsDir(); fi.Name = d; + fi.Name.DeleteBack(); } } else #endif { + const UStringVector *masks = NULL; + if (!Filters.IsEmpty() && _filterCombo.GetCount() > 0) + { + const int selected = _filterCombo.GetCurSel(); + // GetItemData_of_CurSel(); // we don't use data field + if (/* selected >= 0 && */ (unsigned)selected < Filters.Size()) + { + const UStringVector &m = Filters[selected].Masks; + if (m.Size() > 1 || (m.Size() == 1 + && !m[0].IsEqualTo("*.*") + && !m[0].IsEqualTo("*"))) + masks = &m; + } + } CEnumerator enumerator; enumerator.SetDirPrefix(us2fs(pathPrefix)); + CFileInfo fi; for (;;) { bool found; - CFileInfo fi; if (!enumerator.Next(fi, found)) - return GetNormalizedError(); + return GetLastError_noZero_HRESULT(); if (!found) break; if (!fi.IsDir()) { if (FolderMode) continue; - if (!ShowAllFiles) + if (masks) { unsigned i; - for (i = 0; i < Filters.Size(); i++) - if (DoesWildcardMatchName(Filters[i], fs2us(fi.Name))) + const unsigned numMasks = masks->Size(); + for (i = 0; i < numMasks; i++) + if (DoesWildcardMatchName((*masks)[i], fs2us(fi.Name))) break; - if (i == Filters.Size()) + if (i == numMasks) continue; } } @@ -590,19 +606,19 @@ LVITEMW item; - int index = 0; + unsigned index = 0; int cursorIndex = -1; - #ifndef _SFX + #ifndef Z7_SFX if (_showDots && _topDirPrefix != DirPrefix) { - item.iItem = index; + item.iItem = (int)index; const UString itemName (".."); if (selectedName.IsEmpty()) - cursorIndex = index; + cursorIndex = (int)index; item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE; - int subItem = 0; - item.iSubItem = subItem++; + unsigned subItem = 0; + item.iSubItem = (int)(subItem++); item.lParam = kParentIndex; item.pszText = itemName.Ptr_non_const(); item.iImage = _extToIconMap.GetIconIndex(FILE_ATTRIBUTE_DIRECTORY, DirPrefix); @@ -617,15 +633,15 @@ for (unsigned i = 0; i < _files.Size(); i++, index++) { - item.iItem = index; + item.iItem = (int)index; const CFileInfo &fi = _files[i]; const UString name = fs2us(fi.Name); if (!selectedName.IsEmpty() && CompareFileNames(name, selectedName) == 0) - cursorIndex = index; + cursorIndex = (int)index; item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE; - int subItem = 0; - item.iSubItem = subItem++; - item.lParam = i; + unsigned subItem = 0; + item.iSubItem = (int)(subItem++); + item.lParam = (LPARAM)i; item.pszText = name.Ptr_non_const(); const UString fullPath = DirPrefix + name; @@ -675,14 +691,14 @@ HRESULT CBrowseDialog::Reload() { UString selected; - int index = _list.GetNextSelectedItem(-1); + const int index = _list.GetNextSelectedItem(-1); if (index >= 0) { - int fileIndex = GetRealItemIndex(index); + const int fileIndex = GetRealItemIndex(index); if (fileIndex != kParentIndex) selected = fs2us(_files[fileIndex].Name); } - UString dirPathTemp = DirPrefix; + const UString dirPathTemp = DirPrefix; return Reload(dirPathTemp, selected); } @@ -698,14 +714,14 @@ void CBrowseDialog::SetPathEditText() { - int index = _list.GetNextSelectedItem(-1); + const int index = _list.GetNextSelectedItem(-1); if (index < 0) { if (FolderMode) _pathEdit.SetText(DirPrefix); return; } - int fileIndex = GetRealItemIndex(index); + const int fileIndex = GetRealItemIndex(index); if (fileIndex == kParentIndex) { if (FolderMode) @@ -745,7 +761,7 @@ { if (!NDir::CreateComplexDir(destPath)) { - MessageBox_HResError((HWND)*this, GetNormalizedError(), fs2us(destPath)); + MessageBox_HResError((HWND)*this, GetLastError_noZero_HRESULT(), fs2us(destPath)); } else { @@ -759,10 +775,10 @@ void CBrowseDialog::OnItemEnter() { - int index = _list.GetNextSelectedItem(-1); + const int index = _list.GetNextSelectedItem(-1); if (index < 0) return; - int fileIndex = GetRealItemIndex(index); + const int fileIndex = GetRealItemIndex(index); if (fileIndex == kParentIndex) OpenParentFolder(); else @@ -782,7 +798,7 @@ UString s = DirPrefix; s += fs2us(file.Name); s.Add_PathSepar(); - HRESULT res = Reload(s, UString()); + const HRESULT res = Reload(s, UString()); if (res != S_OK) MessageBox_HResError(*this, res, s); SetPathEditText(); @@ -802,10 +818,13 @@ FilePath = fs2us(destPath); if (FolderMode) NormalizeDirPathPrefix(FilePath); + FilterIndex = _filterCombo.GetCurSel(); End(IDOK); } -#endif +#endif // USE_MY_BROWSE_DIALOG + + bool MyBrowseForFolder(HWND owner, LPCWSTR title, LPCWSTR path, UString &resultPath) { @@ -813,12 +832,13 @@ #ifndef UNDER_CE - #ifdef USE_MY_BROWSE_DIALOG +#ifdef USE_MY_BROWSE_DIALOG if (!IsSuperOrDevicePath(path)) - #endif + if (MyStringLen(path) < MAX_PATH) +#endif return NShell::BrowseForFolder(owner, title, path, resultPath); - #endif + #endif // UNDER_CE #ifdef USE_MY_BROWSE_DIALOG @@ -831,64 +851,107 @@ if (dialog.Create(owner) != IDOK) return false; resultPath = dialog.FilePath; - #endif - return true; + + #endif } -bool MyBrowseForFile(HWND owner, LPCWSTR title, LPCWSTR path, - LPCWSTR filterDescription, LPCWSTR filter, UString &resultPath) -{ - resultPath.Empty(); - #ifndef UNDER_CE +// LPCWSTR filterDescription, LPCWSTR filter, - #ifdef USE_MY_BROWSE_DIALOG - if (!IsSuperOrDevicePath(path)) - #endif +bool CBrowseInfo::BrowseForFile(const CObjectVector &filters) +{ +#ifndef UNDER_CE +#ifdef USE_MY_BROWSE_DIALOG + /* win10: + GetOpenFileName() for FilePath doesn't support super prefix "\\\\?\\" + GetOpenFileName() for FilePath doesn't support long path + */ + if (!IsSuperOrDevicePath(FilePath)) + // if (filters.Size() > 100) // for debug +#endif { - if (MyGetOpenFileName(owner, title, NULL, path, filterDescription, filter, resultPath)) + const UString filePath_Store = FilePath; + UString dirPrefix; + { + FString prefix, name; + if (NDir::GetFullPathAndSplit(us2fs(FilePath), prefix, name)) + { + dirPrefix = fs2us(prefix); + FilePath = fs2us(name); + } + } + UStringVector filters2; + FOR_VECTOR (i, filters) + { + const CBrowseFilterInfo &fi = filters[i]; + filters2.Add(fi.Description); + UString s; + FOR_VECTOR (k, fi.Masks) + { + if (k != 0) + s += ";"; + s += fi.Masks[k]; + } + filters2.Add(s); + } + if (CommonDlg_BrowseForFile(!dirPrefix.IsEmpty() ? dirPrefix.Ptr(): NULL, filters2)) return true; - #ifdef UNDER_CE + FilePath = filePath_Store; + + #ifdef UNDER_CE return false; - #else + #else // maybe we must use GetLastError in WinCE. - DWORD errorCode = CommDlgExtendedError(); - const char *errorMessage = NULL; - switch (errorCode) - { - case 0: return false; // cancel or close obn dialog - case FNERR_INVALIDFILENAME: errorMessage = "Invalid File Name"; break; - default: errorMessage = "Open Dialog Error"; - } - if (!errorMessage) - return false; + const DWORD errorCode = CommDlgExtendedError(); + #ifdef USE_MY_BROWSE_DIALOG + // FNERR_INVALIDFILENAME is expected error, if long path was used + if (errorCode != FNERR_INVALIDFILENAME + || FilePath.Len() < MAX_PATH) + #endif { - UString s (errorMessage); + if (errorCode == 0) // cancel or close on dialog + return false; + const char *message = NULL; + if (errorCode == FNERR_INVALIDFILENAME) + message = "Invalid file name"; + UString s ("Open Dialog Error:"); s.Add_LF(); - s += path; - MessageBox_Error_Global(owner, s); + if (message) + s += message; + else + { + char temp[16]; + ConvertUInt32ToHex8Digits(errorCode, temp); + s += "Error #"; + s += temp; + } + s.Add_LF(); + s += FilePath; + MessageBox_Error_Global(hwndOwner, s); } - #endif + #endif // UNDER_CE } - #endif +#endif // UNDER_CE - #ifdef USE_MY_BROWSE_DIALOG +#ifdef USE_MY_BROWSE_DIALOG + CBrowseDialog dialog; - if (title) - dialog.Title = title; - if (path) - dialog.FilePath = path; + dialog.FolderMode = false; - if (filter) - dialog.SetFilter(filter); - if (filterDescription) - dialog.FilterDescription = filterDescription; - if (dialog.Create(owner) != IDOK) + dialog.SaveMode = SaveMode; + dialog.FilterIndex = FilterIndex; + dialog.Filters = filters; + + if (lpstrTitle) + dialog.Title = lpstrTitle; + dialog.FilePath = FilePath; + if (dialog.Create(hwndOwner) != IDOK) return false; - resultPath = dialog.FilePath; - #endif + FilePath = dialog.FilePath; + FilterIndex = dialog.FilterIndex; +#endif return true; } @@ -913,7 +976,9 @@ result.Empty(); UString path = path2; + #ifdef _WIN32 path.Replace(L'/', WCHAR_PATH_SEPARATOR); + #endif unsigned start = 0; UString base; @@ -926,9 +991,7 @@ return true; } #endif - int pos = GetRootPrefixSize(path); - if (pos > 0) - start = pos; + start = GetRootPrefixSize(path); } else { @@ -973,8 +1036,8 @@ { if (start == path.Len()) break; - int slashPos = path.Find(WCHAR_PATH_SEPARATOR, start); - cur.SetFrom(path.Ptr(start), (slashPos < 0 ? path.Len() : slashPos) - start); + const int slashPos = path.Find(WCHAR_PATH_SEPARATOR, start); + cur.SetFrom(path.Ptr(start), (slashPos < 0 ? path.Len() : (unsigned)slashPos) - start); if (checkExist) { CFileInfo fi; @@ -994,8 +1057,8 @@ result += cur; if (slashPos < 0) break; + start = (unsigned)(slashPos + 1); result.Add_PathSepar(); - start = slashPos + 1; } return true; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/BrowseDialog.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/BrowseDialog.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/BrowseDialog.h 2014-07-23 13:45:15.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/BrowseDialog.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,12 +1,23 @@ // BrowseDialog.h -#ifndef __BROWSE_DIALOG_H -#define __BROWSE_DIALOG_H +#ifndef ZIP7_INC_BROWSE_DIALOG_H +#define ZIP7_INC_BROWSE_DIALOG_H -#include "../../../Common/MyString.h" +#include "../../../Windows/CommonDialog.h" bool MyBrowseForFolder(HWND owner, LPCWSTR title, LPCWSTR path, UString &resultPath); -bool MyBrowseForFile(HWND owner, LPCWSTR title, LPCWSTR path, LPCWSTR filterDescription, LPCWSTR filter, UString &resultPath); + +struct CBrowseFilterInfo +{ + UStringVector Masks; + UString Description; +}; + +struct CBrowseInfo: public NWindows::CCommonDialogInfo +{ + bool BrowseForFile(const CObjectVector &filters); +}; + /* CorrectFsPath removes undesirable characters in names (dots and spaces at the end of file) But it doesn't change "bad" name in any of the following cases: diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ComboDialog.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ComboDialog.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ComboDialog.cpp 2013-01-23 10:48:59.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ComboDialog.cpp 2023-01-29 20:00:00.000000000 +0000 @@ -5,7 +5,7 @@ #include "../../../Windows/Control/Static.h" -#ifdef LANG +#ifdef Z7_LANG #include "LangUtils.h" #endif @@ -13,7 +13,7 @@ bool CComboDialog::OnInit() { - #ifdef LANG + #ifdef Z7_LANG LangSetDlgItems(*this, NULL, 0); #endif _comboBox.Attach(GetItem(IDC_COMBO)); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ComboDialog.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ComboDialog.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ComboDialog.h 2013-01-17 10:15:56.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ComboDialog.h 2023-01-28 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ComboDialog.h -#ifndef __COMBO_DIALOG_H -#define __COMBO_DIALOG_H +#ifndef ZIP7_INC_COMBO_DIALOG_H +#define ZIP7_INC_COMBO_DIALOG_H #include "../../../Windows/Control/ComboBox.h" #include "../../../Windows/Control/Dialog.h" @@ -11,9 +11,9 @@ class CComboDialog: public NWindows::NControl::CModalDialog { NWindows::NControl::CComboBox _comboBox; - virtual void OnOK(); - virtual bool OnInit(); - virtual bool OnSize(WPARAM wParam, int xSize, int ySize); + virtual void OnOK() Z7_override; + virtual bool OnInit() Z7_override; + virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override; public: // bool Sorted; UString Title; @@ -22,7 +22,7 @@ UStringVector Strings; // CComboDialog(): Sorted(false) {}; - INT_PTR Create(HWND parentWindow = 0) { return CModalDialog::Create(IDD_COMBO, parentWindow); } + INT_PTR Create(HWND parentWindow = NULL) { return CModalDialog::Create(IDD_COMBO, parentWindow); } }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/CopyDialog.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/CopyDialog.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/CopyDialog.cpp 2015-09-28 13:33:28.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/CopyDialog.cpp 2023-03-19 10:00:00.000000000 +0000 @@ -8,16 +8,13 @@ #include "BrowseDialog.h" #include "CopyDialog.h" - -#ifdef LANG #include "LangUtils.h" -#endif using namespace NWindows; bool CCopyDialog::OnInit() { - #ifdef LANG + #ifdef Z7_LANG LangSetDlgItems(*this, NULL, 0); #endif _path.Attach(GetItem(IDC_COPY)); @@ -45,15 +42,15 @@ int bx1, bx2, by; GetItemSizes(IDCANCEL, bx1, by); GetItemSizes(IDOK, bx2, by); - int y = ySize - my - by; - int x = xSize - mx - bx1; + const int y = ySize - my - by; + const int x = xSize - mx - bx1; InvalidateRect(NULL); { RECT r; GetClientRectOfItem(IDB_COPY_SET_PATH, r); - int bx = RECT_SIZE_X(r); + const int bx = RECT_SIZE_X(r); MoveItem(IDB_COPY_SET_PATH, xSize - mx - bx, r.top, bx, RECT_SIZE_Y(r)); ChangeSubWindowSizeX(_path, xSize - mx - mx - bx - mx); } @@ -63,7 +60,7 @@ GetClientRectOfItem(IDT_COPY_INFO, r); NControl::CStatic staticContol; staticContol.Attach(GetItem(IDT_COPY_INFO)); - int yPos = r.top; + const int yPos = r.top; staticContol.Move(mx, yPos, xSize - mx * 2, y - 2 - yPos); } @@ -73,7 +70,7 @@ return false; } -bool CCopyDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CCopyDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/CopyDialog.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/CopyDialog.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/CopyDialog.h 2013-02-20 09:45:54.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/CopyDialog.h 2023-01-28 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // CopyDialog.h -#ifndef __COPY_DIALOG_H -#define __COPY_DIALOG_H +#ifndef ZIP7_INC_COPY_DIALOG_H +#define ZIP7_INC_COPY_DIALOG_H #include "../../../Windows/Control/ComboBox.h" #include "../../../Windows/Control/Dialog.h" @@ -13,11 +13,11 @@ class CCopyDialog: public NWindows::NControl::CModalDialog { NWindows::NControl::CComboBox _path; - virtual void OnOK(); - virtual bool OnInit(); - virtual bool OnSize(WPARAM wParam, int xSize, int ySize); + virtual void OnOK() Z7_override; + virtual bool OnInit() Z7_override; + virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override; + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; void OnButtonSetPath(); - bool OnButtonClicked(int buttonID, HWND buttonHWND); public: UString Title; UString Static; @@ -25,7 +25,7 @@ UString Info; UStringVector Strings; - INT_PTR Create(HWND parentWindow = 0) { return CModalDialog::Create(IDD_COPY, parentWindow); } + INT_PTR Create(HWND parentWindow = NULL) { return CModalDialog::Create(IDD_COPY, parentWindow); } }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/DialogSize.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/DialogSize.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/DialogSize.h 2013-01-17 10:19:54.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/DialogSize.h 2023-01-10 18:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // DialogSize.h -#ifndef __DIALOG_SIZE_H -#define __DIALOG_SIZE_H +#ifndef ZIP7_INC_DIALOG_SIZE_H +#define ZIP7_INC_DIALOG_SIZE_H #include "../../../Windows/Control/Dialog.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/EditDialog.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/EditDialog.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/EditDialog.cpp 2018-03-19 13:48:58.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/EditDialog.cpp 2023-03-19 10:00:00.000000000 +0000 @@ -4,13 +4,13 @@ #include "EditDialog.h" -#ifdef LANG +#ifdef Z7_LANG #include "LangUtils.h" #endif bool CEditDialog::OnInit() { - #ifdef LANG + #ifdef Z7_LANG LangSetDlgItems(*this, NULL, 0); #endif _edit.Attach(GetItem(IDE_EDIT)); @@ -22,21 +22,21 @@ return CModalDialog::OnInit(); } -// #define MY_CLOSE_BUTTON__ID IDCANCEL -#define MY_CLOSE_BUTTON__ID IDCLOSE +// #define MY_CLOSE_BUTTON_ID IDCANCEL +#define MY_CLOSE_BUTTON_ID IDCLOSE bool CEditDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize) { int mx, my; GetMargins(8, mx, my); int bx1, by; - GetItemSizes(MY_CLOSE_BUTTON__ID, bx1, by); + GetItemSizes(MY_CLOSE_BUTTON_ID, bx1, by); // int bx2; // GetItemSizes(IDOK, bx2, by); - int y = ySize - my - by; - int x = xSize - mx - bx1; + const int y = ySize - my - by; + const int x = xSize - mx - bx1; /* RECT rect; @@ -46,7 +46,7 @@ */ InvalidateRect(NULL); - MoveItem(MY_CLOSE_BUTTON__ID, x, y, bx1, by); + MoveItem(MY_CLOSE_BUTTON_ID, x, y, bx1, by); // MoveItem(IDOK, x - mx - bx2, y, bx2, by); /* if (wParam == SIZE_MAXSHOW || wParam == SIZE_MAXIMIZED || wParam == SIZE_MAXHIDE) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/EditDialog.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/EditDialog.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/EditDialog.h 2018-03-17 11:52:24.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/EditDialog.h 2023-01-28 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // EditDialog.h -#ifndef __EDIT_DIALOG_H -#define __EDIT_DIALOG_H +#ifndef ZIP7_INC_EDIT_DIALOG_H +#define ZIP7_INC_EDIT_DIALOG_H #include "../../../Windows/Control/Dialog.h" #include "../../../Windows/Control/Edit.h" @@ -11,13 +11,13 @@ class CEditDialog: public NWindows::NControl::CModalDialog { NWindows::NControl::CEdit _edit; - virtual bool OnInit(); - virtual bool OnSize(WPARAM wParam, int xSize, int ySize); + virtual bool OnInit() Z7_override; + virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override; public: UString Title; UString Text; - INT_PTR Create(HWND wndParent = 0) { return CModalDialog::Create(IDD_EDIT_DLG, wndParent); } + INT_PTR Create(HWND wndParent = NULL) { return CModalDialog::Create(IDD_EDIT_DLG, wndParent); } CEditDialog() {} }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/EditPage.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/EditPage.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/EditPage.cpp 2017-02-15 09:25:59.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/EditPage.cpp 2023-03-06 16:00:00.000000000 +0000 @@ -12,6 +12,7 @@ using namespace NWindows; +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { IDT_EDIT_EDITOR, @@ -22,6 +23,7 @@ { IDT_EDIT_VIEWER }; +#endif #define kEditTopic "FM/options.htm#editor" @@ -29,8 +31,10 @@ { _initMode = true; - LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); - LangSetDlgItems_Colon(*this, kLangIDs_Colon, ARRAY_SIZE(kLangIDs_Colon)); + #ifdef Z7_LANG + LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs)); + LangSetDlgItems_Colon(*this, kLangIDs_Colon, Z7_ARRAY_SIZE(kLangIDs_Colon)); + #endif _ctrls[0].Ctrl = IDE_EDIT_VIEWER; _ctrls[0].Button = IDB_EDIT_VIEWER; _ctrls[1].Ctrl = IDE_EDIT_EDITOR; _ctrls[1].Button = IDB_EDIT_EDITOR; @@ -91,12 +95,20 @@ SplitCmdLineSmart(cmd, prg, param); - UString resPath; - - if (MyBrowseForFile(hwnd, 0, prg, NULL, L"*.exe", resPath)) + CObjectVector filters; + CBrowseFilterInfo &bfi = filters.AddNew(); + bfi.Description = "*.exe"; + bfi.Masks.Add(UString("*.exe")); + + CBrowseInfo bi; + bi.FilterIndex = 0; + bi.FilePath = prg; + bi.hwndOwner = hwnd; + + if (bi.BrowseForFile(filters)) { - resPath.Trim(); - cmd = resPath; + cmd = bi.FilePath; + cmd.Trim(); /* if (!param.IsEmpty() && !resPath.IsEmpty()) { @@ -112,7 +124,7 @@ } } -bool CEditPage::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CEditPage::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { for (unsigned i = 0; i < 3; i++) { @@ -127,7 +139,7 @@ return CPropertyPage::OnButtonClicked(buttonID, buttonHWND); } -bool CEditPage::OnCommand(int code, int itemID, LPARAM param) +bool CEditPage::OnCommand(unsigned code, unsigned itemID, LPARAM param) { if (!_initMode && code == EN_CHANGE) { diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/EditPage.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/EditPage.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/EditPage.h 2015-11-30 10:50:23.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/EditPage.h 2023-01-28 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // EditPage.h -#ifndef __EDIT_PAGE_H -#define __EDIT_PAGE_H +#ifndef ZIP7_INC_EDIT_PAGE_H +#define ZIP7_INC_EDIT_PAGE_H #include "../../../Windows/Control/PropertyPage.h" #include "../../../Windows/Control/Edit.h" @@ -10,8 +10,8 @@ { NWindows::NControl::CEdit Edit; bool WasChanged; - int Ctrl; - int Button; + unsigned Ctrl; + unsigned Button; }; class CEditPage: public NWindows::NControl::CPropertyPage @@ -20,11 +20,11 @@ bool _initMode; public: - virtual bool OnInit(); - virtual void OnNotifyHelp(); - virtual bool OnCommand(int code, int itemID, LPARAM param); - virtual LONG OnApply(); - virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); + virtual bool OnInit() Z7_override; + virtual void OnNotifyHelp() Z7_override; + virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM param) Z7_override; + virtual LONG OnApply() Z7_override; + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/EnumFormatEtc.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/EnumFormatEtc.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/EnumFormatEtc.cpp 2020-09-28 17:29:26.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/EnumFormatEtc.cpp 2023-02-01 17:00:00.000000000 +0000 @@ -3,28 +3,27 @@ #include "StdAfx.h" #include "EnumFormatEtc.h" +#include "../../IDecl.h" #include "MyCom2.h" -class CEnumFormatEtc : -public IEnumFORMATETC, -public CMyUnknownImp +class CEnumFormatEtc Z7_final: + public IEnumFORMATETC, + public CMyUnknownImp { -public: - MY_UNKNOWN_IMP1_MT(IEnumFORMATETC) + Z7_COM_UNKNOWN_IMP_1_MT(IEnumFORMATETC) - STDMETHOD(Next)(ULONG celt, FORMATETC *rgelt, ULONG *pceltFetched); - STDMETHOD(Skip)(ULONG celt); - STDMETHOD(Reset)(void); - STDMETHOD(Clone)(IEnumFORMATETC **ppEnumFormatEtc); - - CEnumFormatEtc(const FORMATETC *pFormatEtc, ULONG numFormats); - ~CEnumFormatEtc(); - -private: + STDMETHOD(Next)(ULONG celt, FORMATETC *rgelt, ULONG *pceltFetched) Z7_override; + STDMETHOD(Skip)(ULONG celt) Z7_override; + STDMETHOD(Reset)(void) Z7_override; + STDMETHOD(Clone)(IEnumFORMATETC **ppEnumFormatEtc) Z7_override; + LONG m_RefCount; ULONG m_NumFormats; FORMATETC *m_Formats; ULONG m_Index; +public: + CEnumFormatEtc(const FORMATETC *pFormatEtc, ULONG numFormats); + ~CEnumFormatEtc(); }; static void DeepCopyFormatEtc(FORMATETC *dest, const FORMATETC *src) @@ -62,10 +61,10 @@ } } -STDMETHODIMP CEnumFormatEtc::Next(ULONG celt, FORMATETC *pFormatEtc, ULONG *pceltFetched) +Z7_COMWF_B CEnumFormatEtc::Next(ULONG celt, FORMATETC *pFormatEtc, ULONG *pceltFetched) { ULONG copied = 0; - if (celt == 0 || pFormatEtc == 0) + if (celt == 0 || !pFormatEtc) return E_INVALIDARG; while (m_Index < m_NumFormats && copied < celt) { @@ -73,24 +72,24 @@ copied++; m_Index++; } - if (pceltFetched != 0) + if (pceltFetched) *pceltFetched = copied; return (copied == celt) ? S_OK : S_FALSE; } -STDMETHODIMP CEnumFormatEtc::Skip(ULONG celt) +Z7_COMWF_B CEnumFormatEtc::Skip(ULONG celt) { m_Index += celt; return (m_Index <= m_NumFormats) ? S_OK : S_FALSE; } -STDMETHODIMP CEnumFormatEtc::Reset(void) +Z7_COMWF_B CEnumFormatEtc::Reset(void) { m_Index = 0; return S_OK; } -STDMETHODIMP CEnumFormatEtc::Clone(IEnumFORMATETC ** ppEnumFormatEtc) +Z7_COMWF_B CEnumFormatEtc::Clone(IEnumFORMATETC ** ppEnumFormatEtc) { HRESULT hResult = CreateEnumFormatEtc(m_NumFormats, m_Formats, ppEnumFormatEtc); if (hResult == S_OK) @@ -101,7 +100,7 @@ // replacement for SHCreateStdEnumFmtEtc HRESULT CreateEnumFormatEtc(UINT numFormats, const FORMATETC *formats, IEnumFORMATETC **enumFormat) { - if (numFormats == 0 || formats == 0 || enumFormat == 0) + if (numFormats == 0 || !formats || !enumFormat) return E_INVALIDARG; *enumFormat = new CEnumFormatEtc(formats, numFormats); return (*enumFormat) ? S_OK : E_OUTOFMEMORY; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/EnumFormatEtc.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/EnumFormatEtc.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/EnumFormatEtc.h 2021-01-26 19:23:41.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/EnumFormatEtc.h 2023-01-10 18:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // EnumFormatEtc.h -#ifndef __ENUMFORMATETC_H -#define __ENUMFORMATETC_H +#ifndef ZIP7_INC_ENUMFORMATETC_H +#define ZIP7_INC_ENUMFORMATETC_H #include "../../../Common/MyWindows.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ExtractCallback.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ExtractCallback.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ExtractCallback.cpp 2021-10-23 10:26:09.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ExtractCallback.cpp 2023-04-01 13:00:00.000000000 +0000 @@ -17,7 +17,7 @@ #include "../../Common/StreamUtils.h" #include "../Common/ExtractingFilePath.h" -#ifndef _SFX +#ifndef Z7_SFX #include "../Common/ZipRegistry.h" #endif @@ -28,7 +28,7 @@ #include "FormatUtils.h" #include "LangUtils.h" #include "OverwriteDialog.h" -#ifndef _NO_CRYPTO +#ifndef Z7_NO_CRYPTO #include "PasswordDialog.h" #endif #include "PropertyName.h" @@ -48,7 +48,7 @@ NumArchiveErrors = 0; ThereAreMessageErrors = false; - #ifndef _SFX + #ifndef Z7_SFX NumFolders = NumFiles = 0; NeedAddFile = false; #endif @@ -60,29 +60,27 @@ ProgressDialog->Sync.AddError_Message(s); } -#ifndef _SFX +#ifndef Z7_SFX -STDMETHODIMP CExtractCallbackImp::SetNumFiles(UInt64 - #ifndef _SFX - numFiles - #endif - ) +Z7_COM7F_IMF(CExtractCallbackImp::SetNumFiles(UInt64 numFiles)) { - #ifndef _SFX + #ifdef Z7_SFX + UNUSED_VAR(numFiles) + #else ProgressDialog->Sync.Set_NumFilesTotal(numFiles); - #endif + #endif return S_OK; } #endif -STDMETHODIMP CExtractCallbackImp::SetTotal(UInt64 total) +Z7_COM7F_IMF(CExtractCallbackImp::SetTotal(UInt64 total)) { ProgressDialog->Sync.Set_NumBytesTotal(total); return S_OK; } -STDMETHODIMP CExtractCallbackImp::SetCompleted(const UInt64 *value) +Z7_COM7F_IMF(CExtractCallbackImp::SetCompleted(const UInt64 *value)) { return ProgressDialog->Sync.Set_NumBytesCur(value); } @@ -139,7 +137,7 @@ return ProgressDialog->Sync.CheckStop(); } -#ifndef _NO_CRYPTO +#ifndef Z7_NO_CRYPTO HRESULT CExtractCallbackImp::Open_CryptoGetTextPassword(BSTR *password) { @@ -168,8 +166,8 @@ #endif -#ifndef _SFX -STDMETHODIMP CExtractCallbackImp::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) +#ifndef Z7_SFX +Z7_COM7F_IMF(CExtractCallbackImp::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize)) { ProgressDialog->Sync.Set_Ratio(inSize, outSize); return S_OK; @@ -177,13 +175,13 @@ #endif /* -STDMETHODIMP CExtractCallbackImp::SetTotalFiles(UInt64 total) +Z7_COM7F_IMF(CExtractCallbackImp::SetTotalFiles(UInt64 total) { ProgressDialog->Sync.SetNumFilesTotal(total); return S_OK; } -STDMETHODIMP CExtractCallbackImp::SetCompletedFiles(const UInt64 *value) +Z7_COM7F_IMF(CExtractCallbackImp::SetCompletedFiles(const UInt64 *value) { if (value != NULL) ProgressDialog->Sync.SetNumFilesCur(*value); @@ -191,10 +189,10 @@ } */ -STDMETHODIMP CExtractCallbackImp::AskOverwrite( +Z7_COM7F_IMF(CExtractCallbackImp::AskOverwrite( const wchar_t *existName, const FILETIME *existTime, const UInt64 *existSize, const wchar_t *newName, const FILETIME *newTime, const UInt64 *newSize, - Int32 *answer) + Int32 *answer)) { COverwriteDialog dialog; @@ -223,7 +221,7 @@ } -STDMETHODIMP CExtractCallbackImp::PrepareOperation(const wchar_t *name, Int32 isFolder, Int32 askExtractMode, const UInt64 * /* position */) +Z7_COM7F_IMF(CExtractCallbackImp::PrepareOperation(const wchar_t *name, Int32 isFolder, Int32 askExtractMode, const UInt64 * /* position */)) { _isFolder = IntToBool(isFolder); _currentFilePath = name; @@ -241,7 +239,7 @@ return ProgressDialog->Sync.Set_Status2(*msg, name, IntToBool(isFolder)); } -STDMETHODIMP CExtractCallbackImp::MessageError(const wchar_t *s) +Z7_COM7F_IMF(CExtractCallbackImp::MessageError(const wchar_t *s)) { AddError_Message(s); return S_OK; @@ -254,9 +252,9 @@ return S_OK; } -#ifndef _SFX +#ifndef Z7_SFX -STDMETHODIMP CExtractCallbackImp::ShowMessage(const wchar_t *s) +Z7_COM7F_IMF(CExtractCallbackImp::ShowMessage(const wchar_t *s)) { AddError_Message(s); return S_OK; @@ -272,25 +270,33 @@ if (opRes == NArchive::NExtract::NOperationResult::kOK) return; + #ifndef Z7_SFX UINT messageID = 0; + #endif UINT id = 0; switch (opRes) { case NArchive::NExtract::NOperationResult::kUnsupportedMethod: + #ifndef Z7_SFX messageID = IDS_EXTRACT_MESSAGE_UNSUPPORTED_METHOD; + #endif id = IDS_EXTRACT_MSG_UNSUPPORTED_METHOD; break; case NArchive::NExtract::NOperationResult::kDataError: + #ifndef Z7_SFX messageID = encrypted ? IDS_EXTRACT_MESSAGE_DATA_ERROR_ENCRYPTED: IDS_EXTRACT_MESSAGE_DATA_ERROR; + #endif id = IDS_EXTRACT_MSG_DATA_ERROR; break; case NArchive::NExtract::NOperationResult::kCRCError: + #ifndef Z7_SFX messageID = encrypted ? IDS_EXTRACT_MESSAGE_CRC_ERROR_ENCRYPTED: IDS_EXTRACT_MESSAGE_CRC_ERROR; + #endif id = IDS_EXTRACT_MSG_CRC_ERROR; break; case NArchive::NExtract::NOperationResult::kUnavailable: @@ -319,18 +325,19 @@ } UString msg; - UString msgOld; - #ifndef _SFX + #ifndef Z7_SFX + UString msgOld; + #ifdef Z7_LANG if (id != 0) LangString_OnlyFromLangFile(id, msg); if (messageID != 0 && msg.IsEmpty()) LangString_OnlyFromLangFile(messageID, msgOld); - #endif - + #endif if (msg.IsEmpty() && !msgOld.IsEmpty()) s = MyFormatNew(msgOld, fileName); else + #endif { if (msg.IsEmpty() && id != 0) LangString(id, msg); @@ -339,7 +346,7 @@ else { s += "Error #"; - s.Add_UInt32(opRes); + s.Add_UInt32((UInt32)opRes); } if (encrypted && opRes != NArchive::NExtract::NOperationResult::kWrongPassword) @@ -354,7 +361,7 @@ } } -STDMETHODIMP CExtractCallbackImp::SetOperationResult(Int32 opRes, Int32 encrypted) +Z7_COM7F_IMF(CExtractCallbackImp::SetOperationResult(Int32 opRes, Int32 encrypted)) { switch (opRes) { @@ -369,7 +376,7 @@ } } - #ifndef _SFX + #ifndef Z7_SFX if (_isFolder) NumFolders++; else @@ -380,7 +387,7 @@ return S_OK; } -STDMETHODIMP CExtractCallbackImp::ReportExtractResult(Int32 opRes, Int32 encrypted, const wchar_t *name) +Z7_COM7F_IMF(CExtractCallbackImp::ReportExtractResult(Int32 opRes, Int32 encrypted, const wchar_t *name)) { if (opRes != NArchive::NExtract::NOperationResult::kOK) { @@ -397,8 +404,8 @@ HRESULT CExtractCallbackImp::BeforeOpen(const wchar_t *name, bool /* testMode */) { - #ifndef _SFX - RINOK(ProgressDialog->Sync.CheckStop()); + #ifndef Z7_SFX + RINOK(ProgressDialog->Sync.CheckStop()) ProgressDialog->Sync.Set_TitleFileName(name); #endif _currentArchivePath = name; @@ -408,17 +415,17 @@ HRESULT CExtractCallbackImp::SetCurrentFilePath2(const wchar_t *path) { _currentFilePath = path; - #ifndef _SFX + #ifndef Z7_SFX ProgressDialog->Sync.Set_FilePath(path); #endif return S_OK; } -#ifndef _SFX +#ifndef Z7_SFX -HRESULT CExtractCallbackImp::SetCurrentFilePath(const wchar_t *path) +Z7_COM7F_IMF(CExtractCallbackImp::SetCurrentFilePath(const wchar_t *path)) { - #ifndef _SFX + #ifndef Z7_SFX if (NeedAddFile) NumFiles++; NeedAddFile = true; @@ -457,7 +464,7 @@ { UString s; - for (unsigned i = 0; i < ARRAY_SIZE(k_ErrorFlagsIds); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_ErrorFlagsIds); i++) { UInt32 f = ((UInt32)1 << i); if ((errorFlags & f) == 0) @@ -649,7 +656,7 @@ return S_OK; } -#ifndef _NO_CRYPTO +#ifndef Z7_NO_CRYPTO HRESULT CExtractCallbackImp::SetPassword(const UString &password) { @@ -658,14 +665,14 @@ return S_OK; } -STDMETHODIMP CExtractCallbackImp::CryptoGetTextPassword(BSTR *password) +Z7_COM7F_IMF(CExtractCallbackImp::CryptoGetTextPassword(BSTR *password)) { PasswordWasAsked = true; if (!PasswordIsDefined) { CPasswordDialog dialog; - #ifndef _SFX - bool showPassword = NExtract::Read_ShowPassword(); + #ifndef Z7_SFX + const bool showPassword = NExtract::Read_ShowPassword(); dialog.ShowPassword = showPassword; #endif ProgressDialog->WaitCreating(); @@ -673,7 +680,7 @@ return E_ABORT; Password = dialog.Password; PasswordIsDefined = true; - #ifndef _SFX + #ifndef Z7_SFX if (dialog.ShowPassword != showPassword) NExtract::Save_ShowPassword(dialog.ShowPassword); #endif @@ -683,24 +690,24 @@ #endif -#ifndef _SFX +#ifndef Z7_SFX -STDMETHODIMP CExtractCallbackImp::AskWrite( +Z7_COM7F_IMF(CExtractCallbackImp::AskWrite( const wchar_t *srcPath, Int32 srcIsFolder, const FILETIME *srcTime, const UInt64 *srcSize, const wchar_t *destPath, BSTR *destPathResult, - Int32 *writeAnswer) + Int32 *writeAnswer)) { UString destPathResultTemp = destPath; // RINOK(StringToBstr(destPath, destPathResult)); - *destPathResult = 0; + *destPathResult = NULL; *writeAnswer = BoolToInt(false); FString destPathSys = us2fs(destPath); - bool srcIsFolderSpec = IntToBool(srcIsFolder); + const bool srcIsFolderSpec = IntToBool(srcIsFolder); CFileInfo destFileInfo; if (destFileInfo.Find(destPathSys)) @@ -709,7 +716,7 @@ { if (!destFileInfo.IsDir()) { - RINOK(MessageError("Cannot replace file with folder with same name", destPathSys)); + RINOK(MessageError("Cannot replace file with folder with same name", destPathSys)) return E_ABORT; } *writeAnswer = BoolToInt(false); @@ -718,12 +725,12 @@ if (destFileInfo.IsDir()) { - RINOK(MessageError("Cannot replace folder with file with same name", destPathSys)); + RINOK(MessageError("Cannot replace folder with file with same name", destPathSys)) *writeAnswer = BoolToInt(false); return S_OK; } - switch (OverwriteMode) + switch ((int)OverwriteMode) { case NExtract::NOverwriteMode::kSkip: return S_OK; @@ -731,7 +738,7 @@ { Int32 overwriteResult; UString destPathSpec = destPath; - int slashPos = destPathSpec.ReverseFind_PathSepar(); + const int slashPos = destPathSpec.ReverseFind_PathSepar(); destPathSpec.DeleteFrom((unsigned)(slashPos + 1)); destPathSpec += fs2us(destFileInfo.Name); @@ -740,7 +747,7 @@ &destFileInfo.MTime, &destFileInfo.Size, srcPath, srcTime, srcSize, - &overwriteResult)); + &overwriteResult)) switch (overwriteResult) { @@ -763,7 +770,7 @@ { if (!AutoRenamePath(destPathSys)) { - RINOK(MessageError("Cannot create name for file", destPathSys)); + RINOK(MessageError("Cannot create name for file", destPathSys)) return E_ABORT; } destPathResultTemp = fs2us(destPathSys); @@ -774,7 +781,7 @@ if (!NDir::DeleteFileAlways(destPathSys)) if (GetLastError() != ERROR_FILE_NOT_FOUND) { - RINOK(MessageError("Cannot delete output file", destPathSys)); + RINOK(MessageError("Cannot delete output file", destPathSys)) return E_ABORT; } } @@ -784,7 +791,7 @@ } -STDMETHODIMP CExtractCallbackImp::UseExtractToStream(Int32 *res) +Z7_COM7F_IMF(CExtractCallbackImp::UseExtractToStream(Int32 *res)) { *res = BoolToInt(StreamMode); return S_OK; @@ -794,7 +801,7 @@ { ftDefined = false; NCOM::CPropVariant prop; - RINOK(getProp->GetProp(propID, &prop)); + RINOK(getProp->GetProp(propID, &prop)) if (prop.vt == VT_FILETIME) { ft = prop.filetime; @@ -810,7 +817,7 @@ { NCOM::CPropVariant prop; result = false; - RINOK(getProp->GetProp(propID, &prop)); + RINOK(getProp->GetProp(propID, &prop)) if (prop.vt == VT_BOOL) result = VARIANT_BOOLToBool(prop.boolVal); else if (prop.vt != VT_EMPTY) @@ -819,13 +826,13 @@ } -STDMETHODIMP CExtractCallbackImp::GetStream7(const wchar_t *name, +Z7_COM7F_IMF(CExtractCallbackImp::GetStream7(const wchar_t *name, Int32 isDir, ISequentialOutStream **outStream, Int32 askExtractMode, - IGetProp *getProp) + IGetProp *getProp)) { COM_TRY_BEGIN - *outStream = 0; + *outStream = NULL; _newVirtFileWasAdded = false; _hashStreamWasUsed = false; _needUpdateStat = false; @@ -841,20 +848,20 @@ _filePath = name; _isFolder = IntToBool(isDir); _curSize = 0; - _curSizeDefined = false; + _curSize_Defined = false; UInt64 size = 0; bool sizeDefined; { NCOM::CPropVariant prop; - RINOK(getProp->GetProp(kpidSize, &prop)); + RINOK(getProp->GetProp(kpidSize, &prop)) sizeDefined = ConvertPropVariantToUInt64(prop, size); } if (sizeDefined) { _curSize = size; - _curSizeDefined = true; + _curSize_Defined = true; } if (askExtractMode != NArchive::NExtract::NAskMode::kExtract && @@ -874,12 +881,12 @@ file.IsAltStream = _isAltStream; file.Size = 0; - RINOK(GetTime(getProp, kpidCTime, file.CTime, file.CTimeDefined)); - RINOK(GetTime(getProp, kpidATime, file.ATime, file.ATimeDefined)); - RINOK(GetTime(getProp, kpidMTime, file.MTime, file.MTimeDefined)); + RINOK(GetTime(getProp, kpidCTime, file.CTime, file.CTimeDefined)) + RINOK(GetTime(getProp, kpidATime, file.ATime, file.ATimeDefined)) + RINOK(GetTime(getProp, kpidMTime, file.MTime, file.MTimeDefined)) NCOM::CPropVariant prop; - RINOK(getProp->GetProp(kpidAttrib, &prop)); + RINOK(getProp->GetProp(kpidAttrib, &prop)) if (prop.vt == VT_UI4) { file.Attrib = prop.ulVal; @@ -909,7 +916,7 @@ COM_TRY_END } -STDMETHODIMP CExtractCallbackImp::PrepareOperation7(Int32 askExtractMode) +Z7_COM7F_IMF(CExtractCallbackImp::PrepareOperation7(Int32 askExtractMode)) { COM_TRY_BEGIN _needUpdateStat = ( @@ -934,21 +941,21 @@ COM_TRY_END } -STDMETHODIMP CExtractCallbackImp::SetOperationResult8(Int32 opRes, Int32 encrypted, UInt64 size) +Z7_COM7F_IMF(CExtractCallbackImp::SetOperationResult8(Int32 opRes, Int32 encrypted, UInt64 size)) { COM_TRY_BEGIN if (VirtFileSystem && _newVirtFileWasAdded) { // FIXME: probably we must request file size from VirtFileSystem // _curSize = VirtFileSystem->GetLastFileSize() - // _curSizeDefined = true; - RINOK(VirtFileSystemSpec->CloseMemFile()); + // _curSize_Defined = true; + RINOK(VirtFileSystemSpec->CloseMemFile()) } if (_hashStream && _hashStreamWasUsed) { _hashStreamSpec->_hash->Final(_isFolder, _isAltStream, _filePath); _curSize = _hashStreamSpec->GetSize(); - _curSizeDefined = true; + _curSize_Defined = true; _hashStreamSpec->ReleaseStream(); _hashStreamWasUsed = false; } @@ -965,7 +972,7 @@ // static const UInt32 kBlockSize = ((UInt32)1 << 31); -STDMETHODIMP CVirtFileSystem::Write(const void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CVirtFileSystem::Write(const void *data, UInt32 size, UInt32 *processedSize)) { if (processedSize) *processedSize = 0; @@ -1002,7 +1009,7 @@ } _fileMode = true; } - RINOK(FlushToDisk(false)); + RINOK(FlushToDisk(false)) return _outFileStream->Write(data, size, processedSize); } @@ -1026,7 +1033,7 @@ // MessageBoxMyError(UString("Can't create file ") + fs2us(tempFilePath)); } _fileIsOpen = true; - RINOK(WriteStream(_outFileStream, file.Data, (size_t)file.Size)); + RINOK(WriteStream(_outFileStream, file.Data, (size_t)file.Size)) } if (_numFlushed == Files.Size() - 1 && !closeLast) break; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ExtractCallback.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ExtractCallback.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ExtractCallback.h 2021-10-21 18:33:57.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ExtractCallback.h 2023-03-19 19:00:00.000000000 +0000 @@ -1,42 +1,42 @@ // ExtractCallback.h -#ifndef __EXTRACT_CALLBACK_H -#define __EXTRACT_CALLBACK_H +#ifndef ZIP7_INC_EXTRACT_CALLBACK_H +#define ZIP7_INC_EXTRACT_CALLBACK_H #include "../../../../C/Alloc.h" #include "../../../Common/MyCom.h" #include "../../../Common/StringConvert.h" -#ifndef _SFX +#ifndef Z7_SFX #include "../Agent/IFolderArchive.h" #endif #include "../Common/ArchiveExtractCallback.h" #include "../Common/ArchiveOpenCallback.h" -#ifndef _NO_CRYPTO +#ifndef Z7_NO_CRYPTO #include "../../IPassword.h" #endif -#ifndef _SFX +#ifndef Z7_SFX #include "IFolder.h" #endif #include "ProgressDialog2.h" -#ifdef LANG -#include "LangUtils.h" +#ifdef Z7_LANG +// #include "LangUtils.h" #endif -#ifndef _SFX +#ifndef Z7_SFX class CGrowBuf { Byte *_items; size_t _size; - CLASS_NO_COPY(CGrowBuf); + Z7_CLASS_NO_COPY(CGrowBuf) public: bool ReAlloc_KeepData(size_t newSize, size_t keepSize) @@ -52,7 +52,7 @@ return true; } - CGrowBuf(): _items(0), _size(0) {} + CGrowBuf(): _items(NULL), _size(0) {} ~CGrowBuf() { MyFree(_items); } operator Byte *() { return _items; } @@ -92,10 +92,11 @@ IsAltStream(false) {} }; -class CVirtFileSystem: - public ISequentialOutStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_NOQIB_1( + CVirtFileSystem, + ISequentialOutStream +) UInt64 _totalAllocSize; size_t _pos; @@ -156,104 +157,86 @@ HRESULT CloseFile(const FString &path); HRESULT FlushToDisk(bool closeLast); size_t GetPos() const { return _pos; } - - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); }; #endif -class CExtractCallbackImp: - public IExtractCallbackUI, // it includes IFolderArchiveExtractCallback - public IOpenCallbackUI, +class CExtractCallbackImp Z7_final: + public IFolderArchiveExtractCallback, + /* IExtractCallbackUI: + before v23.00 : it included IFolderArchiveExtractCallback + since v23.00 : it doesn't include IFolderArchiveExtractCallback + */ + public IExtractCallbackUI, // NON-COM interface since 23.00 + public IOpenCallbackUI, // NON-COM interface public IFolderArchiveExtractCallback2, - #ifndef _SFX + #ifndef Z7_SFX public IFolderOperationsExtractCallback, public IFolderExtractToStreamCallback, public ICompressProgressInfo, - #endif - #ifndef _NO_CRYPTO + #endif + #ifndef Z7_NO_CRYPTO public ICryptoGetTextPassword, - #endif + #endif public CMyUnknownImp { - HRESULT MessageError(const char *message, const FString &path); - void Add_ArchiveName_Error(); -public: - MY_QUERYINTERFACE_BEGIN2(IFolderArchiveExtractCallback) - MY_QUERYINTERFACE_ENTRY(IFolderArchiveExtractCallback2) - #ifndef _SFX - MY_QUERYINTERFACE_ENTRY(IFolderOperationsExtractCallback) - MY_QUERYINTERFACE_ENTRY(IFolderExtractToStreamCallback) - MY_QUERYINTERFACE_ENTRY(ICompressProgressInfo) - #endif - #ifndef _NO_CRYPTO - MY_QUERYINTERFACE_ENTRY(ICryptoGetTextPassword) - #endif - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IProgress(;) - INTERFACE_IOpenCallbackUI(;) - INTERFACE_IFolderArchiveExtractCallback(;) - INTERFACE_IFolderArchiveExtractCallback2(;) - // STDMETHOD(SetTotalFiles)(UInt64 total); - // STDMETHOD(SetCompletedFiles)(const UInt64 *value); - - INTERFACE_IExtractCallbackUI(;) - - #ifndef _SFX - // IFolderOperationsExtractCallback - STDMETHOD(AskWrite)( - const wchar_t *srcPath, - Int32 srcIsFolder, - const FILETIME *srcTime, - const UInt64 *srcSize, - const wchar_t *destPathRequest, - BSTR *destPathResult, - Int32 *writeAnswer); - STDMETHOD(ShowMessage)(const wchar_t *message); - STDMETHOD(SetCurrentFilePath)(const wchar_t *filePath); - STDMETHOD(SetNumFiles)(UInt64 numFiles); - INTERFACE_IFolderExtractToStreamCallback(;) - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); - #endif + Z7_COM_QI_BEGIN2(IFolderArchiveExtractCallback) + Z7_COM_QI_ENTRY(IFolderArchiveExtractCallback2) + #ifndef Z7_SFX + Z7_COM_QI_ENTRY(IFolderOperationsExtractCallback) + Z7_COM_QI_ENTRY(IFolderExtractToStreamCallback) + Z7_COM_QI_ENTRY(ICompressProgressInfo) + #endif + #ifndef Z7_NO_CRYPTO + Z7_COM_QI_ENTRY(ICryptoGetTextPassword) + #endif + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_IMP(IExtractCallbackUI) + Z7_IFACE_IMP(IOpenCallbackUI) + Z7_IFACE_COM7_IMP(IProgress) + Z7_IFACE_COM7_IMP(IFolderArchiveExtractCallback) + Z7_IFACE_COM7_IMP(IFolderArchiveExtractCallback2) + #ifndef Z7_SFX + Z7_IFACE_COM7_IMP(IFolderOperationsExtractCallback) + Z7_IFACE_COM7_IMP(IFolderExtractToStreamCallback) + Z7_IFACE_COM7_IMP(ICompressProgressInfo) + #endif + #ifndef Z7_NO_CRYPTO + Z7_IFACE_COM7_IMP(ICryptoGetTextPassword) + #endif - // ICryptoGetTextPassword - #ifndef _NO_CRYPTO - STDMETHOD(CryptoGetTextPassword)(BSTR *password); - #endif -private: UString _currentArchivePath; bool _needWriteArchivePath; - UString _currentFilePath; bool _isFolder; + UString _currentFilePath; + UString _filePath; + #ifndef Z7_SFX + bool _needUpdateStat; + bool _newVirtFileWasAdded; bool _isAltStream; + bool _curSize_Defined; UInt64 _curSize; - bool _curSizeDefined; - UString _filePath; // bool _extractMode; // bool _testMode; - bool _newVirtFileWasAdded; - bool _needUpdateStat; - - - HRESULT SetCurrentFilePath2(const wchar_t *filePath); - void AddError_Message(LPCWSTR message); - - #ifndef _SFX bool _hashStreamWasUsed; COutStreamWithHash *_hashStreamSpec; CMyComPtr _hashStream; IHashCalc *_hashCalc; // it's for stat in Test operation - #endif + #endif + + HRESULT SetCurrentFilePath2(const wchar_t *filePath); + void AddError_Message(LPCWSTR message); + HRESULT MessageError(const char *message, const FString &path); + void Add_ArchiveName_Error(); public: - #ifndef _SFX + #ifndef Z7_SFX CVirtFileSystem *VirtFileSystemSpec; CMyComPtr VirtFileSystem; #endif @@ -263,7 +246,7 @@ bool StreamMode; CProgressDialog *ProgressDialog; - #ifndef _SFX + #ifndef Z7_SFX UInt64 NumFolders; UInt64 NumFiles; bool NeedAddFile; @@ -272,7 +255,7 @@ bool ThereAreMessageErrors; NExtract::NOverwriteMode::EEnum OverwriteMode; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO bool PasswordIsDefined; bool PasswordWasAsked; UString Password; @@ -290,13 +273,13 @@ bool MultiArcMode; CExtractCallbackImp(): - #ifndef _SFX + #ifndef Z7_SFX _hashCalc(NULL), #endif ProcessAltStreams(true), StreamMode(false), OverwriteMode(NExtract::NOverwriteMode::kAsk), - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO PasswordIsDefined(false), PasswordWasAsked(false), #endif @@ -308,7 +291,7 @@ ~CExtractCallbackImp(); void Init(); - #ifndef _SFX + #ifndef Z7_SFX void SetHashCalc(IHashCalc *hashCalc) { _hashCalc = hashCalc; } void SetHashMethods(IHashCalc *hash) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FileFolderPluginOpen.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FileFolderPluginOpen.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FileFolderPluginOpen.cpp 2021-01-24 14:00:21.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FileFolderPluginOpen.cpp 2023-04-01 11:00:00.000000000 +0000 @@ -26,8 +26,15 @@ UString ArcFormat; CMyComPtr InStream; CMyComPtr FolderManager; - CMyComPtr OpenCallback; + CMyComPtr OpenCallbackProgress; + COpenArchiveCallback *OpenCallbackSpec; + /* + CMyComPtr + // CMyComPtr + // CMyComPtr + OpenCallbackSpec_Ref; + */ CMyComPtr Folder; HRESULT Result; @@ -37,7 +44,7 @@ try { CProgressCloser closer(OpenCallbackSpec->ProgressDialog); - Result = FolderManager->OpenFolderFile(InStream, Path, ArcFormat, &Folder, OpenCallback); + Result = FolderManager->OpenFolderFile(InStream, Path, ArcFormat, &Folder, OpenCallbackProgress); } catch(...) { Result = E_FAIL; } } @@ -62,7 +69,7 @@ static void SplitNameToPureNameAndExtension(const FString &fullName, FString &pureName, FString &extensionDelimiter, FString &extension) { - int index = fullName.ReverseFind_Dot(); + const int index = fullName.ReverseFind_Dot(); if (index < 0) { pureName = fullName; @@ -71,7 +78,7 @@ } else { - pureName.SetFrom(fullName, index); + pureName.SetFrom(fullName, (unsigned)index); extensionDelimiter = '.'; extension = fullName.Ptr((unsigned)index + 1); } @@ -229,16 +236,21 @@ } } +#ifdef _MSC_VER +#pragma warning(error : 4702) // unreachable code +#endif HRESULT CFfpOpen::OpenFileFolderPlugin(IInStream *inStream, const FString &path, const UString &arcFormat, HWND parentWindow) { + /* CObjectVector plugins; ReadFileFolderPluginInfoList(plugins); + */ FString extension, name, pureName, dot; - int slashPos = path.ReverseFind_PathSepar(); + const int slashPos = path.ReverseFind_PathSepar(); FString dirPrefix; FString fileName; if (slashPos >= 0) @@ -273,31 +285,48 @@ ErrorMessage.Empty(); - FOR_VECTOR (i, plugins) - { + // FOR_VECTOR (i, plugins) + // { + /* const CPluginInfo &plugin = plugins[i]; - if (!plugin.ClassIDDefined) + if (!plugin.ClassID_Defined && !plugin.FilePath.IsEmpty()) continue; + */ CPluginLibrary library; CThreadArchiveOpen t; - if (plugin.FilePath.IsEmpty()) + // if (plugin.FilePath.IsEmpty()) t.FolderManager = new CArchiveFolderManager; + /* else if (library.LoadAndCreateManager(plugin.FilePath, plugin.ClassID, &t.FolderManager) != S_OK) continue; + */ + COpenArchiveCallback OpenCallbackSpec_loc; + t.OpenCallbackSpec = &OpenCallbackSpec_loc; + /* t.OpenCallbackSpec = new COpenArchiveCallback; - t.OpenCallback = t.OpenCallbackSpec; + t.OpenCallbackSpec_Ref = t.OpenCallbackSpec; + */ t.OpenCallbackSpec->PasswordIsDefined = Encrypted; t.OpenCallbackSpec->Password = Password; t.OpenCallbackSpec->ParentWindow = parentWindow; + /* COpenCallbackImp object will exist after Open stage for multivolume archives */ + COpenCallbackImp *openCallbackSpec = new COpenCallbackImp; + t.OpenCallbackProgress = openCallbackSpec; + // openCallbackSpec->Callback_Ref = t.OpenCallbackSpec; + // we set pointer without reference counter: + openCallbackSpec->Callback = + // openCallbackSpec->ReOpenCallback = + t.OpenCallbackSpec; + if (inStream) - t.OpenCallbackSpec->SetSubArchiveName(fs2us(fileName)); + openCallbackSpec->SetSubArchiveName(fs2us(fileName)); else { - RINOK(t.OpenCallbackSpec->LoadFileInfo2(dirPrefix, fileName)); + RINOK(openCallbackSpec->Init2(dirPrefix, fileName)) } t.InStream = inStream; @@ -315,10 +344,20 @@ { NWindows::CThread thread; - RINOK(thread.Create(CThreadArchiveOpen::MyThreadFunction, &t)); + const WRes wres = thread.Create(CThreadArchiveOpen::MyThreadFunction, &t); + if (wres != 0) + return HRESULT_FROM_WIN32(wres); t.OpenCallbackSpec->StartProgressDialog(progressTitle, thread); } + /* + if archive is multivolume: + COpenCallbackImp object will exist after Open stage. + COpenCallbackImp object will be deleted when last reference + from each volume object (CInFileStreamVol) will be closed (when archive will be closed). + */ + t.OpenCallbackProgress.Release(); + if (t.Result != S_FALSE && t.Result != S_OK) return t.Result; @@ -351,7 +390,5 @@ } return t.Result; - } - - return S_FALSE; + // } } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FileFolderPluginOpen.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FileFolderPluginOpen.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FileFolderPluginOpen.h 2020-06-09 09:49:48.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FileFolderPluginOpen.h 2023-01-31 18:00:00.000000000 +0000 @@ -1,13 +1,13 @@ // FileFolderPluginOpen.h -#ifndef __FILE_FOLDER_PLUGIN_OPEN_H -#define __FILE_FOLDER_PLUGIN_OPEN_H +#ifndef ZIP7_INC_FILE_FOLDER_PLUGIN_OPEN_H +#define ZIP7_INC_FILE_FOLDER_PLUGIN_OPEN_H #include "../../../Windows/DLL.h" struct CFfpOpen { - CLASS_NO_COPY(CFfpOpen) + Z7_CLASS_NO_COPY(CFfpOpen) public: // out: bool Encrypted; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FilePlugins.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FilePlugins.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FilePlugins.cpp 2014-07-12 16:26:01.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FilePlugins.cpp 2023-02-01 08:00:00.000000000 +0000 @@ -8,28 +8,37 @@ #include "PluginLoader.h" #include "StringUtils.h" -int CExtDatabase::FindExt(const UString &ext) +int CExtDatabase::FindExt(const UString &ext) const { FOR_VECTOR (i, Exts) if (Exts[i].Ext.IsEqualTo_NoCase(ext)) - return i; + return (int)i; return -1; } void CExtDatabase::Read() { + /* ReadFileFolderPluginInfoList(Plugins); FOR_VECTOR (pluginIndex, Plugins) + */ { - const CPluginInfo &plugin = Plugins[pluginIndex]; + // const CPluginInfo &plugin = Plugins[pluginIndex]; CPluginLibrary pluginLib; CMyComPtr folderManager; - if (plugin.FilePath.IsEmpty()) + // if (plugin.FilePath.IsEmpty()) folderManager = new CArchiveFolderManager; - else if (pluginLib.LoadAndCreateManager(plugin.FilePath, plugin.ClassID, &folderManager) != S_OK) - continue; + /* + else + { + if (!plugin.ClassID_Defined) + continue; + if (pluginLib.LoadAndCreateManager(plugin.FilePath, plugin.ClassID, &folderManager) != S_OK) + continue; + } + */ CMyComBSTR extBSTR; if (folderManager->GetExtensions(&extBSTR) != S_OK) return; @@ -46,15 +55,15 @@ Int32 iconIndex; CMyComBSTR iconPath; CPluginToIcon plugPair; - plugPair.PluginIndex = pluginIndex; + // plugPair.PluginIndex = pluginIndex; if (folderManager->GetIconPath(ext, &iconPath, &iconIndex) == S_OK) - if (iconPath != 0) + if (iconPath) { plugPair.IconPath = (const wchar_t *)iconPath; plugPair.IconIndex = iconIndex; } - int index = FindExt(ext); + const int index = FindExt(ext); if (index >= 0) Exts[index].Plugins.Add(plugPair); else diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FilePlugins.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FilePlugins.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FilePlugins.h 2010-12-11 07:55:04.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FilePlugins.h 2023-01-30 20:00:00.000000000 +0000 @@ -1,15 +1,15 @@ // FilePlugins.h -#ifndef __FILE_PLUGINS_H -#define __FILE_PLUGINS_H +#ifndef ZIP7_INC_FILE_PLUGINS_H +#define ZIP7_INC_FILE_PLUGINS_H #include "RegistryPlugins.h" struct CPluginToIcon { - int PluginIndex; - UString IconPath; + // unsigned PluginIndex; int IconIndex; + UString IconPath; CPluginToIcon(): IconIndex(-1) {} }; @@ -22,10 +22,10 @@ class CExtDatabase { - int FindExt(const UString &ext); + int FindExt(const UString &ext) const; public: CObjectVector Exts; - CObjectVector Plugins; + // CObjectVector Plugins; void Read(); }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FM.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FM.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FM.cpp 2021-01-26 12:19:40.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FM.cpp 2023-03-23 17:00:00.000000000 +0000 @@ -4,8 +4,13 @@ #include "../../../Common/MyWindows.h" +#if defined(__MINGW32__) || defined(__MINGW64__) +#include +#else #include +#endif +#include "../../../../C/Compiler.h" #include "../../../../C/Alloc.h" #ifdef _WIN32 #include "../../../../C/DllSecur.h" @@ -46,7 +51,9 @@ bool g_RAM_Size_Defined; bool g_RAM_Size_Defined; -static bool g_LargePagesMode = false; +extern +bool g_LargePagesMode; +bool g_LargePagesMode = false; // static bool g_OpenArchive = false; static bool g_Maximized = false; @@ -78,20 +85,23 @@ static DWORD GetDllVersion(LPCTSTR dllName) { DWORD dwVersion = 0; - HINSTANCE hinstDll = LoadLibrary(dllName); - if (hinstDll) + const HMODULE hmodule = LoadLibrary(dllName); + if (hmodule) { - DLLGETVERSIONPROC pDllGetVersion = (DLLGETVERSIONPROC)(void *)GetProcAddress(hinstDll, "DllGetVersion"); - if (pDllGetVersion) + const + DLLGETVERSIONPROC f_DllGetVersion = Z7_GET_PROC_ADDRESS( + DLLGETVERSIONPROC, hmodule, + "DllGetVersion"); + if (f_DllGetVersion) { DLLVERSIONINFO dvi; ZeroMemory(&dvi, sizeof(dvi)); dvi.cbSize = sizeof(dvi); - HRESULT hr = (*pDllGetVersion)(&dvi); + const HRESULT hr = f_DllGetVersion(&dvi); if (SUCCEEDED(hr)) - dwVersion = MAKELONG(dvi.dwMinorVersion, dvi.dwMajorVersion); + dwVersion = (DWORD)MAKELONG(dvi.dwMinorVersion, dvi.dwMajorVersion); } - FreeLibrary(hinstDll); + FreeLibrary(hmodule); } return dwVersion; } @@ -180,7 +190,7 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); -static const wchar_t * const kWindowClass = L"FM"; +static const wchar_t * const kWindowClass = L"7-Zip::FM"; #ifdef UNDER_CE #define WS_OVERLAPPEDWINDOW ( \ @@ -222,7 +232,7 @@ wc.hIcon = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_ICON)); // wc.hCursor = LoadCursor (NULL, IDC_ARROW); - wc.hCursor = ::LoadCursor(0, IDC_SIZEWE); + wc.hCursor = ::LoadCursor(NULL, IDC_SIZEWE); // wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH); wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1); @@ -236,7 +246,8 @@ wc.lpszClassName = kWindowClass; - MyRegisterClass(&wc); + if (MyRegisterClass(&wc) == 0) + return FALSE; // RECT rect; // GetClientRect(hWnd, &rect); @@ -305,7 +316,7 @@ { if (windowPosIsRead) placement.rcNormalPosition = info.rect; - placement.showCmd = nCmdShow; + placement.showCmd = (UINT)nCmdShow; wnd.SetPlacement(&placement); } else @@ -343,6 +354,8 @@ #if defined(_WIN32) && !defined(_WIN64) && !defined(UNDER_CE) +extern +bool g_Is_Wow64; bool g_Is_Wow64; typedef BOOL (WINAPI *Func_IsWow64Process)(HANDLE, PBOOL); @@ -350,18 +363,27 @@ static void Set_Wow64() { g_Is_Wow64 = false; - Func_IsWow64Process fnIsWow64Process = (Func_IsWow64Process)(void *)GetProcAddress( - GetModuleHandleA("kernel32.dll"), "IsWow64Process"); - if (fnIsWow64Process) + const + Func_IsWow64Process fn = Z7_GET_PROC_ADDRESS( + Func_IsWow64Process, GetModuleHandleA("kernel32.dll"), + "IsWow64Process"); + if (fn) { BOOL isWow; - if (fnIsWow64Process(GetCurrentProcess(), &isWow)) + if (fn(GetCurrentProcess(), &isWow)) g_Is_Wow64 = (isWow != FALSE); } } #endif +#if _MSC_VER > 1400 /* && _MSC_VER <= 1900 */ + // GetVersion was declared deprecated + #pragma warning(disable : 4996) +#endif +#ifdef __clang__ + #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif bool IsLargePageSupported(); bool IsLargePageSupported() @@ -369,18 +391,17 @@ #ifdef _WIN64 return true; #else - OSVERSIONINFO vi; - vi.dwOSVersionInfoSize = sizeof(vi); - if (!::GetVersionEx(&vi)) - return false; - if (vi.dwPlatformId != VER_PLATFORM_WIN32_NT) - return false; - if (vi.dwMajorVersion < 5) return false; - if (vi.dwMajorVersion > 5) return true; - if (vi.dwMinorVersion < 1) return false; - if (vi.dwMinorVersion > 1) return true; - // return g_Is_Wow64; - return false; + + DWORD v = GetVersion(); + // low byte is major version: + // next byte is minor version: + v = ((v & 0xff) << 8) | ((v >> 8) & 0xFF); + return (v > 0x501); + // if ((Byte)v < 5) return false; + // if ((Byte)v > 5) return true; + // return ((Byte)(v >> 8) > 1); + /* large pages work in 5.1 (XP-32bit) if it's (g_Is_Wow64) mode; + but here we don't enable them in (XP-32bit). */ #endif } @@ -407,12 +428,10 @@ static void Set_SymLink_Supported() { - g_SymLink_Supported = false; - OSVERSIONINFO vi; - vi.dwOSVersionInfoSize = sizeof(vi); - if (!::GetVersionEx(&vi)) - return; - if (vi.dwPlatformId != VER_PLATFORM_WIN32_NT || vi.dwMajorVersion < 6) + // g_SymLink_Supported = false; + const DWORD v = GetVersion(); + // low byte is major version: + if ((Byte)v < 6) return; g_SymLink_Supported = true; // if (g_SymLink_Supported) @@ -444,7 +463,7 @@ static void ErrorMessage(const wchar_t *s) { - MessageBoxW(0, s, L"7-Zip", MB_ICONERROR); + MessageBoxW(NULL, s, L"7-Zip", MB_ICONERROR); } static void ErrorMessage(const char *s) @@ -488,11 +507,15 @@ */ NT_CHECK + #ifdef Z7_LARGE_PAGES SetLargePageSize(); + #endif #endif + #ifdef Z7_LANG LoadLangOneTime(); + #endif InitCommonControls(); @@ -516,7 +539,7 @@ // NCOM::CComInitializer comInitializer; UString commandsString; - // MessageBoxW(0, GetCommandLineW(), L"", 0); + // MessageBoxW(NULL, GetCommandLineW(), L"", 0); #ifdef UNDER_CE commandsString = GetCommandLineW(); @@ -577,7 +600,7 @@ g_MainPath = paramString; // return WinMain2(hInstance, hPrevInstance, lpCmdLine, nCmdShow); - // MessageBoxW(0, paramString, L"", 0); + // MessageBoxW(NULL, paramString, L"", 0); } /* UStringVector commandStrings; @@ -608,7 +631,7 @@ Set_SymLink_Supported(); #endif - g_App.ReloadLang(); + g_App.ReloadLangItems(); MSG msg; if (!InitInstance (nCmdShow)) @@ -654,7 +677,7 @@ // But we suppose that it's better to release DLLs here (before destructor). FreeGlobalCodecs(); - g_HWND = 0; + g_HWND = NULL; #ifndef UNDER_CE OleUninitialize(); #endif @@ -714,7 +737,7 @@ catch(int v) { AString e ("Error: "); - e.Add_UInt32(v); + e.Add_UInt32((unsigned)v); ErrorMessage(e); return 1; } @@ -748,7 +771,7 @@ info.numPanels = g_App.NumPanels; info.currentPanel = g_App.LastFocusedPanel; - info.splitterPos = g_Splitter.GetPos(); + info.splitterPos = (unsigned)g_Splitter.GetPos(); info.Save(); } @@ -825,23 +848,23 @@ WS_CHILD | WS_BORDER | WS_VISIBLE | TBSTYLE_TOOLTIPS, // | TBSTYLE_FLAT baseID + 2, 11, (HINSTANCE)HINST_COMMCTRL, IDB_VIEW_SMALL_COLOR, - (LPCTBBUTTON)&tbb, ARRAY_SIZE(tbb), + (LPCTBBUTTON)&tbb, Z7_ARRAY_SIZE(tbb), 0, 0, 100, 30, sizeof (TBBUTTON))); */ // HCURSOR cursor = ::LoadCursor(0, IDC_SIZEWE); // ::SetCursor(cursor); if (g_PanelsInfoDefined) - g_Splitter.SetPos(hWnd, g_SplitterPos); + g_Splitter.SetPos(hWnd, (int)g_SplitterPos); else { g_Splitter.SetRatio(hWnd, kSplitterRateMax / 2); - g_SplitterPos = g_Splitter.GetPos(); + g_SplitterPos = (unsigned)g_Splitter.GetPos(); } RECT rect; ::GetClientRect(hWnd, &rect); - int xSize = rect.right; + const int xSize = rect.right; int xSizes[2]; xSizes[0] = g_Splitter.GetPos(); xSizes[1] = xSize - kSplitterWidth - xSizes[0]; @@ -954,7 +977,7 @@ g_Splitter.SetPosFromRatio(hWnd); else { - g_Splitter.SetPos(hWnd, g_SplitterPos ); + g_Splitter.SetPos(hWnd, (int)g_SplitterPos ); g_CanChangeSplitter = true; } @@ -1047,7 +1070,7 @@ { HWND hWnd = _window; RECT rect; - if (hWnd == 0) + if (!hWnd) return; ::GetClientRect(hWnd, &rect); int xSize = rect.right; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FM.dsp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FM.dsp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FM.dsp 2021-10-08 17:32:59.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FM.dsp 2023-03-07 10:00:00.000000000 +0000 @@ -45,7 +45,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_MBCS" /D "WIN32" /D "_WINDOWS" /D "LANG" /D "WIN_LONG_PATH" /D "NEW_FOLDER_INTERFACE" /D "EXTERNAL_CODECS" /D "SUPPORT_DEVICE_FILE" /FAcs /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_MBCS" /D "WIN32" /D "_WINDOWS" /D "Z7_LANG" /D "Z7_LONG_PATH" /D "Z7_EXTERNAL_CODECS" /D "Z7_DEVICE_FILE" /FAcs /Yu"StdAfx.h" /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "NDEBUG" @@ -72,7 +72,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /Gz /MDd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_MBCS" /D "WIN32" /D "_WINDOWS" /D "LANG" /D "WIN_LONG_PATH" /D "NEW_FOLDER_INTERFACE" /D "EXTERNAL_CODECS" /D "SUPPORT_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gz /MDd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_MBCS" /D "WIN32" /D "_WINDOWS" /D "Z7_LANG" /D "Z7_LONG_PATH" /D "Z7_EXTERNAL_CODECS" /D "Z7_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "_DEBUG" @@ -99,7 +99,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"StdAfx.h" /FD /c -# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "LANG" /D "WIN_LONG_PATH" /D "NEW_FOLDER_INTERFACE" /D "EXTERNAL_CODECS" /D "SUPPORT_DEVICE_FILE" /Yu"StdAfx.h" /FD /c +# ADD CPP /nologo /Gz /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "Z7_LANG" /D "Z7_LONG_PATH" /D "Z7_EXTERNAL_CODECS" /D "Z7_DEVICE_FILE" /Yu"StdAfx.h" /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "NDEBUG" @@ -127,7 +127,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"StdAfx.h" /FD /GZ /c -# ADD CPP /nologo /Gz /MDd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "LANG" /D "WIN_LONG_PATH" /D "NEW_FOLDER_INTERFACE" /D "EXTERNAL_CODECS" /D "SUPPORT_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c +# ADD CPP /nologo /Gz /MDd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "Z7_LANG" /D "Z7_LONG_PATH" /D "Z7_EXTERNAL_CODECS" /D "Z7_DEVICE_FILE" /Yu"StdAfx.h" /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "_DEBUG" @@ -707,6 +707,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\7zWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\Alloc.c # SUBTRACT CPP /YX /Yc /Yu # End Source File @@ -716,6 +720,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\Compiler.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\CpuArch.c # SUBTRACT CPP /YX /Yc /Yu # End Source File @@ -1112,6 +1120,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyInitGuid.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\MyString.cpp # End Source File # Begin Source File @@ -1132,6 +1144,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\NewHandler.cpp # End Source File # Begin Source File @@ -1431,6 +1447,14 @@ # End Source File # Begin Source File +SOURCE=..\Explorer\MyMessages.cpp +# End Source File +# Begin Source File + +SOURCE=..\Explorer\MyMessages.h +# End Source File +# Begin Source File + SOURCE=..\Explorer\RegistryContextMenu.cpp # End Source File # Begin Source File diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FM.mak 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FM.mak --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FM.mak 2021-01-22 21:27:52.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FM.mak 2023-06-20 07:00:00.000000000 +0000 @@ -1,12 +1,11 @@ CFLAGS = $(CFLAGS) \ - -DLANG \ - -DNEW_FOLDER_INTERFACE \ + -DZ7_LANG \ !IFDEF UNDER_CE LIBS = $(LIBS) ceshell.lib Commctrl.lib !ELSE LIBS = $(LIBS) comctl32.lib htmlhelp.lib comdlg32.lib Mpr.lib Gdi32.lib -CFLAGS = $(CFLAGS) -DWIN_LONG_PATH -DSUPPORT_DEVICE_FILE +CFLAGS = $(CFLAGS) -DZ7_LONG_PATH -DZ7_DEVICE_FILE LFLAGS = $(LFLAGS) /DELAYLOAD:mpr.dll LIBS = $(LIBS) delayimp.lib !ENDIF @@ -47,7 +46,6 @@ $O\ProgramLocation.obj \ $O\PropertyName.obj \ $O\RegistryAssociations.obj \ - $O\RegistryPlugins.obj \ $O\RegistryUtils.obj \ $O\RootFolder.obj \ $O\SplitUtils.obj \ @@ -98,3 +96,5 @@ $O\ArchiveFolderOpen.obj \ $O\ArchiveFolderOut.obj \ $O\UpdateCallbackAgent.obj \ + +# we need empty line after last line above diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FoldersPage.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FoldersPage.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FoldersPage.cpp 2017-02-02 11:41:53.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FoldersPage.cpp 2023-03-19 10:00:00.000000000 +0000 @@ -11,6 +11,7 @@ using namespace NWindows; +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { IDT_FOLDERS_WORKING_FOLDER, @@ -19,8 +20,9 @@ IDR_FOLDERS_WORK_SPECIFIED, IDX_FOLDERS_WORK_FOR_REMOVABLE }; +#endif -static const int kWorkModeButtons[] = +static const unsigned kWorkModeButtons[] = { IDR_FOLDERS_WORK_SYSTEM, IDR_FOLDERS_WORK_CURRENT, @@ -29,19 +31,23 @@ #define kFoldersTopic "fm/options.htm#folders" -static const unsigned kNumWorkModeButtons = ARRAY_SIZE(kWorkModeButtons); +static const unsigned kNumWorkModeButtons = Z7_ARRAY_SIZE(kWorkModeButtons); bool CFoldersPage::OnInit() { _initMode = true; _needSave = false; - LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); + #ifdef Z7_LANG + LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs)); + #endif m_WorkDirInfo.Load(); CheckButton(IDX_FOLDERS_WORK_FOR_REMOVABLE, m_WorkDirInfo.ForRemovableOnly); - CheckRadioButton(kWorkModeButtons[0], kWorkModeButtons[kNumWorkModeButtons - 1], + CheckRadioButton( + kWorkModeButtons[0], + kWorkModeButtons[kNumWorkModeButtons - 1], kWorkModeButtons[m_WorkDirInfo.Mode]); m_WorkPath.Init(*this, IDE_FOLDERS_WORK_PATH); @@ -58,7 +64,7 @@ { for (unsigned i = 0; i < kNumWorkModeButtons; i++) if (IsButtonCheckedBool(kWorkModeButtons[i])) - return i; + return (int)i; throw 0; } @@ -104,7 +110,7 @@ */ } -bool CFoldersPage::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CFoldersPage::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { for (unsigned i = 0; i < kNumWorkModeButtons; i++) if (buttonID == kWorkModeButtons[i]) @@ -129,7 +135,7 @@ return true; } -bool CFoldersPage::OnCommand(int code, int itemID, LPARAM lParam) +bool CFoldersPage::OnCommand(unsigned code, unsigned itemID, LPARAM lParam) { if (code == EN_CHANGE && itemID == IDE_FOLDERS_WORK_PATH) { diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FoldersPage.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FoldersPage.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FoldersPage.h 2015-12-05 10:28:28.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FoldersPage.h 2023-01-28 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // FoldersPage.h -#ifndef __FOLDERS_PAGE_H -#define __FOLDERS_PAGE_H +#ifndef ZIP7_INC_FOLDERS_PAGE_H +#define ZIP7_INC_FOLDERS_PAGE_H #include "../../../Windows/Control/PropertyPage.h" @@ -22,11 +22,11 @@ int GetWorkMode() const; void GetWorkDir(NWorkDir::CInfo &workDirInfo); // bool WasChanged(); - virtual bool OnInit(); - virtual bool OnCommand(int code, int itemID, LPARAM lParam); - virtual void OnNotifyHelp(); - virtual LONG OnApply(); - virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); + virtual bool OnInit() Z7_override; + virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM lParam) Z7_override; + virtual void OnNotifyHelp() Z7_override; + virtual LONG OnApply() Z7_override; + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FormatUtils.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FormatUtils.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FormatUtils.h 2013-01-17 07:55:23.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FormatUtils.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // FormatUtils.h -#ifndef __FORMAT_UTILS_H -#define __FORMAT_UTILS_H +#ifndef ZIP7_INC_FORMAT_UTILS_H +#define ZIP7_INC_FORMAT_UTILS_H #include "../../../Common/MyTypes.h" #include "../../../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FSDrives.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FSDrives.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FSDrives.cpp 2021-12-14 20:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FSDrives.cpp 2023-04-06 11:00:00.000000000 +0000 @@ -41,7 +41,7 @@ struct CPhysTempBuffer { void *buffer; - CPhysTempBuffer(): buffer(0) {} + CPhysTempBuffer(): buffer(NULL) {} ~CPhysTempBuffer() { MidFree(buffer); } }; @@ -50,22 +50,22 @@ { NIO::CInFile inFile; if (!inFile.Open(fromPath)) - return GetLastError(); + return GetLastError_noZero_HRESULT(); if (fileSize == (UInt64)(Int64)-1) { if (!inFile.GetLength(fileSize)) - ::GetLastError(); + return GetLastError_noZero_HRESULT(); } NIO::COutFile outFile; if (writeToDisk) { if (!outFile.Open(toPath, FILE_SHARE_WRITE, OPEN_EXISTING, 0)) - return GetLastError(); + return GetLastError_noZero_HRESULT(); } else if (!outFile.Create(toPath, true)) - return GetLastError(); + return GetLastError_noZero_HRESULT(); CPhysTempBuffer tempBuffer; tempBuffer.buffer = MidAlloc(bufferSize); @@ -75,12 +75,12 @@ for (UInt64 pos = 0; pos < fileSize;) { UInt64 progressCur = progressStart + pos; - RINOK(progress->SetCompleted(&progressCur)); + RINOK(progress->SetCompleted(&progressCur)) UInt64 rem = fileSize - pos; UInt32 curSize = (UInt32)MyMin(rem, (UInt64)bufferSize); UInt32 processedSize; if (!inFile.Read(tempBuffer.buffer, curSize, processedSize)) - return GetLastError(); + return GetLastError_noZero_HRESULT(); if (processedSize == 0) break; curSize = processedSize; @@ -93,7 +93,7 @@ } if (!outFile.Write(tempBuffer.buffer, curSize, processedSize)) - return GetLastError(); + return GetLastError_noZero_HRESULT(); if (curSize != processedSize) return E_FAIL; pos += curSize; @@ -125,7 +125,7 @@ , "RAM disk" }; -STDMETHODIMP CFSDrives::LoadItems() +Z7_COM7F_IMF(CFSDrives::LoadItems()) { _drives.Clear(); @@ -209,13 +209,13 @@ return S_OK; } -STDMETHODIMP CFSDrives::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CFSDrives::GetNumberOfItems(UInt32 *numItems)) { *numItems = _drives.Size(); return S_OK; } -STDMETHODIMP CFSDrives::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CFSDrives::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT *value)) { if (itemIndex >= (UInt32)_drives.Size()) return E_INVALIDARG; @@ -239,7 +239,7 @@ case kpidFreeSpace: if (di.KnownSizes) prop = di.FreeSpace; break; case kpidClusterSize: if (di.KnownSizes) prop = di.ClusterSize; break; case kpidType: - if (di.DriveType < ARRAY_SIZE(kDriveTypes)) + if (di.DriveType < Z7_ARRAY_SIZE(kDriveTypes)) prop = kDriveTypes[di.DriveType]; break; case kpidVolumeName: prop = di.VolumeName; break; @@ -251,7 +251,7 @@ HRESULT CFSDrives::BindToFolderSpec(CFSTR name, IFolderFolder **resultFolder) { - *resultFolder = 0; + *resultFolder = NULL; if (_volumeMode) return S_OK; NFsFolder::CFSFolder *fsFolderSpec = new NFsFolder::CFSFolder; @@ -260,14 +260,14 @@ if (_superMode) path = kSuperPrefix; path += name; - RINOK(fsFolderSpec->Init(path)); + RINOK(fsFolderSpec->Init(path)) *resultFolder = subFolder.Detach(); return S_OK; } -STDMETHODIMP CFSDrives::BindToFolder(UInt32 index, IFolderFolder **resultFolder) +Z7_COM7F_IMF(CFSDrives::BindToFolder(UInt32 index, IFolderFolder **resultFolder)) { - *resultFolder = 0; + *resultFolder = NULL; if (index >= (UInt32)_drives.Size()) return E_INVALIDARG; const CDriveInfo &di = _drives[index]; @@ -285,20 +285,20 @@ return BindToFolderSpec(di.FullSystemName, resultFolder); } -STDMETHODIMP CFSDrives::BindToFolder(const wchar_t *name, IFolderFolder **resultFolder) +Z7_COM7F_IMF(CFSDrives::BindToFolder(const wchar_t *name, IFolderFolder **resultFolder)) { return BindToFolderSpec(us2fs(name), resultFolder); } -STDMETHODIMP CFSDrives::BindToParentFolder(IFolderFolder **resultFolder) +Z7_COM7F_IMF(CFSDrives::BindToParentFolder(IFolderFolder **resultFolder)) { - *resultFolder = 0; + *resultFolder = NULL; return S_OK; } IMP_IFolderFolder_Props(CFSDrives) -STDMETHODIMP CFSDrives::GetFolderProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CFSDrives::GetFolderProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -320,7 +320,7 @@ } -STDMETHODIMP CFSDrives::GetSystemIconIndex(UInt32 index, Int32 *iconIndex) +Z7_COM7F_IMF(CFSDrives::GetSystemIconIndex(UInt32 index, Int32 *iconIndex)) { *iconIndex = 0; const CDriveInfo &di = _drives[index]; @@ -332,39 +332,64 @@ *iconIndex = iconIndexTemp; return S_OK; } - return GetLastError(); + return GetLastError_noZero_HRESULT(); } void CFSDrives::AddExt(FString &s, unsigned index) const { - s += '.'; + s.Add_Dot(); const CDriveInfo &di = _drives[index]; + UString n = di.FileSystemName; + n.MakeLower_Ascii(); const char *ext; if (di.DriveType == DRIVE_CDROM) ext = "iso"; - else if (di.FileSystemName.IsPrefixedBy_Ascii_NoCase("NTFS")) - ext = "ntfs"; - else if (di.FileSystemName.IsPrefixedBy_Ascii_NoCase("FAT")) - ext = "fat"; else + { + unsigned i; + for (i = 0; i < n.Len(); i++) + { + const wchar_t c = n[i]; + if (c < 'a' || c > 'z') + break; + } + if (i != 0) + { + n.DeleteFrom(i); + s += us2fs(n); + return; + } ext = "img"; + } + /* + if (n.IsPrefixedBy_Ascii_NoCase("NTFS")) ext = "ntfs"; + else if (n.IsPrefixedBy_Ascii_NoCase("UDF")) ext = "udf"; + else if (n.IsPrefixedBy_Ascii_NoCase("exFAT")) ext = "exfat"; + */ s += ext; } -HRESULT CFSDrives::GetFileSize(unsigned index, UInt64 &fileSize) const +HRESULT CFSDrives::GetFileSize(unsigned index, UInt64& fileSize) const { +#ifdef Z7_DEVICE_FILE NIO::CInFile inFile; if (!inFile.Open(_drives[index].GetDeviceFileIoName())) - return GetLastError(); - if (!inFile.SizeDefined) - return E_FAIL; - fileSize = inFile.Size; - return S_OK; + return GetLastError_noZero_HRESULT(); + if (inFile.SizeDefined) + { + fileSize = inFile.Size; + return S_OK; + } +#else + UNUSED_VAR(index) +#endif + fileSize = 0; + return E_FAIL; } -STDMETHODIMP CFSDrives::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems, +Z7_COM7F_IMF(CFSDrives::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems, Int32 /* includeAltStreams */, Int32 /* replaceAltStreamColon */, - const wchar_t *path, IFolderOperationsExtractCallback *callback) + const wchar_t *path, IFolderOperationsExtractCallback *callback)) { if (numItems == 0) return S_OK; @@ -383,8 +408,8 @@ if (di.KnownSize) totalSize += di.DriveSize; } - RINOK(callback->SetTotal(totalSize)); - RINOK(callback->SetNumFiles(numItems)); + RINOK(callback->SetTotal(totalSize)) + RINOK(callback->SetNumFiles(numItems)) FString destPath = us2fs(path); if (destPath.IsEmpty()) @@ -400,8 +425,7 @@ } UInt64 completedSize = 0; - RINOK(callback->SetCompleted(&completedSize)); - + RINOK(callback->SetCompleted(&completedSize)) for (i = 0; i < numItems; i++) { unsigned index = indices[i]; @@ -429,66 +453,66 @@ if (!di.KnownSize) { totalSize += fileSize; - RINOK(callback->SetTotal(totalSize)); + RINOK(callback->SetTotal(totalSize)) } Int32 writeAskResult; CMyComBSTR destPathResult; RINOK(callback->AskWrite(fs2us(srcPath), BoolToInt(false), NULL, &fileSize, - fs2us(destPath2), &destPathResult, &writeAskResult)); + fs2us(destPath2), &destPathResult, &writeAskResult)) if (!IntToBool(writeAskResult)) { if (totalSize >= fileSize) totalSize -= fileSize; - RINOK(callback->SetTotal(totalSize)); + RINOK(callback->SetTotal(totalSize)) continue; } - RINOK(callback->SetCurrentFilePath(fs2us(srcPath))); + RINOK(callback->SetCurrentFilePath(fs2us(srcPath))) - static const UInt32 kBufferSize = (4 << 20); - UInt32 bufferSize = (di.DriveType == DRIVE_REMOVABLE) ? (18 << 10) * 4 : kBufferSize; - RINOK(CopyFileSpec(srcPath, us2fs(destPathResult), false, fileSize, bufferSize, completedSize, callback)); + const UInt32 kBufferSize = (4 << 20); + const UInt32 bufferSize = (di.DriveType == DRIVE_REMOVABLE) ? (18 << 10) * 4 : kBufferSize; + RINOK(CopyFileSpec(srcPath, us2fs(destPathResult), false, fileSize, bufferSize, completedSize, callback)) completedSize += fileSize; } return S_OK; } -STDMETHODIMP CFSDrives::CopyFrom(Int32 /* moveMode */, const wchar_t * /* fromFolderPath */, - const wchar_t * const * /* itemsPaths */, UInt32 /* numItems */, IProgress * /* progress */) +Z7_COM7F_IMF(CFSDrives::CopyFrom(Int32 /* moveMode */, const wchar_t * /* fromFolderPath */, + const wchar_t * const * /* itemsPaths */, UInt32 /* numItems */, IProgress * /* progress */)) { return E_NOTIMPL; } -STDMETHODIMP CFSDrives::CopyFromFile(UInt32 /* index */, const wchar_t * /* fullFilePath */, IProgress * /* progress */) +Z7_COM7F_IMF(CFSDrives::CopyFromFile(UInt32 /* index */, const wchar_t * /* fullFilePath */, IProgress * /* progress */)) { return E_NOTIMPL; } -STDMETHODIMP CFSDrives::CreateFolder(const wchar_t * /* name */, IProgress * /* progress */) +Z7_COM7F_IMF(CFSDrives::CreateFolder(const wchar_t * /* name */, IProgress * /* progress */)) { return E_NOTIMPL; } -STDMETHODIMP CFSDrives::CreateFile(const wchar_t * /* name */, IProgress * /* progress */) +Z7_COM7F_IMF(CFSDrives::CreateFile(const wchar_t * /* name */, IProgress * /* progress */)) { return E_NOTIMPL; } -STDMETHODIMP CFSDrives::Rename(UInt32 /* index */, const wchar_t * /* newName */, IProgress * /* progress */) +Z7_COM7F_IMF(CFSDrives::Rename(UInt32 /* index */, const wchar_t * /* newName */, IProgress * /* progress */)) { return E_NOTIMPL; } -STDMETHODIMP CFSDrives::Delete(const UInt32 * /* indices */, UInt32 /* numItems */, IProgress * /* progress */) +Z7_COM7F_IMF(CFSDrives::Delete(const UInt32 * /* indices */, UInt32 /* numItems */, IProgress * /* progress */)) { return E_NOTIMPL; } -STDMETHODIMP CFSDrives::SetProperty(UInt32 /* index */, PROPID /* propID */, - const PROPVARIANT * /* value */, IProgress * /* progress */) +Z7_COM7F_IMF(CFSDrives::SetProperty(UInt32 /* index */, PROPID /* propID */, + const PROPVARIANT * /* value */, IProgress * /* progress */)) { return E_NOTIMPL; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FSDrives.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FSDrives.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FSDrives.h 2014-09-16 11:59:35.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FSDrives.h 2023-04-01 11:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // FSDrives.h -#ifndef __FS_DRIVES_H -#define __FS_DRIVES_H +#ifndef ZIP7_INC_FS_DRIVES_H +#define ZIP7_INC_FS_DRIVES_H #include "../../../Common/MyCom.h" #include "../../../Common/MyString.h" @@ -28,12 +28,12 @@ CDriveInfo(): KnownSize(false), KnownSizes(false), IsPhysicalDrive(false) {} }; -class CFSDrives: - public IFolderFolder, - public IFolderOperations, - public IFolderGetSystemIconIndex, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_3( + CFSDrives + , IFolderFolder + , IFolderOperations + , IFolderGetSystemIconIndex +) CObjectVector _drives; bool _volumeMode; bool _superMode; @@ -42,13 +42,6 @@ void AddExt(FString &s, unsigned index) const; HRESULT GetFileSize(unsigned index, UInt64 &fileSize) const; public: - MY_UNKNOWN_IMP2(IFolderGetSystemIconIndex, IFolderOperations) - - INTERFACE_FolderFolder(;) - INTERFACE_FolderOperations(;) - - STDMETHOD(GetSystemIconIndex)(UInt32 index, Int32 *iconIndex); - void Init(bool volMode = false, bool superMode = false) { _volumeMode = volMode; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FSFolderCopy.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FSFolderCopy.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FSFolderCopy.cpp 2022-07-15 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FSFolderCopy.cpp 2023-04-01 11:00:00.000000000 +0000 @@ -4,8 +4,6 @@ #include "../../../Common/MyWindows.h" -#include - #include "../../../Common/Defs.h" #include "../../../Common/StringConvert.h" #include "../../../Common/Wildcard.h" @@ -29,11 +27,11 @@ extern bool g_IsNT; #endif -#define MY_CAST_FUNC (void(*)()) -// #define MY_CAST_FUNC - namespace NFsFolder { +static const char * const k_CannotCopyDirToAltStream = "Cannot copy folder as alternate stream"; + + HRESULT CCopyStateIO::MyCopyFile(CFSTR inPath, CFSTR outPath, DWORD attrib) { ErrorFileIndex = -1; @@ -85,11 +83,15 @@ if (Progress) { UInt64 completed = StartPos + CurrentSize; - RINOK(Progress->SetCompleted(&completed)); + RINOK(Progress->SetCompleted(&completed)) } } } + /* SetFileAttrib("path:alt_stream_name") sets attributes for main file "path". + But we don't want to change attributes of main file, when we write alt stream. + So we need INVALID_FILE_ATTRIBUTES for alt stream here */ + if (attrib != INVALID_FILE_ATTRIBUTES) SetFileAttrib(outPath, attrib); @@ -177,7 +179,7 @@ pi.FileSize = (UInt64)TotalFileSize.QuadPart; pi.ProgressResult = pi.Progress->SetTotal(pi.TotalSize); } - UInt64 completed = pi.StartPos + TotalBytesTransferred.QuadPart; + const UInt64 completed = pi.StartPos + (UInt64)TotalBytesTransferred.QuadPart; pi.ProgressResult = pi.Progress->SetCompleted(&completed); return (pi.ProgressResult == S_OK ? PROGRESS_CONTINUE : PROGRESS_CANCEL); } @@ -214,6 +216,7 @@ IFolderOperationsExtractCallback *Callback; bool MoveMode; bool UseReadWriteMode; + bool IsAltStreamsDest; Func_CopyFileExW my_CopyFileExW; #ifndef UNDER_CE @@ -248,23 +251,27 @@ my_CopyFileExA = NULL; if (!g_IsNT) { - my_CopyFileExA = (Func_CopyFileExA) - MY_CAST_FUNC - ::GetProcAddress(::GetModuleHandleA("kernel32.dll"), "CopyFileExA"); + my_CopyFileExA = Z7_GET_PROC_ADDRESS( + Func_CopyFileExA, ::GetModuleHandleA("kernel32.dll"), + "CopyFileExA"); } else #endif { - HMODULE module = ::GetModuleHandleW( + const HMODULE module = ::GetModuleHandleW( #ifdef UNDER_CE L"coredll.dll" #else L"kernel32.dll" #endif ); - my_CopyFileExW = (Func_CopyFileExW)My_GetProcAddress(module, "CopyFileExW"); + my_CopyFileExW = Z7_GET_PROC_ADDRESS( + Func_CopyFileExW, module, + "CopyFileExW"); #ifndef UNDER_CE - my_MoveFileWithProgressW = (Func_MoveFileWithProgressW)My_GetProcAddress(module, "MoveFileWithProgressW"); + my_MoveFileWithProgressW = Z7_GET_PROC_ADDRESS( + Func_MoveFileWithProgressW, module, + "MoveFileWithProgressW"); #endif } } @@ -308,7 +315,7 @@ if (CopyFile_NT(fs2us(oldFile), fs2us(newFile))) return true; } - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if (USE_SUPER_PATH_2) { if (IsCallbackProgressError()) @@ -337,7 +344,7 @@ &ProgressInfo, MOVEFILE_COPY_ALLOWED)) return true; } - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if ((!(USE_MAIN_PATH_2) || ::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) && USE_SUPER_PATH_2) { if (IsCallbackProgressError()) @@ -404,7 +411,7 @@ state.MoveMode ? "Cannot move file onto itself" : "Cannot copy file onto itself" - , destPath)); + , destPath)) return E_ABORT; } @@ -416,12 +423,12 @@ &srcFileInfo.MTime, &srcFileInfo.Size, fs2us(destPath), &destPathResult, - &writeAskResult)); + &writeAskResult)) if (IntToBool(writeAskResult)) { FString destPathNew = us2fs((LPCOLESTR)destPathResult); - RINOK(state.Callback->SetCurrentFilePath(fs2us(srcPath))); + RINOK(state.Callback->SetCurrentFilePath(fs2us(srcPath))) if (state.UseReadWriteMode) { @@ -431,7 +438,8 @@ state2.TotalSize = state.ProgressInfo.TotalSize; state2.StartPos = state.ProgressInfo.StartPos; - RINOK(state2.MyCopyFile(srcPath, destPathNew, srcFileInfo.Attrib)); + RINOK(state2.MyCopyFile(srcPath, destPathNew, + state.IsAltStreamsDest ? INVALID_FILE_ATTRIBUTES: srcFileInfo.Attrib)) if (state2.ErrorFileIndex >= 0) { @@ -442,7 +450,7 @@ errorName = srcPath; else errorName = destPathNew; - RINOK(SendMessageError(state.Callback, state2.ErrorMessage, errorName)); + RINOK(SendMessageError(state.Callback, state2.ErrorMessage, errorName)) return E_ABORT; } state.ProgressInfo.StartPos += state2.CurrentSize; @@ -455,11 +463,11 @@ res = state.MoveFile_Sys(srcPath, destPathNew); else res = state.CopyFile_Sys(srcPath, destPathNew); - RINOK(state.ProgressInfo.ProgressResult); + RINOK(state.ProgressInfo.ProgressResult) if (!res) { // GetLastError() is ERROR_REQUEST_ABORTED in case of PROGRESS_CANCEL. - RINOK(SendMessageError(state.Callback, GetLastErrorMessage(), destPathNew)); + RINOK(SendMessageError(state.Callback, GetLastErrorMessage(), destPathNew)) return E_ABORT; } state.ProgressInfo.StartPos += state.ProgressInfo.FileSize; @@ -470,7 +478,7 @@ if (state.ProgressInfo.TotalSize >= srcFileInfo.Size) { state.ProgressInfo.TotalSize -= srcFileInfo.Size; - RINOK(state.ProgressInfo.Progress->SetTotal(state.ProgressInfo.TotalSize)); + RINOK(state.ProgressInfo.Progress->SetTotal(state.ProgressInfo.TotalSize)) } } return state.CallProgress(); @@ -499,7 +507,7 @@ const FString &srcPath, // without TAIL separator const FString &destPath) // without TAIL separator { - RINOK(state.CallProgress()); + RINOK(state.CallProgress()) if (IsDestChild(srcPath, destPath)) { @@ -507,7 +515,7 @@ state.MoveMode ? "Cannot copy folder onto itself" : "Cannot move folder onto itself" - , destPath)); + , destPath)) return E_ABORT; } @@ -521,7 +529,7 @@ if (!CreateComplexDir(destPath)) { - RINOK(SendMessageError(state.Callback, "Cannot create folder", destPath)); + RINOK(SendMessageError(state.Callback, "Cannot create folder", destPath)) return E_ABORT; } @@ -547,7 +555,7 @@ } else { - RINOK(CopyFile_Ask(state, srcPath2, fi, destPath2)); + RINOK(CopyFile_Ask(state, srcPath2, fi, destPath2)) } } @@ -555,7 +563,7 @@ { if (!RemoveDir(srcPath)) { - RINOK(SendMessageError(state.Callback, "Cannot remove folder", srcPath)); + RINOK(SendMessageError(state.Callback, "Cannot remove folder", srcPath)) return E_ABORT; } } @@ -563,38 +571,67 @@ return S_OK; } -STDMETHODIMP CFSFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems, +Z7_COM7F_IMF(CFSFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems, Int32 /* includeAltStreams */, Int32 /* replaceAltStreamColon */, - const wchar_t *path, IFolderOperationsExtractCallback *callback) + const wchar_t *path, IFolderOperationsExtractCallback *callback)) { if (numItems == 0) return S_OK; - FString destPath = us2fs(path); + const FString destPath = us2fs(path); if (destPath.IsEmpty()) return E_INVALIDARG; - bool isAltDest = NName::IsAltPathPrefix(destPath); - bool isDirectPath = (!isAltDest && !IsPathSepar(destPath.Back())); + const bool isAltDest = NName::IsAltPathPrefix(destPath); + const bool isDirectPath = (!isAltDest && !IsPathSepar(destPath.Back())); if (isDirectPath) - { if (numItems > 1) return E_INVALIDARG; - } CFsFolderStat stat; stat.Progress = callback; - RINOK(GetItemsFullSize(indices, numItems, stat)); + UInt32 i; + for (i = 0; i < numItems; i++) + { + const UInt32 index = indices[i]; + /* + if (index >= Files.Size()) + { + size += Streams[index - Files.Size()].Size; + // numFiles++; + continue; + } + */ + const CDirItem &fi = Files[index]; + if (fi.IsDir()) + { + if (!isAltDest) + { + stat.Path = _path; + stat.Path += GetRelPath(fi); + RINOK(stat.Enumerate()) + } + stat.NumFolders++; + } + else + { + stat.NumFiles++; + stat.Size += fi.Size; + } + } + + /* if (stat.NumFolders != 0 && isAltDest) return E_NOTIMPL; + */ - RINOK(callback->SetTotal(stat.Size)); - RINOK(callback->SetNumFiles(stat.NumFiles)); + RINOK(callback->SetTotal(stat.Size)) + RINOK(callback->SetNumFiles(stat.NumFiles)) UInt64 completedSize = 0; - RINOK(callback->SetCompleted(&completedSize)); + RINOK(callback->SetCompleted(&completedSize)) CCopyState state; state.ProgressInfo.TotalSize = stat.Size; @@ -603,12 +640,16 @@ state.ProgressInfo.Init(); state.Callback = callback; state.MoveMode = IntToBool(moveMode); + state.IsAltStreamsDest = isAltDest; + /* CopyFileW(fromFile, toFile:altStream) returns ERROR_INVALID_PARAMETER, + if there are alt streams in fromFile. + So we don't use CopyFileW() for alt Streams. */ state.UseReadWriteMode = isAltDest; state.Prepare(); - for (UInt32 i = 0; i < numItems; i++) + for (i = 0; i < numItems; i++) { - UInt32 index = indices[i]; + const UInt32 index = indices[i]; if (index >= (UInt32)Files.Size()) continue; const CDirItem &fi = Files[index]; @@ -620,57 +661,148 @@ if (fi.IsDir()) { - RINOK(CopyFolder(state, srcPath, destPath2)); + if (isAltDest) + { + RINOK(SendMessageError(callback, k_CannotCopyDirToAltStream, srcPath)) + } + else + { + RINOK(CopyFolder(state, srcPath, destPath2)) + } } else { - RINOK(CopyFile_Ask(state, srcPath, fi, destPath2)); + RINOK(CopyFile_Ask(state, srcPath, fi, destPath2)) } } return S_OK; } -STDMETHODIMP CFSFolder::CopyFrom(Int32 /* moveMode */, const wchar_t * /* fromFolderPath */, - const wchar_t * const * /* itemsPaths */, UInt32 /* numItems */, IProgress * /* progress */) + + +/* we can call CopyFileSystemItems() from CDropTarget::Drop() */ + +HRESULT CopyFileSystemItems( + const UStringVector &itemsPaths, + const FString &destDirPrefix, + bool moveMode, + IFolderOperationsExtractCallback *callback) { - /* - UInt64 numFolders, numFiles, totalSize; - numFiles = numFolders = totalSize = 0; - UInt32 i; - for (i = 0; i < numItems; i++) - { - UString path = (UString)fromFolderPath + itemsPaths[i]; + if (itemsPaths.IsEmpty()) + return S_OK; + + if (destDirPrefix.IsEmpty()) + return E_INVALIDARG; + const bool isAltDest = NName::IsAltPathPrefix(destDirPrefix); + + CFsFolderStat stat; + stat.Progress = callback; + + { + FOR_VECTOR (i, itemsPaths) + { + const UString &path = itemsPaths[i]; CFileInfo fi; - if (!FindFile(path, fi)) - return ::GetLastError(); + if (!fi.Find(us2fs(path))) + continue; if (fi.IsDir()) { - UInt64 subFolders, subFiles, subSize; - RINOK(GetFolderSize(CombinePath(path, fi.Name), subFolders, subFiles, subSize, progress)); - numFolders += subFolders; - numFolders++; - numFiles += subFiles; - totalSize += subSize; + if (!isAltDest) + { + stat.Path = us2fs(path); + RINOK(stat.Enumerate()) + } + stat.NumFolders++; } else { - numFiles++; - totalSize += fi.Size; + stat.NumFiles++; + stat.Size += fi.Size; } } - RINOK(progress->SetTotal(totalSize)); - RINOK(callback->SetNumFiles(numFiles)); - for (i = 0; i < numItems; i++) + } + + /* + if (stat.NumFolders != 0 && isAltDest) + return E_NOTIMPL; + */ + + RINOK(callback->SetTotal(stat.Size)) + // RINOK(progress->SetNumFiles(stat.NumFiles)); + + UInt64 completedSize = 0; + RINOK(callback->SetCompleted(&completedSize)) + + CCopyState state; + state.ProgressInfo.TotalSize = stat.Size; + state.ProgressInfo.StartPos = 0; + state.ProgressInfo.Progress = callback; + state.ProgressInfo.Init(); + state.Callback = callback; + state.MoveMode = moveMode; + state.IsAltStreamsDest = isAltDest; + /* CopyFileW(fromFile, toFile:altStream) returns ERROR_INVALID_PARAMETER, + if there are alt streams in fromFile. + So we don't use CopyFileW() for alt Streams. */ + state.UseReadWriteMode = isAltDest; + state.Prepare(); + + FOR_VECTOR (i, itemsPaths) { - UString path = (UString)fromFolderPath + itemsPaths[i]; + const UString path = itemsPaths[i]; + CFileInfo fi; + + if (!fi.Find(us2fs(path))) + { + RINOK(SendMessageError(callback, "Cannot find the file", us2fs(path))) + continue; + } + + FString destPath = destDirPrefix; + destPath += fi.Name; + + if (fi.IsDir()) + { + if (isAltDest) + { + RINOK(SendMessageError(callback, k_CannotCopyDirToAltStream, us2fs(path))) + } + else + { + RINOK(CopyFolder(state, us2fs(path), destPath)) + } + } + else + { + RINOK(CopyFile_Ask(state, us2fs(path), fi, destPath)) + } } return S_OK; +} + + +/* we don't use CFSFolder::CopyFrom() because the caller of CopyFrom() + is optimized for IFolderArchiveUpdateCallback interface, + but we want to use IFolderOperationsExtractCallback interface instead */ + +Z7_COM7F_IMF(CFSFolder::CopyFrom(Int32 /* moveMode */, const wchar_t * /* fromFolderPath */, + const wchar_t * const * /* itemsPaths */, UInt32 /* numItems */, IProgress * /* progress */)) +{ + /* + Z7_DECL_CMyComPtr_QI_FROM( + IFolderOperationsExtractCallback, + callback, progress) + if (!callback) + return E_NOTIMPL; + return CopyFileSystemItems(_path, + moveMode, fromDirPrefix, + itemsPaths, numItems, callback); */ return E_NOTIMPL; } -STDMETHODIMP CFSFolder::CopyFromFile(UInt32 /* index */, const wchar_t * /* fullFilePath */, IProgress * /* progress */) +Z7_COM7F_IMF(CFSFolder::CopyFromFile(UInt32 /* index */, const wchar_t * /* fullFilePath */, IProgress * /* progress */)) { return E_NOTIMPL; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FSFolder.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FSFolder.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FSFolder.cpp 2022-07-14 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FSFolder.cpp 2023-04-06 17:00:00.000000000 +0000 @@ -2,15 +2,24 @@ #include "StdAfx.h" -#if defined(_MSC_VER) -#include +#ifdef __MINGW32_VERSION +// #if !defined(_MSC_VER) && (__GNUC__) && (__GNUC__ < 10) +// for old mingw +#include #else -#if defined(__GNUC__) && (__GNUC__ >= 10) - // new mingw: +#ifndef Z7_OLD_WIN_SDK + #if !defined(_M_IA64) #include + #endif #else - // old mingw: - #include +typedef LONG NTSTATUS; +typedef struct _IO_STATUS_BLOCK { + union { + NTSTATUS Status; + PVOID Pointer; + }; + ULONG_PTR Information; +} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK; #endif #endif @@ -106,7 +115,7 @@ if (!_findChangeNotification.IsHandleAllocated()) { - DWORD lastError = GetLastError(); + const HRESULT lastError = GetLastError_noZero_HRESULT(); CFindFile findFile; CFileInfo fi; FString path2 = _path; @@ -125,7 +134,7 @@ { if (Progress) { - RINOK(Progress->SetCompleted(NULL)); + RINOK(Progress->SetCompleted(NULL)) } Path.Add_PathSepar(); const unsigned len = Path.Len(); @@ -139,7 +148,7 @@ NumFolders++; Path.DeleteFrom(len); Path += fi.Name; - RINOK(Enumerate()); + RINOK(Enumerate()) } else { @@ -166,7 +175,7 @@ return true; } } - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if (USE_SUPER_PATH) { UString superPath; @@ -285,16 +294,16 @@ const unsigned endIndex = Folders.Size(); for (unsigned i = startIndex; i < endIndex; i++) - LoadSubItems(i, Folders[i]); + LoadSubItems((int)i, Folders[i]); return S_OK; } -STDMETHODIMP CFSFolder::LoadItems() +Z7_COM7F_IMF(CFSFolder::LoadItems()) { Int32 dummy; WasChanged(&dummy); Clear(); - RINOK(LoadSubItems(-1, FString())); + RINOK(LoadSubItems(-1, FString())) _commentsAreLoaded = false; return S_OK; } @@ -356,7 +365,7 @@ return true; } -STDMETHODIMP CFSFolder::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CFSFolder::GetNumberOfItems(UInt32 *numItems)) { *numItems = Files.Size() /* + Streams.Size() */; return S_OK; @@ -364,9 +373,9 @@ #ifdef USE_UNICODE_FSTRING -STDMETHODIMP CFSFolder::GetItemPrefix(UInt32 index, const wchar_t **name, unsigned *len) +Z7_COM7F_IMF(CFSFolder::GetItemPrefix(UInt32 index, const wchar_t **name, unsigned *len)) { - *name = 0; + *name = NULL; *len = 0; /* if (index >= Files.Size()) @@ -383,9 +392,9 @@ return S_OK; } -STDMETHODIMP CFSFolder::GetItemName(UInt32 index, const wchar_t **name, unsigned *len) +Z7_COM7F_IMF(CFSFolder::GetItemName(UInt32 index, const wchar_t **name, unsigned *len)) { - *name = 0; + *name = NULL; *len = 0; if (index < Files.Size()) { @@ -405,7 +414,7 @@ return S_OK; } -STDMETHODIMP_(UInt64) CFSFolder::GetItemSize(UInt32 index) +Z7_COM7F_IMF2(UInt64, CFSFolder::GetItemSize(UInt32 index)) { /* if (index >= Files.Size()) @@ -434,6 +443,8 @@ } +EXTERN_C_BEGIN + typedef struct { LARGE_INTEGER CreationTime; @@ -443,37 +454,57 @@ ULONG FileAttributes; UInt32 Reserved; // it's expected for alignment } -MY__FILE_BASIC_INFORMATION; +Z7_WIN_FILE_BASIC_INFORMATION; typedef enum { - MY__FileDirectoryInformation = 1, - MY__FileFullDirectoryInformation, - MY__FileBothDirectoryInformation, - MY__FileBasicInformation + Z7_WIN_FileDirectoryInformation = 1, + Z7_WIN_FileFullDirectoryInformation, + Z7_WIN_FileBothDirectoryInformation, + Z7_WIN_FileBasicInformation } -MY__FILE_INFORMATION_CLASS; +Z7_WIN_FILE_INFORMATION_CLASS; + +#if (_WIN32_WINNT >= 0x0500) && !defined(_M_IA64) +#define Z7_WIN_NTSTATUS NTSTATUS +#define Z7_WIN_IO_STATUS_BLOCK IO_STATUS_BLOCK +#else +typedef LONG Z7_WIN_NTSTATUS; +typedef struct +{ + union + { + Z7_WIN_NTSTATUS Status; + PVOID Pointer; + } DUMMYUNIONNAME; + ULONG_PTR Information; +} Z7_WIN_IO_STATUS_BLOCK; +#endif -typedef NTSTATUS (WINAPI * Func_NtQueryInformationFile)( - HANDLE handle, IO_STATUS_BLOCK *io, - void *ptr, LONG len, MY__FILE_INFORMATION_CLASS cls); -#define MY__STATUS_SUCCESS 0 +typedef Z7_WIN_NTSTATUS (WINAPI * Func_NtQueryInformationFile)( + HANDLE handle, Z7_WIN_IO_STATUS_BLOCK *io, + void *ptr, LONG len, Z7_WIN_FILE_INFORMATION_CLASS cls); + +#define MY_STATUS_SUCCESS 0 + +EXTERN_C_END static Func_NtQueryInformationFile f_NtQueryInformationFile; static bool g_NtQueryInformationFile_WasRequested = false; + void CFSFolder::ReadChangeTime(CDirItem &di) { di.ChangeTime_WasRequested = true; if (!g_NtQueryInformationFile_WasRequested) { - g_NtQueryInformationFile_WasRequested = true; - f_NtQueryInformationFile = (Func_NtQueryInformationFile) - My_GetProcAddress(::GetModuleHandleW(L"ntdll.dll"), + g_NtQueryInformationFile_WasRequested = true; + f_NtQueryInformationFile = Z7_GET_PROC_ADDRESS( + Func_NtQueryInformationFile, ::GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationFile"); } if (!f_NtQueryInformationFile) @@ -482,23 +513,23 @@ NIO::CInFile file; if (!file.Open_for_ReadAttributes(_path + GetRelPath(di))) return; - MY__FILE_BASIC_INFORMATION fbi; - IO_STATUS_BLOCK IoStatusBlock; - const NTSTATUS status = f_NtQueryInformationFile(file.GetHandle(), &IoStatusBlock, - &fbi, sizeof(fbi), MY__FileBasicInformation); - if (status != MY__STATUS_SUCCESS) + Z7_WIN_FILE_BASIC_INFORMATION fbi; + Z7_WIN_IO_STATUS_BLOCK IoStatusBlock; + const Z7_WIN_NTSTATUS status = f_NtQueryInformationFile(file.GetHandle(), &IoStatusBlock, + &fbi, sizeof(fbi), Z7_WIN_FileBasicInformation); + if (status != MY_STATUS_SUCCESS) return; if (IoStatusBlock.Information != sizeof(fbi)) return; di.ChangeTime.dwLowDateTime = fbi.ChangeTime.u.LowPart; - di.ChangeTime.dwHighDateTime = fbi.ChangeTime.u.HighPart; + di.ChangeTime.dwHighDateTime = (DWORD)fbi.ChangeTime.u.HighPart; di.ChangeTime_Defined = true; } #endif // FS_SHOW_LINKS_INFO -STDMETHODIMP CFSFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CFSFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; /* @@ -622,34 +653,32 @@ // ---------- IArchiveGetRawProps ---------- -STDMETHODIMP CFSFolder::GetNumRawProps(UInt32 *numProps) +Z7_COM7F_IMF(CFSFolder::GetNumRawProps(UInt32 *numProps)) { *numProps = 1; return S_OK; } -STDMETHODIMP CFSFolder::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID) +Z7_COM7F_IMF(CFSFolder::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID)) { *name = NULL; *propID = kpidNtReparse; return S_OK; } -STDMETHODIMP CFSFolder::GetParent(UInt32 /* index */, UInt32 * /* parent */, UInt32 * /* parentType */) +Z7_COM7F_IMF(CFSFolder::GetParent(UInt32 /* index */, UInt32 * /* parent */, UInt32 * /* parentType */)) { return E_FAIL; } -STDMETHODIMP CFSFolder::GetRawProp(UInt32 - #ifndef UNDER_CE - index - #endif - , PROPID - #ifndef UNDER_CE - propID - #endif - , const void **data, UInt32 *dataSize, UInt32 *propType) +Z7_COM7F_IMF(CFSFolder::GetRawProp(UInt32 index, PROPID propID, + const void **data, UInt32 *dataSize, UInt32 *propType)) { + #ifdef UNDER_CE + UNUSED(index) + UNUSED(propID) + #endif + *data = NULL; *dataSize = 0; *propType = 0; @@ -676,11 +705,11 @@ static inline CFSTR GetExtensionPtr(const FString &name) { - int dotPos = name.ReverseFind_Dot(); - return name.Ptr((dotPos < 0) ? name.Len() : dotPos); + const int dotPos = name.ReverseFind_Dot(); + return name.Ptr((dotPos < 0) ? name.Len() : (unsigned)dotPos); } -STDMETHODIMP_(Int32) CFSFolder::CompareItems(UInt32 index1, UInt32 index2, PROPID propID, Int32 /* propIsRaw */) +Z7_COM7F_IMF2(Int32, CFSFolder::CompareItems(UInt32 index1, UInt32 index2, PROPID propID, Int32 /* propIsRaw */)) { /* const CAltStream *ss1 = NULL; @@ -695,7 +724,7 @@ { case kpidName: { - int comp = CompareFileNames_ForFolderList(fi1.Name, fi2.Name); + const int comp = CompareFileNames_ForFolderList(fi1.Name, fi2.Name); /* if (comp != 0) return comp; @@ -783,10 +812,10 @@ HRESULT CFSFolder::BindToFolderSpec(CFSTR name, IFolderFolder **resultFolder) { - *resultFolder = 0; + *resultFolder = NULL; CFSFolder *folderSpec = new CFSFolder; CMyComPtr subFolder = folderSpec; - RINOK(folderSpec->Init(_path + name + FCHAR_PATH_SEPARATOR)); + RINOK(folderSpec->Init(_path + name + FCHAR_PATH_SEPARATOR)) *resultFolder = subFolder.Detach(); return S_OK; } @@ -836,23 +865,23 @@ return Folders[item.Parent] + item.Name; } -STDMETHODIMP CFSFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder) +Z7_COM7F_IMF(CFSFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder)) { - *resultFolder = 0; + *resultFolder = NULL; const CDirItem &fi = Files[index]; if (!fi.IsDir()) return E_INVALIDARG; return BindToFolderSpec(GetRelPath(fi), resultFolder); } -STDMETHODIMP CFSFolder::BindToFolder(const wchar_t *name, IFolderFolder **resultFolder) +Z7_COM7F_IMF(CFSFolder::BindToFolder(const wchar_t *name, IFolderFolder **resultFolder)) { return BindToFolderSpec(us2fs(name), resultFolder); } -STDMETHODIMP CFSFolder::BindToParentFolder(IFolderFolder **resultFolder) +Z7_COM7F_IMF(CFSFolder::BindToParentFolder(IFolderFolder **resultFolder)) { - *resultFolder = 0; + *resultFolder = NULL; /* if (_parentFolder) { @@ -914,17 +943,17 @@ return S_OK; } -STDMETHODIMP CFSFolder::GetNumberOfProperties(UInt32 *numProperties) +Z7_COM7F_IMF(CFSFolder::GetNumberOfProperties(UInt32 *numProperties)) { - *numProperties = ARRAY_SIZE(kProps); + *numProperties = Z7_ARRAY_SIZE(kProps); if (!_flatMode) (*numProperties)--; return S_OK; } -STDMETHODIMP CFSFolder::GetPropertyInfo IMP_IFolderFolder_GetProp(kProps) +IMP_IFolderFolder_GetProp(CFSFolder::GetPropertyInfo, kProps) -STDMETHODIMP CFSFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CFSFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN NWindows::NCOM::CPropVariant prop; @@ -938,7 +967,7 @@ COM_TRY_END } -STDMETHODIMP CFSFolder::WasChanged(Int32 *wasChanged) +Z7_COM7F_IMF(CFSFolder::WasChanged(Int32 *wasChanged)) { bool wasChangedMain = false; @@ -961,7 +990,7 @@ return S_OK; } -STDMETHODIMP CFSFolder::Clone(IFolderFolder **resultFolder) +Z7_COM7F_IMF(CFSFolder::Clone(IFolderFolder **resultFolder)) { CFSFolder *fsFolderSpec = new CFSFolder; CMyComPtr folderNew = fsFolderSpec; @@ -970,35 +999,6 @@ return S_OK; } -HRESULT CFSFolder::GetItemsFullSize(const UInt32 *indices, UInt32 numItems, CFsFolderStat &stat) -{ - for (UInt32 i = 0; i < numItems; i++) - { - UInt32 index = indices[i]; - /* - if (index >= Files.Size()) - { - size += Streams[index - Files.Size()].Size; - // numFiles++; - continue; - } - */ - const CDirItem &fi = Files[index]; - if (fi.IsDir()) - { - stat.Path = _path; - stat.Path += GetRelPath(fi); - RINOK(stat.Enumerate()); - stat.NumFolders++; - } - else - { - stat.NumFiles++; - stat.Size += fi.Size; - } - } - return S_OK; -} /* HRESULT CFSFolder::GetItemFullSize(unsigned index, UInt64 &size, IProgress *progress) @@ -1019,7 +1019,7 @@ return S_OK; } -STDMETHODIMP CFSFolder::GetItemFullSize(UInt32 index, PROPVARIANT *value, IProgress *progress) +Z7_COM7F_IMF(CFSFolder::GetItemFullSize(UInt32 index, PROPVARIANT *value, IProgress *progress) { NCOM::CPropVariant prop; UInt64 size = 0; @@ -1030,7 +1030,7 @@ } */ -STDMETHODIMP CFSFolder::CalcItemFullSize(UInt32 index, IProgress *progress) +Z7_COM7F_IMF(CFSFolder::CalcItemFullSize(UInt32 index, IProgress *progress)) { if (index >= (UInt32)Files.Size()) return S_OK; @@ -1038,7 +1038,7 @@ if (!fi.IsDir()) return S_OK; CFsFolderStat stat(_path + GetRelPath(fi), progress); - RINOK(stat.Enumerate()); + RINOK(stat.Enumerate()) fi.Size = stat.Size; fi.NumFolders = stat.NumFolders; fi.NumFiles = stat.NumFiles; @@ -1054,30 +1054,29 @@ absPath += us2fs(name); } -STDMETHODIMP CFSFolder::CreateFolder(const wchar_t *name, IProgress * /* progress */) +Z7_COM7F_IMF(CFSFolder::CreateFolder(const wchar_t *name, IProgress * /* progress */)) { FString absPath; GetAbsPath(name, absPath); if (CreateDir(absPath)) return S_OK; - if (::GetLastError() == ERROR_ALREADY_EXISTS) - return ::GetLastError(); - if (!CreateComplexDir(absPath)) - return ::GetLastError(); - return S_OK; + if (::GetLastError() != ERROR_ALREADY_EXISTS) + if (CreateComplexDir(absPath)) + return S_OK; + return GetLastError_noZero_HRESULT(); } -STDMETHODIMP CFSFolder::CreateFile(const wchar_t *name, IProgress * /* progress */) +Z7_COM7F_IMF(CFSFolder::CreateFile(const wchar_t *name, IProgress * /* progress */)) { FString absPath; GetAbsPath(name, absPath); NIO::COutFile outFile; if (!outFile.Create(absPath, false)) - return ::GetLastError(); + return GetLastError_noZero_HRESULT(); return S_OK; } -STDMETHODIMP CFSFolder::Rename(UInt32 index, const wchar_t *newName, IProgress * /* progress */) +Z7_COM7F_IMF(CFSFolder::Rename(UInt32 index, const wchar_t *newName, IProgress * /* progress */)) { if (index >= (UInt32)Files.Size()) return E_NOTIMPL; @@ -1088,13 +1087,13 @@ if (fi.Parent >= 0) fullPrefix += Folders[fi.Parent]; if (!MyMoveFile(fullPrefix + fi.Name, fullPrefix + us2fs(newName))) - return GetLastError(); + return GetLastError_noZero_HRESULT(); return S_OK; } -STDMETHODIMP CFSFolder::Delete(const UInt32 *indices, UInt32 numItems,IProgress *progress) +Z7_COM7F_IMF(CFSFolder::Delete(const UInt32 *indices, UInt32 numItems,IProgress *progress)) { - RINOK(progress->SetTotal(numItems)); + RINOK(progress->SetTotal(numItems)) // int prevDeletedFileIndex = -1; for (UInt32 i = 0; i < numItems; i++) { @@ -1123,15 +1122,15 @@ result = DeleteFileAlways(fullPath); } if (!result) - return GetLastError(); - UInt64 completed = i; - RINOK(progress->SetCompleted(&completed)); + return GetLastError_noZero_HRESULT(); + const UInt64 completed = i; + RINOK(progress->SetCompleted(&completed)) } return S_OK; } -STDMETHODIMP CFSFolder::SetProperty(UInt32 index, PROPID propID, - const PROPVARIANT *value, IProgress * /* progress */) +Z7_COM7F_IMF(CFSFolder::SetProperty(UInt32 index, PROPID propID, + const PROPVARIANT *value, IProgress * /* progress */)) { if (index >= (UInt32)Files.Size()) return E_INVALIDARG; @@ -1169,7 +1168,7 @@ return S_OK; } -STDMETHODIMP CFSFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex) +Z7_COM7F_IMF(CFSFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex)) { if (index >= (UInt32)Files.Size()) return E_INVALIDARG; @@ -1181,17 +1180,17 @@ *iconIndex = iconIndexTemp; return S_OK; } - return GetLastError(); + return GetLastError_noZero_HRESULT(); } -STDMETHODIMP CFSFolder::SetFlatMode(Int32 flatMode) +Z7_COM7F_IMF(CFSFolder::SetFlatMode(Int32 flatMode)) { _flatMode = IntToBool(flatMode); return S_OK; } /* -STDMETHODIMP CFSFolder::SetShowNtfsStreamsMode(Int32 showStreamsMode) +Z7_COM7F_IMF(CFSFolder::SetShowNtfsStreamsMode(Int32 showStreamsMode) { _scanAltStreams = IntToBool(showStreamsMode); return S_OK; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FSFolder.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FSFolder.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/FSFolder.h 2022-04-14 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/FSFolder.h 2023-02-01 10:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // FSFolder.h -#ifndef __FS_FOLDER_H -#define __FS_FOLDER_H +#ifndef ZIP7_INC_FS_FOLDER_H +#define ZIP7_INC_FS_FOLDER_H #include "../../../Common/MyCom.h" #include "../../../Common/MyBuffer.h" @@ -78,7 +78,7 @@ HRESULT Enumerate(); }; -class CFSFolder: +class CFSFolder Z7_final: public IFolderFolder, public IArchiveGetRawProps, public IFolderCompare, @@ -95,42 +95,36 @@ // public IFolderSetShowNtfsStreamsMode, public CMyUnknownImp { -public: - MY_QUERYINTERFACE_BEGIN2(IFolderFolder) - MY_QUERYINTERFACE_ENTRY(IArchiveGetRawProps) - MY_QUERYINTERFACE_ENTRY(IFolderCompare) + Z7_COM_QI_BEGIN2(IFolderFolder) + Z7_COM_QI_ENTRY(IArchiveGetRawProps) + Z7_COM_QI_ENTRY(IFolderCompare) #ifdef USE_UNICODE_FSTRING - MY_QUERYINTERFACE_ENTRY(IFolderGetItemName) + Z7_COM_QI_ENTRY(IFolderGetItemName) #endif - MY_QUERYINTERFACE_ENTRY(IFolderWasChanged) - // MY_QUERYINTERFACE_ENTRY(IFolderOperationsDeleteToRecycleBin) - MY_QUERYINTERFACE_ENTRY(IFolderOperations) - MY_QUERYINTERFACE_ENTRY(IFolderCalcItemFullSize) - MY_QUERYINTERFACE_ENTRY(IFolderClone) - MY_QUERYINTERFACE_ENTRY(IFolderGetSystemIconIndex) - MY_QUERYINTERFACE_ENTRY(IFolderSetFlatMode) - // MY_QUERYINTERFACE_ENTRY(IFolderSetShowNtfsStreamsMode) - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - - INTERFACE_FolderFolder(;) - INTERFACE_IArchiveGetRawProps(;) - INTERFACE_FolderOperations(;) - - STDMETHOD_(Int32, CompareItems)(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw); - + Z7_COM_QI_ENTRY(IFolderWasChanged) + // Z7_COM_QI_ENTRY(IFolderOperationsDeleteToRecycleBin) + Z7_COM_QI_ENTRY(IFolderOperations) + Z7_COM_QI_ENTRY(IFolderCalcItemFullSize) + Z7_COM_QI_ENTRY(IFolderClone) + Z7_COM_QI_ENTRY(IFolderGetSystemIconIndex) + Z7_COM_QI_ENTRY(IFolderSetFlatMode) + // Z7_COM_QI_ENTRY(IFolderSetShowNtfsStreamsMode) + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(IFolderFolder) + Z7_IFACE_COM7_IMP(IArchiveGetRawProps) + Z7_IFACE_COM7_IMP(IFolderCompare) #ifdef USE_UNICODE_FSTRING - INTERFACE_IFolderGetItemName(;) + Z7_IFACE_COM7_IMP(IFolderGetItemName) #endif - STDMETHOD(WasChanged)(Int32 *wasChanged); - STDMETHOD(Clone)(IFolderFolder **resultFolder); - STDMETHOD(CalcItemFullSize)(UInt32 index, IProgress *progress); - - STDMETHOD(SetFlatMode)(Int32 flatMode); - // STDMETHOD(SetShowNtfsStreamsMode)(Int32 showStreamsMode); - - STDMETHOD(GetSystemIconIndex)(UInt32 index, Int32 *iconIndex); + Z7_IFACE_COM7_IMP(IFolderWasChanged) + Z7_IFACE_COM7_IMP(IFolderOperations) + Z7_IFACE_COM7_IMP(IFolderCalcItemFullSize) + Z7_IFACE_COM7_IMP(IFolderClone) + Z7_IFACE_COM7_IMP(IFolderGetSystemIconIndex) + Z7_IFACE_COM7_IMP(IFolderSetFlatMode) + // Z7_IFACE_COM7_IMP(IFolderSetShowNtfsStreamsMode) private: FString _path; @@ -150,9 +144,7 @@ NWindows::NFile::NFind::CFindChangeNotification _findChangeNotification; #endif - HRESULT GetItemsFullSize(const UInt32 *indices, UInt32 numItems, CFsFolderStat &stat); - - HRESULT GetItemFullSize(unsigned index, UInt64 &size, IProgress *progress); + // HRESULT GetItemFullSize(unsigned index, UInt64 &size, IProgress *progress); void GetAbsPath(const wchar_t *name, FString &absPath); HRESULT BindToFolderSpec(CFSTR name, IFolderFolder **resultFolder); @@ -215,6 +207,15 @@ HRESULT SendLastErrorMessage(IFolderOperationsExtractCallback *callback, const FString &fileName); +/* destDirPrefix is allowed to be: + "full_path\" or "full_path:" for alt streams */ + +HRESULT CopyFileSystemItems( + const UStringVector &itemsPaths, + const FString &destDirPrefix, + bool moveMode, + IFolderOperationsExtractCallback *callback); + } #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/HelpUtils.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/HelpUtils.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/HelpUtils.cpp 2022-04-22 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/HelpUtils.cpp 2023-03-21 12:00:00.000000000 +0000 @@ -4,7 +4,7 @@ #include "HelpUtils.h" -#if defined(UNDER_CE) || !defined(_WIN32) /* || !defined(_MSC_VER) */ +#if defined(UNDER_CE) || defined(__MINGW32_VERSION) void ShowHelpWindow(LPCSTR) { @@ -12,11 +12,15 @@ #else -// #define USE_EXTERNAL_HELP +/* USE_EXTERNAL_HELP creates new help process window for each HtmlHelp() call. + HtmlHelp() call uses one window. */ -#if defined(_MSC_VER) +#if defined(__MINGW32_VERSION) /* || defined(Z7_OLD_WIN_SDK) */ +#define USE_EXTERNAL_HELP #endif +// #define USE_EXTERNAL_HELP + #ifdef USE_EXTERNAL_HELP #include "../../../Windows/ProcessUtils.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/HelpUtils.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/HelpUtils.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/HelpUtils.h 2017-01-31 17:58:52.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/HelpUtils.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // HelpUtils.h -#ifndef __HELP_UTILS_H -#define __HELP_UTILS_H +#ifndef ZIP7_INC_HELP_UTILS_H +#define ZIP7_INC_HELP_UTILS_H #include "../../../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/IFolder.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/IFolder.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/IFolder.h 2015-02-09 11:06:43.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/IFolder.h 2023-03-16 12:00:00.000000000 +0000 @@ -1,13 +1,19 @@ // IFolder.h -#ifndef __IFOLDER_H -#define __IFOLDER_H +#ifndef ZIP7_INC_IFOLDER_H +#define ZIP7_INC_IFOLDER_H #include "../../IProgress.h" #include "../../IStream.h" -#define FOLDER_INTERFACE_SUB(i, b, x) DECL_INTERFACE_SUB(i, b, 8, x) -#define FOLDER_INTERFACE(i, x) FOLDER_INTERFACE_SUB(i, IUnknown, x) +Z7_PURE_INTERFACES_BEGIN + +#define Z7_IFACE_CONSTR_FOLDER_SUB(i, base, n) \ + Z7_DECL_IFACE_7ZIP_SUB(i, base, 8, n) \ + { Z7_IFACE_COM7_PURE(i) }; + +#define Z7_IFACE_CONSTR_FOLDER(i, n) \ + Z7_IFACE_CONSTR_FOLDER_SUB(i, IUnknown, n) namespace NPlugin { @@ -20,199 +26,162 @@ }; } -#define INTERFACE_FolderFolder(x) \ - STDMETHOD(LoadItems)() x; \ - STDMETHOD(GetNumberOfItems)(UInt32 *numItems) x; \ - STDMETHOD(GetProperty)(UInt32 itemIndex, PROPID propID, PROPVARIANT *value) x; \ - STDMETHOD(BindToFolder)(UInt32 index, IFolderFolder **resultFolder) x; \ - STDMETHOD(BindToFolder)(const wchar_t *name, IFolderFolder **resultFolder) x; \ - STDMETHOD(BindToParentFolder)(IFolderFolder **resultFolder) x; \ - STDMETHOD(GetNumberOfProperties)(UInt32 *numProperties) x; \ - STDMETHOD(GetPropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) x; \ - STDMETHOD(GetFolderProperty)(PROPID propID, PROPVARIANT *value) x; \ +#define Z7_IFACEM_IFolderFolder(x) \ + x(LoadItems()) \ + x(GetNumberOfItems(UInt32 *numItems)) \ + x(GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT *value)) \ + x(BindToFolder(UInt32 index, IFolderFolder **resultFolder)) \ + x(BindToFolder(const wchar_t *name, IFolderFolder **resultFolder)) \ + x(BindToParentFolder(IFolderFolder **resultFolder)) \ + x(GetNumberOfProperties(UInt32 *numProperties)) \ + x(GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \ + x(GetFolderProperty(PROPID propID, PROPVARIANT *value)) \ -FOLDER_INTERFACE(IFolderFolder, 0x00) -{ - INTERFACE_FolderFolder(PURE) -}; +Z7_IFACE_CONSTR_FOLDER(IFolderFolder, 0x00) /* IFolderAltStreams:: BindToAltStreams((UInt32)(Int32)-1, ... ) means alt streams of that folder */ -#define INTERFACE_FolderAltStreams(x) \ - STDMETHOD(BindToAltStreams)(UInt32 index, IFolderFolder **resultFolder) x; \ - STDMETHOD(BindToAltStreams)(const wchar_t *name, IFolderFolder **resultFolder) x; \ - STDMETHOD(AreAltStreamsSupported)(UInt32 index, Int32 *isSupported) x; \ - -FOLDER_INTERFACE(IFolderAltStreams, 0x17) -{ - INTERFACE_FolderAltStreams(PURE) -}; - -FOLDER_INTERFACE(IFolderWasChanged, 0x04) -{ - STDMETHOD(WasChanged)(Int32 *wasChanged) PURE; -}; - -FOLDER_INTERFACE_SUB(IFolderOperationsExtractCallback, IProgress, 0x0B) -{ - // STDMETHOD(SetTotalFiles)(UInt64 total) PURE; - // STDMETHOD(SetCompletedFiles)(const UInt64 *completedValue) PURE; - STDMETHOD(AskWrite)( - const wchar_t *srcPath, - Int32 srcIsFolder, - const FILETIME *srcTime, - const UInt64 *srcSize, - const wchar_t *destPathRequest, - BSTR *destPathResult, - Int32 *writeAnswer) PURE; - STDMETHOD(ShowMessage)(const wchar_t *message) PURE; - STDMETHOD(SetCurrentFilePath)(const wchar_t *filePath) PURE; - STDMETHOD(SetNumFiles)(UInt64 numFiles) PURE; -}; - -#define INTERFACE_FolderOperations(x) \ - STDMETHOD(CreateFolder)(const wchar_t *name, IProgress *progress) x; \ - STDMETHOD(CreateFile)(const wchar_t *name, IProgress *progress) x; \ - STDMETHOD(Rename)(UInt32 index, const wchar_t *newName, IProgress *progress) x; \ - STDMETHOD(Delete)(const UInt32 *indices, UInt32 numItems, IProgress *progress) x; \ - STDMETHOD(CopyTo)(Int32 moveMode, const UInt32 *indices, UInt32 numItems, \ +#define Z7_IFACEM_IFolderAltStreams(x) \ + x(BindToAltStreams(UInt32 index, IFolderFolder **resultFolder)) \ + x(BindToAltStreams(const wchar_t *name, IFolderFolder **resultFolder)) \ + x(AreAltStreamsSupported(UInt32 index, Int32 *isSupported)) \ + +Z7_IFACE_CONSTR_FOLDER(IFolderAltStreams, 0x17) + +#define Z7_IFACEM_IFolderWasChanged(x) \ + x(WasChanged(Int32 *wasChanged)) +Z7_IFACE_CONSTR_FOLDER(IFolderWasChanged, 0x04) + + /* x(SetTotalFiles(UInt64 total)) */ \ + /* x(SetCompletedFiles(const UInt64 *completedValue)) */ \ +#define Z7_IFACEM_IFolderOperationsExtractCallback(x) \ + x(AskWrite( \ + const wchar_t *srcPath, \ + Int32 srcIsFolder, \ + const FILETIME *srcTime, \ + const UInt64 *srcSize, \ + const wchar_t *destPathRequest, \ + BSTR *destPathResult, \ + Int32 *writeAnswer)) \ + x(ShowMessage(const wchar_t *message)) \ + x(SetCurrentFilePath(const wchar_t *filePath)) \ + x(SetNumFiles(UInt64 numFiles)) \ + +Z7_IFACE_CONSTR_FOLDER_SUB(IFolderOperationsExtractCallback, IProgress, 0x0B) + + +#define Z7_IFACEM_IFolderOperations(x) \ + x(CreateFolder(const wchar_t *name, IProgress *progress)) \ + x(CreateFile(const wchar_t *name, IProgress *progress)) \ + x(Rename(UInt32 index, const wchar_t *newName, IProgress *progress)) \ + x(Delete(const UInt32 *indices, UInt32 numItems, IProgress *progress)) \ + x(CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems, \ Int32 includeAltStreams, Int32 replaceAltStreamCharsMode, \ - const wchar_t *path, IFolderOperationsExtractCallback *callback) x; \ - STDMETHOD(CopyFrom)(Int32 moveMode, const wchar_t *fromFolderPath, \ - const wchar_t * const *itemsPaths, UInt32 numItems, IProgress *progress) x; \ - STDMETHOD(SetProperty)(UInt32 index, PROPID propID, const PROPVARIANT *value, IProgress *progress) x; \ - STDMETHOD(CopyFromFile)(UInt32 index, const wchar_t *fullFilePath, IProgress *progress) x; \ + const wchar_t *path, IFolderOperationsExtractCallback *callback)) \ + x(CopyFrom(Int32 moveMode, const wchar_t *fromFolderPath, \ + const wchar_t * const *itemsPaths, UInt32 numItems, IProgress *progress)) \ + x(SetProperty(UInt32 index, PROPID propID, const PROPVARIANT *value, IProgress *progress)) \ + x(CopyFromFile(UInt32 index, const wchar_t *fullFilePath, IProgress *progress)) \ -FOLDER_INTERFACE(IFolderOperations, 0x13) -{ - INTERFACE_FolderOperations(PURE) -}; +Z7_IFACE_CONSTR_FOLDER(IFolderOperations, 0x13) /* FOLDER_INTERFACE2(IFolderOperationsDeleteToRecycleBin, 0x06, 0x03) { - STDMETHOD(DeleteToRecycleBin)(const UInt32 *indices, UInt32 numItems, IProgress *progress) PURE; + x(DeleteToRecycleBin(const UInt32 *indices, UInt32 numItems, IProgress *progress)) \ }; */ -FOLDER_INTERFACE(IFolderGetSystemIconIndex, 0x07) -{ - STDMETHOD(GetSystemIconIndex)(UInt32 index, Int32 *iconIndex) PURE; -}; - -FOLDER_INTERFACE(IFolderGetItemFullSize, 0x08) -{ - STDMETHOD(GetItemFullSize)(UInt32 index, PROPVARIANT *value, IProgress *progress) PURE; -}; - -FOLDER_INTERFACE(IFolderCalcItemFullSize, 0x14) -{ - STDMETHOD(CalcItemFullSize)(UInt32 index, IProgress *progress) PURE; -}; - -FOLDER_INTERFACE(IFolderClone, 0x09) -{ - STDMETHOD(Clone)(IFolderFolder **resultFolder) PURE; -}; - -FOLDER_INTERFACE(IFolderSetFlatMode, 0x0A) -{ - STDMETHOD(SetFlatMode)(Int32 flatMode) PURE; -}; +#define Z7_IFACEM_IFolderGetSystemIconIndex(x) \ + x(GetSystemIconIndex(UInt32 index, Int32 *iconIndex)) +Z7_IFACE_CONSTR_FOLDER(IFolderGetSystemIconIndex, 0x07) + +#define Z7_IFACEM_IFolderGetItemFullSize(x) \ + x(GetItemFullSize(UInt32 index, PROPVARIANT *value, IProgress *progress)) +Z7_IFACE_CONSTR_FOLDER(IFolderGetItemFullSize, 0x08) + +#define Z7_IFACEM_IFolderCalcItemFullSize(x) \ + x(CalcItemFullSize(UInt32 index, IProgress *progress)) +Z7_IFACE_CONSTR_FOLDER(IFolderCalcItemFullSize, 0x14) + +#define Z7_IFACEM_IFolderClone(x) \ + x(Clone(IFolderFolder **resultFolder)) +Z7_IFACE_CONSTR_FOLDER(IFolderClone, 0x09) + +#define Z7_IFACEM_IFolderSetFlatMode(x) \ + x(SetFlatMode(Int32 flatMode)) +Z7_IFACE_CONSTR_FOLDER(IFolderSetFlatMode, 0x0A) /* -FOLDER_INTERFACE(IFolderSetShowNtfsStreamsMode, 0xFA) -{ - STDMETHOD(SetShowNtfsStreamsMode)(Int32 showStreamsMode) PURE; -}; +#define Z7_IFACEM_IFolderSetShowNtfsStreamsMode(x) \ + x(SetShowNtfsStreamsMode(Int32 showStreamsMode)) +Z7_IFACE_CONSTR_FOLDER(IFolderSetShowNtfsStreamsMode, 0xFA) */ -#define INTERFACE_FolderProperties(x) \ - STDMETHOD(GetNumberOfFolderProperties)(UInt32 *numProperties) x; \ - STDMETHOD(GetFolderPropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) x; \ - -FOLDER_INTERFACE(IFolderProperties, 0x0E) -{ - INTERFACE_FolderProperties(PURE) -}; - -#define INTERFACE_IFolderArcProps(x) \ - STDMETHOD(GetArcNumLevels)(UInt32 *numLevels) x; \ - STDMETHOD(GetArcProp)(UInt32 level, PROPID propID, PROPVARIANT *value) x; \ - STDMETHOD(GetArcNumProps)(UInt32 level, UInt32 *numProps) x; \ - STDMETHOD(GetArcPropInfo)(UInt32 level, UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) x; \ - STDMETHOD(GetArcProp2)(UInt32 level, PROPID propID, PROPVARIANT *value) x; \ - STDMETHOD(GetArcNumProps2)(UInt32 level, UInt32 *numProps) x; \ - STDMETHOD(GetArcPropInfo2)(UInt32 level, UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) x; \ - -FOLDER_INTERFACE(IFolderArcProps, 0x10) -{ - INTERFACE_IFolderArcProps(PURE) -}; - -FOLDER_INTERFACE(IGetFolderArcProps, 0x11) -{ - STDMETHOD(GetFolderArcProps)(IFolderArcProps **object) PURE; -}; - -FOLDER_INTERFACE(IFolderCompare, 0x15) -{ - STDMETHOD_(Int32, CompareItems)(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw) PURE; -}; - -#define INTERFACE_IFolderGetItemName(x) \ - STDMETHOD(GetItemName)(UInt32 index, const wchar_t **name, unsigned *len) x; \ - STDMETHOD(GetItemPrefix)(UInt32 index, const wchar_t **name, unsigned *len) x; \ - STDMETHOD_(UInt64, GetItemSize)(UInt32 index) x; \ - -FOLDER_INTERFACE(IFolderGetItemName, 0x16) -{ - INTERFACE_IFolderGetItemName(PURE) -}; - -#define FOLDER_MANAGER_INTERFACE(i, x) DECL_INTERFACE(i, 9, x) - -#define INTERFACE_IFolderManager(x) \ - STDMETHOD(OpenFolderFile)(IInStream *inStream, const wchar_t *filePath, const wchar_t *arcFormat, IFolderFolder **resultFolder, IProgress *progress) x; \ - STDMETHOD(GetExtensions)(BSTR *extensions) x; \ - STDMETHOD(GetIconPath)(const wchar_t *ext, BSTR *iconPath, Int32 *iconIndex) x; \ +#define Z7_IFACEM_IFolderProperties(x) \ + x(GetNumberOfFolderProperties(UInt32 *numProperties)) \ + x(GetFolderPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \ + +Z7_IFACE_CONSTR_FOLDER(IFolderProperties, 0x0E) + +#define Z7_IFACEM_IFolderArcProps(x) \ + x(GetArcNumLevels(UInt32 *numLevels)) \ + x(GetArcProp(UInt32 level, PROPID propID, PROPVARIANT *value)) \ + x(GetArcNumProps(UInt32 level, UInt32 *numProps)) \ + x(GetArcPropInfo(UInt32 level, UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \ + x(GetArcProp2(UInt32 level, PROPID propID, PROPVARIANT *value)) \ + x(GetArcNumProps2(UInt32 level, UInt32 *numProps)) \ + x(GetArcPropInfo2(UInt32 level, UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \ + +Z7_IFACE_CONSTR_FOLDER(IFolderArcProps, 0x10) + +#define Z7_IFACEM_IGetFolderArcProps(x) \ + x(GetFolderArcProps(IFolderArcProps **object)) +Z7_IFACE_CONSTR_FOLDER(IGetFolderArcProps, 0x11) + +#define Z7_IFACEM_IFolderCompare(x) \ + x##2(Int32, CompareItems(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw)) +Z7_IFACE_CONSTR_FOLDER(IFolderCompare, 0x15) + +#define Z7_IFACEM_IFolderGetItemName(x) \ + x(GetItemName(UInt32 index, const wchar_t **name, unsigned *len)) \ + x(GetItemPrefix(UInt32 index, const wchar_t **name, unsigned *len)) \ + x##2(UInt64, GetItemSize(UInt32 index)) \ + +Z7_IFACE_CONSTR_FOLDER(IFolderGetItemName, 0x16) + + +#define Z7_IFACEM_IFolderManager(x) \ + x(OpenFolderFile(IInStream *inStream, const wchar_t *filePath, const wchar_t *arcFormat, IFolderFolder **resultFolder, IProgress *progress)) \ + x(GetExtensions(BSTR *extensions)) \ + x(GetIconPath(const wchar_t *ext, BSTR *iconPath, Int32 *iconIndex)) \ - // STDMETHOD(GetTypes)(BSTR *types) PURE; - // STDMETHOD(CreateFolderFile)(const wchar_t *type, const wchar_t *filePath, IProgress *progress) PURE; - -FOLDER_MANAGER_INTERFACE(IFolderManager, 0x05) -{ - INTERFACE_IFolderManager(PURE); -}; + // x(GetTypes(BSTR *types)) + // x(CreateFolderFile(const wchar_t *type, const wchar_t *filePath, IProgress *progress)) + +Z7_DECL_IFACE_7ZIP(IFolderManager, 9, 5) + { Z7_IFACE_COM7_PURE(IFolderManager) }; /* -#define IMP_IFolderFolder_GetProp(k) \ - (UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) \ - { if (index >= ARRAY_SIZE(k)) return E_INVALIDARG; \ const CMy_STATPROPSTG_2 &srcItem = k[index]; \ *propID = srcItem.propid; *varType = srcItem.vt; *name = 0; return S_OK; } \ - -#define IMP_IFolderFolder_Props(c) \ - STDMETHODIMP c::GetNumberOfProperties(UInt32 *numProperties) \ - { *numProperties = ARRAY_SIZE(kProps); return S_OK; } \ - STDMETHODIMP c::GetPropertyInfo IMP_IFolderFolder_GetProp(kProps) */ - -#define IMP_IFolderFolder_GetProp(k) \ - (UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) \ - { if (index >= ARRAY_SIZE(k)) return E_INVALIDARG; \ - *propID = k[index]; *varType = k7z_PROPID_To_VARTYPE[(unsigned)*propID]; *name = 0; return S_OK; } \ +#define IMP_IFolderFolder_GetProp(fn, k) \ + Z7_COM7F_IMF(fn(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \ + { if (index >= Z7_ARRAY_SIZE(k)) return E_INVALIDARG; \ + *propID = k[index]; *varType = k7z_PROPID_To_VARTYPE[(unsigned)*propID]; *name = NULL; return S_OK; } \ #define IMP_IFolderFolder_Props(c) \ - STDMETHODIMP c::GetNumberOfProperties(UInt32 *numProperties) \ - { *numProperties = ARRAY_SIZE(kProps); return S_OK; } \ - STDMETHODIMP c::GetPropertyInfo IMP_IFolderFolder_GetProp(kProps) + Z7_COM7F_IMF(c::GetNumberOfProperties(UInt32 *numProperties)) \ + { *numProperties = Z7_ARRAY_SIZE(kProps); return S_OK; } \ + IMP_IFolderFolder_GetProp(c::GetPropertyInfo, kProps) int CompareFileNames_ForFolderList(const wchar_t *s1, const wchar_t *s2); // int CompareFileNames_ForFolderList(const FChar *s1, const FChar *s2); +Z7_PURE_INTERFACES_END #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/LangPage.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/LangPage.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/LangPage.cpp 2017-02-27 16:16:30.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/LangPage.cpp 2023-06-18 11:00:00.000000000 +0000 @@ -15,13 +15,37 @@ using namespace NWindows; + +static const unsigned k_NumLangLines_EN = 429; + +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { IDT_LANG_LANG }; +#endif #define kLangTopic "fm/options.htm#language" + +struct CLangListRecord +{ + int Order; + unsigned LangInfoIndex; + bool IsSelected; + UString Mark; + UString Name; + + CLangListRecord(): Order (10), IsSelected(false) {} + int Compare(const CLangListRecord &a) const + { + if (Order < a.Order) return -1; + if (Order > a.Order) return 1; + return MyStringCompareNoCase(Name, a.Name); + } +}; + + static void NativeLangString(UString &dest, const wchar_t *s) { dest += " ("; @@ -33,23 +57,51 @@ bool CLangPage::OnInit() { - LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); - +#ifdef Z7_LANG + LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs)); +#endif _langCombo.Attach(GetItem(IDC_LANG_LANG)); - UString temp = MyLoadString(IDS_LANG_ENGLISH); - NativeLangString(temp, MyLoadString(IDS_LANG_NATIVE)); - int index = (int)_langCombo.AddString(temp); - _langCombo.SetItemData(index, _paths.Size()); - _paths.Add(L"-"); - _langCombo.SetCurSel(0); + + unsigned listRecords_SelectedIndex = 0; + + CObjectVector listRecords; + { + CLangListRecord listRecord; + listRecord.Order = 0; + listRecord.Mark = "---"; + listRecord.Name = MyLoadString(IDS_LANG_ENGLISH); + NativeLangString(listRecord.Name, MyLoadString(IDS_LANG_NATIVE)); + listRecord.LangInfoIndex = _langs.Size(); + listRecords.Add(listRecord); + } + + AStringVector names; + unsigned subLangIndex = 0; + Lang_GetShortNames_for_DefaultLang(names, subLangIndex); const FString dirPrefix = GetLangDirPrefix(); NFile::NFind::CEnumerator enumerator; enumerator.SetDirPrefix(dirPrefix); NFile::NFind::CFileInfo fi; + + CLang lang_en; + { + CLangInfo &langInfo = _langs.AddNew(); + langInfo.Name = "-"; + if (LangOpen(lang_en, dirPrefix + FTEXT("en.ttt"))) + { + langInfo.NumLines = lang_en._ids.Size(); + // langInfo.Comments = lang_en.Comments; + } + else + langInfo.NumLines = k_NumLangLines_EN; + NumLangLines_EN = langInfo.NumLines; + } + CLang lang; UString error; + UString n; while (enumerator.Next(fi)) { @@ -73,6 +125,39 @@ } const UString shortName = fs2us(fi.Name.Left(pos)); + + CLangListRecord listRecord; + if (!names.IsEmpty()) + { + for (unsigned i = 0; i < names.Size(); i++) + if (shortName.IsEqualTo_Ascii_NoCase(names[i])) + { + if (subLangIndex == i || names.Size() == 1) + { + listRecord.Mark = "***"; + // listRecord.Order = 1; + } + else + { + listRecord.Mark = "+++"; + // listRecord.Order = 2; + } + break; + } + if (listRecord.Mark.IsEmpty()) + { + const int minusPos = shortName.Find(L'-'); + if (minusPos >= 0) + { + const UString shortName2 = shortName.Left(minusPos); + if (shortName2.IsEqualTo_Ascii_NoCase(names[0])) + { + listRecord.Mark = "+++"; + // listRecord.Order = 3; + } + } + } + } UString s = shortName; const wchar_t *eng = lang.Get(IDS_LANG_ENGLISH); if (eng) @@ -80,25 +165,119 @@ const wchar_t *native = lang.Get(IDS_LANG_NATIVE); if (native) NativeLangString(s, native); - index = (int)_langCombo.AddString(s); - _langCombo.SetItemData(index, _paths.Size()); - _paths.Add(shortName); + + listRecord.Name = s; + listRecord.LangInfoIndex = _langs.Size(); + listRecords.Add(listRecord); if (g_LangID.IsEqualTo_NoCase(shortName)) + listRecords_SelectedIndex = listRecords.Size() - 1; + + CLangInfo &langInfo = _langs.AddNew(); + langInfo.Comments = lang.Comments; + langInfo.Name = shortName; + unsigned numLines = lang._ids.Size(); + if (!lang_en.IsEmpty()) + { + numLines = 0; + unsigned i1 = 0; + unsigned i2 = 0; + for (;;) + { + UInt32 id1 = (UInt32)0 - 1; + UInt32 id2 = (UInt32)0 - 1; + bool id1_defined = false; + bool id2_defined = false; + if (i1 < lang_en._ids.Size()) + { + id1 = lang_en._ids[i1]; + id1_defined = true; + } + if (i2 < lang._ids.Size()) + { + id2 = lang._ids[i2]; + id2_defined = true; + } + + bool id1_is_smaller = true; + if (id1_defined) + { + if (id2_defined) + { + if (id1 == id2) + { + i1++; + i2++; + numLines++; + continue; + } + if (id1 > id2) + id1_is_smaller = false; + } + } + else if (!id2_defined) + break; + else + id1_is_smaller = false; + + n.Empty(); + if (id1_is_smaller) + { + n.Add_UInt32(id1); + n += " : "; + n += lang_en.Get_by_index(i1); + langInfo.MissingLines.Add(n); + i1++; + } + else + { + n.Add_UInt32(id2); + n += " : "; + n += lang.Get_by_index(i2); + langInfo.ExtraLines.Add(n); + i2++; + } + } + } + langInfo.NumLines = numLines + langInfo.ExtraLines.Size(); + } + + listRecords[listRecords_SelectedIndex].IsSelected = true; + + listRecords.Sort(); + FOR_VECTOR (i, listRecords) + { + const CLangListRecord &rec= listRecords[i]; + UString temp = rec.Name; + if (!rec.Mark.IsEmpty()) + { + temp += " "; + temp += rec.Mark; + } + const int index = (int)_langCombo.AddString(temp); + _langCombo.SetItemData(index, (LPARAM)rec.LangInfoIndex); + if (rec.IsSelected) _langCombo.SetCurSel(index); } + + ShowLangInfo(); if (!error.IsEmpty()) - MessageBoxW(0, error, L"Error in Lang file", MB_ICONERROR); + MessageBoxW(NULL, error, L"Error in Lang file", MB_ICONERROR); return CPropertyPage::OnInit(); } LONG CLangPage::OnApply() { - int pathIndex = (int)_langCombo.GetItemData_of_CurSel(); if (_needSave) - SaveRegLang(_paths[pathIndex]); + { + const int pathIndex = (int)_langCombo.GetItemData_of_CurSel(); + if ((unsigned)pathIndex < _langs.Size()) + SaveRegLang(_langs[pathIndex].Name); + } _needSave = false; + #ifdef Z7_LANG ReloadLang(); + #endif LangWasChanged = true; return PSNRET_NOERROR; } @@ -108,13 +287,75 @@ ShowHelpWindow(kLangTopic); } -bool CLangPage::OnCommand(int code, int itemID, LPARAM param) +bool CLangPage::OnCommand(unsigned code, unsigned itemID, LPARAM param) { if (code == CBN_SELCHANGE && itemID == IDC_LANG_LANG) { _needSave = true; Changed(); + ShowLangInfo(); return true; } return CPropertyPage::OnCommand(code, itemID, param); } + +static void AddVectorToString(UString &s, const UStringVector &v) +{ + UString a; + FOR_VECTOR (i, v) + { + if (i >= 50) + break; + a = v[i]; + if (a.Len() > 1500) + continue; + if (a[0] == ';') + { + a.DeleteFrontal(1); + a.Trim(); + } + s += a; + s.Add_LF(); + } +} + +static void AddVectorToString2(UString &s, const char *name, const UStringVector &v) +{ + if (v.IsEmpty()) + return; + s.Add_LF(); + s += "------ "; + s += name; + s += ": "; + s.Add_UInt32(v.Size()); + s += " :"; + s.Add_LF(); + AddVectorToString(s, v); +} + +void CLangPage::ShowLangInfo() +{ + UString s; + const int pathIndex = (int)_langCombo.GetItemData_of_CurSel(); + if ((unsigned)pathIndex < _langs.Size()) + { + const CLangInfo &langInfo = _langs[pathIndex]; + const unsigned numLines = langInfo.NumLines; + s += langInfo.Name; + s += " : "; + s.Add_UInt32(numLines); + if (NumLangLines_EN != 0) + { + s += " / "; + s.Add_UInt32(NumLangLines_EN); + s += " = "; + s.Add_UInt32(numLines * 100 / NumLangLines_EN); + s += "%"; + } + s.Add_LF(); + AddVectorToString(s, langInfo.Comments); + AddVectorToString2(s, "Missing lines", langInfo.MissingLines); + AddVectorToString2(s, "Extra lines", langInfo.ExtraLines); + } + SetItemText(IDT_LANG_INFO, s); +} diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/LangPage.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/LangPage.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/LangPage.h 2015-11-29 10:10:01.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/LangPage.h 2023-05-16 14:00:00.000000000 +0000 @@ -1,25 +1,36 @@ // LangPage.h -#ifndef __LANG_PAGE_H -#define __LANG_PAGE_H +#ifndef ZIP7_INC_LANG_PAGE_H +#define ZIP7_INC_LANG_PAGE_H #include "../../../Windows/Control/PropertyPage.h" #include "../../../Windows/Control/ComboBox.h" +struct CLangInfo +{ + unsigned NumLines; + UString Name; + UStringVector Comments; + UStringVector MissingLines; + UStringVector ExtraLines; +}; + class CLangPage: public NWindows::NControl::CPropertyPage { NWindows::NControl::CComboBox _langCombo; - UStringVector _paths; - + CObjectVector _langs; + unsigned NumLangLines_EN; bool _needSave; + + void ShowLangInfo(); public: bool LangWasChanged; CLangPage(): _needSave(false), LangWasChanged(false) {} - virtual bool OnInit(); - virtual void OnNotifyHelp(); - virtual bool OnCommand(int code, int itemID, LPARAM param); - virtual LONG OnApply(); + virtual bool OnInit() Z7_override; + virtual void OnNotifyHelp() Z7_override; + virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM param) Z7_override; + virtual LONG OnApply() Z7_override; }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/LangPage.rc 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/LangPage.rc --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/LangPage.rc 2014-09-01 11:53:08.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/LangPage.rc 2023-06-18 11:00:00.000000000 +0000 @@ -1,14 +1,17 @@ #include "LangPageRes.h" #include "../../GuiCommon.rc" -#define xc 160 -#define yc 100 +#define xc 240 +#define yc 252 + +#define y 32 IDD_LANG DIALOG 0, 0, xs, ys MY_PAGE_STYLE MY_FONT CAPTION "Language" { LTEXT "Language:", IDT_LANG_LANG, m, m, xc, 8 - COMBOBOX IDC_LANG_LANG, m, 20, xc, yc - 20, MY_COMBO_SORTED + COMBOBOX IDC_LANG_LANG, m, 20, 160, yc - 20, MY_COMBO // MY_COMBO_SORTED + LTEXT "", IDT_LANG_INFO, m, m + y, xc, yc - y, SS_NOPREFIX } @@ -24,7 +27,7 @@ CAPTION "Language" { LTEXT "Language:", IDT_LANG_LANG, m, m, xc, 8 - COMBOBOX IDC_LANG_LANG, m, 20, xc, yc - 20, MY_COMBO_SORTED + COMBOBOX IDC_LANG_LANG, m, 20, xc, yc - 20, MY_COMBO // MY_COMBO_SORTED } #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/LangPageRes.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/LangPageRes.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/LangPageRes.h 2011-05-08 06:05:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/LangPageRes.h 2023-05-15 07:00:00.000000000 +0000 @@ -6,3 +6,4 @@ #define IDT_LANG_LANG 2102 #define IDC_LANG_LANG 100 +#define IDT_LANG_INFO 101 diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/LangUtils.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/LangUtils.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/LangUtils.cpp 2021-01-22 20:51:43.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/LangUtils.cpp 2023-06-18 11:00:00.000000000 +0000 @@ -19,7 +19,8 @@ UString g_LangID; -static CLang g_Lang; +// static +CLang g_Lang; static bool g_Loaded = false; static NSynchronization::CCriticalSection g_CriticalSection; @@ -34,6 +35,8 @@ return NDLL::GetModuleDirPrefix() + FTEXT("Lang") FSTRING_PATH_SEPARATOR; } +#ifdef Z7_LANG + void LoadLangOneTime() { NSynchronization::CCriticalSectionLock lock(g_CriticalSection); @@ -48,7 +51,7 @@ const wchar_t *s = g_Lang.Get(langID); if (s) { - CWindow window(GetDlgItem(dialog, controlID)); + CWindow window(GetDlgItem(dialog, (int)controlID)); window.SetText(s); } } @@ -67,10 +70,10 @@ void LangSetDlgItems(HWND dialog, const UInt32 *ids, unsigned numItems) { unsigned i; - for (i = 0; i < ARRAY_SIZE(kLangPairs); i++) + for (i = 0; i < Z7_ARRAY_SIZE(kLangPairs); i++) { const CIDLangPair &pair = kLangPairs[i]; - CWindow window(GetDlgItem(dialog, pair.ControlID)); + CWindow window(GetDlgItem(dialog, (int)pair.ControlID)); if (window) { const wchar_t *s = g_Lang.Get(pair.LangID); @@ -81,7 +84,7 @@ for (i = 0; i < numItems; i++) { - UInt32 id = ids[i]; + const UInt32 id = ids[i]; LangSetDlgItemText(dialog, id, id); } } @@ -90,11 +93,11 @@ { for (unsigned i = 0; i < numItems; i++) { - UInt32 id = ids[i]; + const UInt32 id = ids[i]; const wchar_t *s = g_Lang.Get(id); if (s) { - CWindow window(GetDlgItem(dialog, id)); + CWindow window(GetDlgItem(dialog, (int)id)); UString s2 = s; s2 += ':'; window.SetText(s2); @@ -102,6 +105,23 @@ } } +void LangSetDlgItems_RemoveColon(HWND dialog, const UInt32 *ids, unsigned numItems) +{ + for (unsigned i = 0; i < numItems; i++) + { + const UInt32 id = ids[i]; + const wchar_t *s = g_Lang.Get(id); + if (s) + { + CWindow window(GetDlgItem(dialog, (int)id)); + UString s2 = s; + if (!s2.IsEmpty() && s2.Back() == ':') + s2.DeleteBack(); + window.SetText(s2); + } + } +} + void LangSetWindowText(HWND window, UInt32 langID) { const wchar_t *s = g_Lang.Get(langID); @@ -214,14 +234,18 @@ // typedef LANGID (WINAPI *GetUserDefaultUILanguageP)(); -static void OpenDefaultLang() +void Lang_GetShortNames_for_DefaultLang(AStringVector &names, unsigned &subLang) { - LANGID sysLang = GetSystemDefaultLangID(); // "Language for non-Unicode programs" in XP64 - LANGID userLang = GetUserDefaultLangID(); // "Standards and formats" language in XP64 + names.Clear(); + subLang = 0; + const LANGID sysLang = GetSystemDefaultLangID(); // "Language for non-Unicode programs" in XP64 + const LANGID userLang = GetUserDefaultLangID(); // "Standards and formats" language in XP64 if (sysLang != userLang) return; - LANGID langID = userLang; + const LANGID langID = userLang; + + // const LANGID langID = MAKELANGID(0x1a, 1); // for debug /* LANGID sysUILang; // english in XP64 @@ -237,15 +261,22 @@ sysUILang = fn(); */ - WORD primLang = (WORD)(PRIMARYLANGID(langID)); - WORD subLang = (WORD)(SUBLANGID(langID)); + const WORD primLang = (WORD)(PRIMARYLANGID(langID)); + subLang = SUBLANGID(langID); + FindShortNames(primLang, names); +} + + +static void OpenDefaultLang() +{ + AStringVector names; + unsigned subLang; + Lang_GetShortNames_for_DefaultLang(names, subLang); { - AStringVector names; - FindShortNames(primLang, names); const FString dirPrefix (GetLangDirPrefix()); for (unsigned i = 0; i < 2; i++) { - unsigned index = (i == 0 ? subLang : 0); + const unsigned index = (i == 0 ? subLang : 0); if (index < names.Size()) { const AString &name = names[index]; @@ -282,12 +313,14 @@ if (g_LangID.Len() > 1 || g_LangID[0] != L'-') { FString s = us2fs(g_LangID); - if (s.Find(FCHAR_PATH_SEPARATOR) < 0) + if (s.ReverseFind_PathSepar() < 0) { - if (s.Find(FTEXT('.')) < 0) + if (s.ReverseFind_Dot() < 0) s += ".txt"; s.Insert(0, GetLangDirPrefix()); + LangOpen(g_Lang, s); } - LangOpen(g_Lang, s); } } + +#endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/LangUtils.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/LangUtils.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/LangUtils.h 2014-08-04 14:35:22.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/LangUtils.h 2023-06-18 08:00:00.000000000 +0000 @@ -1,13 +1,16 @@ // LangUtils.h -#ifndef __LANG_UTILS_H -#define __LANG_UTILS_H +#ifndef ZIP7_INC_LANG_UTILS_H +#define ZIP7_INC_LANG_UTILS_H -#include "../../../Windows/ResourceString.h" +#include "../../../Common/Lang.h" -#ifdef LANG +#include "../../../Windows/ResourceString.h" extern UString g_LangID; +extern CLang g_Lang; + +#ifdef Z7_LANG struct CIDLangPair { @@ -17,11 +20,11 @@ void ReloadLang(); void LoadLangOneTime(); -FString GetLangDirPrefix(); void LangSetDlgItemText(HWND dialog, UInt32 controlID, UInt32 langID); void LangSetDlgItems(HWND dialog, const UInt32 *ids, unsigned numItems); void LangSetDlgItems_Colon(HWND dialog, const UInt32 *ids, unsigned numItems); +void LangSetDlgItems_RemoveColon(HWND dialog, const UInt32 *ids, unsigned numItems); void LangSetWindowText(HWND window, UInt32 langID); UString LangString(UInt32 langID); @@ -37,4 +40,9 @@ #endif +FString GetLangDirPrefix(); +// bool LangOpen(CLang &lang, CFSTR fileName); + +void Lang_GetShortNames_for_DefaultLang(AStringVector &names, unsigned &subLang); + #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/LinkDialog.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/LinkDialog.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/LinkDialog.cpp 2020-12-22 16:00:37.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/LinkDialog.cpp 2023-03-19 17:00:00.000000000 +0000 @@ -8,9 +8,7 @@ #include "../../../Windows/FileIO.h" #include "../../../Windows/FileName.h" -#ifdef LANG #include "LangUtils.h" -#endif #include "BrowseDialog.h" #include "CopyDialogRes.h" @@ -26,7 +24,7 @@ using namespace NWindows; using namespace NFile; -#ifdef LANG +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { IDB_LINK_LINK, @@ -73,7 +71,7 @@ } -static const int k_LinkType_Buttons[] = +static const unsigned k_LinkType_Buttons[] = { IDR_LINK_TYPE_HARD, IDR_LINK_TYPE_SYM_FILE, @@ -82,16 +80,19 @@ IDR_LINK_TYPE_WSL }; -void CLinkDialog::Set_LinkType_Radio(int idb) +void CLinkDialog::Set_LinkType_Radio(unsigned idb) { - CheckRadioButton(k_LinkType_Buttons[0], k_LinkType_Buttons[ARRAY_SIZE(k_LinkType_Buttons) - 1], idb); + CheckRadioButton( + k_LinkType_Buttons[0], + k_LinkType_Buttons[Z7_ARRAY_SIZE(k_LinkType_Buttons) - 1], + idb); } bool CLinkDialog::OnInit() { - #ifdef LANG + #ifdef Z7_LANG LangSetWindowText(*this, IDD_LINK); - LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); + LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs)); #endif _pathFromCombo.Attach(GetItem(IDC_LINK_PATH_FROM)); @@ -100,7 +101,7 @@ if (!FilePath.IsEmpty()) { NFind::CFileInfo fi; - int linkType = 0; + unsigned linkType = 0; if (!fi.Find(us2fs(FilePath))) linkType = IDR_LINK_TYPE_SYM_FILE; else @@ -109,7 +110,7 @@ { CReparseAttr attr; UString error; - bool res = GetSymLink(us2fs(FilePath), attr, error); + const bool res = GetSymLink(us2fs(FilePath), attr, error); if (!res && error.IsEmpty()) { DWORD lastError = GetLastError(); @@ -138,7 +139,7 @@ SetItemText(IDT_LINK_PATH_TO_CUR, s); - UString destPath = attr.GetPath(); + const UString destPath = attr.GetPath(); _pathFromCombo.SetText(FilePath); _pathToCombo.SetText(destPath); @@ -215,7 +216,7 @@ return false; } -bool CLinkDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CLinkDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -240,7 +241,7 @@ _pathFromCombo; combo.GetText(currentPath); // UString title = "Specify a location for output folder"; - UString title = LangString(IDS_SET_FOLDER); + const UString title = LangString(IDS_SET_FOLDER); UString resultPath; if (!MyBrowseForFolder(*this, title, currentPath, resultPath)) @@ -271,10 +272,10 @@ if (!NName::IsAbsolutePath(from)) from.Insert(0, CurDirPrefix); - int idb = -1; + unsigned idb = 0; for (unsigned i = 0;; i++) { - if (i >= ARRAY_SIZE(k_LinkType_Buttons)) + if (i >= Z7_ARRAY_SIZE(k_LinkType_Buttons)) return; idb = k_LinkType_Buttons[i]; if (IsButtonCheckedBool(idb)) @@ -355,7 +356,7 @@ void CApp::Link() { - unsigned srcPanelIndex = GetFocusedPanelIndex(); + const unsigned srcPanelIndex = GetFocusedPanelIndex(); CPanel &srcPanel = Panels[srcPanelIndex]; if (!srcPanel.IsFSFolder()) { @@ -363,7 +364,7 @@ return; } CRecordVector indices; - srcPanel.GetOperatedItemIndices(indices); + srcPanel.Get_ItemIndices_Operated(indices); if (indices.IsEmpty()) return; if (indices.Size() != 1) @@ -371,14 +372,14 @@ srcPanel.MessageBox_Error_LangID(IDS_SELECT_ONE_FILE); return; } - int index = indices[0]; + const UInt32 index = indices[0]; const UString itemName = srcPanel.GetItemName(index); const UString fsPrefix = srcPanel.GetFsPath(); const UString srcPath = fsPrefix + srcPanel.GetItemPrefix(index); UString path = srcPath; { - unsigned destPanelIndex = (NumPanels <= 1) ? srcPanelIndex : (1 - srcPanelIndex); + const unsigned destPanelIndex = (NumPanels <= 1) ? srcPanelIndex : (1 - srcPanelIndex); CPanel &destPanel = Panels[destPanelIndex]; if (NumPanels > 1) if (destPanel.IsFSFolder()) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/LinkDialog.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/LinkDialog.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/LinkDialog.h 2015-07-09 07:13:50.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/LinkDialog.h 2023-01-28 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // LinkDialog.h -#ifndef __LINK_DIALOG_H -#define __LINK_DIALOG_H +#ifndef ZIP7_INC_LINK_DIALOG_H +#define ZIP7_INC_LINK_DIALOG_H #include "../../../Windows/Control/Dialog.h" #include "../../../Windows/Control/ComboBox.h" @@ -13,21 +13,21 @@ NWindows::NControl::CComboBox _pathFromCombo; NWindows::NControl::CComboBox _pathToCombo; - virtual bool OnInit(); - virtual bool OnSize(WPARAM wParam, int xSize, int ySize); - virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); + virtual bool OnInit() Z7_override; + virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override; + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; void OnButton_SetPath(bool to); void OnButton_Link(); void ShowLastErrorMessage(); void ShowError(const wchar_t *s); - void Set_LinkType_Radio(int idb); + void Set_LinkType_Radio(unsigned idb); public: UString CurDirPrefix; UString FilePath; UString AnotherPath; - INT_PTR Create(HWND parentWindow = 0) + INT_PTR Create(HWND parentWindow = NULL) { return CModalDialog::Create(IDD_LINK, parentWindow); } }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ListViewDialog.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ListViewDialog.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ListViewDialog.cpp 2018-11-11 11:22:27.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ListViewDialog.cpp 2023-03-17 12:00:00.000000000 +0000 @@ -8,7 +8,7 @@ #include "ListViewDialog.h" #include "RegistryUtils.h" -#ifdef LANG +#ifdef Z7_LANG #include "LangUtils.h" #endif @@ -26,14 +26,14 @@ index = listView.GetNextSelectedItem(index); if (index < 0) break; - vector.Add(index); + vector.Add((unsigned)index); } } bool CListViewDialog::OnInit() { - #ifdef LANG + #ifdef Z7_LANG LangSetDlgItems(*this, NULL, 0); #endif _listView.Attach(GetItem(IDL_LISTVIEW)); @@ -227,17 +227,17 @@ { for (;;) { - int index = _listView.GetNextSelectedItem(-1); + const int index = _listView.GetNextSelectedItem(-1); if (index < 0) break; StringsWereChanged = true; - _listView.DeleteItem(index); + _listView.DeleteItem((unsigned)index); if ((unsigned)index < Strings.Size()) - Strings.Delete(index); + Strings.Delete((unsigned)index); if ((unsigned)index < Values.Size()) - Values.Delete(index); + Values.Delete((unsigned)index); } - int focusedIndex = _listView.GetFocusedItem(); + const int focusedIndex = _listView.GetFocusedItem(); if (focusedIndex >= 0) _listView.SetItemState_FocusedSelected(focusedIndex); _listView.SetColumnWidthAuto(0); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ListViewDialog.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ListViewDialog.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ListViewDialog.h 2018-03-19 15:30:47.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ListViewDialog.h 2023-01-28 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ListViewDialog.h -#ifndef __LISTVIEW_DIALOG_H -#define __LISTVIEW_DIALOG_H +#ifndef ZIP7_INC_LISTVIEW_DIALOG_H +#define ZIP7_INC_LISTVIEW_DIALOG_H #include "../../../Windows/Control/Dialog.h" #include "../../../Windows/Control/ListView.h" @@ -11,10 +11,10 @@ class CListViewDialog: public NWindows::NControl::CModalDialog { NWindows::NControl::CListView _listView; - virtual void OnOK(); - virtual bool OnInit(); - virtual bool OnSize(WPARAM wParam, int xSize, int ySize); - virtual bool OnNotify(UINT controlID, LPNMHDR header); + virtual void OnOK() Z7_override; + virtual bool OnInit() Z7_override; + virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override; + virtual bool OnNotify(UINT controlID, LPNMHDR header) Z7_override; void CopyToClipboard(); void DeleteItems(); void ShowItemInfo(); @@ -32,7 +32,7 @@ int FocusedItemIndex; unsigned NumColumns; - INT_PTR Create(HWND wndParent = 0) { return CModalDialog::Create(IDD_LISTVIEW, wndParent); } + INT_PTR Create(HWND wndParent = NULL) { return CModalDialog::Create(IDD_LISTVIEW, wndParent); } CListViewDialog(): SelectFirst(false), diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/makefile 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/makefile --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/makefile 2021-10-07 18:26:13.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/makefile 2023-01-29 17:00:00.000000000 +0000 @@ -1,6 +1,6 @@ PROG = 7zFM.exe CFLAGS = $(CFLAGS) \ - -DEXTERNAL_CODECS \ + -DZ7_EXTERNAL_CODECS \ !include "FM.mak" @@ -85,6 +85,7 @@ EXPLORER_OBJS = \ $O\ContextMenu.obj \ + $O\MyMessages.obj \ $O\RegistryContextMenu.obj \ GUI_OBJS = \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/MenuPage.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/MenuPage.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/MenuPage.cpp 2022-06-11 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/MenuPage.cpp 2023-03-19 17:00:00.000000000 +0000 @@ -26,6 +26,7 @@ using namespace NWindows; using namespace NContextMenuFlags; +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { IDX_SYSTEM_INTEGRATE_TO_MENU, @@ -35,12 +36,13 @@ IDT_SYSTEM_ZONE, IDT_SYSTEM_CONTEXT_MENU_ITEMS }; +#endif #define kMenuTopic "fm/options.htm#sevenZip" struct CContextMenuItem { - int ControlID; + unsigned ControlID; UInt32 Flag; }; @@ -97,7 +99,9 @@ Clear_MenuChanged(); - LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); +#ifdef Z7_LANG + LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs)); +#endif #ifdef UNDER_CE @@ -219,7 +223,7 @@ if (i == 0) s.Insert(0, L"* "); const int index = (int)_zoneCombo.AddString(s); - _zoneCombo.SetItemData(index, val); + _zoneCombo.SetItemData(index, (LPARAM)val); if (val == wz) _zoneCombo.SetCurSel(index); } @@ -231,7 +235,7 @@ _listView.InsertColumn(0, L"", 200); - for (unsigned i = 0; i < ARRAY_SIZE(kMenuItems); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(kMenuItems); i++) { const CContextMenuItem &menuItem = kMenuItems[i]; @@ -272,8 +276,8 @@ } } - int itemIndex = _listView.InsertItem(i, s); - _listView.SetCheckState(itemIndex, ((ci.Flags & menuItem.Flag) != 0)); + const int itemIndex = _listView.InsertItem(i, s); + _listView.SetCheckState((unsigned)itemIndex, ((ci.Flags & menuItem.Flag) != 0)); } _listView.SetColumnWidthAuto(0); @@ -303,8 +307,8 @@ CShellDll &dll = _dlls[d]; if (dll.wasChanged && !dll.Path.IsEmpty()) { - bool newVal = IsButtonCheckedBool(dll.ctrl); - LONG res = SetContextMenuHandler(newVal, fs2us(dll.Path), dll.wow); + const bool newVal = IsButtonCheckedBool(dll.ctrl); + const LONG res = SetContextMenuHandler(newVal, fs2us(dll.Path), dll.wow); if (res != ERROR_SUCCESS && (dll.prevValue != newVal || newVal)) ShowMenuErrorMessage(NError::MyFormatMessage(res), *this); dll.prevValue = CheckContextMenuHandler(fs2us(dll.Path), dll.wow); @@ -340,7 +344,7 @@ ci.Flags = 0; - for (unsigned i = 0; i < ARRAY_SIZE(kMenuItems); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(kMenuItems); i++) if (_listView.GetCheckState(i)) ci.Flags |= kMenuItems[i].Flag; @@ -360,7 +364,7 @@ ShowHelpWindow(kMenuTopic); } -bool CMenuPage::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CMenuPage::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -392,7 +396,7 @@ } -bool CMenuPage::OnCommand(int code, int itemID, LPARAM param) +bool CMenuPage::OnCommand(unsigned code, unsigned itemID, LPARAM param) { if (code == CBN_SELCHANGE && itemID == IDC_SYSTEM_ZONE) { diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/MenuPage.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/MenuPage.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/MenuPage.h 2022-05-30 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/MenuPage.h 2023-03-19 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // MenuPage.h -#ifndef __MENU_PAGE_H -#define __MENU_PAGE_H +#ifndef ZIP7_INC_MENU_PAGE_H +#define ZIP7_INC_MENU_PAGE_H #include "../../../Windows/Control/PropertyPage.h" #include "../../../Windows/Control/ComboBox.h" @@ -12,7 +12,7 @@ FString Path; bool wasChanged; bool prevValue; - int ctrl; + unsigned ctrl; UInt32 wow; CShellDll(): wasChanged (false), prevValue(false), ctrl(0), wow(0) {} @@ -44,14 +44,14 @@ NWindows::NControl::CListView _listView; NWindows::NControl::CComboBox _zoneCombo; - virtual bool OnInit(); - virtual void OnNotifyHelp(); - virtual bool OnNotify(UINT controlID, LPNMHDR lParam); - virtual bool OnItemChanged(const NMLISTVIEW *info); - virtual LONG OnApply(); - virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); - virtual bool OnCommand(int code, int itemID, LPARAM param); -public: + virtual bool OnInit() Z7_override; + virtual void OnNotifyHelp() Z7_override; + virtual bool OnNotify(UINT controlID, LPNMHDR lParam) Z7_override; + virtual LONG OnApply() Z7_override; + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; + virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM param) Z7_override; + + bool OnItemChanged(const NMLISTVIEW* info); }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/MessagesDialog.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/MessagesDialog.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/MessagesDialog.cpp 2013-02-20 10:05:03.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/MessagesDialog.cpp 2023-01-29 20:00:00.000000000 +0000 @@ -16,9 +16,9 @@ void CMessagesDialog::AddMessageDirect(LPCWSTR message) { - int i = _messageList.GetItemCount(); + const unsigned i = (unsigned)_messageList.GetItemCount(); wchar_t sz[16]; - ConvertUInt32ToString((UInt32)i, sz); + ConvertUInt32ToString(i, sz); _messageList.InsertItem(i, sz); _messageList.SetSubItem(i, 1, message); } @@ -28,18 +28,18 @@ UString s = message; while (!s.IsEmpty()) { - int pos = s.Find(L'\n'); + const int pos = s.Find(L'\n'); if (pos < 0) break; AddMessageDirect(s.Left(pos)); - s.DeleteFrontal(pos + 1); + s.DeleteFrontal((unsigned)pos + 1); } AddMessageDirect(s); } bool CMessagesDialog::OnInit() { - #ifdef LANG + #ifdef Z7_LANG LangSetWindowText(*this, IDD_MESSAGES); LangSetDlgItems(*this, NULL, 0); SetItemText(IDOK, LangString(IDS_CLOSE)); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/MessagesDialog.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/MessagesDialog.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/MessagesDialog.h 2013-01-17 10:10:25.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/MessagesDialog.h 2023-01-28 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // MessagesDialog.h -#ifndef __MESSAGES_DIALOG_H -#define __MESSAGES_DIALOG_H +#ifndef ZIP7_INC_MESSAGES_DIALOG_H +#define ZIP7_INC_MESSAGES_DIALOG_H #include "../../../Windows/Control/Dialog.h" #include "../../../Windows/Control/ListView.h" @@ -14,12 +14,12 @@ void AddMessageDirect(LPCWSTR message); void AddMessage(LPCWSTR message); - virtual bool OnInit(); - virtual bool OnSize(WPARAM wParam, int xSize, int ySize); + virtual bool OnInit() Z7_override; + virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override; public: const UStringVector *Messages; - INT_PTR Create(HWND parent = 0) { return CModalDialog::Create(IDD_MESSAGES, parent); } + INT_PTR Create(HWND parent = NULL) { return CModalDialog::Create(IDD_MESSAGES, parent); } }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/MyCom2.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/MyCom2.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/MyCom2.h 2022-07-14 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/MyCom2.h 2023-04-01 12:00:00.000000000 +0000 @@ -1,48 +1,55 @@ // MyCom2.h -#ifndef __MYCOM2_H -#define __MYCOM2_H +#ifndef ZIP7_INC_MYCOM2_H +#define ZIP7_INC_MYCOM2_H #include "../../../Common/MyCom.h" -#define MY_ADDREF_RELEASE_MT \ -STDMETHOD_(ULONG, AddRef)() { InterlockedIncrement((LONG *)&__m_RefCount); return __m_RefCount; } \ -STDMETHOD_(ULONG, Release)() { InterlockedDecrement((LONG *)&__m_RefCount); \ - if (__m_RefCount != 0) return __m_RefCount; \ - delete this; return 0; } - -#define MY_UNKNOWN_IMP_SPEC_MT2(i1, i) \ - MY_QUERYINTERFACE_BEGIN \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ +#define Z7_COM_ADDREF_RELEASE_MT \ + private: \ + STDMETHOD_(ULONG, AddRef)() Z7_override Z7_final \ + { return (ULONG)InterlockedIncrement((LONG *)&_m_RefCount); } \ + STDMETHOD_(ULONG, Release)() Z7_override Z7_final \ + { const LONG v = InterlockedDecrement((LONG *)&_m_RefCount); \ + if (v != 0) return (ULONG)v; \ + delete this; return 0; } + +#define Z7_COM_UNKNOWN_IMP_SPEC_MT2(i1, i) \ + Z7_COM_QI_BEGIN \ + Z7_COM_QI_ENTRY_UNKNOWN(i1) \ i \ - MY_QUERYINTERFACE_END \ - MY_ADDREF_RELEASE_MT + Z7_COM_QI_END \ + Z7_COM_ADDREF_RELEASE_MT -#define MY_UNKNOWN_IMP1_MT(i) MY_UNKNOWN_IMP_SPEC_MT2( \ +#define Z7_COM_UNKNOWN_IMP_1_MT(i) \ + Z7_COM_UNKNOWN_IMP_SPEC_MT2( \ i, \ - MY_QUERYINTERFACE_ENTRY(i) \ + Z7_COM_QI_ENTRY(i) \ ) -#define MY_UNKNOWN_IMP2_MT(i1, i2) MY_UNKNOWN_IMP_SPEC_MT2( \ +#define Z7_COM_UNKNOWN_IMP_2_MT(i1, i2) \ + Z7_COM_UNKNOWN_IMP_SPEC_MT2( \ i1, \ - MY_QUERYINTERFACE_ENTRY(i1) \ - MY_QUERYINTERFACE_ENTRY(i2) \ + Z7_COM_QI_ENTRY(i1) \ + Z7_COM_QI_ENTRY(i2) \ ) -#define MY_UNKNOWN_IMP3_MT(i1, i2, i3) MY_UNKNOWN_IMP_SPEC_MT2( \ +#define Z7_COM_UNKNOWN_IMP_3_MT(i1, i2, i3) \ + Z7_COM_UNKNOWN_IMP_SPEC_MT2( \ i1, \ - MY_QUERYINTERFACE_ENTRY(i1) \ - MY_QUERYINTERFACE_ENTRY(i2) \ - MY_QUERYINTERFACE_ENTRY(i3) \ + Z7_COM_QI_ENTRY(i1) \ + Z7_COM_QI_ENTRY(i2) \ + Z7_COM_QI_ENTRY(i3) \ ) -#define MY_UNKNOWN_IMP4_MT(i1, i2, i3, i4) MY_UNKNOWN_IMP_SPEC_MT2( \ +#define Z7_COM_UNKNOWN_IMP_4_MT(i1, i2, i3, i4) \ + Z7_COM_UNKNOWN_IMP_SPEC_MT2( \ i1, \ - MY_QUERYINTERFACE_ENTRY(i1) \ - MY_QUERYINTERFACE_ENTRY(i2) \ - MY_QUERYINTERFACE_ENTRY(i3) \ - MY_QUERYINTERFACE_ENTRY(i4) \ + Z7_COM_QI_ENTRY(i1) \ + Z7_COM_QI_ENTRY(i2) \ + Z7_COM_QI_ENTRY(i3) \ + Z7_COM_QI_ENTRY(i4) \ ) #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/MyLoadMenu.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/MyLoadMenu.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/MyLoadMenu.cpp 2022-01-14 16:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/MyLoadMenu.cpp 2023-03-06 16:00:00.000000000 +0000 @@ -17,14 +17,15 @@ #include "MyLoadMenu.h" #include "RegistryUtils.h" +#include "PropertyNameRes.h" #include "resource.h" using namespace NWindows; -static const UINT kOpenBookmarkMenuID = 830; -static const UINT kSetBookmarkMenuID = 810; -static const UINT kMenuID_Time_Parent = 760; -static const UINT kMenuID_Time = 761; +static const UINT k_MenuID_OpenBookmark = 830; +static const UINT k_MenuID_SetBookmark = 810; +static const UINT k_MenuID_TimePopup = IDM_VIEW_TIME_POPUP; +static const UINT k_MenuID_Time = IDM_VIEW_TIME; extern HINSTANCE g_hInstance; @@ -34,35 +35,45 @@ enum { - kMenuIndex_File = 0, - kMenuIndex_Edit, - kMenuIndex_View, - kMenuIndex_Bookmarks + k_MenuIndex_File = 0, + k_MenuIndex_Edit, + k_MenuIndex_View, + k_MenuIndex_Bookmarks }; -static const UInt32 kTopMenuLangIDs[] = { 500, 501, 502, 503, 504, 505 }; +#ifdef Z7_LANG +static const UInt32 k_LangID_TopMenuItems[] = +{ + IDM_FILE, + IDM_EDIT, + IDM_VIEW, + IDM_FAVORITES, + IDM_TOOLS, + IDM_HELP +}; -static const UInt32 kAddToFavoritesLangID = 800; -static const UInt32 kToolbarsLangID = 733; +static const UInt32 k_LangID_Toolbars = IDM_VIEW_TOOLBARS; +static const UInt32 k_LangID_AddToFavorites = IDM_ADD_TO_FAVORITES; static const CIDLangPair kIDLangPairs[] = { - { IDCLOSE, 557 }, - { IDM_VIEW_ARANGE_BY_NAME, 1004 }, - { IDM_VIEW_ARANGE_BY_TYPE, 1020 }, - { IDM_VIEW_ARANGE_BY_DATE, 1012 }, - { IDM_VIEW_ARANGE_BY_SIZE, 1007 } + { IDCLOSE, 557 }, // IDM_EXIT + { IDM_VIEW_ARANGE_BY_NAME, IDS_PROP_NAME }, + { IDM_VIEW_ARANGE_BY_TYPE, IDS_PROP_FILE_TYPE }, + { IDM_VIEW_ARANGE_BY_DATE, IDS_PROP_MTIME }, + { IDM_VIEW_ARANGE_BY_SIZE, IDS_PROP_SIZE } }; static int FindLangItem(unsigned controlID) { - for (unsigned i = 0; i < ARRAY_SIZE(kIDLangPairs); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(kIDLangPairs); i++) if (kIDLangPairs[i].ControlID == controlID) - return i; + return (int)i; return -1; } +#endif -static int GetSortControlID(PROPID propID) +static unsigned GetSortControlID(PROPID propID) { switch (propID) { @@ -72,54 +83,55 @@ case kpidSize: return IDM_VIEW_ARANGE_BY_SIZE; case kpidNoProperty: return IDM_VIEW_ARANGE_NO_SORT; } - return -1; + return IDM_VIEW_ARANGE_BY_NAME; + // IDM_VIEW_ARANGE_NO_SORT; + // return -1; } /* -static bool g_IsNew_fMask = true; +#if _MSC_VER > 1400 +// GetVersion was declared deprecated +#pragma warning(disable : 4996) +#endif -class CInit_fMask +static bool g_IsNew_fMask = false; +static class CInit_fMask { public: CInit_fMask() { - g_IsNew_fMask = false; - OSVERSIONINFO vi; - vi.dwOSVersionInfoSize = sizeof(vi); - if (::GetVersionEx(&vi)) - { - g_IsNew_fMask = (vi.dwMajorVersion > 4 || - (vi.dwMajorVersion == 4 && vi.dwMinorVersion > 0)); - } - g_IsNew_fMask = false; + DWORD v = GetVersion(); + v = ((v & 0xff) << 8) | ((v >> 8) & 0xFF); + g_IsNew_fMask = (v > 0x400); // (win98/win2000) or newer } } g_Init_fMask; - -// it's hack for supporting Windows NT -// constants are from WinUser.h - -#if (WINVER < 0x0500) -#define MIIM_STRING 0x00000040 -#define MIIM_BITMAP 0x00000080 -#define MIIM_FTYPE 0x00000100 -#endif - static UINT Get_fMask_for_String() -{ - return g_IsNew_fMask ? MIIM_STRING : MIIM_TYPE; -} - + { return g_IsNew_fMask ? MIIM_STRING : MIIM_TYPE; } static UINT Get_fMask_for_FType_and_String() -{ - return g_IsNew_fMask ? (MIIM_STRING | MIIM_FTYPE) : MIIM_TYPE; -} + { return g_IsNew_fMask ? (MIIM_STRING | MIIM_FTYPE) : MIIM_TYPE; } */ +/* +We can use new MIIM_STRING / MIIM_FTYPE flags in the following conditions: + 1) we run at new Windows (win98/win2000) or newer + 2) also we probably must set MENUITEMINFO::cbSize as sizeof of full + (MENUITEMINFO) that was compiled with (WINVER >= 0x0500) +But it's simpler to use old MIIM_TYPE without these complex checks. +*/ + +// /* static inline UINT Get_fMask_for_String() { return MIIM_TYPE; } static inline UINT Get_fMask_for_FType_and_String() { return MIIM_TYPE; } +// */ +static bool Is_MenuItem_TimePopup(const CMenuItem &item) +{ + return item.wID == k_MenuID_TimePopup || + item.StringValue.IsPrefixedBy_Ascii_NoCase("20"); +} -static void MyChangeMenu(HMENU menuLoc, int level, int menuIndex) +#ifdef Z7_LANG +static void MyChangeMenu(HMENU menuLoc, unsigned menuID, unsigned level, unsigned menuIndex) { CMenu menu; menu.Attach(menuLoc); @@ -127,55 +139,90 @@ for (unsigned i = 0;; i++) { CMenuItem item; - item.fMask = Get_fMask_for_String() | MIIM_SUBMENU | MIIM_ID; - item.fType = MFT_STRING; + /* here we can use + Get_fMask_for_String() or + Get_fMask_for_FType_and_String() + We want to change only String of menu item. + It's not required to change (fType) of menu item. + We can look (fType) to check for SEPARATOR item. + But String of separator is empty and (wID == 0). + So we can check for SEPARATOR without (fType) requesting. + So it's enough to use Get_fMask_for_String() here */ + item.fMask = + Get_fMask_for_String() + // Get_fMask_for_FType_and_String() + | MIIM_SUBMENU | MIIM_ID; if (!menu.GetItem(i, true, item)) break; { UString newString; if (item.hSubMenu) { - UInt32 langID = 0; - if (level == 1 && menuIndex == kMenuIndex_Bookmarks) - langID = kAddToFavoritesLangID; - else + /* in win10: + MENU+POPUP: + (wID == item.hSubMenu) + MENUEX+POPUP where ID is not set: + (wID == 0) + MENU+SEPARATOR + (wID == 0) + */ + UInt32 langID = item.wID; + if (langID >= (1 << 16)) { - MyChangeMenu(item.hSubMenu, level + 1, i); - if (level == 1 && menuIndex == kMenuIndex_View) + // here we try to exclude the case (wID == item.hSubMenu) if (MENU+POPUP) + continue; + } + if (langID == 0) + { + if (level == 0) { - if (item.wID == kMenuID_Time_Parent || item.StringValue.IsPrefixedBy_Ascii_NoCase("20")) - continue; - else - langID = kToolbarsLangID; + if (i < Z7_ARRAY_SIZE(k_LangID_TopMenuItems)) + langID = k_LangID_TopMenuItems[i]; + } + else if (level == 1) + { + if (menuID == IDM_FAVORITES || (menuID == 0 && menuIndex == k_MenuIndex_Bookmarks)) + langID = k_LangID_AddToFavorites; + else if (menuID == IDM_VIEW || (menuID == 0 && menuIndex == k_MenuIndex_View)) + { + if (Is_MenuItem_TimePopup(item)) + langID = k_MenuID_TimePopup; + else + langID = k_LangID_Toolbars; + } } - else if (level == 0 && i < ARRAY_SIZE(kTopMenuLangIDs)) - langID = kTopMenuLangIDs[i]; - else - continue; } - + if (langID == k_MenuID_TimePopup) + continue; + if (langID != k_LangID_AddToFavorites) + MyChangeMenu(item.hSubMenu, langID, level + 1, i); + if (langID == 0) + continue; LangString_OnlyFromLangFile(langID, newString); - if (newString.IsEmpty()) continue; } else { + if (item.fMask & (MIIM_TYPE | MIIM_FTYPE)) if (item.IsSeparator()) continue; - int langPos = FindLangItem(item.wID); - + if (item.StringValue.IsEmpty()) + continue; + const int langPos = FindLangItem(item.wID); // we don't need lang change for CRC items!!! + const UInt32 langID = langPos >= 0 ? kIDLangPairs[langPos].LangID : item.wID; + if (langID == 0) + continue; - UInt32 langID = langPos >= 0 ? kIDLangPairs[langPos].LangID : item.wID; - - if (langID == IDM_OPEN_INSIDE_ONE || langID == IDM_OPEN_INSIDE_PARSER) + if (langID == IDM_OPEN_INSIDE_ONE || + langID == IDM_OPEN_INSIDE_PARSER) { LangString_OnlyFromLangFile(IDM_OPEN_INSIDE, newString); if (newString.IsEmpty()) continue; newString.Replace(L"&", L""); - int tabPos = newString.Find(L"\t"); + const int tabPos = newString.Find(L"\t"); if (tabPos >= 0) newString.DeleteFrom(tabPos); newString += (langID == IDM_OPEN_INSIDE_ONE ? " *" : " #"); @@ -186,37 +233,40 @@ if (newString.IsEmpty()) continue; newString.Replace(L"&", L""); - int tabPos = newString.Find(L"\t"); + const int tabPos = newString.Find(L"\t"); if (tabPos >= 0) newString.DeleteFrom(tabPos); newString += " 2"; } else + { LangString_OnlyFromLangFile(langID, newString); + } if (newString.IsEmpty()) continue; - int tabPos = item.StringValue.ReverseFind(L'\t'); + const int tabPos = item.StringValue.ReverseFind(L'\t'); if (tabPos >= 0) newString += item.StringValue.Ptr(tabPos); } { item.StringValue = newString; + // we want to change only String item.fMask = Get_fMask_for_String(); - item.fType = MFT_STRING; menu.SetItem(i, true, item); } } } } +#endif static CMenu g_FileMenu; static struct CFileMenuDestroyer { - ~CFileMenuDestroyer() { if ((HMENU)g_FileMenu != 0) g_FileMenu.Destroy(); } + ~CFileMenuDestroyer() { if ((HMENU)g_FileMenu) g_FileMenu.Destroy(); } } g_FileMenuDestroyer; @@ -224,6 +274,12 @@ static void CopyPopMenu_IfRequired(CMenuItem &item) { + /* if (item.hSubMenu) is defined + { + - it creates new (popup) menu + - it copies menu items from old item.hSubMenu menu to new (popup) menu + - it sets item.hSubMenu to handle of created (popup) menu + } */ if (item.hSubMenu) { CMenu popup; @@ -233,64 +289,91 @@ } } +/* destMenuSpec must be non-NULL handle to created empty popup menu */ static void CopyMenu(HMENU srcMenuSpec, HMENU destMenuSpec) { CMenu srcMenu; srcMenu.Attach(srcMenuSpec); CMenu destMenu; destMenu.Attach(destMenuSpec); - int startPos = 0; - for (int i = 0;; i++) + unsigned startPos = 0; + for (unsigned i = 0;; i++) { CMenuItem item; item.fMask = MIIM_SUBMENU | MIIM_STATE | MIIM_ID | Get_fMask_for_FType_and_String(); - item.fType = MFT_STRING; - if (!srcMenu.GetItem(i, true, item)) break; - CopyPopMenu_IfRequired(item); if (destMenu.InsertItem(startPos, true, item)) startPos++; } } -void MyLoadMenu() -{ - HMENU baseMenu; +/* use for (needResetMenu): + false : for call from program window creation code + true : for another calls : (from Options language change) +*/ +void MyLoadMenu(bool needResetMenu) +{ #ifdef UNDER_CE - HMENU oldMenu = g_App._commandBar.GetMenu(0); + const HMENU oldMenu = g_App._commandBar.GetMenu(0); if (oldMenu) ::DestroyMenu(oldMenu); /* BOOL b = */ g_App._commandBar.InsertMenubar(g_hInstance, IDM_MENU, 0); - baseMenu = g_App._commandBar.GetMenu(0); + const HMENU baseMenu = g_App._commandBar.GetMenu(0); // if (startInit) - // SetIdsForSubMenes(baseMenu, 0, 0); + // SetIdsForSubMenus(baseMenu, 0, 0); if (!g_LangID.IsEmpty()) MyChangeMenu(baseMenu, 0, 0); g_App._commandBar.DrawMenuBar(0); - #else + #else // UNDER_CE - HWND hWnd = g_HWND; - HMENU oldMenu = ::GetMenu(hWnd); - ::SetMenu(hWnd, ::LoadMenu(g_hInstance, MAKEINTRESOURCE(IDM_MENU))); - ::DestroyMenu(oldMenu); - baseMenu = ::GetMenu(hWnd); + const HWND hWnd = g_HWND; + bool menuWasChanged = false; + /* + We must reload to english default menu for at least two cases: + - if some submenu was changed (File or another submenu can be changed after menu activating). + - for change from non-english lang to another partial non-english lang, + where we still need some english strings. + But we reload menu to default menu everytime except of program starting stage. + That scheme is simpler than complex checks for exact conditions for menu reload. + */ + if (needResetMenu) + { + const HMENU oldMenu = ::GetMenu(hWnd); + const HMENU newMenu = ::LoadMenu(g_hInstance, MAKEINTRESOURCE(IDM_MENU)); + // docs for SetMenu(): the window is redrawn to reflect the menu change. + if (newMenu && ::SetMenu(hWnd, newMenu)) + ::DestroyMenu(oldMenu); + menuWasChanged = true; + } + const HMENU baseMenu = ::GetMenu(hWnd); // if (startInit) - // SetIdsForSubMenes(baseMenu, 0, 0); - if (!g_LangID.IsEmpty()) - MyChangeMenu(baseMenu, 0, 0); - ::DrawMenuBar(hWnd); - + // SetIdsForSubMenus(baseMenu, 0, 0); + #ifdef Z7_LANG + if (!g_Lang.IsEmpty()) // !g_LangID.IsEmpty() && + { + MyChangeMenu(baseMenu, 0, 0, 0); + menuWasChanged = true; + } #endif - if ((HMENU)g_FileMenu != 0) - g_FileMenu.Destroy(); - g_FileMenu.CreatePopup(); - CopyMenu(::GetSubMenu(baseMenu, 0), g_FileMenu); + if (menuWasChanged) + ::DrawMenuBar(hWnd); + + #endif // UNDER_CE + + // menuWasChanged = false; // for debug + if (menuWasChanged || !(HMENU)g_FileMenu) + { + if ((HMENU)g_FileMenu) + g_FileMenu.Destroy(); + g_FileMenu.CreatePopup(); + CopyMenu(::GetSubMenu(baseMenu, k_MenuIndex_File), g_FileMenu); + } } void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position) @@ -306,14 +389,14 @@ if (::GetSubMenu(mainMenu, position) != hMenu) return; - if (position == kMenuIndex_File) + if (position == k_MenuIndex_File) { CMenu menu; menu.Attach(hMenu); menu.RemoveAllItems(); g_App.GetFocusedPanel().CreateFileMenu(hMenu); } - else if (position == kMenuIndex_Edit) + else if (position == k_MenuIndex_Edit) { /* CMenu menu; @@ -323,16 +406,20 @@ menu.EnableItem(IDM_EDIT_PASTE, IsClipboardFormatAvailableHDROP() ? MF_ENABLED : MF_GRAYED); */ } - else if (position == kMenuIndex_View) + else if (position == k_MenuIndex_View) { // View; CMenu menu; menu.Attach(hMenu); - menu.CheckRadioItem(IDM_VIEW_LARGE_ICONS, IDM_VIEW_DETAILS, - IDM_VIEW_LARGE_ICONS + g_App.GetListViewMode(), MF_BYCOMMAND); - - menu.CheckRadioItem(IDM_VIEW_ARANGE_BY_NAME, IDM_VIEW_ARANGE_NO_SORT, - GetSortControlID(g_App.GetSortID()), MF_BYCOMMAND); + menu.CheckRadioItem( + IDM_VIEW_LARGE_ICONS, IDM_VIEW_DETAILS, + IDM_VIEW_LARGE_ICONS + g_App.GetListViewMode(), MF_BYCOMMAND); + + menu.CheckRadioItem( + IDM_VIEW_ARANGE_BY_NAME, + IDM_VIEW_ARANGE_NO_SORT, + GetSortControlID(g_App.GetSortID()), + MF_BYCOMMAND); menu.CheckItemByID(IDM_VIEW_TWO_PANELS, g_App.NumPanels == 2); menu.CheckItemByID(IDM_VIEW_FLAT_VIEW, g_App.GetFlatMode()); @@ -344,16 +431,14 @@ // menu.CheckItemByID(IDM_VIEW_SHOW_STREAMS, g_App.Get_ShowNtfsStrems_Mode()); // menu.CheckItemByID(IDM_VIEW_SHOW_DELETED, g_App.ShowDeletedFiles); - for (int i = 0;; i++) + for (unsigned i = 0;; i++) { CMenuItem item; item.fMask = Get_fMask_for_String() | MIIM_SUBMENU | MIIM_ID; item.fType = MFT_STRING; if (!menu.GetItem(i, true, item)) break; - if (item.hSubMenu && (item.wID == kMenuID_Time_Parent - || item.StringValue.IsPrefixedBy_Ascii_NoCase("20") - )) + if (item.hSubMenu && Is_MenuItem_TimePopup(item)) { FILETIME ft; NTime::GetCurUtcFileTime(ft); @@ -367,11 +452,11 @@ item.fMask = Get_fMask_for_String() | MIIM_ID; item.fType = MFT_STRING; - item.wID = kMenuID_Time_Parent; + item.wID = k_MenuID_TimePopup; menu.SetItem(i, true, item); CMenu subMenu; - subMenu.Attach(menu.GetSubMenu(i)); + subMenu.Attach(menu.GetSubMenu((int)i)); subMenu.RemoveAllItems(); const int k_TimeLevels[] = @@ -384,16 +469,16 @@ kTimestampPrintLevel_NS }; - unsigned last = kMenuID_Time; + unsigned last = k_MenuID_Time; unsigned selectedCommand = 0; g_App._timestampLevels.Clear(); - unsigned id = kMenuID_Time; + unsigned id = k_MenuID_Time; - for (unsigned k = 0; k < ARRAY_SIZE(k_TimeLevels); k++) + for (unsigned k = 0; k < Z7_ARRAY_SIZE(k_TimeLevels); k++) { wchar_t s[64]; s[0] = 0; - int timestampLevel = k_TimeLevels[k]; + const int timestampLevel = k_TimeLevels[k]; if (ConvertUtcFileTimeToString(ft, s, timestampLevel)) { if (subMenu.AppendItem(MF_STRING, id, s)) @@ -407,11 +492,11 @@ } } if (selectedCommand != 0) - menu.CheckRadioItem(kMenuID_Time, last, selectedCommand, MF_BYCOMMAND); + menu.CheckRadioItem(k_MenuID_Time, last, selectedCommand, MF_BYCOMMAND); } } } - else if (position == kMenuIndex_Bookmarks) + else if (position == k_MenuIndex_Bookmarks) { CMenu menu; menu.Attach(hMenu); @@ -419,17 +504,17 @@ CMenu subMenu; subMenu.Attach(menu.GetSubMenu(0)); subMenu.RemoveAllItems(); - int i; + unsigned i; for (i = 0; i < 10; i++) { UString s = LangString(IDS_BOOKMARK); s.Add_Space(); - char c = (char)(L'0' + i); + const char c = (char)(L'0' + i); s += c; s += "\tAlt+Shift+"; s += c; - subMenu.AppendItem(MF_STRING, kSetBookmarkMenuID + i, s); + subMenu.AppendItem(MF_STRING, k_MenuID_SetBookmark + i, s); } menu.RemoveAllItemsFrom(2); @@ -448,7 +533,7 @@ s = '-'; s += "\tAlt+"; s += (char)('0' + i); - menu.AppendItem(MF_STRING, kOpenBookmarkMenuID + i, s); + menu.AppendItem(MF_STRING, k_MenuID_OpenBookmark + i, s); } } } @@ -596,7 +681,7 @@ NFile::NFind::CFileInfo fi; if (fi.Find(FilePath) && fi.Size < ((UInt32)1 << 31) && !fi.IsDir()) { - for (unsigned k = 0; k < ARRAY_SIZE(g_Zvc_IDs); k++) + for (unsigned k = 0; k < Z7_ARRAY_SIZE(g_Zvc_IDs); k++) { const unsigned id = g_Zvc_IDs[k]; if (fi.IsReadOnly()) @@ -756,7 +841,7 @@ g_App.SetListViewMode(index); /* CMenu menu; - menu.Attach(::GetSubMenu(::GetMenu(hWnd), kMenuIndex_View)); + menu.Attach(::GetSubMenu(::GetMenu(hWnd), k_MenuIndex_View)); menu.CheckRadioItem(IDM_VIEW_LARGE_ICONS, IDM_VIEW_DETAILS, id, MF_BYCOMMAND); */ @@ -811,20 +896,19 @@ } default: { - if (id >= kOpenBookmarkMenuID && id <= kOpenBookmarkMenuID + 9) + if (id >= k_MenuID_OpenBookmark && id <= k_MenuID_OpenBookmark + 9) { - g_App.OpenBookmark(id - kOpenBookmarkMenuID); + g_App.OpenBookmark(id - k_MenuID_OpenBookmark); return true; } - else if (id >= kSetBookmarkMenuID && id <= kSetBookmarkMenuID + 9) + else if (id >= k_MenuID_SetBookmark && id <= k_MenuID_SetBookmark + 9) { - g_App.SetBookmark(id - kSetBookmarkMenuID); + g_App.SetBookmark(id - k_MenuID_SetBookmark); return true; } - else if (id >= kMenuID_Time && (unsigned)id <= kMenuID_Time + g_App._timestampLevels.Size()) + else if (id >= k_MenuID_Time && (unsigned)id < k_MenuID_Time + g_App._timestampLevels.Size()) { - unsigned index = id - kMenuID_Time; - g_App.SetTimestampLevel(g_App._timestampLevels[index]); + g_App.SetTimestampLevel(g_App._timestampLevels[id - k_MenuID_Time]); return true; } return false; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/MyLoadMenu.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/MyLoadMenu.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/MyLoadMenu.h 2021-10-23 09:23:15.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/MyLoadMenu.h 2023-01-21 16:00:00.000000000 +0000 @@ -1,14 +1,14 @@ // MyLoadMenu.h -#ifndef __MY_LOAD_MENU_H -#define __MY_LOAD_MENU_H +#ifndef ZIP7_INC_MY_LOAD_MENU_H +#define ZIP7_INC_MY_LOAD_MENU_H void OnMenuActivating(HWND hWnd, HMENU hMenu, int position); // void OnMenuUnActivating(HWND hWnd, HMENU hMenu, int id); // void OnMenuUnActivating(HWND hWnd); bool OnMenuCommand(HWND hWnd, unsigned id); -void MyLoadMenu(); +void MyLoadMenu(bool needResetMenu); struct CFileMenu { @@ -18,7 +18,7 @@ bool isFsFolder; bool allAreFiles; bool isAltStreamsSupported; - int numItems; + unsigned numItems; FString FilePath; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/MyWindowsNew.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/MyWindowsNew.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/MyWindowsNew.h 2014-12-31 08:49:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/MyWindowsNew.h 2023-04-13 10:00:00.000000000 +0000 @@ -1,11 +1,54 @@ // MyWindowsNew.h -#ifndef __MY_WINDOWS_NEW_H -#define __MY_WINDOWS_NEW_H +#ifndef ZIP7_INC_MY_WINDOWS_NEW_H +#define ZIP7_INC_MY_WINDOWS_NEW_H -#ifdef _MSC_VER +#if defined(__MINGW32__) || defined(__MINGW64__) || defined(__MINGW32_VERSION) +#include +#if defined(__MINGW32_VERSION) && !defined(__ITaskbarList3_INTERFACE_DEFINED__) +// for old mingw +extern "C" { +DEFINE_GUID(IID_ITaskbarList3, 0xEA1AFB91, 0x9E28, 0x4B86, 0x90, 0xE9, 0x9E, 0x9F, 0x8A, 0x5E, 0xEF, 0xAF); +DEFINE_GUID(CLSID_TaskbarList, 0x56fdf344, 0xfd6d, 0x11d0, 0x95,0x8a, 0x00,0x60,0x97,0xc9,0xa0,0x90); +} +#endif + +#else // is not __MINGW* + +#ifndef Z7_OLD_WIN_SDK #include +#else + +#ifndef HIMAGELIST +struct _IMAGELIST; +typedef struct _IMAGELIST* HIMAGELIST; +#endif + +#ifndef __ITaskbarList_INTERFACE_DEFINED__ +#define __ITaskbarList_INTERFACE_DEFINED__ +DEFINE_GUID(IID_ITaskbarList, 0x56FDF342, 0xFD6D, 0x11d0, 0x95, 0x8A, 0x00, 0x60, 0x97, 0xC9, 0xA0, 0x90); +struct ITaskbarList: public IUnknown +{ + STDMETHOD(HrInit)(void) = 0; + STDMETHOD(AddTab)(HWND hwnd) = 0; + STDMETHOD(DeleteTab)(HWND hwnd) = 0; + STDMETHOD(ActivateTab)(HWND hwnd) = 0; + STDMETHOD(SetActiveAlt)(HWND hwnd) = 0; +}; +#endif // __ITaskbarList_INTERFACE_DEFINED__ + +#ifndef __ITaskbarList2_INTERFACE_DEFINED__ +#define __ITaskbarList2_INTERFACE_DEFINED__ +DEFINE_GUID(IID_ITaskbarList2, 0x602D4995, 0xB13A, 0x429b, 0xA6, 0x6E, 0x19, 0x35, 0xE4, 0x4F, 0x43, 0x17); +struct ITaskbarList2: public ITaskbarList +{ + STDMETHOD(MarkFullscreenWindow)(HWND hwnd, BOOL fFullscreen) = 0; +}; +#endif // __ITaskbarList2_INTERFACE_DEFINED__ + +#endif // Z7_OLD_WIN_SDK + #ifndef __ITaskbarList3_INTERFACE_DEFINED__ #define __ITaskbarList3_INTERFACE_DEFINED__ @@ -69,8 +112,8 @@ STDMETHOD(SetThumbnailClip)(HWND hwnd, RECT *prcClip) = 0; }; -#endif +#endif // __ITaskbarList3_INTERFACE_DEFINED__ -#endif +#endif // __MINGW* #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/NetFolder.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/NetFolder.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/NetFolder.cpp 2017-02-07 18:44:04.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/NetFolder.cpp 2023-01-28 17:00:00.000000000 +0000 @@ -55,9 +55,9 @@ UString systemPathPart; DWORD result = GetResourceInformation(resource, destResource, systemPathPart); if (result == NO_ERROR) - Init(&destResource, 0, path); + Init(&destResource, NULL, path); else - Init(0, 0 , L""); + Init(NULL, NULL , L""); return; } @@ -65,8 +65,8 @@ IFolderFolder *parentFolder, const UString &path) { _path = path; - if (netResource == 0) - _netResourcePointer = 0; + if (!netResource) + _netResourcePointer = NULL; else { _netResource = *netResource; @@ -86,7 +86,7 @@ _parentFolder = parentFolder; } -STDMETHODIMP CNetFolder::LoadItems() +Z7_COM7F_IMF(CNetFolder::LoadItems()) { _items.Clear(); CEnum enumerator; @@ -102,35 +102,35 @@ if (result == NO_ERROR) break; if (result != ERROR_ACCESS_DENIED) - return result; - if (_netResourcePointer != 0) + return HRESULT_FROM_WIN32(result); + if (_netResourcePointer) result = AddConnection2(_netResource, - 0, 0, CONNECT_INTERACTIVE); + NULL, NULL, CONNECT_INTERACTIVE); if (result != NO_ERROR) - return result; + return HRESULT_FROM_WIN32(result); } for (;;) { CResourceEx resource; - DWORD result = enumerator.Next(resource); + const DWORD result = enumerator.Next(resource); if (result == NO_ERROR) { if (!resource.RemoteNameIsDefined) // For Win 98, I don't know what's wrong resource.RemoteName = resource.Comment; resource.Name = resource.RemoteName; - int pos = resource.Name.ReverseFind_PathSepar(); + const int pos = resource.Name.ReverseFind_PathSepar(); if (pos >= 0) { // _path = resource.Name.Left(pos + 1); - resource.Name.DeleteFrontal(pos + 1); + resource.Name.DeleteFrontal((unsigned)pos + 1); } _items.Add(resource); } else if (result == ERROR_NO_MORE_ITEMS) break; else - return result; + return HRESULT_FROM_WIN32(result); } /* @@ -160,13 +160,13 @@ } -STDMETHODIMP CNetFolder::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CNetFolder::GetNumberOfItems(UInt32 *numItems)) { *numItems = _items.Size(); return S_OK; } -STDMETHODIMP CNetFolder::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CNetFolder::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; const CResourceEx &item = _items[itemIndex]; @@ -185,16 +185,16 @@ return S_OK; } -STDMETHODIMP CNetFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder) +Z7_COM7F_IMF(CNetFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder)) { - *resultFolder = 0; + *resultFolder = NULL; const CResourceEx &resource = _items[index]; if (resource.Usage == RESOURCEUSAGE_CONNECTABLE || resource.DisplayType == RESOURCEDISPLAYTYPE_SHARE) { NFsFolder::CFSFolder *fsFolderSpec = new NFsFolder::CFSFolder; CMyComPtr subFolder = fsFolderSpec; - RINOK(fsFolderSpec->Init(us2fs(resource.RemoteName + WCHAR_PATH_SEPARATOR))); // , this + RINOK(fsFolderSpec->Init(us2fs(resource.RemoteName + WCHAR_PATH_SEPARATOR))) // , this *resultFolder = subFolder.Detach(); } else @@ -207,32 +207,32 @@ return S_OK; } -STDMETHODIMP CNetFolder::BindToFolder(const wchar_t * /* name */, IFolderFolder ** /* resultFolder */) +Z7_COM7F_IMF(CNetFolder::BindToFolder(const wchar_t * /* name */, IFolderFolder ** /* resultFolder */)) { return E_NOTIMPL; } -STDMETHODIMP CNetFolder::BindToParentFolder(IFolderFolder **resultFolder) +Z7_COM7F_IMF(CNetFolder::BindToParentFolder(IFolderFolder **resultFolder)) { - *resultFolder = 0; + *resultFolder = NULL; if (_parentFolder) { CMyComPtr parentFolder = _parentFolder; *resultFolder = parentFolder.Detach(); return S_OK; } - if (_netResourcePointer != 0) + if (_netResourcePointer) { CResourceW resourceParent; - DWORD result = GetResourceParent(_netResource, resourceParent); + const DWORD result = GetResourceParent(_netResource, resourceParent); if (result != NO_ERROR) - return result; + return HRESULT_FROM_WIN32(result); if (!_netResource.RemoteNameIsDefined) return S_OK; CNetFolder *netFolder = new CNetFolder; CMyComPtr subFolder = netFolder; - netFolder->Init(&resourceParent, 0, WSTRING_PATH_SEPARATOR); + netFolder->Init(&resourceParent, NULL, WSTRING_PATH_SEPARATOR); *resultFolder = subFolder.Detach(); } return S_OK; @@ -240,7 +240,7 @@ IMP_IFolderFolder_Props(CNetFolder) -STDMETHODIMP CNetFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CNetFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value)) { NWindows::NCOM::CPropVariant prop; switch (propID) @@ -252,7 +252,7 @@ return S_OK; } -STDMETHODIMP CNetFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex) +Z7_COM7F_IMF(CNetFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex)) { if (index >= (UInt32)_items.Size()) return E_INVALIDARG; @@ -277,5 +277,5 @@ } // *anIconIndex = GetRealIconIndex(0, L"\\\\HOME"); } - return GetLastError(); + return GetLastError_noZero_HRESULT(); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/NetFolder.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/NetFolder.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/NetFolder.h 2013-01-17 10:00:05.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/NetFolder.h 2023-04-01 11:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // NetFolder.h -#ifndef __NET_FOLDER_H -#define __NET_FOLDER_H +#ifndef ZIP7_INC_NET_FOLDER_H +#define ZIP7_INC_NET_FOLDER_H #include "../../../Common/MyCom.h" @@ -14,11 +14,11 @@ UString Name; }; -class CNetFolder: - public IFolderFolder, - public IFolderGetSystemIconIndex, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_2( + CNetFolder + , IFolderFolder + , IFolderGetSystemIconIndex +) NWindows::NNet::CResourceW _netResource; NWindows::NNet::CResourceW *_netResourcePointer; @@ -27,11 +27,7 @@ CMyComPtr _parentFolder; UString _path; public: - MY_UNKNOWN_IMP1(IFolderGetSystemIconIndex) - INTERFACE_FolderFolder(;) - STDMETHOD(GetSystemIconIndex)(UInt32 index, Int32 *iconIndex); - - CNetFolder(): _netResourcePointer(0) {} + CNetFolder(): _netResourcePointer(NULL) {} void Init(const UString &path); void Init(const NWindows::NNet::CResourceW *netResource, IFolderFolder *parentFolder, const UString &path); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/OpenCallback.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/OpenCallback.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/OpenCallback.cpp 2021-12-14 20:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/OpenCallback.cpp 2023-04-01 12:00:00.000000000 +0000 @@ -17,9 +17,11 @@ using namespace NWindows; -STDMETHODIMP COpenArchiveCallback::SetTotal(const UInt64 *numFiles, const UInt64 *numBytes) +HRESULT COpenArchiveCallback::Open_SetTotal(const UInt64 *numFiles, const UInt64 *numBytes) +// Z7_COM7F_IMF(COpenArchiveCallback::SetTotal(const UInt64 *numFiles, const UInt64 *numBytes)) { - RINOK(ProgressDialog.Sync.CheckStop()); + // COM_TRY_BEGIN + RINOK(ProgressDialog.Sync.CheckStop()) { // NSynchronization::CCriticalSectionLock lock(_criticalSection); ProgressDialog.Sync.Set_NumFilesTotal(numFiles ? *numFiles : (UInt64)(Int64)-1); @@ -31,83 +33,37 @@ ProgressDialog.Sync.Set_NumBytesTotal(*numBytes); } return S_OK; + // COM_TRY_END } -STDMETHODIMP COpenArchiveCallback::SetCompleted(const UInt64 *numFiles, const UInt64 *numBytes) +HRESULT COpenArchiveCallback::Open_SetCompleted(const UInt64 *numFiles, const UInt64 *numBytes) +// Z7_COM7F_IMF(COpenArchiveCallback::SetCompleted(const UInt64 *numFiles, const UInt64 *numBytes)) { + // COM_TRY_BEGIN // NSynchronization::CCriticalSectionLock lock(_criticalSection); if (numFiles) ProgressDialog.Sync.Set_NumFilesCur(*numFiles); if (numBytes) ProgressDialog.Sync.Set_NumBytesCur(*numBytes); return ProgressDialog.Sync.CheckStop(); + // COM_TRY_END } -STDMETHODIMP COpenArchiveCallback::SetTotal(const UInt64 total) +HRESULT COpenArchiveCallback::Open_CheckBreak() { - RINOK(ProgressDialog.Sync.CheckStop()); - ProgressDialog.Sync.Set_NumBytesTotal(total); - return S_OK; -} - -STDMETHODIMP COpenArchiveCallback::SetCompleted(const UInt64 *completed) -{ - return ProgressDialog.Sync.Set_NumBytesCur(completed); -} - -STDMETHODIMP COpenArchiveCallback::GetProperty(PROPID propID, PROPVARIANT *value) -{ - NCOM::CPropVariant prop; - if (_subArchiveMode) - { - switch (propID) - { - case kpidName: prop = _subArchiveName; break; - } - } - else - { - switch (propID) - { - case kpidName: prop = fs2us(_fileInfo.Name); break; - case kpidIsDir: prop = _fileInfo.IsDir(); break; - case kpidSize: prop = _fileInfo.Size; break; - case kpidAttrib: prop = (UInt32)_fileInfo.Attrib; break; - case kpidCTime: prop = _fileInfo.CTime; break; - case kpidATime: prop = _fileInfo.ATime; break; - case kpidMTime: prop = _fileInfo.MTime; break; - } - } - prop.Detach(value); - return S_OK; + return ProgressDialog.Sync.CheckStop(); } -STDMETHODIMP COpenArchiveCallback::GetStream(const wchar_t *name, IInStream **inStream) +HRESULT COpenArchiveCallback::Open_Finished() { - COM_TRY_BEGIN - *inStream = NULL; - if (_subArchiveMode) - return S_FALSE; - - FString fullPath; - if (!NFile::NName::GetFullPath(_folderPrefix, us2fs(name), fullPath)) - return S_FALSE; - if (!_fileInfo.Find_FollowLink(fullPath)) - return S_FALSE; - if (_fileInfo.IsDir()) - return S_FALSE; - CInFileStream *inFile = new CInFileStream; - CMyComPtr inStreamTemp = inFile; - if (!inFile->Open(fullPath)) - return ::GetLastError(); - *inStream = inStreamTemp.Detach(); - return S_OK; - COM_TRY_END + return ProgressDialog.Sync.CheckStop(); } -STDMETHODIMP COpenArchiveCallback::CryptoGetTextPassword(BSTR *password) +#ifndef Z7_NO_CRYPTO +HRESULT COpenArchiveCallback::Open_CryptoGetTextPassword(BSTR *password) +// Z7_COM7F_IMF(COpenArchiveCallback::CryptoGetTextPassword(BSTR *password)) { - COM_TRY_BEGIN + // COM_TRY_BEGIN PasswordWasAsked = true; if (!PasswordIsDefined) { @@ -125,5 +81,6 @@ NExtract::Save_ShowPassword(dialog.ShowPassword); } return StringToBstr(Password, password); - COM_TRY_END + // COM_TRY_END } +#endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/OpenCallback.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/OpenCallback.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/OpenCallback.h 2020-09-23 10:30:16.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/OpenCallback.h 2023-02-01 15:00:00.000000000 +0000 @@ -1,37 +1,28 @@ // OpenCallback.h -#ifndef __OPEN_CALLBACK_H -#define __OPEN_CALLBACK_H +#ifndef ZIP7_INC_OPEN_CALLBACK_H +#define ZIP7_INC_OPEN_CALLBACK_H -#include "../../../Common/MyCom.h" +#include "../Common/ArchiveOpenCallback.h" -#include "../../../Windows/FileFind.h" - -#include "../../IPassword.h" - -#include "../../Archive/IArchive.h" - -#ifdef _SFX +#ifdef Z7_SFX #include "ProgressDialog.h" #else #include "ProgressDialog2.h" #endif +/* we can use IArchiveOpenCallback or IOpenCallbackUI here */ -class COpenArchiveCallback: +class COpenArchiveCallback Z7_final: + /* public IArchiveOpenCallback, - public IArchiveOpenVolumeCallback, - public IArchiveOpenSetSubArchiveName, public IProgress, public ICryptoGetTextPassword, public CMyUnknownImp + */ + public IOpenCallbackUI { - FString _folderPrefix; - NWindows::NFile::NFind::CFileInfo _fileInfo; // NWindows::NSynchronization::CCriticalSection _criticalSection; - bool _subArchiveMode; - UString _subArchiveName; - public: bool PasswordIsDefined; bool PasswordWasAsked; @@ -39,31 +30,25 @@ HWND ParentWindow; CProgressDialog ProgressDialog; - MY_UNKNOWN_IMP5( - IArchiveOpenCallback, + /* + Z7_COM_UNKNOWN_IMP_3( IArchiveOpenVolumeCallback, - IArchiveOpenSetSubArchiveName, - IProgress, - ICryptoGetTextPassword) - - INTERFACE_IProgress(;) - INTERFACE_IArchiveOpenCallback(;) - INTERFACE_IArchiveOpenVolumeCallback(;) + IProgress + ICryptoGetTextPassword + ) + Z7_IFACE_COM7_IMP(IProgress) + Z7_IFACE_COM7_IMP(IArchiveOpenCallback) // ICryptoGetTextPassword - STDMETHOD(CryptoGetTextPassword)(BSTR *password); + Z7_COM7F_IMP(CryptoGetTextPassword(BSTR *password)) + */ - STDMETHOD(SetSubArchiveName(const wchar_t *name)) - { - _subArchiveMode = true; - _subArchiveName = name; - return S_OK; - } + Z7_IFACE_IMP(IOpenCallbackUI) COpenArchiveCallback(): - ParentWindow(0) + ParentWindow(NULL) { - _subArchiveMode = false; + // _subArchiveMode = false; PasswordIsDefined = false; PasswordWasAsked = false; } @@ -75,18 +60,6 @@ } */ - HRESULT LoadFileInfo2(const FString &folderPrefix, const FString &fileName) - { - _folderPrefix = folderPrefix; - if (!_fileInfo.Find_FollowLink(_folderPrefix + fileName)) - { - return GetLastError_noZero_HRESULT(); - } - return S_OK; - } - - void ShowMessage(const UInt64 *completed); - INT_PTR StartProgressDialog(const UString &title, NWindows::CThread &thread) { return ProgressDialog.Create(title, thread, ParentWindow); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/OptionsDialog.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/OptionsDialog.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/OptionsDialog.cpp 2021-01-22 21:11:45.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/OptionsDialog.cpp 2023-03-06 16:00:00.000000000 +0000 @@ -51,25 +51,27 @@ NControl::CPropertyPage *pagePointers[] = { &systemPage, &menuPage, &foldersPage, &editPage, &settingsPage, &langPage }; - for (unsigned i = 0; i < ARRAY_SIZE(pageIDs); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(pageIDs); i++) { NControl::CPageInfo &page = pages.AddNew(); page.ID = pageIDs[i]; + #ifdef Z7_LANG LangString_OnlyFromLangFile(page.ID, page.Title); + #endif page.Page = pagePointers[i]; } - INT_PTR res = NControl::MyPropertySheet(pages, hwndOwner, LangString(IDS_OPTIONS)); + const INT_PTR res = NControl::MyPropertySheet(pages, hwndOwner, LangString(IDS_OPTIONS)); if (res != -1 && res != 0) { if (langPage.LangWasChanged) { // g_App._window.SetText(LangString(IDS_APP_TITLE, 0x03000000)); - MyLoadMenu(); + MyLoadMenu(true); // needResetMenu g_App.ReloadToolbars(); g_App.MoveSubWindows(); // we need it to change list window aafter _toolBar.AutoSize(); - g_App.ReloadLang(); + g_App.ReloadLangItems(); } /* diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/OverwriteDialog.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/OverwriteDialog.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/OverwriteDialog.cpp 2021-01-24 14:02:16.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/OverwriteDialog.cpp 2023-03-17 10:00:00.000000000 +0000 @@ -17,7 +17,7 @@ using namespace NWindows; -#ifdef LANG +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { IDT_OVERWRITE_HEADER, @@ -48,7 +48,7 @@ } } -void COverwriteDialog::SetFileInfoControl(int textID, int iconID, +void COverwriteDialog::SetFileInfoControl(unsigned textID, unsigned iconID, const NOverwriteDialog::CFileInfo &fileInfo) { UString sizeString; @@ -96,9 +96,9 @@ bool COverwriteDialog::OnInit() { - #ifdef LANG + #ifdef Z7_LANG LangSetWindowText(*this, IDD_OVERWRITE); - LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); + LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs)); #endif SetFileInfoControl(IDT_OVERWRITE_OLD_FILE_SIZE_TIME, IDI_OVERWRITE_OLD_FILE, OldFileInfo); SetFileInfoControl(IDT_OVERWRITE_NEW_FILE_SIZE_TIME, IDI_OVERWRITE_NEW_FILE, NewFileInfo); @@ -122,7 +122,7 @@ return CModalDialog::OnInit(); } -bool COverwriteDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool COverwriteDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -131,7 +131,7 @@ case IDB_YES_TO_ALL: case IDB_NO_TO_ALL: case IDB_AUTO_RENAME: - End(buttonID); + End((INT_PTR)buttonID); return true; } return CModalDialog::OnButtonClicked(buttonID, buttonHWND); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/OverwriteDialog.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/OverwriteDialog.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/OverwriteDialog.h 2021-01-22 11:42:53.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/OverwriteDialog.h 2023-03-17 10:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // OverwriteDialog.h -#ifndef __OVERWRITE_DIALOG_H -#define __OVERWRITE_DIALOG_H +#ifndef ZIP7_INC_OVERWRITE_DIALOG_H +#define ZIP7_INC_OVERWRITE_DIALOG_H #include "../../../Windows/Control/Dialog.h" @@ -49,9 +49,9 @@ { bool _isBig; - void SetFileInfoControl(int textID, int iconID, const NOverwriteDialog::CFileInfo &fileInfo); - virtual bool OnInit(); - bool OnButtonClicked(int buttonID, HWND buttonHWND); + void SetFileInfoControl(unsigned textID, unsigned iconID, const NOverwriteDialog::CFileInfo &fileInfo); + virtual bool OnInit() Z7_override; + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; void ReduceString(UString &s); public: @@ -61,7 +61,7 @@ COverwriteDialog(): ShowExtraButtons(true), DefaultButton_is_NO(false) {} - INT_PTR Create(HWND parent = 0) + INT_PTR Create(HWND parent = NULL) { BIG_DIALOG_SIZE(280, 200); #ifdef UNDER_CE diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelCopy.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelCopy.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelCopy.cpp 2022-06-06 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelCopy.cpp 2023-05-01 08:00:00.000000000 +0000 @@ -2,29 +2,29 @@ #include "StdAfx.h" -#include "../../../Common/MyException.h" - #include "../Common/ZipRegistry.h" #include "../GUI/HashGUI.h" +#include "FSFolder.h" #include "ExtractCallback.h" #include "LangUtils.h" #include "Panel.h" -#include "resource.h" #include "UpdateCallback100.h" -using namespace NWindows; +#include "resource.h" + class CPanelCopyThread: public CProgressThreadVirt { bool ResultsWereShown; bool NeedShowRes; - HRESULT ProcessVirt(); - virtual void ProcessWasFinished_GuiVirt(); + HRESULT ProcessVirt() Z7_override; + virtual void ProcessWasFinished_GuiVirt() Z7_override; public: const CCopyToOptions *options; + const UStringVector *CopyFrom_Paths; CMyComPtr FolderOperations; CRecordVector Indices; CExtractCallbackImp *ExtractCallbackSpec; @@ -39,7 +39,8 @@ CPanelCopyThread(): ResultsWereShown(false), - NeedShowRes(false) + NeedShowRes(false), + CopyFrom_Paths(NULL) // , Result2(E_FAIL) {} }; @@ -72,23 +73,32 @@ HRESULT result2; + if (FolderOperations) { CMyComPtr setZoneMode; FolderOperations.QueryInterface(IID_IFolderSetZoneIdMode, &setZoneMode); if (setZoneMode) { - RINOK(setZoneMode->SetZoneIdMode(options->ZoneIdMode)); + RINOK(setZoneMode->SetZoneIdMode(options->ZoneIdMode)) } } - if (options->testMode) + if (CopyFrom_Paths) + { + result2 = NFsFolder::CopyFileSystemItems( + *CopyFrom_Paths, + us2fs(options->folder), + options->moveMode, + (IFolderOperationsExtractCallback *)ExtractCallbackSpec); + } + else if (options->testMode) { CMyComPtr archiveFolder; FolderOperations.QueryInterface(IID_IArchiveFolder, &archiveFolder); if (!archiveFolder) return E_NOTIMPL; CMyComPtr extractCallback2; - RINOK(ExtractCallback.QueryInterface(IID_IFolderArchiveExtractCallback, &extractCallback2)); + RINOK(ExtractCallback.QueryInterface(IID_IFolderArchiveExtractCallback, &extractCallback2)) NExtract::NPathMode::EEnum pathMode = NExtract::NPathMode::kCurPaths; // NExtract::NPathMode::kFullPathnames; @@ -122,7 +132,7 @@ /* -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS static void ThrowException_if_Error(HRESULT res) { @@ -133,9 +143,11 @@ #endif */ -HRESULT CPanel::CopyTo(CCopyToOptions &options, const CRecordVector &indices, +HRESULT CPanel::CopyTo(CCopyToOptions &options, + const CRecordVector &indices, UStringVector *messages, - bool &usePassword, UString &password) + bool &usePassword, UString &password, + const UStringVector *filePaths) { if (options.NeedRegistryZone && !options.testMode) { @@ -151,9 +163,10 @@ return E_NOTIMPL; } + if (!filePaths) if (!_folderOperations) { - UString errorMessage = LangString(IDS_OPERATION_IS_NOT_SUPPORTED); + const UString errorMessage = LangString(IDS_OPERATION_IS_NOT_SUPPORTED); if (options.showErrorMessages) MessageBox_Error(errorMessage); else if (messages) @@ -165,7 +178,7 @@ { /* - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS CExternalCodecs g_ExternalCodecs; #endif */ @@ -203,7 +216,7 @@ But new code uses global codecs so we don't need to call LoadGlobalCodecs again */ /* - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS ThrowException_if_Error(LoadGlobalCodecs()); #endif */ @@ -248,13 +261,18 @@ extracter.ExtractCallbackSpec->OverwriteMode = NExtract::NOverwriteMode::kAsk; extracter.ExtractCallbackSpec->Init(); - extracter.Indices = indices; - extracter.FolderOperations = _folderOperations; + + extracter.CopyFrom_Paths = filePaths; + if (!filePaths) + { + extracter.Indices = indices; + extracter.FolderOperations = _folderOperations; + } extracter.ExtractCallbackSpec->PasswordIsDefined = usePassword; extracter.ExtractCallbackSpec->Password = password; - RINOK(extracter.Create(title, GetParent())); + RINOK(extracter.Create(title, GetParent())) if (messages) @@ -335,8 +353,8 @@ updater.UpdateCallbackSpec->ProgressDialog = &updater.ProgressDialog; - UString title = LangString(IDS_COPYING); - UString progressWindowTitle ("7-Zip"); // LangString(IDS_APP_TITLE); + const UString title = LangString(IDS_COPYING); + const UString progressWindowTitle ("7-Zip"); // LangString(IDS_APP_TITLE); updater.ProgressDialog.MainWindow = GetParent(); updater.ProgressDialog.MainTitle = progressWindowTitle; @@ -363,7 +381,9 @@ { NWindows::CThread thread; - RINOK(thread.Create(CThreadUpdate::MyThreadFunction, &updater)); + const WRes wres = thread.Create(CThreadUpdate::MyThreadFunction, &updater); + if (wres != 0) + return HRESULT_FROM_WIN32(wres); updater.ProgressDialog.Create(title, thread, GetParent()); } @@ -375,7 +395,7 @@ if (res == E_NOINTERFACE) { - UString errorMessage = LangString(IDS_OPERATION_IS_NOT_SUPPORTED); + const UString errorMessage = LangString(IDS_OPERATION_IS_NOT_SUPPORTED); if (showErrorMessages) MessageBox_Error(errorMessage); else if (messages) @@ -387,7 +407,7 @@ return res; } -void CPanel::CopyFromNoAsk(const UStringVector &filePaths) +void CPanel::CopyFromNoAsk(bool moveMode, const UStringVector &filePaths) { CDisableTimerProcessing disableTimerProcessing(*this); @@ -396,7 +416,7 @@ CDisableNotify disableNotify(*this); - HRESULT result = CopyFrom(false, L"", filePaths, true, 0); + const HRESULT result = CopyFrom(moveMode, L"", filePaths, true, NULL); if (result != S_OK) { @@ -413,17 +433,3 @@ disableNotify.Restore(); SetFocusToList(); } - -void CPanel::CopyFromAsk(const UStringVector &filePaths) -{ - UString title = LangString(IDS_CONFIRM_FILE_COPY); - UString message = LangString(IDS_WANT_TO_COPY_FILES); - message += "\n\'"; - message += _currentFolderPrefix; - message += "\' ?"; - int res = ::MessageBoxW(*(this), message, title, MB_YESNOCANCEL | MB_ICONQUESTION); - if (res != IDYES) - return; - - CopyFromNoAsk(filePaths); -} diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/Panel.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/Panel.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/Panel.cpp 2022-06-03 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/Panel.cpp 2023-03-20 13:00:00.000000000 +0000 @@ -2,8 +2,7 @@ #include "StdAfx.h" -#include -// #include +#include #include "../../../Common/IntToString.h" #include "../../../Common/StringConvert.h" @@ -28,6 +27,7 @@ #include "ExtractCallback.h" #include "FSFolder.h" #include "FormatUtils.h" +#include "LangUtils.h" #include "Panel.h" #include "RootFolder.h" @@ -65,8 +65,8 @@ HWND CPanel::GetParent() const { - HWND h = CWindow2::GetParent(); - return (h == 0) ? _mainWindow : h; + const HWND h = CWindow2::GetParent(); + return h ? h : _mainWindow; } #define kClassName L"7-Zip::Panel" @@ -101,12 +101,12 @@ cfp = fs2us(cfpF); } - RINOK(BindToPath(cfp, arcFormat, openRes)); + RINOK(BindToPath(cfp, arcFormat, openRes)) if (needOpenArc && !openRes.ArchiveIsOpened) return S_OK; - if (!CreateEx(0, kClassName, 0, WS_CHILD | WS_VISIBLE, + if (!CreateEx(0, kClassName, NULL, WS_CHILD | WS_VISIBLE, 0, 0, _xSize, 260, parentWindow, (HMENU)(UINT_PTR)id, g_hInstance)) return E_FAIL; @@ -318,6 +318,16 @@ } break; } + case 'W': + { + bool ctrl = IsKeyDown(VK_CONTROL); + if (ctrl) + { + PostMessage(g_HWND, WM_COMMAND, IDCLOSE, 0); + return 0; + } + break; + } } break; case WM_CHAR: @@ -336,6 +346,40 @@ return CallWindowProc(_origWindowProc, *this, message, wParam, lParam); } + +/* + REBARBANDINFO in vista (_WIN32_WINNT >= 0x0600) has additional fields + we want 2000/xp compatibility. + so we must use reduced structure, if we compile with (_WIN32_WINNT >= 0x0600) + Also there are additional fields, if (_WIN32_IE >= 0x0400). + but (_WIN32_IE >= 0x0400) is expected. + note: + in x64 (64-bit): + { + (108 == REBARBANDINFO_V6_SIZE) + (112 == sizeof(REBARBANDINFO) // for (_WIN32_WINNT < 0x0600) + (128 == sizeof(REBARBANDINFO) // for (_WIN32_WINNT >= 0x0600) + there is difference in sizes, because REBARBANDINFO size was + not aligned for 8-bytes in (_WIN32_WINNT < 0x0600). + We hope that WinVista+ support support both (108 and 112) sizes. + But does WinXP-x64 support (108 == REBARBANDINFO_V6_SIZE)? + { + 96 LPARAM lParam; + 104 UINT cxHeader; + #if (_WIN32_WINNT >= 0x0600) + 108 RECT rcChevronLocation; + 124 UINT uChevronState; + #endif + } +*/ + +#if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0600) && defined(REBARBANDINFOA_V6_SIZE) + #define my_compatib_REBARBANDINFO_size REBARBANDINFO_V6_SIZE +#else + #define my_compatib_REBARBANDINFO_size sizeof(REBARBANDINFO) +#endif + + bool CPanel::OnCreate(CREATESTRUCT * /* createStruct */) { // _virtualMode = false; @@ -351,11 +395,11 @@ style |= WS_CLIPCHILDREN; style |= WS_CLIPSIBLINGS; - const UInt32 kNumListModes = ARRAY_SIZE(kStyles); - if (_ListViewMode >= kNumListModes) - _ListViewMode = kNumListModes - 1; + const UInt32 kNumListModes = Z7_ARRAY_SIZE(kStyles); + if (_listViewMode >= kNumListModes) + _listViewMode = kNumListModes - 1; - style |= kStyles[_ListViewMode] + style |= kStyles[_listViewMode] | WS_TABSTOP | LVS_EDITLABELS; if (_mySelectMode) @@ -397,7 +441,7 @@ icex.dwICC = ICC_BAR_CLASSES; InitCommonControlsEx(&icex); - TBBUTTON tbb [ ] = + const TBBUTTON tbb[] = { // {0, 0, TBSTATE_ENABLED, BTNS_SEP, 0L, 0}, {VIEW_PARENTFOLDER, kParentFolderID, TBSTATE_ENABLED, BTNS_BUTTON, { 0, 0 }, 0, 0 }, @@ -445,7 +489,7 @@ _baseID + 2, 11, (HINSTANCE)HINST_COMMCTRL, IDB_VIEW_SMALL_COLOR, - (LPCTBBUTTON)&tbb, ARRAY_SIZE(tbb), + (LPCTBBUTTON)&tbb, Z7_ARRAY_SIZE(tbb), 0, 0, 0, 0, sizeof (TBBUTTON))); #ifndef UNDER_CE @@ -464,7 +508,7 @@ , NULL, WS_BORDER | WS_VISIBLE |WS_CHILD | CBS_DROPDOWN | CBS_AUTOHSCROLL, 0, 0, 100, 520, - ((_headerReBar == 0) ? (HWND)*this : _headerToolBar), + (_headerReBar ? _headerToolBar : (HWND)*this), (HMENU)(UINT_PTR)(_comboBoxID), g_hInstance, NULL); #ifndef UNDER_CE @@ -513,20 +557,23 @@ _headerToolBar.GetMaxSize(&size); REBARBANDINFO rbBand; - rbBand.cbSize = sizeof(REBARBANDINFO); // Required + memset(&rbBand, 0, sizeof(rbBand)); + // rbBand.cbSize = sizeof(rbBand); // for debug + // rbBand.cbSize = REBARBANDINFO_V3_SIZE; // for debug + rbBand.cbSize = my_compatib_REBARBANDINFO_size; rbBand.fMask = RBBIM_STYLE | RBBIM_CHILD | RBBIM_CHILDSIZE | RBBIM_SIZE; rbBand.fStyle = RBBS_NOGRIPPER; - rbBand.cxMinChild = size.cx; - rbBand.cyMinChild = size.cy; - rbBand.cyChild = size.cy; - rbBand.cx = size.cx; + rbBand.cxMinChild = (UINT)size.cx; + rbBand.cyMinChild = (UINT)size.cy; + rbBand.cyChild = (UINT)size.cy; + rbBand.cx = (UINT)size.cx; rbBand.hwndChild = _headerToolBar; _headerReBar.InsertBand(-1, &rbBand); RECT rc; ::GetWindowRect(_headerComboBox, &rc); rbBand.cxMinChild = 30; - rbBand.cyMinChild = rc.bottom - rc.top; + rbBand.cyMinChild = (UINT)(rc.bottom - rc.top); rbBand.cx = 1000; rbBand.hwndChild = _headerComboBox; _headerReBar.InsertBand(-1, &rbBand); @@ -562,7 +609,7 @@ void CPanel::ChangeWindowSize(int xSize, int ySize) { - if ((HWND)*this == 0) + if (!(HWND)*this) return; int kHeaderSize; int kStatusBarSize; @@ -601,7 +648,7 @@ bool CPanel::OnSize(WPARAM /* wParam */, int xSize, int ySize) { - if ((HWND)*this == 0) + if (!(HWND)*this) return true; if (_headerReBar) _headerReBar.Move(0, 0, xSize, 0); @@ -682,7 +729,7 @@ return false; } -bool CPanel::OnCommand(int code, int itemID, LPARAM lParam, LRESULT &result) +bool CPanel::OnCommand(unsigned code, unsigned itemID, LPARAM lParam, LRESULT &result) { if (itemID == kParentFolderID) { @@ -745,7 +792,7 @@ } void CPanel::MessageBox_LastError(LPCWSTR caption) const - { MessageBox_Error_HRESULT_Caption(::GetLastError(), caption); } + { MessageBox_Error_HRESULT_Caption(GetLastError_noZero_HRESULT(), caption); } void CPanel::MessageBox_LastError() const { MessageBox_LastError(L"7-Zip"); } @@ -830,13 +877,13 @@ { if (index >= 4) return; - _ListViewMode = index; - DWORD oldStyle = (DWORD)_listView.GetStyle(); - DWORD newStyle = kStyles[index]; + _listViewMode = index; + const LONG_PTR oldStyle = _listView.GetStyle(); + const DWORD newStyle = kStyles[index]; // DWORD tickCount1 = GetTickCount(); - if ((oldStyle & LVS_TYPEMASK) != newStyle) - _listView.SetStyle((oldStyle & ~LVS_TYPEMASK) | newStyle); + if ((oldStyle & LVS_TYPEMASK) != (LONG_PTR)newStyle) + _listView.SetStyle((oldStyle & ~(LONG_PTR)(DWORD)LVS_TYPEMASK) | (LONG_PTR)newStyle); // RefreshListCtrlSaveFocused(); /* DWORD tickCount2 = GetTickCount(); @@ -879,33 +926,34 @@ void CPanel::AddToArchive() { - CRecordVector indices; - GetOperatedItemIndices(indices); if (!Is_IO_FS_Folder()) { MessageBox_Error_UnsupportOperation(); return; } + CRecordVector indices; + Get_ItemIndices_Operated(indices); if (indices.Size() == 0) { MessageBox_Error_LangID(IDS_SELECT_FILES); return; } - UStringVector names; - - const UString curPrefix = GetFsPath(); - UString destCurDirPrefix = curPrefix; + UString destCurDirPrefix = GetFsPath(); if (IsFSDrivesFolder()) destCurDirPrefix = ROOT_FS_FOLDER; - - FOR_VECTOR (i, indices) - names.Add(curPrefix + GetItemRelPath2(indices[i])); - - const UString arcName = CreateArchiveName(names); - - HRESULT res = CompressFiles(destCurDirPrefix, arcName, L"", - true, // addExtension - names, false, true, false); + UStringVector names; + GetFilePaths(indices, names); + UString baseName; + const UString arcName = CreateArchiveName(names, + false, // isHash + NULL, // CFileInfo *fi + baseName); + const HRESULT res = CompressFiles(destCurDirPrefix, arcName, L"", + true, // addExtension + names, + false, // email + true, // showDialog + false); // waitFinish if (res != S_OK) { if (destCurDirPrefix.Len() >= MAX_PATH) @@ -931,26 +979,37 @@ return s; } -void CPanel::GetFilePaths(const CRecordVector &indices, UStringVector &paths, bool allowFolders) + +int CPanel::FindDir_InOperatedList(const CRecordVector &operatedIndices) const { - const UString prefix = GetFsPath(); - FOR_VECTOR (i, indices) - { - int index = indices[i]; - if (!allowFolders && IsItem_Folder(index)) - { - paths.Clear(); - break; - } - paths.Add(prefix + GetItemRelPath2(index)); - } - if (paths.Size() == 0) - { - MessageBox_Error_LangID(IDS_SELECT_FILES); - return; + const bool *isDirVector = &_isDirVector.Front(); + const UInt32 *indices = &operatedIndices.Front(); + const unsigned numItems = operatedIndices.Size(); + for (unsigned i = 0; i < numItems; i++) + if (isDirVector[indices[i]]) + return (int)i; + return -1; +} + + +void CPanel::GetFilePaths(const CRecordVector &operatedIndices, UStringVector &paths) const +{ + paths.ClearAndReserve(operatedIndices.Size()); + UString path = GetFsPath(); + const unsigned prefixLen = path.Len(); + const UInt32 *indices = &operatedIndices.Front(); + const unsigned numItems = operatedIndices.Size(); + // for (unsigned y = 0; y < 10000; y++, paths.Clear()) + for (unsigned i = 0; i < numItems; i++) + { + path.DeleteFrom(prefixLen); + Add_ItemRelPath2_To_String(indices[i], path); + // ODS_U(path) + paths.AddInReserved(path); } } + void CPanel::ExtractArchives() { if (_parentFolders.Size() > 0) @@ -959,12 +1018,14 @@ return; } CRecordVector indices; - GetOperatedItemIndices(indices); + Get_ItemIndices_Operated(indices); + if (indices.IsEmpty() || FindDir_InOperatedList(indices) != -1) + { + MessageBox_Error_LangID(IDS_SELECT_FILES); + return; + } UStringVector paths; GetFilePaths(indices, paths); - if (paths.IsEmpty()) - return; - UString outFolder = GetFsPath(); if (indices.Size() == 1) outFolder += GetSubFolderNameForExtract2(GetItemRelPath(indices[0])); @@ -976,8 +1037,8 @@ ci.Load(); ::ExtractArchives(paths, outFolder - , true // showDialog - , false // elimDup + , true // showDialog + , false // elimDup , ci.WriteZone ); } @@ -1047,7 +1108,7 @@ void CPanel::TestArchives() { CRecordVector indices; - GetOperatedIndicesSmart(indices); + Get_ItemIndices_OperSmart(indices); CMyComPtr archiveFolder; _folder.QueryInterface(IID_IArchiveFolder, &archiveFolder); if (archiveFolder) @@ -1086,7 +1147,7 @@ extracter.Indices = indices; - UString title = LangString(IDS_PROGRESS_TESTING); + const UString title = LangString(IDS_PROGRESS_TESTING); extracter.ProgressDialog.CompressingMode = false; extracter.ProgressDialog.MainWindow = GetParent(); @@ -1111,8 +1172,11 @@ return; } UStringVector paths; - GetFilePaths(indices, paths, true); + GetFilePaths(indices, paths); if (paths.IsEmpty()) + { + MessageBox_Error_LangID(IDS_SELECT_FILES); return; + } ::TestArchives(paths); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelCrc.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelCrc.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelCrc.cpp 2022-06-01 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelCrc.cpp 2023-03-20 13:03:00.000000000 +0000 @@ -20,7 +20,7 @@ using namespace NWindows; using namespace NFile; -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS extern CExternalCodecs g_ExternalCodecs; HRESULT LoadGlobalCodecs(); #endif @@ -38,7 +38,7 @@ FStringVector Prefixes; unsigned Index; - CDirEnumerator(): EnterToDirs(false), Index(0) {}; + CDirEnumerator(): EnterToDirs(false), Index(0) {} void Init(); DWORD GetNextFile(NFind::CFileInfo &fi, bool &filled, FString &resPath); @@ -53,8 +53,8 @@ static DWORD GetNormalizedError() { - DWORD error = GetLastError(); - return (error == 0) ? E_FAIL : error; + const DWORD error = GetLastError(); + return (error == 0) ? (DWORD)E_FAIL : error; } DWORD CDirEnumerator::GetNextFile(NFind::CFileInfo &fi, bool &filled, FString &resPath) @@ -73,9 +73,9 @@ if (Index >= FilePaths.Size()) return S_OK; const FString &path = FilePaths[Index++]; - int pos = path.ReverseFind_PathSepar(); + const int pos = path.ReverseFind_PathSepar(); if (pos >= 0) - resPath.SetFrom(path, pos + 1); + resPath.SetFrom(path, (unsigned)pos + 1); #if defined(_WIN32) && !defined(UNDER_CE) if (isRootPrefix && path.Len() == 2 && NName::IsDrivePath2(path)) @@ -90,7 +90,7 @@ #endif if (!fi.Find(BasePrefix + path)) { - DWORD error = GetNormalizedError(); + const DWORD error = GetNormalizedError(); resPath = path; return error; } @@ -110,7 +110,7 @@ } else { - DWORD error = GetNormalizedError(); + const DWORD error = GetNormalizedError(); resPath = Prefixes.Back(); Enumerators.DeleteBack(); Prefixes.DeleteBack(); @@ -142,8 +142,8 @@ bool ResultsWereShown; bool WasFinished; - HRESULT ProcessVirt(); - virtual void ProcessWasFinished_GuiVirt(); + HRESULT ProcessVirt() Z7_override; + virtual void ProcessWasFinished_GuiVirt() Z7_override; public: CDirEnumerator Enumerator; CHashBundle Hash; @@ -176,7 +176,7 @@ void CThreadCrc::AddErrorMessage(DWORD systemError, const FChar *name) { - Sync.AddError_Code_Name(systemError, fs2us(Enumerator.BasePrefix + name)); + Sync.AddError_Code_Name(HRESULT_FROM_WIN32(systemError), fs2us(Enumerator.BasePrefix + name)); Hash.NumErrors++; } @@ -214,7 +214,7 @@ for (;;) { bool filled; - DWORD error = Enumerator.GetNextFile(fi, filled, path); + const DWORD error = Enumerator.GetNextFile(fi, filled, path); if (error != 0) { AddErrorMessage(error, path); @@ -246,10 +246,10 @@ */ if (needPrint) { - RINOK(sync.ScanProgress(numFiles, totalSize, path, fi.IsDir())); + RINOK(sync.ScanProgress(numFiles, totalSize, path, fi.IsDir())) } } - RINOK(sync.ScanProgress(numFiles, totalSize, FString(), false)); + RINOK(sync.ScanProgress(numFiles, totalSize, FString(), false)) // sync.SetNumFilesTotal(numFiles); // sync.SetProgress(totalSize, 0); // SetStatus(LangString(IDS_CHECKSUM_CALCULATING)); @@ -312,16 +312,16 @@ Hash.Update(buf, size); if (Hash.CurSize - progress_Prev >= ((UInt32)1 << 21)) { - RINOK(sync.Set_NumBytesCur(errorsFilesSize + Hash.FilesSize + Hash.CurSize)); + RINOK(sync.Set_NumBytesCur(errorsFilesSize + Hash.FilesSize + Hash.CurSize)) progress_Prev = Hash.CurSize; } } } if (error == 0) Hash.Final(fi.IsDir(), false, fs2us(path)); - RINOK(sync.Set_NumBytesCur(errorsFilesSize + Hash.FilesSize)); + RINOK(sync.Set_NumBytesCur(errorsFilesSize + Hash.FilesSize)) } - RINOK(sync.Set_NumBytesCur(errorsFilesSize + Hash.FilesSize)); + RINOK(sync.Set_NumBytesCur(errorsFilesSize + Hash.FilesSize)) sync.Set_NumFilesCur(Hash.NumFiles); if (Hash.NumFiles != 1) sync.Set_FilePath(L""); @@ -341,7 +341,7 @@ CPanel &srcPanel = Panels[srcPanelIndex]; CRecordVector indices; - srcPanel.GetOperatedIndicesSmart(indices); + srcPanel.Get_ItemIndices_OperSmart(indices); if (indices.IsEmpty()) return S_OK; @@ -357,7 +357,7 @@ return srcPanel.CopyTo(options, indices, &messages); } - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS LoadGlobalCodecs(); @@ -369,7 +369,7 @@ { UStringVector methods; methods.Add(methodName); - RINOK(t.Hash.SetMethods(EXTERNAL_CODECS_VARS_G methods)); + RINOK(t.Hash.SetMethods(EXTERNAL_CODECS_VARS_G methods)) } FOR_VECTOR (i, indices) @@ -382,7 +382,7 @@ UString basePrefix2 = basePrefix; if (basePrefix2.Back() == ':') { - int pos = basePrefix2.ReverseFind_PathSepar(); + const int pos = basePrefix2.ReverseFind_PathSepar(); if (pos >= 0) basePrefix2.DeleteFrom((unsigned)(pos + 1)); } @@ -394,14 +394,14 @@ t.ShowCompressionInfo = false; - UString title = LangString(IDS_CHECKSUM_CALCULATING); + const UString title = LangString(IDS_CHECKSUM_CALCULATING); t.MainWindow = _window; t.MainTitle = "7-Zip"; // LangString(IDS_APP_TITLE); t.MainAddTitle = title; t.MainAddTitle.Add_Space(); - RINOK(t.Create(title, _window)); + RINOK(t.Create(title, _window)) t.ShowFinalResults(_window); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelDrag.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelDrag.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelDrag.cpp 2021-01-26 11:58:32.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelDrag.cpp 2023-05-15 18:00:00.000000000 +0000 @@ -6,10 +6,15 @@ #include #endif +#include "../../../../C/7zVersion.h" +#include "../../../../C/CpuArch.h" + #include "../../../Common/StringConvert.h" #include "../../../Common/Wildcard.h" +#include "../../../Windows/COM.h" #include "../../../Windows/MemoryGlobal.h" +#include "../../../Windows/Menu.h" #include "../../../Windows/FileDir.h" #include "../../../Windows/FileName.h" #include "../../../Windows/Shell.h" @@ -22,6 +27,11 @@ #include "App.h" #include "EnumFormatEtc.h" +#include "FormatUtils.h" +#include "LangUtils.h" + +#include "resource.h" +#include "../Explorer/resource.h" using namespace NWindows; using namespace NFile; @@ -31,88 +41,1003 @@ extern bool g_IsNT; #endif -#define kTempDirPrefix FTEXT("7zE") +#define PRF(x) +#define PRF_W(x) +// #define PRF2(x) +#define PRF3(x) +#define PRF3_W(x) +#define PRF4(x) +// #define PRF4(x) OutputDebugStringA(x) +// #define PRF4_W(x) OutputDebugStringW(x) -static LPCTSTR const kSvenZipSetFolderFormat = TEXT("7-Zip::SetTargetFolder"); +// #define SHOW_DEBUG_DRAG -//////////////////////////////////////////////////////// +#ifdef SHOW_DEBUG_DRAG + +#define PRF_(x) { x; } + +static void Print_Point(const char *name, DWORD keyState, const POINTL &pt, DWORD effect) +{ + AString s (name); + s += " x="; s.Add_UInt32((unsigned)pt.x); + s += " y="; s.Add_UInt32((unsigned)pt.y); + s += " k="; s.Add_UInt32(keyState); + s += " e="; s.Add_UInt32(effect); + PRF4(s); +} + +#else + +#define PRF_(x) + +#endif + + +#define kTempDirPrefix FTEXT("7zE") + +// all versions: k_Format_7zip_SetTargetFolder format to transfer folder path from target to source +static LPCTSTR const k_Format_7zip_SetTargetFolder = TEXT("7-Zip::SetTargetFolder"); +// new v23 formats: +static LPCTSTR const k_Format_7zip_SetTransfer = TEXT("7-Zip::SetTransfer"); +static LPCTSTR const k_Format_7zip_GetTransfer = TEXT("7-Zip::GetTransfer"); + +/* + Win10: clipboard formats. + There are about 16K free ids (formats) per system that can be + registered with RegisterClipboardFormat() with different names. + Probably that 16K ids space is common for ids registering for both + formats: RegisterClipboardFormat(), and registered window classes: + RegisterClass(). But ids for window classes will be deleted from + the list after process finishing. And registered clipboard + formats probably will be deleted from the list only after reboot. +*/ + +// static bool const g_CreateArchive_for_Drag_from_7zip = false; +// static bool const g_CreateArchive_for_Drag_from_Explorer = true; + // = false; // for debug + +/* +How DoDragDrop() works: +{ + IDropSource::QueryContinueDrag() (keyState & MK_LBUTTON) != 0 + IDropTarget::Enter() + IDropSource::GiveFeedback() + IDropTarget::DragOver() + IDropSource::GiveFeedback() + + for() + { + IDropSource::QueryContinueDrag() (keyState & MK_LBUTTON) != 0 + IDropTarget::DragOver() (keyState & MK_LBUTTON) != 0 + IDropSource::GiveFeedback() + } + + { + // DoDragDrop() in Win10 before calling // QueryContinueDrag() + // with (*(keyState & MK_LBUTTON) == 0) probably calls: + // 1) IDropTarget::DragOver() with same point values (x,y), but (keyState & MK_LBUTTON) != 0) + // 2) IDropSource::GiveFeedback(). + // so DropSource can know exact GiveFeedback(effect) mode just before LBUTTON releasing. + + if (IDropSource::QueryContinueDrag() for (keyState & MK_LBUTTON) == 0 + returns DRAGDROP_S_DROP), it will call + IDropTarget::Drop() + } + or + { + IDropSource::QueryContinueDrag() + IDropTarget::DragLeave() + IDropSource::GiveFeedback(0) + } + or + { + if (IDropSource::QueryContinueDrag() + returns DRAGDROP_S_CANCEL) + IDropTarget::DragLeave() + } +} +*/ + + +// ---------- CDropTarget ---------- + +static const UInt32 k_Struct_Id_SetTranfer = 2; // it's our selected id +static const UInt32 k_Struct_Id_GetTranfer = 3; // it's our selected id + +static const UInt64 k_Program_Id = 1; // "7-Zip" + +enum E_Program_ISA +{ + k_Program_ISA_x86 = 2, + k_Program_ISA_x64 = 3, + k_Program_ISA_armt = 4, + k_Program_ISA_arm64 = 5, + k_Program_ISA_arm32 = 6, + k_Program_ISA_ia64 = 9 +}; + +#define k_Program_Ver ((MY_VER_MAJOR << 16) | MY_VER_MINOR) + + +// k_SourceFlags_* are flags that are sent from Source to Target + +static const UInt32 k_SourceFlags_DoNotProcessInTarget = 1 << 1; +/* Do not process in Target. Source will process operation instead of Target. + By default Target processes Drop opearation. */ +// static const UInt32 k_SourceFlags_ProcessInTarget = 1 << 2; + +static const UInt32 k_SourceFlags_DoNotWaitFinish = 1 << 3; +static const UInt32 k_SourceFlags_WaitFinish = 1 << 4; +/* usually Source needs WaitFinish, if temp files were created. */ + +static const UInt32 k_SourceFlags_TempFiles = 1 << 6; +static const UInt32 k_SourceFlags_NamesAreParent = 1 << 7; +/* if returned path list for GetData(CF_HDROP) contains + path of parent temp folder instead of final paths of items + that will be extracted later from archive */ + +static const UInt32 k_SourceFlags_SetTargetFolder = 1 << 8; +/* SetData::("SetTargetFolder") was called (with empty or non-empty string) */ + +static const UInt32 k_SourceFlags_SetTargetFolder_NonEmpty = 1 << 9; +/* SetData::("SetTargetFolder") was called with non-empty string */ + +static const UInt32 k_SourceFlags_NeedExtractOpToFs = 1 << 10; + +static const UInt32 k_SourceFlags_Copy_WasCalled = 1 << 11; + +static const UInt32 k_SourceFlags_LeftButton = 1 << 14; +static const UInt32 k_SourceFlags_RightButton = 1 << 15; + + +static const UInt32 k_TargetFlags_WasCanceled = 1 << 0; +static const UInt32 k_TargetFlags_MustBeProcessedBySource = 1 << 1; +static const UInt32 k_TargetFlags_WasProcessed = 1 << 2; +static const UInt32 k_TargetFlags_DoNotWaitFinish = 1 << 3; +static const UInt32 k_TargetFlags_WaitFinish = 1 << 4; +static const UInt32 k_TargetFlags_MenuWasShown = 1 << 16; + +struct CDataObject_TransferBase +{ + UInt32 Struct_Id; + UInt32 Struct_Size; + + UInt64 Program_Id; + UInt32 Program_Ver_Main; + UInt32 Program_Ver_Build; + UInt32 Program_ISA; + UInt32 Program_Flags; + + UInt32 ProcessId; + UInt32 _reserved1[7]; + +protected: + void Init_Program(); +}; + + +void CDataObject_TransferBase::Init_Program() +{ + Program_Id = k_Program_Id; + Program_ISA = + #if defined(MY_CPU_AMD64) + k_Program_ISA_x64 + #elif defined(MY_CPU_X86) + k_Program_ISA_x86 + #elif defined(MY_CPU_ARM64) + k_Program_ISA_arm64 + #elif defined(MY_CPU_ARM32) + k_Program_ISA_arm32 + #elif defined(MY_CPU_ARMT) || defined(MY_CPU_ARM) + k_Program_ISA_armt + #elif defined(MY_CPU_IA64) + k_Program_ISA_ia64 + #else + 0 + #endif + ; + Program_Flags = sizeof(size_t); + Program_Ver_Main = k_Program_Ver; + // Program_Ver_Build = 0; + ProcessId = GetCurrentProcessId(); +} + + +#if defined(__GNUC__) && !defined(__clang__) +/* 'void* memset(void*, int, size_t)' clearing an object + of non-trivial type 'struct CDataObject_SetTransfer' */ +#pragma GCC diagnostic ignored "-Wclass-memaccess" +#endif + + +struct CDataObject_GetTransfer: +public CDataObject_TransferBase +{ + UInt32 Flags; + + UInt32 _reserved2[11]; + + CDataObject_GetTransfer() + { + memset(this, 0, sizeof(*this)); + Init_Program(); + Struct_Id = k_Struct_Id_GetTranfer; + Struct_Size = sizeof(*this); + } -class CDataObject: + bool Check() const + { + return Struct_Size >= sizeof(*this) && Struct_Id == k_Struct_Id_GetTranfer; + } +}; + + +enum Enum_FolderType +{ + k_FolderType_None, + k_FolderType_Unknown = 1, + k_FolderType_Fs = 2, + k_FolderType_AltStreams = 3, + k_FolderType_Archive = 4 +}; + +struct CTargetTransferInfo +{ + UInt32 Flags; + UInt32 FuncType; + + UInt32 KeyState; + UInt32 OkEffects; + POINTL Point; + + UInt32 Cmd_Effect; + UInt32 Cmd_Type; + UInt32 FolderType; + UInt32 _reserved3[3]; + + CTargetTransferInfo() + { + memset(this, 0, sizeof(*this)); + } +}; + +struct CDataObject_SetTransfer: +public CDataObject_TransferBase +{ + CTargetTransferInfo Target; + + void Init() + { + memset(this, 0, sizeof(*this)); + Init_Program(); + Struct_Id = k_Struct_Id_SetTranfer; + Struct_Size = sizeof(*this); + } + + bool Check() const + { + return Struct_Size >= sizeof(*this) && Struct_Id == k_Struct_Id_SetTranfer; + } +}; + + + + + +enum Enum_DragTargetMode +{ + k_DragTargetMode_None = 0, + k_DragTargetMode_Leave = 1, + k_DragTargetMode_Enter = 2, + k_DragTargetMode_Over = 3, + k_DragTargetMode_Drop_Begin = 4, + k_DragTargetMode_Drop_End = 5 +}; + + +// ---- menu ---- + +namespace NDragMenu { + +enum Enum_CmdId +{ + k_None = 0, + k_Cancel = 1, + k_Copy_Base = 2, // to fs + k_Copy_ToArc = 3, + k_AddToArc = 4 + /* + k_OpenArc = 8, + k_TestArc = 9, + k_ExtractFiles = 10, + k_ExtractHere = 11 + */ +}; + +struct CCmdLangPair +{ + unsigned CmdId_and_Flags; + unsigned LangId; +}; + +static const UInt32 k_MenuFlags_CmdMask = (1 << 7) - 1; +static const UInt32 k_MenuFlag_Copy = 1 << 14; +static const UInt32 k_MenuFlag_Move = 1 << 15; +// #define IDS_CANCEL (IDCANCEL + 400) +#define IDS_CANCEL 402 + +static const CCmdLangPair g_Pairs[] = +{ + { k_Copy_Base | k_MenuFlag_Copy, IDS_COPY }, + { k_Copy_Base | k_MenuFlag_Move, IDS_MOVE }, + { k_Copy_ToArc | k_MenuFlag_Copy, IDS_COPY_TO }, + // { k_Copy_ToArc | k_MenuFlag_Move, IDS_MOVE_TO }, // IDS_CONTEXT_COMPRESS_TO + // { k_OpenArc, IDS_CONTEXT_OPEN }, + // { k_ExtractFiles, IDS_CONTEXT_EXTRACT }, + // { k_ExtractHere, IDS_CONTEXT_EXTRACT_HERE }, + // { k_TestArc, IDS_CONTEXT_TEST }, + { k_AddToArc | k_MenuFlag_Copy, IDS_CONTEXT_COMPRESS }, + { k_Cancel, IDS_CANCEL } +}; + +} + + +class CDropTarget Z7_final: + public IDropTarget, + public CMyUnknownImp +{ + Z7_COM_UNKNOWN_IMP_1_MT(IDropTarget) + STDMETHOD(DragEnter)(IDataObject *dataObject, DWORD keyState, POINTL pt, DWORD *effect) Z7_override; + STDMETHOD(DragOver)(DWORD keyState, POINTL pt, DWORD *effect) Z7_override; + STDMETHOD(DragLeave)() Z7_override; + STDMETHOD(Drop)(IDataObject *dataObject, DWORD keyState, POINTL pt, DWORD *effect) Z7_override; + + bool m_IsRightButton; + bool m_GetTransfer_WasSuccess; + bool m_DropIsAllowed; // = true, if data IDataObject can return CF_HDROP (so we can get list of paths) + bool m_PanelDropIsAllowed; // = false, if current target_panel is source_panel. + // check it only if m_DropIsAllowed == true + // we use it to show icon effect that drop is not allowed here. + + CMyComPtr m_DataObject; // we set it in DragEnter() + UStringVector m_SourcePaths; + + // int m_DropHighlighted_SelectionIndex; + // int m_SubFolderIndex; // realIndex of item in m_Panel list (if drop cursor to that item) + // UString m_DropHighlighted_SubFolderName; // name of folder in m_Panel list (if drop cursor to that folder) + + CPanel *m_Panel; + bool m_IsAppTarget; // true, if we want to drop to app window (not to panel) + + bool m_TargetPath_WasSent_ToDataObject; // true, if TargetPath was sent + bool m_TargetPath_NonEmpty_WasSent_ToDataObject; // true, if non-empty TargetPath was sent + bool m_Transfer_WasSent_ToDataObject; // true, if Transfer was sent + UINT m_Format_7zip_SetTargetFolder; + UINT m_Format_7zip_SetTransfer; + UINT m_Format_7zip_GetTransfer; + + UInt32 m_ProcessId; // for sending + + bool IsItSameDrive() const; + + // void Try_QueryGetData(IDataObject *dataObject); + void LoadNames_From_DataObject(IDataObject *dataObject); + + UInt32 GetFolderType() const; + bool IsFsFolderPath() const; + DWORD GetEffect(DWORD keyState, POINTL pt, DWORD allowedEffect) const; + void RemoveSelection(); + void PositionCursor(const POINTL &ptl); + UString GetTargetPath() const; + bool SendToSource_TargetPath_enable(IDataObject *dataObject, bool enablePath); + bool SendToSource_UInt32(IDataObject *dataObject, UINT format, UInt32 value); + bool SendToSource_TransferInfo(IDataObject *dataObject, + const CTargetTransferInfo &info); + void SendToSource_auto(IDataObject *dataObject, + const CTargetTransferInfo &info); + void SendToSource_Drag(CTargetTransferInfo &info) + { + SendToSource_auto(m_DataObject, info); + } + + void ClearState(); + +public: + CDropTarget(); + + CApp *App; + int SrcPanelIndex; // index of D&D source_panel + int TargetPanelIndex; // what panel to use as target_panel of Application +}; + + + + +// ---------- CDataObject ---------- + +/* + Some programs (like Sticky Notes in Win10) do not like + virtual non-existing items (files/dirs) in CF_HDROP format. + So we use two versions of CF_HDROP data: + m_hGlobal_HDROP_Pre : the list contains only destination path of temp directory. + That directory later will be filled with extracted items. + m_hGlobal_HDROP_Final : the list contains paths of all root items that + will be created in temp directory by archive extraction operation, + or the list of existing fs items, if source is filesystem directory. + + The DRAWBACK: some programs (like Edge in Win10) can use names from IDataObject::GetData() + call that was called before IDropSource::QueryContinueDrag() where we set (UseFinalGlobal = true) + So such programs will use non-relevant m_hGlobal_HDROP_Pre item, + instead of m_hGlobal_HDROP_Final items. +*/ + +class CDataObject Z7_final: public IDataObject, public CMyUnknownImp { + Z7_COM_UNKNOWN_IMP_1_MT(IDataObject) + + Z7_COMWF_B GetData(LPFORMATETC pformatetcIn, LPSTGMEDIUM medium) Z7_override; + Z7_COMWF_B GetDataHere(LPFORMATETC pformatetc, LPSTGMEDIUM medium) Z7_override; + Z7_COMWF_B QueryGetData(LPFORMATETC pformatetc) Z7_override; + + Z7_COMWF_B GetCanonicalFormatEtc(LPFORMATETC /* pformatetc */, LPFORMATETC pformatetcOut) Z7_override + { + if (!pformatetcOut) + return E_INVALIDARG; + pformatetcOut->ptd = NULL; + return E_NOTIMPL; + } + + Z7_COMWF_B SetData(LPFORMATETC etc, STGMEDIUM *medium, BOOL release) Z7_override; + Z7_COMWF_B EnumFormatEtc(DWORD drection, LPENUMFORMATETC *enumFormatEtc) Z7_override; + + Z7_COMWF_B DAdvise(FORMATETC * /* etc */, DWORD /* advf */, LPADVISESINK /* pAdvSink */, DWORD * /* pdwConnection */) Z7_override + { return OLE_E_ADVISENOTSUPPORTED; } + Z7_COMWF_B DUnadvise(DWORD /* dwConnection */) Z7_override + { return OLE_E_ADVISENOTSUPPORTED; } + Z7_COMWF_B EnumDAdvise(LPENUMSTATDATA *ppenumAdvise) Z7_override + { + if (ppenumAdvise) + *ppenumAdvise = NULL; + return OLE_E_ADVISENOTSUPPORTED; + } + + bool m_PerformedDropEffect_WasSet; + bool m_LogicalPerformedDropEffect_WasSet; + bool m_DestDirPrefix_FromTarget_WasSet; +public: + bool m_Transfer_WasSet; private: + // GetData formats (source to target): FORMATETC m_Etc; - UINT m_SetFolderFormat; + // UINT m_Format_FileOpFlags; + // UINT m_Format_PreferredDropEffect; + + // SetData() formats (target to source): + // 7-Zip's format: + UINT m_Format_7zip_SetTargetFolder; + UINT m_Format_7zip_SetTransfer; + UINT m_Format_7zip_GetTransfer; // for GetData() + + UINT m_Format_PerformedDropEffect; + UINT m_Format_LogicalPerformedDropEffect; + UINT m_Format_DisableDragText; + UINT m_Format_IsShowingLayered; + UINT m_Format_IsShowingText; + UINT m_Format_DropDescription; + UINT m_Format_TargetCLSID; + + DWORD m_PerformedDropEffect; + DWORD m_LogicalPerformedDropEffect; + + void CopyFromPanelTo_Folder(); + HRESULT SetData2(const FORMATETC *formatetc, const STGMEDIUM *medium); public: - MY_UNKNOWN_IMP1_MT(IDataObject) + bool IsRightButton; + bool IsTempFiles; - STDMETHODIMP GetData(LPFORMATETC pformatetcIn, LPSTGMEDIUM medium); - STDMETHODIMP GetDataHere(LPFORMATETC pformatetc, LPSTGMEDIUM medium); - STDMETHODIMP QueryGetData(LPFORMATETC pformatetc ); + bool UsePreGlobal; + bool DoNotProcessInTarget; - STDMETHODIMP GetCanonicalFormatEtc ( LPFORMATETC /* pformatetc */, LPFORMATETC pformatetcOut) - { pformatetcOut->ptd = NULL; return ResultFromScode(E_NOTIMPL); } + bool NeedCall_Copy; + bool Copy_WasCalled; - STDMETHODIMP SetData(LPFORMATETC etc, STGMEDIUM *medium, BOOL release); - STDMETHODIMP EnumFormatEtc(DWORD drection, LPENUMFORMATETC *enumFormatEtc); + NMemory::CGlobal m_hGlobal_HDROP_Pre; + NMemory::CGlobal m_hGlobal_HDROP_Final; + // NMemory::CGlobal m_hGlobal_FileOpFlags; + // NMemory::CGlobal m_hGlobal_PreferredDropEffect; - STDMETHODIMP DAdvise(FORMATETC * /* etc */, DWORD /* advf */, LPADVISESINK /* pAdvSink */, DWORD * /* pdwConnection */) - { return OLE_E_ADVISENOTSUPPORTED; } - STDMETHODIMP DUnadvise(DWORD /* dwConnection */) { return OLE_E_ADVISENOTSUPPORTED; } - STDMETHODIMP EnumDAdvise( LPENUMSTATDATA * /* ppenumAdvise */) { return OLE_E_ADVISENOTSUPPORTED; } + CPanel *Panel; + CRecordVector Indices; - CDataObject(); + UString SrcDirPrefix_Temp; // FS directory with source files or Temp + UString DestDirPrefix_FromTarget; + /* destination Path that was sent by Target via SetData(). + it can be altstreams prefix. + if (!DestDirPrefix_FromTarget.IsEmpty()) m_Panel->CompressDropFiles() was not called by Target. + So we must do drop actions in Source */ + HRESULT Copy_HRESULT; + UStringVector Messages; - NMemory::CGlobal hGlobal; - UString Path; + CDataObject(); +public: + CDataObject_SetTransfer m_Transfer; }; + +// for old mingw: +#ifndef CFSTR_LOGICALPERFORMEDDROPEFFECT +#define CFSTR_LOGICALPERFORMEDDROPEFFECT TEXT("Logical Performed DropEffect") +#endif +#ifndef CFSTR_TARGETCLSID +#define CFSTR_TARGETCLSID TEXT("TargetCLSID") // HGLOBAL with a CLSID of the drop target +#endif + + + CDataObject::CDataObject() { - m_SetFolderFormat = RegisterClipboardFormat(kSvenZipSetFolderFormat); + // GetData formats (source to target): + // and we use CF_HDROP format to transfer file paths from source to target: m_Etc.cfFormat = CF_HDROP; m_Etc.ptd = NULL; m_Etc.dwAspect = DVASPECT_CONTENT; m_Etc.lindex = -1; m_Etc.tymed = TYMED_HGLOBAL; + + // m_Format_FileOpFlags = RegisterClipboardFormat(TEXT("FileOpFlags")); + // m_Format_PreferredDropEffect = RegisterClipboardFormat(CFSTR_PREFERREDDROPEFFECT); // "Preferred DropEffect" + + // SetData() formats (target to source): + m_Format_7zip_SetTargetFolder = RegisterClipboardFormat(k_Format_7zip_SetTargetFolder); + m_Format_7zip_SetTransfer = RegisterClipboardFormat(k_Format_7zip_SetTransfer); + m_Format_7zip_GetTransfer = RegisterClipboardFormat(k_Format_7zip_GetTransfer); + + m_Format_PerformedDropEffect = RegisterClipboardFormat(CFSTR_PERFORMEDDROPEFFECT); // "Performed DropEffect" + m_Format_LogicalPerformedDropEffect = RegisterClipboardFormat(CFSTR_LOGICALPERFORMEDDROPEFFECT); // "Logical Performed DropEffect" + m_Format_DisableDragText = RegisterClipboardFormat(TEXT("DisableDragText")); + m_Format_IsShowingLayered = RegisterClipboardFormat(TEXT("IsShowingLayered")); + m_Format_IsShowingText = RegisterClipboardFormat(TEXT("IsShowingText")); + m_Format_DropDescription = RegisterClipboardFormat(TEXT("DropDescription")); + m_Format_TargetCLSID = RegisterClipboardFormat(CFSTR_TARGETCLSID); + + m_PerformedDropEffect = 0; + m_LogicalPerformedDropEffect = 0; + + m_PerformedDropEffect_WasSet = false; + m_LogicalPerformedDropEffect_WasSet = false; + + m_DestDirPrefix_FromTarget_WasSet = false; + m_Transfer_WasSet = false; + + IsRightButton = false; + IsTempFiles = false; + + UsePreGlobal = false; + DoNotProcessInTarget = false; + + NeedCall_Copy = false; + Copy_WasCalled = false; + + Copy_HRESULT = S_OK; } -STDMETHODIMP CDataObject::SetData(LPFORMATETC etc, STGMEDIUM *medium, BOOL /* release */) + + +void CDataObject::CopyFromPanelTo_Folder() { - if (etc->cfFormat == m_SetFolderFormat - && etc->tymed == TYMED_HGLOBAL - && etc->dwAspect == DVASPECT_CONTENT - && medium->tymed == TYMED_HGLOBAL) + try { - Path.Empty(); - if (!medium->hGlobal) - return S_OK; - size_t size = GlobalSize(medium->hGlobal) / sizeof(wchar_t); - const wchar_t *src = (const wchar_t *)GlobalLock(medium->hGlobal); - if (src) + CCopyToOptions options; + options.folder = SrcDirPrefix_Temp; + /* 15.13: fixed problem with mouse cursor for password window. + DoDragDrop() probably calls SetCapture() to some hidden window. + But it's problem, if we show some modal window, like MessageBox. + So we return capture to our window. + If you know better way to solve the problem, please notify 7-Zip developer. + */ + // MessageBoxW(*Panel, L"test", L"test", 0); + /* HWND oldHwnd = */ SetCapture(*Panel); + Copy_WasCalled = true; + Copy_HRESULT = E_FAIL; + Copy_HRESULT = Panel->CopyTo(options, Indices, &Messages); + // do we need to restore capture? + // ReleaseCapture(); + // oldHwnd = SetCapture(oldHwnd); + } + catch(...) + { + Copy_HRESULT = E_FAIL; + } +} + + +#ifdef SHOW_DEBUG_DRAG + +static void PrintFormat2(AString &s, unsigned format) +{ + s += " "; + s += "= format="; + s.Add_UInt32(format); + s += " "; + const int k_len = 512; + CHAR temp[k_len]; + if (GetClipboardFormatNameA(format, temp, k_len) && strlen(temp) != 0) + s += temp; +} + +static void PrintFormat(const char *title, unsigned format) +{ + AString s (title); + PrintFormat2(s, format); + PRF4(s); +} + +static void PrintFormat_AndData(const char *title, unsigned format, const void *data, size_t size) +{ + AString s (title); + PrintFormat2(s, format); + s += " size="; + s.Add_UInt32((UInt32)size); + for (size_t i = 0; i < size && i < 16; i++) + { + s += " "; + s.Add_UInt32(((const Byte *)data)[i]); + } + PRF4(s); +} + +static void PrintFormat_GUIDToStringW(const void *p) +{ + const GUID *guid = (const GUID *)p; + UString s; + const unsigned kSize = 48; + StringFromGUID2(*guid, s.GetBuf(kSize), kSize); + s.ReleaseBuf_CalcLen(kSize); + PRF3_W(s); +} + +// Vista +typedef enum +{ + MY_DROPIMAGE_INVALID = -1, // no image preference (use default) + MY_DROPIMAGE_NONE = 0, // red "no" circle + MY_DROPIMAGE_COPY = DROPEFFECT_COPY, // plus for copy + MY_DROPIMAGE_MOVE = DROPEFFECT_MOVE, // movement arrow for move + MY_DROPIMAGE_LINK = DROPEFFECT_LINK, // link arrow for link + MY_DROPIMAGE_LABEL = 6, // tag icon to indicate metadata will be changed + MY_DROPIMAGE_WARNING = 7, // yellow exclamation, something is amiss with the operation + MY_DROPIMAGE_NOIMAGE = 8 // no image at all +} MY_DROPIMAGETYPE; + +typedef struct { + MY_DROPIMAGETYPE type; + WCHAR szMessage[MAX_PATH]; + WCHAR szInsert[MAX_PATH]; +} MY_DROPDESCRIPTION; + +#endif + + +/* +IDataObject::SetData(LPFORMATETC etc, STGMEDIUM *medium, BOOL release) +====================================================================== + + Main purpose of CDataObject is to transfer data from source to target + of drag and drop operation. + But also CDataObject can be used to transfer data in backward direction + from target to source (even if target and source are different processes). + There are some predefined Explorer's formats to transfer some data from target to source. + And 7-Zip uses 7-Zip's format k_Format_7zip_SetTargetFolder to transfer + destination directory path from target to source. + + Our CDataObject::SetData() function here is used only to transfer data from target to source. + Usual source_to_target data is filled to m_hGlobal_* objects directly without SetData() calling. + +The main problem of SetData() is ownership of medium for (release == TRUE) case. + +SetData(,, release = TRUE) from different processes (DropSource and DropTarget) +=============================================================================== +{ + MS DOCs about (STGMEDIUM *medium) ownership: + The data object called does not take ownership of the data + until it has successfully received it and no error code is returned. + + Each of processes (Source and Target) has own copy of medium allocated. + Windows code creates proxy IDataObject object in Target process to transferr + SetData() call between Target and Source processes via special proxies: + DropTarget -> + proxy_DataObject_in_Target -> + proxy_in_Source -> + DataObject_in_Source + when Target calls SetData() with proxy_DataObject_in_Target, + the system and proxy_in_Source + - allocates proxy-medium-in-Source process + - copies medium data from Target to that proxy-medium-in-Source + - sends proxy-medium-in-Source to DataObject_in_Source->SetData(). + + after returning from SetData() to Target process: + Win10 proxy_DataObject_in_Target releases original medium in Target process, + only if SetData() in Source returns S_OK. It's consistent with DOCs above. + + for unsupported cfFormat: + [DropSource is 7-Zip 22.01 (old) : (etc->cfFormat != m_Format_7zip_SetTargetFolder && release == TRUE)] + (DropSource is WinRAR case): + Source doesn't release medium and returns error (for example, E_NOTIMPL) + { + Then Win10 proxy_in_Source also doesn't release proxy-medium-in-Source. + So there is memory leak in Source process. + Probably Win10 proxy_in_Source tries to avoid possible double releasing + that can be more fatal than memory leak. + + Then Win10 proxy_DataObject_in_Target also doesn't release + original medium, that was allocated by DropTarget. + So if DropTarget also doesn't release medium, there is memory leak in + DropTarget process too. + DropTarget is Win10-Explorer probably doesn't release medium in that case. + } + + [DropSource is 7-Zip 22.01 (old) : (etc->cfFormat == m_Format_7zip_SetTargetFolder && release == TRUE)] + DropSource returns S_OK and doesn't release medium: + { + then there is memory leak in DropSource process only. + } + + (DropSource is 7-Zip v23 (new)): + (DropSource is Win10-Explorer case) + { + Win10-Explorer-DropSource probably always releases medium, + and then it always returns S_OK. + So Win10 proxy_DataObject_in_Target also releases + original medium, that was allocated by DropTarget. + So there is no memory leak in Source and Target processes. + } + + if (DropTarget is Win10-Explorer) + { + Explorer Target uses SetData(,, (release = TRUE)) and + Explorer Target probably doesn't free memory after SetData(), + even if SetData(,, (release = TRUE)) returns E_NOTIMPL; + } + + if (DropSource is Win10-Explorer) + { + (release == FALSE) doesn't work, and SetData() returns E_NOTIMPL; + (release == TRUE) works, and SetData() returns S_OK, and + it returns S_OK even for formats unsupported by Explorer. + } + + To be more compatible with DOCs and Win10-Explorer and to avoid memory leaks, + we use the following scheme for our IDataObject::SetData(,, release == TRUE) + in DropSource code: + if (release == TRUE) { our SetData() always releases medium + with ReleaseStgMedium() and returns S_OK; } + The DRAWBACK of that scheme: + The caller always receives S_OK, + so the caller doesn't know about any error in SetData() in that case. + +for 7zip-Target to 7zip-Source calls: + we use (release == FALSE) + So we avoid (release == TRUE) memory leak problems, + and we can get real return code from SetData(). + +for 7zip-Target to Explorer-Source calls: + we use (release == TRUE). + beacuse Explorer-Source doesn't accept (release == FALSE). +} +*/ + +/* +https://github.com/MicrosoftDocs/win32/blob/docs/desktop-src/shell/datascenarios.md +CFSTR_PERFORMEDDROPEFFECT: + is used by the target to inform the data object through its + IDataObject::SetData method of the outcome of a data transfer. +CFSTR_PREFERREDDROPEFFECT: + is used by the source to specify whether its preferred method of data transfer is move or copy. +*/ + +Z7_COMWF_B CDataObject::SetData(LPFORMATETC etc, STGMEDIUM *medium, BOOL release) +{ + try { + const HRESULT hres = SetData2(etc, medium); + // PrintFormat(release ? "SetData RELEASE=TRUE" : "SetData RELEASE=FALSE" , etc->cfFormat); + if (release) + { + /* + const DWORD tymed = medium->tymed; + IUnknown *pUnkForRelease = medium->pUnkForRelease; + */ + // medium->tymed = NULL; // for debug + // return E_NOTIMPL; // for debug + ReleaseStgMedium(medium); + /* ReleaseStgMedium() will change STGMEDIUM::tymed to (TYMED_NULL = 0). + but we also can clear (medium.hGlobal = NULL), + to prevent some incorrect releasing, if the caller will try to release the data */ + /* + if (medium->tymed == TYMED_NULL && tymed == TYMED_HGLOBAL && !pUnkForRelease) + medium->hGlobal = NULL; + */ + // do we need return S_OK; for (tymed != TYMED_HGLOBAL) cases ? + /* we return S_OK here to shows that we take ownership of the data in (medium), + so the caller will not try to release (medium) */ + return S_OK; // to be more compatible with Win10-Explorer and DOCs. + } + return hres; + } catch(...) { return E_FAIL; } +} + + + +HRESULT CDataObject::SetData2(const FORMATETC *etc, const STGMEDIUM *medium) +{ + // PRF3("== CDataObject::SetData()"); + + HRESULT hres = S_OK; + + if (etc->cfFormat == 0) + return DV_E_FORMATETC; + if (etc->tymed != TYMED_HGLOBAL) + return E_NOTIMPL; // DV_E_TYMED; + if (etc->dwAspect != DVASPECT_CONTENT) + return E_NOTIMPL; // DV_E_DVASPECT; + if (medium->tymed != TYMED_HGLOBAL) + return E_NOTIMPL; // DV_E_TYMED; + + if (!medium->hGlobal) + return S_OK; + + if (etc->cfFormat == m_Format_7zip_SetTargetFolder) + { + DestDirPrefix_FromTarget.Empty(); + m_DestDirPrefix_FromTarget_WasSet = true; + } + else if (etc->cfFormat == m_Format_7zip_SetTransfer) + m_Transfer_WasSet = false; + + const size_t size = GlobalSize(medium->hGlobal); + // GlobalLock() can return NULL, if memory block has a zero size + if (size == 0) + return S_OK; + const void *src = (const Byte *)GlobalLock(medium->hGlobal); + if (!src) + return E_FAIL; + + PRF_(PrintFormat_AndData("SetData", etc->cfFormat, src, size)) + + if (etc->cfFormat == m_Format_7zip_SetTargetFolder) + { + /* this is our registered k_Format_7zip_SetTargetFolder format. + so it's call from 7-zip's CDropTarget */ + /* 7-zip's CDropTarget calls SetData() for m_Format_7zip_SetTargetFolder + with (release == FALSE) */ + const size_t num = size / sizeof(wchar_t); + if (size != num * sizeof(wchar_t)) + return E_FAIL; + // if (num == 0) return S_OK; + // GlobalLock() can return NULL, if memory block has a zero-byte size + const wchar_t *s = (const wchar_t *)src; + UString &dest = DestDirPrefix_FromTarget; + for (size_t i = 0; i < num; i++) + { + const wchar_t c = s[i]; + if (c == 0) + break; + dest += c; + } + // PRF_(PrintFormat_AndData("SetData", etc->cfFormat, src, size)) + PRF3_W(DestDirPrefix_FromTarget); + } + else if (etc->cfFormat == m_Format_7zip_SetTransfer) + { + /* 7-zip's CDropTarget calls SetData() for m_Format_7zip_SetTransfer + with (release == FALSE) */ + if (size < sizeof(CDataObject_SetTransfer)) + return E_FAIL; + const CDataObject_SetTransfer *t = (const CDataObject_SetTransfer *)src; + if (!t->Check()) + return E_FAIL; + m_Transfer = *t; + if (t->Target.FuncType != k_DragTargetMode_Leave) + m_Transfer_WasSet = true; + bool needProcessBySource = !DestDirPrefix_FromTarget.IsEmpty(); + if (t->Target.FuncType == k_DragTargetMode_Drop_Begin) + { + if (t->Target.Cmd_Type != NDragMenu::k_Copy_Base + // || t->Target.Cmd_Effect != DROPEFFECT_COPY + ) + needProcessBySource = false; + } + if (t->Target.FuncType == k_DragTargetMode_Drop_End) { - for (size_t i = 0; i < size; i++) + if (t->Target.Flags & k_TargetFlags_MustBeProcessedBySource) + needProcessBySource = true; + else if (t->Target.Flags & k_TargetFlags_WasProcessed) + needProcessBySource = false; + } + DoNotProcessInTarget = needProcessBySource; + } + else + { + // SetData() from Explorer Target: + if (etc->cfFormat == m_Format_PerformedDropEffect) + { + m_PerformedDropEffect_WasSet = false; + if (size == sizeof(DWORD)) { - wchar_t c = src[i]; - if (c == 0) - break; - Path += c; + m_PerformedDropEffect = *(const DWORD *)src; + m_PerformedDropEffect_WasSet = true; } - GlobalUnlock(medium->hGlobal); - return S_OK; } + else if (etc->cfFormat == m_Format_LogicalPerformedDropEffect) + { + m_LogicalPerformedDropEffect_WasSet = false; + if (size == sizeof(DWORD)) + { + m_LogicalPerformedDropEffect = *(const DWORD *)src; + m_LogicalPerformedDropEffect_WasSet = true; + } + } + else if (etc->cfFormat == m_Format_DropDescription) + { + // drop description contains only name of dest folder without full path + #ifdef SHOW_DEBUG_DRAG + if (size == sizeof(MY_DROPDESCRIPTION)) + { + // const MY_DROPDESCRIPTION *s = (const MY_DROPDESCRIPTION *)src; + // PRF3_W(s->szMessage); + // PRF3_W(s->szInsert); + } + #endif + } + else if (etc->cfFormat == m_Format_TargetCLSID) + { + // it's called after call QueryContinueDrag() (keyState & MK_LBUTTON) == 0 + // Shell File System Folder (explorer) guid: F3364BA0-65B9-11CE-A9BA-00AA004AE837 + #ifdef SHOW_DEBUG_DRAG + if (size == 16) + { + PrintFormat_GUIDToStringW((const Byte *)src); + } + #endif + } + else if (etc->cfFormat == m_Format_DisableDragText) + { + // (size == 4) (UInt32 value) + // value==0 : if drag to folder item or folder + // value==1 : if drag to file or non list_view */ + } + else if ( + etc->cfFormat == m_Format_IsShowingLayered || + etc->cfFormat == m_Format_IsShowingText) + { + // (size == 4) (UInt32 value) value==0 : + } + else + hres = DV_E_FORMATETC; + // hres = E_NOTIMPL; // for debug + // hres = DV_E_FORMATETC; // for debug } - return E_NOTIMPL; + + GlobalUnlock(medium->hGlobal); + return hres; } + + static HGLOBAL DuplicateGlobalMem(HGLOBAL srcGlobal) { - SIZE_T size = GlobalSize(srcGlobal); + /* GlobalSize() returns 0: If the specified handle + is not valid or if the object has been discarded */ + const SIZE_T size = GlobalSize(srcGlobal); + if (size == 0) + return NULL; + // GlobalLock() can return NULL, if memory block has a zero-byte size const void *src = GlobalLock(srcGlobal); if (!src) - return 0; + return NULL; HGLOBAL destGlobal = GlobalAlloc(GHND | GMEM_SHARE, size); if (destGlobal) { @@ -120,7 +1045,7 @@ if (!dest) { GlobalFree(destGlobal); - destGlobal = 0; + destGlobal = NULL; } else { @@ -132,118 +1057,370 @@ return destGlobal; } -STDMETHODIMP CDataObject::GetData(LPFORMATETC etc, LPSTGMEDIUM medium) + +static bool Medium_CopyFrom(LPSTGMEDIUM medium, const void *data, size_t size) +{ + medium->tymed = TYMED_NULL; + medium->pUnkForRelease = NULL; + medium->hGlobal = NULL; + const HGLOBAL global = GlobalAlloc(GHND | GMEM_SHARE, size); + if (!global) + return false; + void *dest = GlobalLock(global); + if (!dest) + { + GlobalFree(global); + return false; + } + memcpy(dest, data, size); + GlobalUnlock(global); + medium->hGlobal = global; + medium->tymed = TYMED_HGLOBAL; + return true; +} + + +Z7_COMWF_B CDataObject::GetData(LPFORMATETC etc, LPSTGMEDIUM medium) { - RINOK(QueryGetData(etc)); + try { + PRF_(PrintFormat("-- GetData", etc->cfFormat)) + + medium->tymed = TYMED_NULL; + medium->pUnkForRelease = NULL; + medium->hGlobal = NULL; + + if (NeedCall_Copy && !Copy_WasCalled) + CopyFromPanelTo_Folder(); + + // PRF3("+ CDataObject::GetData"); + // PrintFormat(etc->cfFormat); + HGLOBAL global; + RINOK(QueryGetData(etc)) + + /* + if (etc->cfFormat == m_Format_FileOpFlags) + global = m_hGlobal_FileOpFlags; + else if (etc->cfFormat == m_Format_PreferredDropEffect) + { + // Explorer requests PreferredDropEffect only if Move/Copy selection is possible: + // Shift is not pressed and Ctrl is not pressed + PRF3("------ CDataObject::GetData() PreferredDropEffect"); + global = m_hGlobal_PreferredDropEffect; + } + else + */ + if (etc->cfFormat == m_Etc.cfFormat) // CF_HDROP + global = UsePreGlobal ? m_hGlobal_HDROP_Pre : m_hGlobal_HDROP_Final; + else if (etc->cfFormat == m_Format_7zip_GetTransfer) + { + CDataObject_GetTransfer transfer; + if (m_DestDirPrefix_FromTarget_WasSet) + { + transfer.Flags |= k_SourceFlags_SetTargetFolder; + } + if (!DestDirPrefix_FromTarget.IsEmpty()) + { + transfer.Flags |= k_SourceFlags_SetTargetFolder_NonEmpty; + } + if (IsTempFiles) + { + transfer.Flags |= k_SourceFlags_TempFiles; + transfer.Flags |= k_SourceFlags_WaitFinish; + transfer.Flags |= k_SourceFlags_NeedExtractOpToFs; + if (UsePreGlobal) + transfer.Flags |= k_SourceFlags_NamesAreParent; + } + else + transfer.Flags |= k_SourceFlags_DoNotWaitFinish; + + if (IsRightButton) + transfer.Flags |= k_SourceFlags_RightButton; + else + transfer.Flags |= k_SourceFlags_LeftButton; + + if (DoNotProcessInTarget) + transfer.Flags |= k_SourceFlags_DoNotProcessInTarget; + if (Copy_WasCalled) + transfer.Flags |= k_SourceFlags_Copy_WasCalled; + + if (Medium_CopyFrom(medium, &transfer, sizeof(transfer))) + return S_OK; + return E_OUTOFMEMORY; + } + else + return DV_E_FORMATETC; + + if (!global) + return DV_E_FORMATETC; medium->tymed = m_Etc.tymed; - medium->pUnkForRelease = 0; - medium->hGlobal = DuplicateGlobalMem(hGlobal); + medium->hGlobal = DuplicateGlobalMem(global); if (!medium->hGlobal) return E_OUTOFMEMORY; return S_OK; + } catch(...) { return E_FAIL; } } -STDMETHODIMP CDataObject::GetDataHere(LPFORMATETC /* etc */, LPSTGMEDIUM /* medium */) +Z7_COMWF_B CDataObject::GetDataHere(LPFORMATETC /* etc */, LPSTGMEDIUM /* medium */) { + PRF3("CDataObject::GetDataHere()"); // Seems Windows doesn't call it, so we will not implement it. return E_UNEXPECTED; } -STDMETHODIMP CDataObject::QueryGetData(LPFORMATETC etc) +/* + IDataObject::QueryGetData() Determines whether the data object is capable of + rendering the data as specified. Objects attempting a paste or drop + operation can call this method before calling IDataObject::GetData + to get an indication of whether the operation may be successful. + + The client of a data object calls QueryGetData to determine whether + passing the specified FORMATETC structure to a subsequent call to + IDataObject::GetData is likely to be successful. + + we check Try_QueryGetData with CF_HDROP +*/ + +Z7_COMWF_B CDataObject::QueryGetData(LPFORMATETC etc) { - if ((m_Etc.tymed & etc->tymed) && - m_Etc.cfFormat == etc->cfFormat && - m_Etc.dwAspect == etc->dwAspect) - return S_OK; - return DV_E_FORMATETC; + PRF3("-- CDataObject::QueryGetData()"); + if ( etc->cfFormat == m_Etc.cfFormat // CF_HDROP + || etc->cfFormat == m_Format_7zip_GetTransfer + // || (etc->cfFormat == m_Format_FileOpFlags && (HGLOBAL)m_hGlobal_FileOpFlags) + // || (etc->cfFormat == m_Format_PreferredDropEffect && (HGLOBAL)m_hGlobal_PreferredDropEffect) + ) + { + } + else + return DV_E_FORMATETC; + if (etc->dwAspect != m_Etc.dwAspect) + return DV_E_DVASPECT; + /* GetData(): It is possible to specify more than one medium by using the Boolean OR + operator, allowing the method to choose the best medium among those specified. */ + if ((etc->tymed & m_Etc.tymed) == 0) + return DV_E_TYMED; + return S_OK; } -STDMETHODIMP CDataObject::EnumFormatEtc(DWORD direction, LPENUMFORMATETC FAR* enumFormatEtc) +Z7_COMWF_B CDataObject::EnumFormatEtc(DWORD direction, LPENUMFORMATETC FAR* enumFormatEtc) { + // we don't enumerate for DATADIR_SET. Seems it can work without it. if (direction != DATADIR_GET) return E_NOTIMPL; + // we don't enumerate for m_Format_FileOpFlags also. Seems it can work without it. return CreateEnumFormatEtc(1, &m_Etc, enumFormatEtc); } + + //////////////////////////////////////////////////////// -class CDropSource: +class CDropSource Z7_final: public IDropSource, public CMyUnknownImp { + Z7_COM_UNKNOWN_IMP_1_MT(IDropSource) + STDMETHOD(QueryContinueDrag)(BOOL escapePressed, DWORD keyState) Z7_override; + STDMETHOD(GiveFeedback)(DWORD effect) Z7_override; + DWORD m_Effect; public: - MY_UNKNOWN_IMP1_MT(IDropSource) - STDMETHOD(QueryContinueDrag)(BOOL escapePressed, DWORD keyState); - STDMETHOD(GiveFeedback)(DWORD effect); - - - bool NeedExtract; - CPanel *Panel; - CRecordVector Indices; - UString Folder; CDataObject *DataObjectSpec; CMyComPtr DataObject; - bool NeedPostCopy; - HRESULT Result; - UStringVector Messages; + HRESULT DragProcessing_HRESULT; + bool DragProcessing_WasFinished; - CDropSource(): m_Effect(DROPEFFECT_NONE), Panel(NULL), NeedPostCopy(false), Result(S_OK) {} + CDropSource(): + m_Effect(DROPEFFECT_NONE), + // Panel(NULL), + DragProcessing_HRESULT(S_OK), + DragProcessing_WasFinished(false) + {} }; -STDMETHODIMP CDropSource::QueryContinueDrag(BOOL escapePressed, DWORD keyState) +// static bool g_Debug = 0; + + +Z7_COMWF_B CDropSource::QueryContinueDrag(BOOL escapePressed, DWORD keyState) { - if (escapePressed == TRUE) - return DRAGDROP_S_CANCEL; + // try { + + /* Determines whether a drag-and-drop operation should be continued, canceled, or completed. + escapePressed : Indicates whether the Esc key has been pressed + since the previous call to QueryContinueDrag + or to DoDragDrop if this is the first call to QueryContinueDrag: + TRUE : the end user has pressed the escape key; + FALSE : it has not been pressed. + keyState : The current state of the keyboard modifier keys on the keyboard. + Possible values can be a combination of any of the flags: + MK_CONTROL, MK_SHIFT, MK_ALT, MK_BUTTON, MK_LBUTTON, MK_MBUTTON, and MK_RBUTTON. + */ + #ifdef SHOW_DEBUG_DRAG + { + AString s ("CDropSource::QueryContinueDrag()"); + s.Add_Space(); + s += "keystate="; + s.Add_UInt32(keyState); + PRF4(s); + } + #endif + + /* if ((keyState & MK_LBUTTON) == 0) { - if (m_Effect == DROPEFFECT_NONE) - return DRAGDROP_S_CANCEL; - Result = S_OK; - bool needExtract = NeedExtract; - // MoveMode = (((keyState & MK_SHIFT) != 0) && MoveIsAllowed); - if (!DataObjectSpec->Path.IsEmpty()) + // PRF4("CDropSource::QueryContinueDrag() (keyState & MK_LBUTTON) == 0"); + g_Debug = true; + } + else + { + // PRF4("CDropSource::QueryContinueDrag() (keyState & MK_LBUTTON) != 0"); + } + */ + + if (escapePressed) + { + // The drag operation should be canceled with no drop operation occurring. + DragProcessing_WasFinished = true; + DragProcessing_HRESULT = DRAGDROP_S_CANCEL; + return DRAGDROP_S_CANCEL; + } + + if (DragProcessing_WasFinished) + return DragProcessing_HRESULT; + + if ((keyState & MK_RBUTTON) != 0) + { + if (!DataObjectSpec->IsRightButton) { - needExtract = false; - NeedPostCopy = true; + DragProcessing_WasFinished = true; + DragProcessing_HRESULT = DRAGDROP_S_CANCEL; + return DRAGDROP_S_CANCEL; } - if (needExtract) + return S_OK; + } + + if ((keyState & MK_LBUTTON) != 0) + { + if (DataObjectSpec->IsRightButton) { - CCopyToOptions options; - options.folder = Folder; + DragProcessing_WasFinished = true; + DragProcessing_HRESULT = DRAGDROP_S_CANCEL; + return DRAGDROP_S_CANCEL; + } + /* The drag operation should continue. This result occurs if no errors are detected, + the mouse button starting the drag-and-drop operation has not been released, + and the Esc key has not been detected. */ + return S_OK; + } + { + // the mouse button starting the drag-and-drop operation has been released. + + /* Win10 probably calls DragOver()/GiveFeedback() just before LBUTTON releasing. + so m_Effect is effect returned by DropTarget::DragOver() + just before LBUTTON releasing. + So here we can use Effect sent to last GiveFeedback() */ - // 15.13: fixed problem with mouse cursor for password window. - // DoDragDrop() probably calls SetCapture() to some hidden window. - // But it's problem, if we show some modal window, like MessageBox. - // So we return capture to our window. - // If you know better way to solve the problem, please notify 7-Zip developer. - - // MessageBoxW(*Panel, L"test", L"test", 0); - - /* HWND oldHwnd = */ SetCapture(*Panel); - - Result = Panel->CopyTo(options, Indices, &Messages); - - // do we need to restore capture? - // ReleaseCapture(); - // oldHwnd = SetCapture(oldHwnd); + if (m_Effect == DROPEFFECT_NONE) + { + DragProcessing_WasFinished = true; + DragProcessing_HRESULT = DRAGDROP_S_CANCEL; + // Drop target cannot accept the data. So we cancel drag and drop + // maybe return DRAGDROP_S_DROP also OK here ? + // return DRAGDROP_S_DROP; // for debug + return DRAGDROP_S_CANCEL; + } - if (Result != S_OK || !Messages.IsEmpty()) - return DRAGDROP_S_CANCEL; + // we switch to real names for items that will be created in temp folder + DataObjectSpec->UsePreGlobal = false; + DataObjectSpec->Copy_HRESULT = S_OK; + // MoveMode = (((keyState & MK_SHIFT) != 0) && MoveIsAllowed); + /* + if (DataObjectSpec->IsRightButton) + return DRAGDROP_S_DROP; + */ + + if (DataObjectSpec->IsTempFiles) + { + if (!DataObjectSpec->DestDirPrefix_FromTarget.IsEmpty()) + { + /* we know the destination Path. + So we can copy or extract items later in Source with simpler code. */ + DataObjectSpec->DoNotProcessInTarget = true; + // return DRAGDROP_S_CANCEL; + } + else + { + DataObjectSpec->NeedCall_Copy = true; + /* + if (Copy_HRESULT != S_OK || !Messages.IsEmpty()) + { + DragProcessing_WasFinished = true; + DragProcessing_HRESULT = DRAGDROP_S_CANCEL; + return DRAGDROP_S_CANCEL; + } + */ + } } + DragProcessing_HRESULT = DRAGDROP_S_DROP; + DragProcessing_WasFinished = true; return DRAGDROP_S_DROP; } - return S_OK; + // } catch(...) { return E_FAIL; } } -STDMETHODIMP CDropSource::GiveFeedback(DWORD effect) + +Z7_COMWF_B CDropSource::GiveFeedback(DWORD effect) { + // PRF3("CDropSource::GiveFeedback"); + /* Enables a source application to give visual feedback to the end user + during a drag-and-drop operation by providing the DoDragDrop function + with an enumeration value specifying the visual effect. + in (effect): + The DROPEFFECT value returned by the most recent call to + IDropTarget::DragEnter, + IDropTarget::DragOver, + or DROPEFFECT_NONE after IDropTarget::DragLeave. + 0: DROPEFFECT_NONE + 1: DROPEFFECT_COPY + 2: DROPEFFECT_MOVE + 4: DROPEFFECT_LINK + 0x80000000: DROPEFFECT_SCROLL + The dwEffect parameter can include DROPEFFECT_SCROLL, indicating that the + source should put up the drag-scrolling variation of the appropriate pointer. + */ m_Effect = effect; + + #ifdef SHOW_DEBUG_DRAG + AString w ("GiveFeedback effect="); + if (effect & DROPEFFECT_SCROLL) + w += " SCROLL "; + w.Add_UInt32(effect & ~DROPEFFECT_SCROLL); + // if (g_Debug) + PRF4(w); + #endif + + /* S_OK : no special drag and drop cursors. + Maybe it's for case where we created custom custom cursors. + DRAGDROP_S_USEDEFAULTCURSORS: Indicates successful completion of the method, + and requests OLE to update the cursor using the OLE-provided default cursors. */ + // return S_OK; // for debug return DRAGDROP_S_USEDEFAULTCURSORS; } + + +/* +static bool Global_SetUInt32(NMemory::CGlobal &hg, const UInt32 v) +{ + if (!hg.Alloc(GHND | GMEM_SHARE, sizeof(v))) + return false; + NMemory::CGlobalLock dropLock(hg); + *(UInt32 *)dropLock.GetPointer() = v; + return true; +} +*/ + static bool CopyNamesToHGlobal(NMemory::CGlobal &hgDrop, const UStringVector &names) { size_t totalLen = 1; @@ -255,14 +1432,14 @@ unsigned i; for (i = 0; i < names.Size(); i++) namesA.Add(GetSystemString(names[i])); - for (i = 0; i < names.Size(); i++) + for (i = 0; i < namesA.Size(); i++) totalLen += namesA[i].Len() + 1; if (!hgDrop.Alloc(GHND | GMEM_SHARE, totalLen * sizeof(CHAR) + sizeof(DROPFILES))) return false; NMemory::CGlobalLock dropLock(hgDrop); - DROPFILES* dropFiles = (DROPFILES*)dropLock.GetPointer(); + DROPFILES *dropFiles = (DROPFILES *)dropLock.GetPointer(); if (!dropFiles) return false; dropFiles->fNC = FALSE; @@ -270,11 +1447,11 @@ dropFiles->pt.y = 0; dropFiles->pFiles = sizeof(DROPFILES); dropFiles->fWide = FALSE; - CHAR *p = (CHAR *)((BYTE *)dropFiles + sizeof(DROPFILES)); - for (i = 0; i < names.Size(); i++) + CHAR *p = (CHAR *) (void *) ((BYTE *)dropFiles + sizeof(DROPFILES)); + for (i = 0; i < namesA.Size(); i++) { const AString &s = namesA[i]; - unsigned fullLen = s.Len() + 1; + const unsigned fullLen = s.Len() + 1; MyStringCopy(p, (const char *)s); p += fullLen; totalLen -= fullLen; @@ -292,9 +1469,13 @@ return false; NMemory::CGlobalLock dropLock(hgDrop); - DROPFILES* dropFiles = (DROPFILES*)dropLock.GetPointer(); + DROPFILES *dropFiles = (DROPFILES *)dropLock.GetPointer(); if (!dropFiles) return false; + /* fNC: + TRUE : pt specifies the screen coordinates of a point in a window's nonclient area. + FALSE : pt specifies the client coordinates of a point in the client area. + */ dropFiles->fNC = FALSE; dropFiles->pt.x = 0; dropFiles->pt.y = 0; @@ -304,38 +1485,74 @@ for (i = 0; i < names.Size(); i++) { const UString &s = names[i]; - unsigned fullLen = s.Len() + 1; + const unsigned fullLen = s.Len() + 1; MyStringCopy(p, (const WCHAR *)s); p += fullLen; totalLen -= fullLen; } *p = 0; } + // if (totalLen != 1) return false; return true; } -void CPanel::OnDrag(LPNMLISTVIEW /* nmListView */) + +void CPanel::OnDrag(LPNMLISTVIEW /* nmListView */, bool isRightButton) { + PRF("CPanel::OnDrag"); if (!DoesItSupportOperations()) return; CDisableTimerProcessing disableTimerProcessing2(*this); CRecordVector indices; - GetOperatedItemIndices(indices); + Get_ItemIndices_Operated(indices); if (indices.Size() == 0) return; // CSelectedState selState; // SaveSelectedState(selState); - // FString dirPrefix2; - FString dirPrefix; + const bool isFSFolder = IsFSFolder(); + // why we don't allow drag with rightButton from archive? + if (!isFSFolder && isRightButton) + return; + + UString dirPrefix; CTempDir tempDirectory; - bool isFSFolder = IsFSFolder(); + CDataObject *dataObjectSpec = new CDataObject; + CMyComPtr dataObject = dataObjectSpec; + dataObjectSpec->IsRightButton = isRightButton; + + { + /* we can change confirmation mode and another options. + Explorer target requests that FILEOP_FLAGS value. */ + /* + const FILEOP_FLAGS fopFlags = + FOF_NOCONFIRMATION + | FOF_NOCONFIRMMKDIR + | FOF_NOERRORUI + | FOF_SILENT; + // | FOF_SIMPLEPROGRESS; // it doesn't work as expected in Win10 + Global_SetUInt32(dataObjectSpec->m_hGlobal_FileOpFlags, fopFlags); + // dataObjectSpec->m_hGlobal_FileOpFlags.Free(); // for debug : disable these options + */ + } + { + /* we can change Preferred DropEffect. + Explorer target requests that FILEOP_FLAGS value. */ + /* + const DWORD effect = DROPEFFECT_MOVE; // DROPEFFECT_COPY; + Global_SetUInt32(dataObjectSpec->m_hGlobal_PreferredDropEffect, effect); + */ + } if (isFSFolder) - dirPrefix = us2fs(GetFsPath()); + { + dirPrefix = GetFsPath(); // why this in 22.01 ? + dataObjectSpec->UsePreGlobal = false; + // dataObjectSpec->IsTempFiles = false; + } else { if (!tempDirectory.Create(kTempDirPrefix)) @@ -343,23 +1560,32 @@ MessageBox_Error(L"Can't create temp folder"); return; } - dirPrefix = tempDirectory.GetPath(); - // dirPrefix2 = dirPrefix; + dirPrefix = fs2us(tempDirectory.GetPath()); + { + UStringVector names; + names.Add(dirPrefix); + dataObjectSpec->IsTempFiles = true; + dataObjectSpec->UsePreGlobal = true; + if (!CopyNamesToHGlobal(dataObjectSpec->m_hGlobal_HDROP_Pre, names)) + return; + } NFile::NName::NormalizeDirPathPrefix(dirPrefix); + /* + { + FString path2 = dirPrefix; + path2 += "1.txt"; + CopyFileW(L"C:\\1\\1.txt", path2, FALSE); + } + */ } - CDataObject *dataObjectSpec = new CDataObject; - CMyComPtr dataObject = dataObjectSpec; - { UStringVector names; - // names variable is USED for drag and drop from 7-zip to Explorer or to 7-zip archive folder. // names variable is NOT USED for drag and drop from 7-zip to 7-zip File System folder. - FOR_VECTOR (i, indices) { - UInt32 index = indices[i]; + const UInt32 index = indices[i]; UString s; if (isFSFolder) s = GetItemRelPath(index); @@ -370,14 +1596,12 @@ // We use (keepAndReplaceEmptyPrefixes = true) in CAgentFolder::Extract // So the following code is not required. // Maybe we also can change IFolder interface and send some flag also. - if (s.IsEmpty()) { // Correct_FsFile_Name("") returns "_". // If extracting code removes empty folder prefixes from path (as it was in old version), // Explorer can't find "_" folder in temp folder. // We can ask Explorer to copy parent temp folder "7zE" instead. - names.Clear(); names.Add(dirPrefix2); break; @@ -385,18 +1609,18 @@ */ s = Get_Correct_FsFile_Name(s); } - names.Add(fs2us(dirPrefix) + s); + names.Add(dirPrefix + s); } - if (!CopyNamesToHGlobal(dataObjectSpec->hGlobal, names)) + if (!CopyNamesToHGlobal(dataObjectSpec->m_hGlobal_HDROP_Final, names)) return; } - + CDropSource *dropSourceSpec = new CDropSource; CMyComPtr dropSource = dropSourceSpec; - dropSourceSpec->NeedExtract = !isFSFolder; - dropSourceSpec->Panel = this; - dropSourceSpec->Indices = indices; - dropSourceSpec->Folder = fs2us(dirPrefix); + dataObjectSpec->Panel = this; + dataObjectSpec->Indices = indices; + dataObjectSpec->SrcDirPrefix_Temp = dirPrefix; + dropSourceSpec->DataObjectSpec = dataObjectSpec; dropSourceSpec->DataObject = dataObjectSpec; @@ -404,17 +1628,17 @@ /* CTime - file creation timestamp. There are two operations in Windows with Drag and Drop: - COPY_OPERATION - icon with Plus sign - CTime will be set as current_time. - MOVE_OPERATION - icon without Plus sign - CTime will be preserved + COPY_OPERATION : icon with Plus sign : CTime will be set as current_time. + MOVE_OPERATION : icon without Plus sign : CTime will be preserved. Note: if we call DoDragDrop() with (effectsOK = DROPEFFECT_MOVE), then - it will use MOVE_OPERATION and CTime will be preserved. - But MoveFile() function doesn't preserve CTime, if different volumes are used. - Why it's so? - Does DoDragDrop() use some another function (not MoveFile())? + it will use MOVE_OPERATION and CTime will be preserved. + But MoveFile() function doesn't preserve CTime, if different volumes are used. + Why it's so? + Does DoDragDrop() use some another function (not MoveFile())? if (effectsOK == DROPEFFECT_COPY) it works as COPY_OPERATION - + if (effectsOK == DROPEFFECT_MOVE) drag works as MOVE_OPERATION if (effectsOK == (DROPEFFECT_COPY | DROPEFFECT_MOVE)) @@ -431,7 +1655,7 @@ We want to use MOVE_OPERATION for extracting from archive (open in 7-Zip) to Explorer: It has the following advantages: 1) it uses fast MOVE_OPERATION instead of slow COPY_OPERATION and DELETE, if same volume. - 2) it preserved CTime + 2) it preserves CTime Some another programs support only COPY_OPERATION. So we can use (DROPEFFECT_COPY | DROPEFFECT_MOVE) @@ -444,252 +1668,401 @@ IDropSource *dropSource IDataObject *dataObject if DropTarget is 7-Zip window, then 7-Zip's - IDropTarget::DragOver() sets Path in IDataObject. + IDropTarget::DragOver() sets DestDirPrefix_FromTarget in IDataObject. and - IDropSource::QueryContinueDrag() sets NeedPostCopy, if Path is not epmty. + IDropSource::QueryContinueDrag() sets DoNotProcessInTarget, if DestDirPrefix_FromTarget is not empty. So we can detect destination path after DoDragDrop(). Now we don't know any good way to detect destination path for D&D to Explorer. */ - bool moveIsAllowed = isFSFolder; /* DWORD effectsOK = DROPEFFECT_COPY; if (moveIsAllowed) effectsOK |= DROPEFFECT_MOVE; */ - - // 18.04: was changed - DWORD effectsOK = DROPEFFECT_MOVE | DROPEFFECT_COPY; - - DWORD effect; + const bool moveIsAllowed = isFSFolder; _panelCallback->DragBegin(); - - HRESULT res = DoDragDrop(dataObject, dropSource, effectsOK, &effect); - + PRF("=== DoDragDrop()"); + DWORD effect = 0; + // 18.04: was changed + const DWORD effectsOK = DROPEFFECT_MOVE | DROPEFFECT_COPY; + // effectsOK |= (1 << 8); // for debug + HRESULT res = ::DoDragDrop(dataObject, dropSource, effectsOK, &effect); + PRF("=== After DoDragDrop()"); _panelCallback->DragEnd(); - bool canceled = (res == DRAGDROP_S_CANCEL); + + /* + Win10 drag and drop to Explorer: + DoDragDrop() output variables: + for MOVE operation: + { + effect == DROPEFFECT_NONE; + dropSourceSpec->m_PerformedDropEffect == DROPEFFECT_MOVE; + } + for COPY operation: + { + effect == DROPEFFECT_COPY; + dropSourceSpec->m_PerformedDropEffect == DROPEFFECT_COPY; + } + DOCs: The source inspects the two values that can be returned by the target. + If both are set to DROPEFFECT_MOVE, it completes the unoptimized move + by deleting the original data. Otherwise, the target did an optimized + move and the original data has been deleted. + + We didn't see "unoptimized move" case (two values of DROPEFFECT_MOVE), + where we still need to delete source files. + So we don't delete files after DoDragDrop(). + + Also DOCs say for "optimized move": + The target also calls the data object's IDataObject::SetData method and passes + it a CFSTR_PERFORMEDDROPEFFECT format identifier set to DROPEFFECT_NONE. + but actually in Win10 we always have + (dropSourceSpec->m_PerformedDropEffect == DROPEFFECT_MOVE) + for any MOVE operation. + */ + + const bool canceled = (res == DRAGDROP_S_CANCEL); CDisableNotify disableNotify(*this); if (res == DRAGDROP_S_DROP) { - res = dropSourceSpec->Result; - if (dropSourceSpec->NeedPostCopy) - if (!dataObjectSpec->Path.IsEmpty()) + /* DRAGDROP_S_DROP is returned. It means that + - IDropTarget::Drop() was called, + - IDropTarget::Drop() returned (ret_code >= 0) + */ + res = dataObjectSpec->Copy_HRESULT; + bool need_Process = dataObjectSpec->DoNotProcessInTarget; + if (dataObjectSpec->m_Transfer_WasSet) + { + if (dataObjectSpec->m_Transfer.Target.FuncType == k_DragTargetMode_Drop_End) + { + if (dataObjectSpec->m_Transfer.Target.Flags & k_TargetFlags_MustBeProcessedBySource) + need_Process = true; + } + } + + if (need_Process) + if (!dataObjectSpec->DestDirPrefix_FromTarget.IsEmpty()) { - NFile::NName::NormalizeDirPathPrefix(dataObjectSpec->Path); + if (!NFile::NName::IsAltStreamPrefixWithColon(dataObjectSpec->DestDirPrefix_FromTarget)) + NFile::NName::NormalizeDirPathPrefix(dataObjectSpec->DestDirPrefix_FromTarget); CCopyToOptions options; - options.folder = dataObjectSpec->Path; + options.folder = dataObjectSpec->DestDirPrefix_FromTarget; // if MOVE is not allowed, we just use COPY operation - options.moveMode = (effect == DROPEFFECT_MOVE && moveIsAllowed); - res = CopyTo(options, indices, &dropSourceSpec->Messages); + /* it was 7-zip's Target that set non-empty dataObjectSpec->DestDirPrefix_FromTarget. + it means that target didn't completed operation, + and we can use (effect) value returned by target via DoDragDrop(). + as indicator of type of operation + */ + // options.moveMode = (moveIsAllowed && effect == DROPEFFECT_MOVE) // before v23.00: + options.moveMode = moveIsAllowed; + if (moveIsAllowed) + { + if (dataObjectSpec->m_Transfer_WasSet) + options.moveMode = ( + dataObjectSpec->m_Transfer.Target.Cmd_Effect == DROPEFFECT_MOVE); + else + options.moveMode = (effect == DROPEFFECT_MOVE); + // we expect (DROPEFFECT_MOVE) as indicator of move operation for Drag&Drop MOVE ver 22.01. + } + res = CopyTo(options, indices, &dataObjectSpec->Messages); } /* - if (effect == DROPEFFECT_MOVE) + if (effect & DROPEFFECT_MOVE) RefreshListCtrl(selState); */ } else { // we ignore E_UNEXPECTED that is returned if we drag file to printer - if (res != DRAGDROP_S_CANCEL && res != S_OK + if (res != DRAGDROP_S_CANCEL + && res != S_OK && res != E_UNEXPECTED) MessageBox_Error_HRESULT(res); - - res = dropSourceSpec->Result; + res = dataObjectSpec->Copy_HRESULT; } - if (!dropSourceSpec->Messages.IsEmpty()) + if (!dataObjectSpec->Messages.IsEmpty()) { CMessagesDialog messagesDialog; - messagesDialog.Messages = &dropSourceSpec->Messages; + messagesDialog.Messages = &dataObjectSpec->Messages; messagesDialog.Create((*this)); } if (res != S_OK && res != E_ABORT) { - // we restore Notify before MessageBox_Error_HRESULT. So we will se files selection + // we restore Notify before MessageBox_Error_HRESULT. So we will see files selection disableNotify.Restore(); // SetFocusToList(); MessageBox_Error_HRESULT(res); } - if (res == S_OK && dropSourceSpec->Messages.IsEmpty() && !canceled) + if (res == S_OK && dataObjectSpec->Messages.IsEmpty() && !canceled) KillSelection(); } -void CDropTarget::QueryGetData(IDataObject *dataObject) + + + + +CDropTarget::CDropTarget(): + m_IsRightButton(false), + m_GetTransfer_WasSuccess(false), + m_DropIsAllowed(false), + m_PanelDropIsAllowed(false), + // m_DropHighlighted_SelectionIndex(-1), + // m_SubFolderIndex(-1), + m_Panel(NULL), + m_IsAppTarget(false), + m_TargetPath_WasSent_ToDataObject(false), + m_TargetPath_NonEmpty_WasSent_ToDataObject(false), + m_Transfer_WasSent_ToDataObject(false), + App(NULL), + SrcPanelIndex(-1), + TargetPanelIndex(-1) +{ + m_Format_7zip_SetTargetFolder = RegisterClipboardFormat(k_Format_7zip_SetTargetFolder); + m_Format_7zip_SetTransfer = RegisterClipboardFormat(k_Format_7zip_SetTransfer); + m_Format_7zip_GetTransfer = RegisterClipboardFormat(k_Format_7zip_GetTransfer); + + m_ProcessId = GetCurrentProcessId(); + // m_TransactionId = ((UInt64)m_ProcessId << 32) + 1; + // ClearState(); +} + +// clear internal state +void CDropTarget::ClearState() +{ + m_DataObject.Release(); + m_SourcePaths.Clear(); + + m_IsRightButton = false; + + m_GetTransfer_WasSuccess = false; + m_DropIsAllowed = false; + + m_PanelDropIsAllowed = false; + // m_SubFolderIndex = -1; + // m_DropHighlighted_SubFolderName.Empty(); + m_Panel = NULL; + m_IsAppTarget = false; + m_TargetPath_WasSent_ToDataObject = false; + m_TargetPath_NonEmpty_WasSent_ToDataObject = false; + m_Transfer_WasSent_ToDataObject = false; +} + +/* + IDataObject::QueryGetData() Determines whether the data object is capable of + rendering the data as specified. Objects attempting a paste or drop + operation can call this method before calling IDataObject::GetData + to get an indication of whether the operation may be successful. + + The client of a data object calls QueryGetData to determine whether + passing the specified FORMATETC structure to a subsequent call to + IDataObject::GetData is likely to be successful. + + We check Try_QueryGetData with CF_HDROP +*/ +/* +void CDropTarget::Try_QueryGetData(IDataObject *dataObject) { FORMATETC etc = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL }; m_DropIsAllowed = (dataObject->QueryGetData(&etc) == S_OK); - } +*/ -static void MySetDropHighlighted(HWND hWnd, int index, bool enable) +static void ListView_SetItemState_DropHighlighted( + NControl::CListView &listView, int index, bool highlighted) { + // LVIS_DROPHILITED : The item is highlighted as a drag-and-drop target + /* LVITEM item; item.mask = LVIF_STATE; item.iItem = index; item.iSubItem = 0; item.state = enable ? LVIS_DROPHILITED : 0; item.stateMask = LVIS_DROPHILITED; - item.pszText = 0; - ListView_SetItem(hWnd, &item); + item.pszText = NULL; + listView.SetItem(&item); + */ + listView.SetItemState(index, highlighted ? LVIS_DROPHILITED : 0, LVIS_DROPHILITED); } +// Removes DropHighlighted state in ListView item, if it was set before void CDropTarget::RemoveSelection() { - if (m_SelectionIndex >= 0 && m_Panel) - MySetDropHighlighted(m_Panel->_listView, m_SelectionIndex, false); - m_SelectionIndex = -1; + if (m_Panel) + { + m_Panel->m_DropHighlighted_SubFolderName.Empty(); + if (m_Panel->m_DropHighlighted_SelectionIndex >= 0) + { + ListView_SetItemState_DropHighlighted(m_Panel->_listView, + m_Panel->m_DropHighlighted_SelectionIndex, false); + m_Panel->m_DropHighlighted_SelectionIndex = -1; + } + } } #ifdef UNDER_CE #define ChildWindowFromPointEx(hwndParent, pt, uFlags) ChildWindowFromPoint(hwndParent, pt) #endif -void CDropTarget::PositionCursor(POINTL ptl) -{ - m_SubFolderIndex = -1; - POINT pt; - pt.x = ptl.x; - pt.y = ptl.y; +/* + PositionCursor() function sets m_Panel under cursor drop, and + m_SubFolderIndex/m_DropHighlighted_SubFolderName, if drop to some folder in Panel list. +*/ +/* +PositionCursor() uses as input variables: + m_DropIsAllowed must be set before PositionCursor() + if (m_DropHighlighted_SelectionIndex >= 0 && m_Panel) it uses m_Panel and removes previous selection +PositionCursor() sets + m_PanelDropIsAllowed + m_Panel + m_IsAppTarget + m_SubFolderIndex + m_DropHighlighted_SubFolderName + m_DropHighlighted_SelectionIndex +*/ +void CDropTarget::PositionCursor(const POINTL &ptl) +{ RemoveSelection(); + + // m_SubFolderIndex = -1; + // m_DropHighlighted_SubFolderName.Empty(); m_IsAppTarget = true; m_Panel = NULL; + m_PanelDropIsAllowed = false; - m_PanelDropIsAllowed = true; if (!m_DropIsAllowed) return; + + POINT pt; + pt.x = ptl.x; + pt.y = ptl.y; { POINT pt2 = pt; - App->_window.ScreenToClient(&pt2); - for (unsigned i = 0; i < kNumPanelsMax; i++) - if (App->IsPanelVisible(i)) - if (App->Panels[i].IsEnabled()) - if (ChildWindowFromPointEx(App->_window, pt2, - CWP_SKIPINVISIBLE | CWP_SKIPDISABLED) == (HWND)App->Panels[i]) + if (App->_window.ScreenToClient(&pt2)) + for (unsigned i = 0; i < kNumPanelsMax; i++) + if (App->IsPanelVisible(i)) + { + CPanel *panel = &App->Panels[i]; + if (panel->IsEnabled()) + if (::ChildWindowFromPointEx(App->_window, pt2, + CWP_SKIPINVISIBLE | CWP_SKIPDISABLED) == (HWND)*panel) { - m_Panel = &App->Panels[i]; + m_Panel = panel; m_IsAppTarget = false; if ((int)i == SrcPanelIndex) - { - m_PanelDropIsAllowed = false; - return; - } + return; // we don't allow to drop to source panel break; } - if (m_IsAppTarget) - { - if (TargetPanelIndex >= 0) - m_Panel = &App->Panels[TargetPanelIndex]; - return; - } + } + } + + m_PanelDropIsAllowed = true; + + if (!m_Panel) + { + if (TargetPanelIndex >= 0) + m_Panel = &App->Panels[TargetPanelIndex]; + // we don't need to find item in panel + return; } + // we will try to find and highlight drop folder item in listView under cursor /* m_PanelDropIsAllowed = m_Panel->DoesItSupportOperations(); if (!m_PanelDropIsAllowed) return; */ - + /* now we don't allow drop to subfolder under cursor, if dest panel is archive. + Another code must be fixed for that case, where we must use m_SubFolderIndex/m_DropHighlighted_SubFolderName */ if (!m_Panel->IsFsOrPureDrivesFolder()) return; - if (WindowFromPoint(pt) != (HWND)m_Panel->_listView) + if (::WindowFromPoint(pt) != (HWND)m_Panel->_listView) return; LVHITTESTINFO info; m_Panel->_listView.ScreenToClient(&pt); info.pt = pt; - int index = ListView_HitTest(m_Panel->_listView, &info); + const int index = ListView_HitTest(m_Panel->_listView, &info); if (index < 0) return; - int realIndex = m_Panel->GetRealItemIndex(index); + const unsigned realIndex = m_Panel->GetRealItemIndex(index); if (realIndex == kParentIndex) return; if (!m_Panel->IsItem_Folder(realIndex)) return; - m_SubFolderIndex = realIndex; - m_SubFolderName = m_Panel->GetItemName(m_SubFolderIndex); - MySetDropHighlighted(m_Panel->_listView, index, true); - m_SelectionIndex = index; + // m_SubFolderIndex = (int)realIndex; + m_Panel->m_DropHighlighted_SubFolderName = m_Panel->GetItemName(realIndex); + ListView_SetItemState_DropHighlighted(m_Panel->_listView, index, true); + m_Panel->m_DropHighlighted_SelectionIndex = index; } -bool CDropTarget::IsFsFolderPath() const -{ - if (!m_IsAppTarget && m_Panel) - return (m_Panel->IsFSFolder() || (m_Panel->IsFSDrivesFolder() && m_SelectionIndex >= 0)); - return false; -} -static void ReadUnicodeStrings(const wchar_t *p, size_t size, UStringVector &names) +/* returns true, if !m_IsAppTarget + and target is FS folder or altStream folder +*/ + +UInt32 CDropTarget::GetFolderType() const { - names.Clear(); - UString name; - for (;size > 0; size--) - { - wchar_t c = *p++; - if (c == 0) - { - if (name.IsEmpty()) - break; - names.Add(name); - name.Empty(); - } - else - name += c; - } + if (m_IsAppTarget || !m_Panel) + return k_FolderType_None; + if (m_Panel->IsFSFolder() || + (m_Panel->IsFSDrivesFolder() + && m_Panel->m_DropHighlighted_SelectionIndex >= 0)) + return k_FolderType_Fs; + if (m_Panel->IsAltStreamsFolder()) + return k_FolderType_AltStreams; + if (m_Panel->IsArcFolder()) + return k_FolderType_Archive; + return k_FolderType_Unknown; } -static void ReadAnsiStrings(const char *p, size_t size, UStringVector &names) +bool CDropTarget::IsFsFolderPath() const { - names.Clear(); - AString name; - for (;size > 0; size--) - { - char c = *p++; - if (c == 0) - { - if (name.IsEmpty()) - break; - names.Add(GetUnicodeString(name)); - name.Empty(); - } - else - name += c; - } + if (m_IsAppTarget || !m_Panel) + return false; + if (m_Panel->IsFSFolder()) + return true; + if (m_Panel->IsAltStreamsFolder()) + return true; + return m_Panel->IsFSDrivesFolder() && + m_Panel->m_DropHighlighted_SelectionIndex >= 0; } -static void GetNamesFromDataObject(IDataObject *dataObject, UStringVector &names) + +#define INIT_FORMATETC_HGLOBAL(type) { (type), NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL } + +static bool DataObject_GetData_GetTransfer(IDataObject *dataObject, + UINT a_Format_7zip_GetTransfer, CDataObject_GetTransfer &transfer) { - names.Clear(); - FORMATETC etc = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL }; - STGMEDIUM medium; - HRESULT res = dataObject->GetData(&etc, &medium); + FORMATETC etc = INIT_FORMATETC_HGLOBAL((CLIPFORMAT)a_Format_7zip_GetTransfer); + NCOM::CStgMedium medium; + const HRESULT res = dataObject->GetData(&etc, &medium); if (res != S_OK) - return; + return false; if (medium.tymed != TYMED_HGLOBAL) - return; - { - NMemory::CGlobal global; - global.Attach(medium.hGlobal); - size_t blockSize = GlobalSize(medium.hGlobal); - NMemory::CGlobalLock dropLock(medium.hGlobal); - const DROPFILES* dropFiles = (DROPFILES*)dropLock.GetPointer(); - if (!dropFiles) - return; - if (blockSize < dropFiles->pFiles) - return; - size_t size = blockSize - dropFiles->pFiles; - const void *namesData = (const Byte *)dropFiles + dropFiles->pFiles; - if (dropFiles->fWide) - ReadUnicodeStrings((const wchar_t *)namesData, size / sizeof(wchar_t), names); - else - ReadAnsiStrings((const char *)namesData, size, names); - } + return false; + const size_t size = GlobalSize(medium.hGlobal); + if (size < sizeof(transfer)) + return false; + NMemory::CGlobalLock dropLock(medium.hGlobal); + const CDataObject_GetTransfer *t = (const CDataObject_GetTransfer *)dropLock.GetPointer(); + if (!t) + return false; + if (!t->Check()) // isSetData + return false; + transfer = *t; + return true; } +/* + returns true, if all m_SourcePaths[] items are same drive + as destination drop path in m_Panel +*/ bool CDropTarget::IsItSameDrive() const { if (!m_Panel) @@ -705,9 +2078,10 @@ if (drive.IsEmpty()) return false; } - else if (m_Panel->IsFSDrivesFolder() && m_SelectionIndex >= 0) + else if (m_Panel->IsFSDrivesFolder() + && m_Panel->m_DropHighlighted_SelectionIndex >= 0) { - drive = m_SubFolderName; + drive = m_Panel->m_DropHighlighted_SubFolderName; drive.Add_PathSepar(); } else @@ -721,16 +2095,18 @@ if (!m_SourcePaths[i].IsPrefixedBy_NoCase(drive)) return false; } - return true; } /* There are 2 different actions, when we drag to 7-Zip: - 1) Drag from any external program except of Explorer to "7-Zip" FS folder. - We want to create new archive for that operation. - 2) all another operation work as usual file COPY/MOVE + 1) if target panel is "7-Zip" FS and any of the 2 cases: + - Drag from any non "7-Zip" program; + or + - Drag from "7-Zip" to non-panel area of "7-Zip". + We want to create new archive for that operation with "Add to Archive" window. + 2) all another operations work as usual file COPY/MOVE - Drag from "7-Zip" FS to "7-Zip" FS. COPY/MOVE are supported. - Drag to open archive in 7-Zip. @@ -740,217 +2116,891 @@ We replace COPY to MOVE. */ -DWORD CDropTarget::GetEffect(DWORD keyState, POINTL /* pt */, DWORD allowedEffect) +// we try to repeat Explorer's effects. +// out: 0 - means that use default effect +static DWORD GetEffect_ForKeys(DWORD keyState) { - if (!m_DropIsAllowed || !m_PanelDropIsAllowed) - return DROPEFFECT_NONE; + if (keyState & MK_CONTROL) + { + if (keyState & MK_ALT) + return 0; + if (keyState & MK_SHIFT) + return DROPEFFECT_LINK; // CONTROL + SHIFT + return DROPEFFECT_COPY; // CONTROL + } + // no CONTROL + if (keyState & MK_SHIFT) + { + if (keyState & MK_ALT) + return 0; + return DROPEFFECT_MOVE; // SHIFT + } + // no CONTROL, no SHIFT + if (keyState & MK_ALT) + return DROPEFFECT_LINK; // ALT + return 0; +} - if (!IsFsFolderPath() || !m_SetPathIsOK) - allowedEffect &= ~DROPEFFECT_MOVE; - DWORD effect = 0; - - if (keyState & MK_CONTROL) - effect = allowedEffect & DROPEFFECT_COPY; - else if (keyState & MK_SHIFT) - effect = allowedEffect & DROPEFFECT_MOVE; - +/* GetEffect() uses m_TargetPath_WasSentToDataObject + to disale MOVE operation, if Source is not 7-Zip +*/ +DWORD CDropTarget::GetEffect(DWORD keyState, POINTL /* pt */, DWORD allowedEffect) const +{ + // (DROPEFFECT_NONE == 0) + if (!m_DropIsAllowed || !m_PanelDropIsAllowed) + return 0; + if (!IsFsFolderPath() || !m_TargetPath_WasSent_ToDataObject) + { + // we don't allow MOVE, if Target is archive or Source is not 7-Zip + // disabled for debug: + // allowedEffect &= ~DROPEFFECT_MOVE; + } + DWORD effect; + { + effect = GetEffect_ForKeys(keyState); + if (effect == DROPEFFECT_LINK) + return 0; + effect &= allowedEffect; + } if (effect == 0) { if (allowedEffect & DROPEFFECT_COPY) - effect = DROPEFFECT_COPY; + effect = DROPEFFECT_COPY; if (allowedEffect & DROPEFFECT_MOVE) { + /* MOVE operation can be optimized. So MOVE is preferred way + for default action, if Source and Target are at same drive */ if (IsItSameDrive()) effect = DROPEFFECT_MOVE; } } - if (effect == 0) - return DROPEFFECT_NONE; return effect; } + +/* returns: + - target folder path prefix, if target is FS folder + - empty string, if target is not FS folder +*/ UString CDropTarget::GetTargetPath() const { if (!IsFsFolderPath()) return UString(); UString path = m_Panel->GetFsPath(); - if (m_SubFolderIndex >= 0 && !m_SubFolderName.IsEmpty()) + if (/* m_SubFolderIndex >= 0 && */ + !m_Panel->m_DropHighlighted_SubFolderName.IsEmpty()) { - path += m_SubFolderName; + path += m_Panel->m_DropHighlighted_SubFolderName; path.Add_PathSepar(); } return path; } -bool CDropTarget::SetPath(bool enablePath) const + +/* +if IDropSource is Win10-Explorer +-------------------------------- + As in MS DOCs: + The source inspects the two (effect) values that can be returned by the target: + 1) SetData(CFSTR_PERFORMEDDROPEFFECT) + 2) returned value (*effect) by + CDropTarget::Drop(IDataObject *dataObject, DWORD keyState, + POINTL pt, DWORD *effect) + If both are set to DROPEFFECT_MOVE, Explorer completes the unoptimized move by deleting + the original data. + // Otherwise, the target did an optimized move and the original data has been deleted. +*/ + + +/* + Send targetPath from target to dataObject (to Source) + input: set (enablePath = false) to send empty path + returns true, if SetData() returns S_OK : (source is 7-zip) + returns false, if SetData() doesn't return S_OK : (source is Explorer) +*/ +bool CDropTarget::SendToSource_TargetPath_enable(IDataObject *dataObject, bool enablePath) { - UINT setFolderFormat = RegisterClipboardFormat(kSvenZipSetFolderFormat); - - FORMATETC etc = { (CLIPFORMAT)setFolderFormat, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL }; - STGMEDIUM medium; - medium.tymed = etc.tymed; - medium.pUnkForRelease = 0; + m_TargetPath_NonEmpty_WasSent_ToDataObject = false; UString path; if (enablePath) path = GetTargetPath(); - size_t size = path.Len() + 1; - medium.hGlobal = GlobalAlloc(GHND | GMEM_SHARE, size * sizeof(wchar_t)); + PRF("CDropTarget::SetPath"); + PRF_W(path); + if (!dataObject || m_Format_7zip_SetTargetFolder == 0) + return false; + FORMATETC etc = INIT_FORMATETC_HGLOBAL((CLIPFORMAT)m_Format_7zip_SetTargetFolder); + STGMEDIUM medium; + medium.tymed = etc.tymed; + medium.pUnkForRelease = NULL; + const size_t num = path.Len() + 1; // + (1 << 19) // for debug + medium.hGlobal = GlobalAlloc(GHND | GMEM_SHARE, num * sizeof(wchar_t)); if (!medium.hGlobal) return false; + // Sleep(1000); wchar_t *dest = (wchar_t *)GlobalLock(medium.hGlobal); - if (!dest) + // Sleep(1000); + bool res = false; + if (dest) + { + MyStringCopy(dest, (const wchar_t *)path); + GlobalUnlock(medium.hGlobal); + // OutputDebugString("m_DataObject->SetData"); + const BOOL release = FALSE; // that way is more simple for correct releasing. + // TRUE; // for debug : is not good for some cases. + /* If DropSource is Win10-Explorer, dataObject->SetData() returns E_NOTIMPL; */ + const HRESULT hres = dataObject->SetData(&etc, &medium, release); + // Sleep(1000); + res = (hres == S_OK); + } + + ReleaseStgMedium(&medium); + if (res && !path.IsEmpty()) + m_TargetPath_NonEmpty_WasSent_ToDataObject = true; + // Sleep(1000); + return res; +} + + +void CDropTarget::SendToSource_auto(IDataObject *dataObject, + const CTargetTransferInfo &info) +{ + /* we try to send target path to Source. + If Source is 7-Zip, then it will accept k_Format_7zip_SetTargetFolder. + That sent path will be non-Empty, if this target is FS folder and drop is allowed */ + bool need_Send = false; + if ( info.FuncType == k_DragTargetMode_Enter + || info.FuncType == k_DragTargetMode_Over + || (info.FuncType == k_DragTargetMode_Drop_Begin + // && targetOp_Cmd != NDragMenu::k_None + && info.Cmd_Type != NDragMenu::k_Cancel)) + // if (!g_CreateArchive_for_Drag_from_7zip) + need_Send = m_DropIsAllowed && m_PanelDropIsAllowed && IsFsFolderPath(); + m_TargetPath_WasSent_ToDataObject = SendToSource_TargetPath_enable(dataObject, need_Send); + SendToSource_TransferInfo(dataObject, info); +} + + +bool CDropTarget::SendToSource_TransferInfo(IDataObject *dataObject, + const CTargetTransferInfo &info) +{ + m_Transfer_WasSent_ToDataObject = false; + PRF("CDropTarget::SendToSource_TransferInfo"); + + if (!dataObject || m_Format_7zip_SetTransfer == 0) + return false; + FORMATETC etc = INIT_FORMATETC_HGLOBAL((CLIPFORMAT)m_Format_7zip_SetTransfer); + STGMEDIUM medium; + medium.tymed = etc.tymed; + medium.pUnkForRelease = NULL; + CDataObject_SetTransfer transfer; + const size_t size = sizeof(transfer); // + (1 << 19) // for debug + // OutputDebugString("GlobalAlloc"); + medium.hGlobal = GlobalAlloc(GHND | GMEM_SHARE, size); + // Sleep(1000); + if (!medium.hGlobal) + return false; + // OutputDebugString("GlobalLock"); + void *dest = (wchar_t *)GlobalLock(medium.hGlobal); + // Sleep(1000); + bool res = false; + if (dest) { + transfer.Init(); + transfer.Target = info; + + memcpy(dest, &transfer, sizeof(transfer)); GlobalUnlock(medium.hGlobal); + // OutputDebugString("m_DataObject->SetData"); + const BOOL release = FALSE; // that way is more simple for correct releasing. + // TRUE; // for debug : is not good for some cases + const HRESULT hres = dataObject->SetData(&etc, &medium, release); + res = (hres == S_OK); + } + + ReleaseStgMedium(&medium); + if (res) + m_Transfer_WasSent_ToDataObject = true; + return res; +} + + +bool CDropTarget::SendToSource_UInt32(IDataObject *dataObject, UINT format, UInt32 value) +{ + PRF("CDropTarget::Send_UInt32 (Performed)"); + + if (!dataObject || format == 0) + return false; + FORMATETC etc = INIT_FORMATETC_HGLOBAL((CLIPFORMAT)format); + STGMEDIUM medium; + medium.tymed = etc.tymed; + medium.pUnkForRelease = NULL; + const size_t size = 4; + medium.hGlobal = GlobalAlloc(GHND | GMEM_SHARE, size); + if (!medium.hGlobal) return false; + void *dest = GlobalLock(medium.hGlobal); + bool res = false; + if (dest) + { + *(UInt32 *)dest = value; + GlobalUnlock(medium.hGlobal); + // OutputDebugString("m_DataObject->SetData"); + const BOOL release = TRUE; + // FALSE; // for debug + /* If DropSource is Win10-Explorer, then (release == FALSE) doesn't work + and dataObject->SetData() returns E_NOTIMPL; + So we use release = TRUE; here */ + const HRESULT hres = dataObject->SetData(&etc, &medium, release); + // we return here without calling ReleaseStgMedium(). + return (hres == S_OK); + // Sleep(1000); + /* + if (we use release = TRUE), we expect that + - SetData() will release medium, and + - SetData() will set STGMEDIUM::tymed to (TYMED_NULL = 0). + but some "incorrect" SetData() implementations can keep STGMEDIUM::tymed unchanged. + And it's not safe to call ReleaseStgMedium() here for that case, + because DropSource also could release medium. + We can reset (medium.tymed = TYMED_NULL) manually here to disable + unsafe medium releasing in ReleaseStgMedium(). + */ + /* + if (release) + { + medium.tymed = TYMED_NULL; + medium.pUnkForRelease = NULL; + medium.hGlobal = NULL; + } + res = (hres == S_OK); + */ } - MyStringCopy(dest, (const wchar_t *)path); - GlobalUnlock(medium.hGlobal); - bool res = m_DataObject->SetData(&etc, &medium, FALSE) == S_OK; - GlobalFree(medium.hGlobal); + ReleaseStgMedium(&medium); return res; } -bool CDropTarget::SetPath() + +void CDropTarget::LoadNames_From_DataObject(IDataObject *dataObject) { - m_SetPathIsOK = SetPath(m_DropIsAllowed && m_PanelDropIsAllowed && IsFsFolderPath()); - return m_SetPathIsOK; + // "\\\\.\\" prefix is possible for long names + m_DropIsAllowed = NShell::DataObject_GetData_HDROP_or_IDLIST_Names(dataObject, m_SourcePaths) == S_OK; } -STDMETHODIMP CDropTarget::DragEnter(IDataObject * dataObject, DWORD keyState, - POINTL pt, DWORD *effect) + +Z7_COMWF_B CDropTarget::DragEnter(IDataObject *dataObject, DWORD keyState, POINTL pt, DWORD *effect) { - GetNamesFromDataObject(dataObject, m_SourcePaths); - QueryGetData(dataObject); + /* *(effect): + - on input : value of the dwOKEffects parameter of the DoDragDrop() function. + - on return : must contain one of the DROPEFFECT flags, which indicates + what the result of the drop operation would be. + (pt): the current cursor coordinates in screen coordinates. + */ + PRF_(Print_Point("CDropTarget::DragEnter", keyState, pt, *effect)) + try { + + if ((keyState & (MK_RBUTTON | MK_MBUTTON)) != 0) + m_IsRightButton = true; + + LoadNames_From_DataObject(dataObject); + // Try_QueryGetData(dataObject); + // we will use (m_DataObject) later in DragOver() and DragLeave(). m_DataObject = dataObject; - return DragOver(keyState, pt, effect); + // return DragOver(keyState, pt, effect); + PositionCursor(pt); + CTargetTransferInfo target; + target.FuncType = k_DragTargetMode_Enter; + target.KeyState = keyState; + target.Point = pt; + target.OkEffects = *effect; + SendToSource_Drag(target); + + CDataObject_GetTransfer transfer; + m_GetTransfer_WasSuccess = DataObject_GetData_GetTransfer( + dataObject, m_Format_7zip_GetTransfer, transfer); + if (m_GetTransfer_WasSuccess) + { + if (transfer.Flags & k_SourceFlags_LeftButton) + m_IsRightButton = false; + else if (transfer.Flags & k_SourceFlags_RightButton) + m_IsRightButton = true; + } + + *effect = GetEffect(keyState, pt, *effect); + return S_OK; + } catch(...) { return E_FAIL; } } -STDMETHODIMP CDropTarget::DragOver(DWORD keyState, POINTL pt, DWORD *effect) +Z7_COMWF_B CDropTarget::DragOver(DWORD keyState, POINTL pt, DWORD *effect) { + PRF_(Print_Point("CDropTarget::DragOver", keyState, pt, *effect)) + /* + For efficiency reasons, a data object is not passed in IDropTarget::DragOver. + The data object passed in the most recent call to IDropTarget::DragEnter + is available and can be used. + + When IDropTarget::DragOver has completed its operation, the DoDragDrop + function calls IDropSource::GiveFeedback so the source application can display + the appropriate visual feedback to the user. + */ + /* + we suppose that it's unexpected that (keyState) shows that mouse + button is not pressed, because such cases will be processed by + IDropSource::QueryContinueDrag() that returns DRAGDROP_S_DROP or DRAGDROP_S_CANCEL. + So DragOver() will not be called. + */ + + if ((keyState & MK_LBUTTON) == 0) + { + PRF4("CDropTarget::DragOver() (keyState & MK_LBUTTON) == 0"); + // g_Debug = true; + } + + try { + /* we suppose that source names were not changed after DragEnter() + so we don't request GetNames_From_DataObject() for each call of DragOver() */ PositionCursor(pt); - SetPath(); + CTargetTransferInfo target; + target.FuncType = k_DragTargetMode_Over; + target.KeyState = keyState; + target.Point = pt; + target.OkEffects = *effect; + SendToSource_Drag(target); *effect = GetEffect(keyState, pt, *effect); + // *effect = 1 << 8; // for debug return S_OK; + } catch(...) { return E_FAIL; } } -STDMETHODIMP CDropTarget::DragLeave() +Z7_COMWF_B CDropTarget::DragLeave() { + PRF4("CDropTarget::DragLeave"); + try { RemoveSelection(); - SetPath(false); - m_DataObject.Release(); + // we send empty TargetPath to 7-Zip Source to clear value of TargetPath that was sent before + + CTargetTransferInfo target; + target.FuncType = k_DragTargetMode_Leave; + /* + target.KeyState = 0; + target.Point = pt; + pt.x = 0; // -1 + pt.y = 0; // -1 + target.Effect = 0; + */ + SendToSource_Drag(target); + ClearState(); return S_OK; + } catch(...) { return E_FAIL; } } -// We suppose that there was ::DragOver for same POINTL_pt before ::Drop -// So SetPath() is same as in Drop. -STDMETHODIMP CDropTarget::Drop(IDataObject *dataObject, DWORD keyState, - POINTL pt, DWORD * effect) +static unsigned Drag_OnContextMenu(int xPos, int yPos, UInt32 cmdFlags); + +/* + We suppose that there was DragEnter/DragOver for same (POINTL pt) before Drop(). + But we can work without DragEnter/DragOver too. +*/ +Z7_COMWF_B CDropTarget::Drop(IDataObject *dataObject, DWORD keyState, + POINTL pt, DWORD *effect) { - QueryGetData(dataObject); + PRF_(Print_Point("CDropTarget::Drop", keyState, pt, *effect)) + /* Drop() is called after SourceDrop::QueryContinueDrag() returned DRAGDROP_S_DROP. + So it's possible that Source have done some operations already. + */ + HRESULT hres = S_OK; + bool needDrop_by_Source = false; + DWORD opEffect = DROPEFFECT_NONE; + + try { + // we don't need m_DataObject reference anymore, because we use local (dataObject) + m_DataObject.Release(); + + /* in normal case : we called LoadNames_From_DataObject() in DragEnter() already. + But if by some reason DragEnter() was not called, + we need to call LoadNames_From_DataObject() before PositionCursor(). + */ + if (!m_DropIsAllowed) LoadNames_From_DataObject(dataObject); PositionCursor(pt); - m_DataObject = dataObject; - bool needDrop = true; - if (m_DropIsAllowed && m_PanelDropIsAllowed) - if (IsFsFolderPath()) - needDrop = !SetPath(); - *effect = GetEffect(keyState, pt, *effect); - if (m_DropIsAllowed && m_PanelDropIsAllowed) + + CPanel::CDisableTimerProcessing2 disableTimerProcessing(m_Panel); + // CDisableNotify disableNotify2(m_Panel); + + UInt32 cmd = NDragMenu::k_None; + UInt32 cmdEffect = DROPEFFECT_NONE; + bool menu_WasShown = false; + if (m_IsRightButton && m_Panel) + { + UInt32 flagsMask; + if (m_Panel->IsArcFolder()) + flagsMask = (UInt32)1 << NDragMenu::k_Copy_ToArc; + else + { + flagsMask = (UInt32)1 << NDragMenu::k_AddToArc; + if (IsFsFolderPath()) + flagsMask |= (UInt32)1 << NDragMenu::k_Copy_Base; + } + // flagsMask |= (UInt32)1 << NDragMenu::k_Cancel; + const UInt32 cmd32 = Drag_OnContextMenu(pt.x, pt.y, flagsMask); + cmd = cmd32 & NDragMenu::k_MenuFlags_CmdMask; + if (cmd32 & NDragMenu::k_MenuFlag_Copy) + cmdEffect = DROPEFFECT_COPY; + else if (cmd32 & NDragMenu::k_MenuFlag_Move) + cmdEffect = DROPEFFECT_MOVE; + opEffect = cmdEffect; + menu_WasShown = true; + } + else + { + opEffect = GetEffect(keyState, pt, *effect); + if (m_IsAppTarget) + cmd = NDragMenu::k_AddToArc; + else if (m_Panel) + { + if (IsFsFolderPath()) + { + const bool is7zip = m_TargetPath_WasSent_ToDataObject; + bool createNewArchive = false; + if (is7zip) + createNewArchive = false; // g_CreateArchive_for_Drag_from_7zip; + else + createNewArchive = true; // g_CreateArchive_for_Drag_from_Explorer; + + if (createNewArchive) + cmd = NDragMenu::k_AddToArc; + else + { + if (opEffect != 0) + cmd = NDragMenu::k_Copy_Base; + cmdEffect = opEffect; + } + } + else + { + /* if we are inside open archive: + if archive support operations -> we will call operations + if archive doesn't support operations -> we will create new archove + */ + if (m_Panel->IsArcFolder() + || m_Panel->DoesItSupportOperations()) + { + cmd = NDragMenu::k_Copy_ToArc; + // we don't want move to archive operation here. + // so we force to DROPEFFECT_COPY. + if (opEffect != DROPEFFECT_NONE) + opEffect = DROPEFFECT_COPY; + cmdEffect = opEffect; + } + else + cmd = NDragMenu::k_AddToArc; + } + } + } + + if (cmd == 0) + cmd = NDragMenu::k_AddToArc; + + if (cmd == NDragMenu::k_AddToArc) + { + opEffect = DROPEFFECT_COPY; + cmdEffect = DROPEFFECT_COPY; + } + + if (m_Panel) + if (cmd == NDragMenu::k_Copy_ToArc) + { + const UString title = LangString(IDS_CONFIRM_FILE_COPY); + UString s = LangString(cmdEffect == DROPEFFECT_MOVE ? + IDS_MOVE_TO : IDS_COPY_TO); + s.Add_LF(); + s += "\'"; + s += m_Panel->_currentFolderPrefix; + s += "\'"; + s.Add_LF(); + s += LangString(IDS_WANT_TO_COPY_FILES); + s += " ?"; + const int res = ::MessageBoxW(*m_Panel, s, title, MB_YESNOCANCEL | MB_ICONQUESTION); + if (res != IDYES) + cmd = NDragMenu::k_Cancel; + } + + CTargetTransferInfo target; + target.FuncType = k_DragTargetMode_Drop_Begin; + target.KeyState = keyState; + target.Point = pt; + target.OkEffects = *effect; + target.Flags = 0; + + target.Cmd_Effect = cmdEffect; + target.Cmd_Type = cmd; + target.FolderType = GetFolderType(); + + if (cmd == NDragMenu::k_Cancel) + target.Flags |= k_TargetFlags_WasCanceled; + if (menu_WasShown) + target.Flags |= k_TargetFlags_MenuWasShown; + + SendToSource_auto(dataObject, target); + + CDataObject_GetTransfer transfer; + m_GetTransfer_WasSuccess = DataObject_GetData_GetTransfer( + dataObject, m_Format_7zip_GetTransfer, transfer); + + /* The Source (for example, 7-zip) could change file names when drop was confirmed. + So we must reload source file paths here */ + if (cmd != NDragMenu::k_Cancel) + LoadNames_From_DataObject(dataObject); + + if (cmd == NDragMenu::k_Cancel) + { + opEffect = DROPEFFECT_NONE; + cmdEffect = DROPEFFECT_NONE; + } + else { - if (needDrop) + if (m_GetTransfer_WasSuccess) + needDrop_by_Source = ((transfer.Flags & k_SourceFlags_DoNotProcessInTarget) != 0); + if (!needDrop_by_Source) { - UString path = GetTargetPath(); - if (m_IsAppTarget && m_Panel) - if (m_Panel->IsFSFolder()) - path = m_Panel->GetFsPath(); - m_Panel->DropObject(dataObject, path); + bool moveMode = (cmdEffect == DROPEFFECT_MOVE); + bool needDrop = false; + if (m_IsRightButton && m_Panel) + needDrop = true; + if (m_DropIsAllowed && m_PanelDropIsAllowed) + { + /* if non-empty TargetPath was sent successfully to DataObject, + then the Source is 7-Zip, and that 7zip-Source can copy to FS operation. + So we can disable Drop operation here for such case. + */ + needDrop_by_Source = (cmd != NDragMenu::k_AddToArc + && m_TargetPath_WasSent_ToDataObject + && m_TargetPath_NonEmpty_WasSent_ToDataObject); + needDrop = !(needDrop_by_Source); + } + if (needDrop) + { + UString path = GetTargetPath(); + if (m_IsAppTarget && m_Panel) + if (m_Panel->IsFSFolder()) + path = m_Panel->GetFsPath(); + + UInt32 sourceFlags = 0; + if (m_GetTransfer_WasSuccess) + sourceFlags = transfer.Flags; + + if (menu_WasShown) + target.Flags |= k_TargetFlags_MenuWasShown; + + target.Flags |= k_TargetFlags_WasProcessed; + + RemoveSelection(); + // disableTimerProcessing.Restore(); + m_Panel->CompressDropFiles(m_SourcePaths, path, + (cmd == NDragMenu::k_AddToArc), // createNewArchive, + moveMode, sourceFlags, + target.Flags + ); + } } + } // end of if (cmd != NDragMenu::k_Cancel) + { + /* note that, if (we send CFSTR_PERFORMEDDROPEFFECT as DROPEFFECT_MOVE + and Drop() returns (*effect == DROPEFFECT_MOVE), then + Win10-Explorer-Source will try to remove files just after Drop() exit. + But our CompressFiles() could be run without waiting finishing. + DOCs say, that we must send CFSTR_PERFORMEDDROPEFFECT + - DROPEFFECT_NONE : for optimized move + - DROPEFFECT_MOVE : for unoptimized move. + But actually Win10-Explorer-Target sends (DROPEFFECT_MOVE) for move operation. + And it still works as in optimized mode, because "unoptimized" deleting by Source will be performed + if both conditions are met: + 1) DROPEFFECT_MOVE is sent to (CFSTR_PERFORMEDDROPEFFECT) and + 2) (*effect == DROPEFFECT_MOVE) is returend by Drop(). + We don't want to send DROPEFFECT_MOVE here to protect from + deleting file by Win10-Explorer. + We are not sure that allfile fieree processed by move. + */ + + // for debug: we test the case when source tries to delete original files + // bool res; + // only CFSTR_PERFORMEDDROPEFFECT affects file removing in Win10-Explorer. + // res = SendToSource_UInt32(dataObject, RegisterClipboardFormat(CFSTR_LOGICALPERFORMEDDROPEFFECT), DROPEFFECT_MOVE); // for debug + /* res = */ SendToSource_UInt32(dataObject, + RegisterClipboardFormat(CFSTR_PERFORMEDDROPEFFECT), + cmd == NDragMenu::k_Cancel ? DROPEFFECT_NONE : DROPEFFECT_COPY); + // res = res; } RemoveSelection(); - m_DataObject.Release(); - return S_OK; -} -void CPanel::DropObject(IDataObject *dataObject, const UString &folderPath) -{ - UStringVector names; - GetNamesFromDataObject(dataObject, names); - CompressDropFiles(names, folderPath); -} + target.FuncType = k_DragTargetMode_Drop_End; + target.Cmd_Type = cmd; + if (needDrop_by_Source) + target.Flags |= k_TargetFlags_MustBeProcessedBySource; -/* -void CPanel::CompressDropFiles(HDROP dr) -{ - UStringVector fileNames; + SendToSource_TransferInfo(dataObject, target); + } catch(...) { hres = E_FAIL; } + + ClearState(); + // *effect |= (1 << 10); // for debug + // *effect = DROPEFFECT_COPY; // for debug + + /* + if we return (*effect == DROPEFFECT_MOVE) here, + Explorer-Source at some conditions can treat it as (unoptimized move) mode, + and Explorer-Source will remove source files after DoDragDrop() + in that (unoptimized move) mode. + We want to avoid such (unoptimized move) cases. + So we don't return (*effect == DROPEFFECT_MOVE), here if Source is not 7-Zip. + If source is 7-Zip that will do acual opeartion, then we can return DROPEFFECT_MOVE. + */ + if (hres != S_OK || (opEffect == DROPEFFECT_MOVE && !needDrop_by_Source)) { - NShell::CDrop drop(true); - drop.Attach(dr); - drop.QueryFileNames(fileNames); + // opEffect = opEffect; + // opEffect = DROPEFFECT_NONE; // for debug disabled } - CompressDropFiles(fileNamesUnicode); + + *effect = opEffect; + /* if (hres < 0), DoDragDrop() also will return (hres). + if (hres >= 0), DoDragDrop() will return DRAGDROP_S_DROP; + */ + return hres; } -*/ -static bool IsFolderInTemp(const FString &path) + + +// ---------- CPanel ---------- + + +static bool Is_Path1_Prefixed_by_Path2(const UString &path, const UString &prefix) { - FString tempPath; - if (!MyGetTempPath(tempPath)) + const unsigned len = prefix.Len(); + if (path.Len() < len) return false; - if (tempPath.IsEmpty()) + return CompareFileNames(path.Left(len), prefix) == 0; +} + +static bool IsFolderInTemp(const UString &path) +{ + FString tempPathF; + if (!MyGetTempPath(tempPathF)) return false; - unsigned len = tempPath.Len(); - if (path.Len() < len) + const UString tempPath = fs2us(tempPathF); + if (tempPath.IsEmpty()) return false; - return CompareFileNames(path.Left(len), tempPath) == 0; + return Is_Path1_Prefixed_by_Path2(path, tempPath); } -static bool AreThereNamesFromTemp(const UStringVector &fileNames) +static bool AreThereNamesFromTemp(const UStringVector &filePaths) { FString tempPathF; if (!MyGetTempPath(tempPathF)) return false; - UString tempPath = fs2us(tempPathF); + const UString tempPath = fs2us(tempPathF); if (tempPath.IsEmpty()) return false; - FOR_VECTOR (i, fileNames) - if (fileNames[i].IsPrefixedBy_NoCase(tempPath)) + FOR_VECTOR (i, filePaths) + if (Is_Path1_Prefixed_by_Path2(filePaths[i], tempPath)) return true; return false; } -void CPanel::CompressDropFiles(const UStringVector &fileNames, const UString &folderPath) + +/* + empty folderPath means create new Archive to path of first fileName. + createNewArchive == true : show "Add to archive ..." dialog with external program + folderPath.IsEmpty() : create archive in folder of filePaths[0]. + createNewArchive == false : + folderPath.IsEmpty() : copy to archive folder that is open in panel + !folderPath.IsEmpty() : CopyFsItems() to folderPath. +*/ +void CPanel::CompressDropFiles( + const UStringVector &filePaths, + const UString &folderPath, + bool createNewArchive, + bool moveMode, + UInt32 sourceFlags, + UInt32 &targetFlags + ) { - if (fileNames.Size() == 0) + if (filePaths.Size() == 0) return; - bool createNewArchive = true; - if (!IsFSFolder()) - createNewArchive = !DoesItSupportOperations(); + // createNewArchive = false; // for debug if (createNewArchive) { UString folderPath2 = folderPath; + // folderPath2.Empty(); // for debug if (folderPath2.IsEmpty()) { - FString folderPath2F; - GetOnlyDirPrefix(us2fs(fileNames.Front()), folderPath2F); - folderPath2 = fs2us(folderPath2F); - if (IsFolderInTemp(folderPath2F)) + { + FString folderPath2F; + GetOnlyDirPrefix(us2fs(filePaths.Front()), folderPath2F); + folderPath2 = fs2us(folderPath2F); + } + if (IsFolderInTemp(folderPath2)) + { + /* we don't want archive to be created in temp directory. + so we change the path to root folder (non-temp) */ folderPath2 = ROOT_FS_FOLDER; + } } + + UString arcName_base; + const UString arcName = CreateArchiveName(filePaths, + false, // isHash + NULL, // CFileInfo *fi + arcName_base); - const UString arcName = CreateArchiveName(fileNames); - - CompressFiles(folderPath2, arcName, L"", - true, // addExtension - fileNames, - false, // email - true, // showDialog - AreThereNamesFromTemp(fileNames) // waitFinish - ); + bool needWait; + if (sourceFlags & k_SourceFlags_WaitFinish) + needWait = true; + else if (sourceFlags & k_SourceFlags_DoNotWaitFinish) + needWait = false; + else if (sourceFlags & k_SourceFlags_TempFiles) + needWait = true; + else + needWait = AreThereNamesFromTemp(filePaths); + + targetFlags |= (needWait ? + k_TargetFlags_WaitFinish : + k_TargetFlags_DoNotWaitFinish); + + CompressFiles(folderPath2, arcName, + L"", // arcType + true, // addExtension + filePaths, + false, // email + true, // showDialog + needWait); } else - CopyFromAsk(fileNames); + { + targetFlags |= k_TargetFlags_WaitFinish; + if (!folderPath.IsEmpty()) + { + CCopyToOptions options; + options.moveMode = moveMode; + options.folder = folderPath; + options.showErrorMessages = true; // showErrorMessages is not used for this operation + options.NeedRegistryZone = false; + options.ZoneIdMode = NExtract::NZoneIdMode::kNone; + // maybe we need more options here: FIXME + /* HRESULT hres = */ CopyFsItems(options, + filePaths, + NULL // UStringVector *messages + ); + // hres = hres; + } + else + { + CopyFromNoAsk(moveMode, filePaths); + } + } +} + + + +static unsigned Drag_OnContextMenu(int xPos, int yPos, UInt32 cmdFlags) +{ + CMenu menu; + CMenuDestroyer menuDestroyer(menu); + /* + Esc key in shown menu doesn't work if we call Drag_OnContextMenu from ::Drop(). + We call SetFocus() tp solve that problem. + But the focus will be changed to Target Window after Drag and Drop. + Is it OK to use SetFocus() here ? + Is there another way to enable Esc key ? + */ + // _listView.SetFocus(); // for debug + ::SetFocus(g_HWND); + menu.CreatePopup(); + /* + int defaultCmd; // = NDragMenu::k_Move; + defaultCmd = NDragMenu::k_None; + */ + for (unsigned i = 0; i < Z7_ARRAY_SIZE(NDragMenu::g_Pairs); i++) + { + const NDragMenu::CCmdLangPair &pair = NDragMenu::g_Pairs[i]; + const UInt32 cmdAndFlags = pair.CmdId_and_Flags; + const UInt32 cmdId = cmdAndFlags & NDragMenu::k_MenuFlags_CmdMask; + if (cmdId != NDragMenu::k_Cancel) + if ((cmdFlags & ((UInt32)1 << cmdId)) == 0) + continue; + const UINT flags = MF_STRING; + /* + if (prop.IsVisible) + flags |= MF_CHECKED; + if (i == 0) + flags |= MF_GRAYED; + */ + // MF_DEFAULT doesn't work + // if (i == 2) flags |= MF_DEFAULT; + // if (i == 4) flags |= MF_HILITE; + // if (cmd == defaultCmd) flags |= MF_HILITE; + UString name = LangString(pair.LangId); + if (name.IsEmpty()) + { + if (cmdId == NDragMenu::k_Cancel) + name = "Cancel"; + else + name.Add_UInt32(pair.LangId); + } + if (cmdId == NDragMenu::k_Copy_ToArc) + { + // UString destPath = _currentFolderPrefix; + /* + UString destPath = LangString(IDS_CONTEXT_ARCHIVE); + name = MyFormatNew(name, destPath); + */ + name.Add_Space(); + name += LangString(IDS_CONTEXT_ARCHIVE); + } + if (cmdId == NDragMenu::k_Cancel) + menu.AppendItem(MF_SEPARATOR, 0, (LPCTSTR)NULL); + menu.AppendItem(flags, cmdAndFlags, name); + } + /* + if (defaultCmd != 0) + SetMenuDefaultItem(menu, (unsigned)defaultCmd, + FALSE); // byPos + */ + int menuResult = menu.Track( + TPM_LEFTALIGN | TPM_RETURNCMD | TPM_NONOTIFY, + xPos, yPos, + g_HWND + // _listView // for debug + ); + /* menu.Track() return value is zero, if the user cancels + the menu without making a selection, or if an error occurs */ + if (menuResult <= 0) + menuResult = NDragMenu::k_Cancel; + return (unsigned)menuResult; +} + + + +void CApp::CreateDragTarget() +{ + _dropTargetSpec = new CDropTarget(); + _dropTarget = _dropTargetSpec; + _dropTargetSpec->App = (this); +} + +void CApp::SetFocusedPanel(unsigned index) +{ + LastFocusedPanel = index; + _dropTargetSpec->TargetPanelIndex = (int)LastFocusedPanel; +} + +void CApp::DragBegin(unsigned panelIndex) +{ + _dropTargetSpec->TargetPanelIndex = (int)(NumPanels > 1 ? 1 - panelIndex : panelIndex); + _dropTargetSpec->SrcPanelIndex = (int)panelIndex; +} + +void CApp::DragEnd() +{ + _dropTargetSpec->TargetPanelIndex = (int)LastFocusedPanel; + _dropTargetSpec->SrcPanelIndex = -1; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelFolderChange.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelFolderChange.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelFolderChange.cpp 2021-01-24 14:21:41.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelFolderChange.cpp 2023-01-22 07:00:00.000000000 +0000 @@ -133,8 +133,9 @@ CloseOpenFolders(); UString sysPath = path; - - unsigned prefixSize = NName::GetRootPrefixSize(sysPath); + /* we will Empty() sysPath variable, if we need to BindToFolder() + directly with (path) variable */ + const unsigned prefixSize = NName::GetRootPrefixSize(sysPath); if (prefixSize == 0 || sysPath[prefixSize] == 0) sysPath.Empty(); @@ -142,6 +143,7 @@ if (!sysPath.IsEmpty() && sysPath.Back() == ':' && (sysPath.Len() != 2 || !NName::IsDrivePath2(sysPath))) { + // if base item for alt streams prefix "base:" exists, we will use it UString baseFile = sysPath; baseFile.DeleteBack(); if (NFind::DoesFileOrDirExist(us2fs(baseFile))) @@ -153,22 +155,50 @@ while (!sysPath.IsEmpty()) { + if (sysPath.Len() <= prefixSize) + { + path.DeleteFrom(prefixSize); + sysPath.Empty(); + break; + } + + fileInfo.ClearBase(); + if (IsPathSepar(sysPath.Back())) + { + /* Windows 10 by default doesn't allow look "Local Settings" that is junction to "AppData\Local", + but it does allow look "Local Settings\Temp\*" + 22.02: at first we try to use paths with slashes "path\" */ + CFileInfo fi; + // CFindFile findFile; + // FString path2 = us2fs(sysPath); + // path2 += '*'; // CHAR_ANY_MASK; + // if (findFile.FindFirst(path2, fi)) + CEnumerator enumerator; + enumerator.SetDirPrefix(us2fs(sysPath)); + bool found = false; + if (enumerator.Next(fi, found)) + { + // sysPath.DeleteBack(); + fileInfo.SetAsDir(); + fileInfo.Size = 0; + fileInfo.Name.Empty(); + break; + } + sysPath.DeleteBack(); + continue; + } + if (fileInfo.Find(us2fs(sysPath))) break; int pos = sysPath.ReverseFind_PathSepar(); if (pos < 0) + { sysPath.Empty(); - else + break; + } { - /* - if (reducedParts.Size() > 0 || pos < (int)sysPath.Len() - 1) - reducedParts.Add(sysPath.Ptr(pos + 1)); - */ - #if defined(_WIN32) && !defined(UNDER_CE) - if (pos == 2 && NName::IsDrivePath2(sysPath) && sysPath.Len() > 3) + if ((unsigned)pos != sysPath.Len() - 1) pos++; - #endif - sysPath.DeleteFrom((unsigned)pos); } } @@ -225,7 +255,7 @@ _folder->BindToFolder(fs2us(dirPrefix), &newFolder); else { - RINOK(res); + RINOK(res) openRes.ArchiveIsOpened = true; _parentFolders.Back().ParentFolderPath = fs2us(dirPrefix); path.DeleteFrontal(sysPath.Len()); @@ -248,12 +278,12 @@ for (unsigned curPos = 0; curPos != path.Len();) { UString s = path.Ptr(curPos); - int slashPos = NName::FindSepar(s); + const int slashPos = NName::FindSepar(s); unsigned skipLen = s.Len(); if (slashPos >= 0) { s.DeleteFrom((unsigned)slashPos); - skipLen = slashPos + 1; + skipLen = (unsigned)slashPos + 1; } CMyComPtr newFolder; @@ -262,13 +292,13 @@ curPos += skipLen; else if (_folderAltStreams) { - int pos = s.Find(L':'); + const int pos = s.Find(L':'); if (pos >= 0) { UString baseName = s; baseName.DeleteFrom((unsigned)pos); if (_folderAltStreams->BindToAltStreams(baseName, &newFolder) == S_OK && newFolder) - curPos += pos + 1; + curPos += (unsigned)pos + 1; } } @@ -516,14 +546,18 @@ pathParts.DeleteBack(); for (i = 0; i < pathParts.Size(); i++) { - UString name = pathParts[i]; + const UString name = pathParts[i]; sumPass += name; sumPass.Add_PathSepar(); CFileInfo info; DWORD attrib = FILE_ATTRIBUTE_DIRECTORY; if (info.Find(us2fs(sumPass))) attrib = info.Attrib; - AddComboBoxItem(name.IsEmpty() ? L"\\" : name, GetRealIconIndex(us2fs(sumPass), attrib), i, false); + AddComboBoxItem( + name.IsEmpty() ? L"\\" : name, + GetRealIconIndex(us2fs(sumPass), attrib), + (int)i, // iIndent + false); // addToList ComboBoxPaths.Add(sumPass); } @@ -633,7 +667,7 @@ if (listViewDialog.StringsWereChanged) { _appState->FolderHistory.RemoveAll(); - for (int i = listViewDialog.Strings.Size() - 1; i >= 0; i--) + for (int i = (int)listViewDialog.Strings.Size() - 1; i >= 0; i--) _appState->FolderHistory.AddString(listViewDialog.Strings[i]); if (listViewDialog.FocusedItemIndex >= 0) selectString = listViewDialog.Strings[listViewDialog.FocusedItemIndex]; @@ -695,12 +729,12 @@ if (focusedName != L"\\\\." && focusedName != L"\\\\?") { - int pos = focusedName.ReverseFind_PathSepar(); + const int pos = focusedName.ReverseFind_PathSepar(); if (pos >= 0) { parentFolderPrefix = focusedName; parentFolderPrefix.DeleteFrom((unsigned)(pos + 1)); - focusedName.DeleteFrontal(pos + 1); + focusedName.DeleteFrontal((unsigned)(pos + 1)); } } } @@ -812,7 +846,7 @@ RefreshListCtrl(); } -void CPanel::OpenFolder(int index) +void CPanel::OpenFolder(unsigned index) { if (index == kParentIndex) { @@ -820,7 +854,7 @@ return; } CMyComPtr newFolder; - HRESULT res = _folder->BindToFolder(index, &newFolder); + const HRESULT res = _folder->BindToFolder((unsigned)index, &newFolder); if (res != 0) { MessageBox_Error_HRESULT(res); @@ -839,17 +873,17 @@ void CPanel::OpenAltStreams() { CRecordVector indices; - GetOperatedItemIndices(indices); + Get_ItemIndices_Operated(indices); Int32 realIndex = -1; if (indices.Size() > 1) return; if (indices.Size() == 1) - realIndex = indices[0]; + realIndex = (Int32)indices[0]; if (_folderAltStreams) { CMyComPtr newFolder; - _folderAltStreams->BindToAltStreams(realIndex, &newFolder); + _folderAltStreams->BindToAltStreams((UInt32)realIndex, &newFolder); if (newFolder) { CDisableTimerProcessing disableTimerProcessing(*this); @@ -864,7 +898,7 @@ #if defined(_WIN32) && !defined(UNDER_CE) UString path; if (realIndex >= 0) - path = GetItemFullPath(realIndex); + path = GetItemFullPath((UInt32)realIndex); else { path = GetFsPath(); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/Panel.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/Panel.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/Panel.h 2022-05-31 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/Panel.h 2023-05-15 18:00:00.000000000 +0000 @@ -1,11 +1,15 @@ // Panel.h -#ifndef __PANEL_H -#define __PANEL_H +#ifndef ZIP7_INC_PANEL_H +#define ZIP7_INC_PANEL_H #include "../../../Common/MyWindows.h" +#if defined(__MINGW32__) || defined(__MINGW64__) +#include +#else #include +#endif #include "../../../../C/Alloc.h" @@ -47,7 +51,7 @@ const int kParentFolderID = 100; -const int kParentIndex = -1; +const unsigned kParentIndex = (unsigned)(int)-1; const UInt32 kParentIndex_UInt32 = (UInt32)(Int32)kParentIndex; #if !defined(_WIN32) || defined(UNDER_CE) @@ -56,7 +60,9 @@ #define ROOT_FS_FOLDER L"C:\\" #endif -struct CPanelCallback +Z7_PURE_INTERFACES_BEGIN + +DECLARE_INTERFACE(CPanelCallback) { virtual void OnTab() = 0; virtual void SetFocusToPath(unsigned index) = 0; @@ -68,6 +74,7 @@ virtual void DragEnd() = 0; virtual void RefreshTitle(bool always) = 0; }; +Z7_PURE_INTERFACES_END void PanelCopyItems(); @@ -116,7 +123,7 @@ { FOR_VECTOR (i, (*this)) if ((*this)[i].ID == id) - return i; + return (int)i; return -1; } @@ -194,11 +201,15 @@ class CPanel; -class CMyListView: public NWindows::NControl::CListView2 +class CMyListView Z7_final: public NWindows::NControl::CListView2 { + // ~CMyListView() ZIP7_eq_delete; + // CMyListView() ZIP7_eq_delete; public: + // CMyListView() {} + // ~CMyListView() Z7_DESTRUCTOR_override {} // change it CPanel *_panel; - LRESULT OnMessage(UINT message, WPARAM wParam, LPARAM lParam); + LRESULT OnMessage(UINT message, WPARAM wParam, LPARAM lParam) Z7_override; }; /* @@ -223,10 +234,16 @@ int FocusedItem; bool SelectFocused; bool FocusedName_Defined; + bool CalledFromTimer; UString FocusedName; UStringVector SelectedNames; - - CSelectedState(): FocusedItem(-1), SelectFocused(true), FocusedName_Defined(false) {} + + CSelectedState(): + FocusedItem(-1), + SelectFocused(true), + FocusedName_Defined(false), + CalledFromTimer(false) + {} }; #ifdef UNDER_CE @@ -286,21 +303,21 @@ -class CPanel: public NWindows::NControl::CWindow2 +class CPanel Z7_final: public NWindows::NControl::CWindow2 { CExtToIconMap _extToIconMap; UINT _baseID; - int _comboBoxID; + unsigned _comboBoxID; UINT _statusBarID; CAppState *_appState; - bool OnCommand(int code, int itemID, LPARAM lParam, LRESULT &result); - LRESULT OnMessage(UINT message, WPARAM wParam, LPARAM lParam); - virtual bool OnCreate(CREATESTRUCT *createStruct); - virtual bool OnSize(WPARAM wParam, int xSize, int ySize); - virtual void OnDestroy(); - virtual bool OnNotify(UINT controlID, LPNMHDR lParam, LRESULT &result); + virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM lParam, LRESULT &result) Z7_override; + virtual LRESULT OnMessage(UINT message, WPARAM wParam, LPARAM lParam) Z7_override; + virtual bool OnCreate(CREATESTRUCT *createStruct) Z7_override; + virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override; + virtual void OnDestroy() Z7_override; + virtual bool OnNotify(UINT controlID, LPNMHDR lParam, LRESULT &result) Z7_override; void AddComboBoxItem(const UString &name, int iconIndex, int indent, bool addToList); @@ -321,7 +338,7 @@ void OnItemChanged(NMLISTVIEW *item); void OnNotifyActivateItems(); bool OnNotifyList(LPNMHDR lParam, LRESULT &result); - void OnDrag(LPNMLISTVIEW nmListView); + void OnDrag(LPNMLISTVIEW nmListView, bool isRightButton = false); bool OnKeyDown(LPNMLVKEYDOWN keyDownInfo, LRESULT &result); BOOL OnBeginLabelEdit(LV_DISPINFOW * lpnmh); BOOL OnEndLabelEdit(LV_DISPINFOW * lpnmh); @@ -437,19 +454,19 @@ return (UInt32)item.lParam; } - int GetRealItemIndex(int indexInListView) const + unsigned GetRealItemIndex(int indexInListView) const { /* if (_virtualMode) return indexInListView; */ LPARAM param; - if (!_listView.GetItemParam(indexInListView, param)) + if (!_listView.GetItemParam((unsigned)indexInListView, param)) throw 1; - return (int)param; + return (unsigned)param; } - UInt32 _ListViewMode; + UInt32 _listViewMode; int _xSize; bool _flatMode; @@ -469,12 +486,19 @@ NWindows::NDLL::CLibrary _library; CMyComPtr _folder; + CBoolVector _isDirVector; CMyComPtr _folderCompare; CMyComPtr _folderGetItemName; CMyComPtr _folderRawProps; CMyComPtr _folderAltStreams; CMyComPtr _folderOperations; + + // for drag and drop highliting + int m_DropHighlighted_SelectionIndex; + // int m_SubFolderIndex; // realIndex of item in m_Panel list (if drop cursor to that item) + UString m_DropHighlighted_SubFolderName; // name of folder in m_Panel list (if drop cursor to that folder) + void ReleaseFolder(); void SetNewFolder(IFolderFolder *newFolder); @@ -485,22 +509,28 @@ void GetSelectedNames(UStringVector &selectedNames); void SaveSelectedState(CSelectedState &s); HRESULT RefreshListCtrl(const CSelectedState &s); - HRESULT RefreshListCtrl_SaveFocused(); + HRESULT RefreshListCtrl_SaveFocused(bool onTimer = false); + + // UInt32 GetItem_Attrib(UInt32 itemIndex) const; bool GetItem_BoolProp(UInt32 itemIndex, PROPID propID) const; - bool IsItem_Deleted(int itemIndex) const; - bool IsItem_Folder(int itemIndex) const; - bool IsItem_AltStream(int itemIndex) const; - - UString GetItemName(int itemIndex) const; - UString GetItemName_for_Copy(int itemIndex) const; - void GetItemName(int itemIndex, UString &s) const; - UString GetItemPrefix(int itemIndex) const; - UString GetItemRelPath(int itemIndex) const; - UString GetItemRelPath2(int itemIndex) const; - UString GetItemFullPath(int itemIndex) const; - UInt64 GetItem_UInt64Prop(int itemIndex, PROPID propID) const; - UInt64 GetItemSize(int itemIndex) const; + + bool IsItem_Deleted(unsigned itemIndex) const; + bool IsItem_Folder(unsigned itemIndex) const; + bool IsItem_AltStream(unsigned itemIndex) const; + + UString GetItemName(unsigned itemIndex) const; + UString GetItemName_for_Copy(unsigned itemIndex) const; + void GetItemName(unsigned itemIndex, UString &s) const; + UString GetItemPrefix(unsigned itemIndex) const; + UString GetItemRelPath(unsigned itemIndex) const; + UString GetItemRelPath2(unsigned itemIndex) const; + + void Add_ItemRelPath2_To_String(unsigned itemIndex, UString &s) const; + + UString GetItemFullPath(unsigned itemIndex) const; + UInt64 GetItem_UInt64Prop(unsigned itemIndex, PROPID propID) const; + UInt64 GetItemSize(unsigned itemIndex) const; //////////////////////// // PanelFolderChange.cpp @@ -552,7 +582,7 @@ _markDeletedItems(true), PanelCreated(false), - _ListViewMode(3), + _listViewMode(3), _xSize(300), _flatMode(false), @@ -565,6 +595,8 @@ _dontShowMode(false), + m_DropHighlighted_SelectionIndex(-1), + _needSaveInfo(false), _startGroupSelect(0), _selectionIsDefined(false) @@ -572,7 +604,7 @@ void SetExtendedStyle() { - if (_listView != 0) + if (_listView) _listView.SetExtendedListViewStyle(_exStyle); } @@ -592,30 +624,38 @@ void SetSortRawStatus(); void Release(); - ~CPanel(); + ~CPanel() Z7_DESTRUCTOR_override; void OnLeftClick(MY_NMLISTVIEW_NMITEMACTIVATE *itemActivate); bool OnRightClick(MY_NMLISTVIEW_NMITEMACTIVATE *itemActivate, LRESULT &result); void ShowColumnsContextMenu(int x, int y); void OnTimer(); - void OnReload(); + void OnReload(bool onTimer = false); bool OnContextMenu(HANDLE windowHandle, int xPos, int yPos); CMyComPtr _sevenZipContextMenu; CMyComPtr _systemContextMenu; + HRESULT CreateShellContextMenu( const CRecordVector &operatedIndices, CMyComPtr &systemContextMenu); + void CreateSystemMenu(HMENU menu, + bool showExtendedVerbs, const CRecordVector &operatedIndices, CMyComPtr &systemContextMenu); + void CreateSevenZipMenu(HMENU menu, + bool showExtendedVerbs, const CRecordVector &operatedIndices, + int firstDirIndex, CMyComPtr &sevenZipContextMenu); + void CreateFileMenu(HMENU menu, CMyComPtr &sevenZipContextMenu, CMyComPtr &systemContextMenu, bool programMenu); + void CreateFileMenu(HMENU menu); bool InvokePluginCommand(unsigned id); bool InvokePluginCommand(unsigned id, IContextMenu *sevenZipContextMenu, @@ -637,10 +677,10 @@ // void SortItems(int index); void SortItemsWithPropID(PROPID propID); - void GetSelectedItemsIndices(CRecordVector &indices) const; - void GetOperatedItemIndices(CRecordVector &indices) const; - void GetAllItemIndices(CRecordVector &indices) const; - void GetOperatedIndicesSmart(CRecordVector &indices) const; + void Get_ItemIndices_Selected(CRecordVector &indices) const; + void Get_ItemIndices_Operated(CRecordVector &indices) const; + void Get_ItemIndices_All(CRecordVector &indices) const; + void Get_ItemIndices_OperSmart(CRecordVector &indices) const; // void GetOperatedListViewIndices(CRecordVector &indices) const; void KillSelection(); @@ -712,12 +752,11 @@ class CDisableTimerProcessing { - CLASS_NO_COPY(CDisableTimerProcessing); + Z7_CLASS_NO_COPY(CDisableTimerProcessing) bool _processTimer; - CPanel &_panel; - + public: CDisableTimerProcessing(CPanel &panel): _panel(panel) { Disable(); } @@ -733,9 +772,38 @@ } }; + class CDisableTimerProcessing2 + { + Z7_CLASS_NO_COPY(CDisableTimerProcessing2) + + bool _processTimer; + CPanel *_panel; + + public: + + CDisableTimerProcessing2(CPanel *panel): _processTimer(true), _panel(panel) { Disable(); } + ~CDisableTimerProcessing2() { Restore(); } + void Disable() + { + if (_panel) + { + _processTimer = _panel->_processTimer; + _panel->_processTimer = false; + } + } + void Restore() + { + if (_panel) + { + _panel->_processTimer = _processTimer; + _panel = NULL; + } + } + }; + class CDisableNotify { - CLASS_NO_COPY(CDisableNotify); + Z7_CLASS_NO_COPY(CDisableNotify) bool _processNotify; bool _processStatusBar; @@ -789,9 +857,9 @@ void OpenFocusedItemAsInternal(const wchar_t *type = NULL); void OpenSelectedItems(bool internal); - void OpenFolderExternal(int index); + void OpenFolderExternal(unsigned index); - void OpenFolder(int index); + void OpenFolder(unsigned index); HRESULT OpenParentArchiveFolder(); HRESULT OpenAsArc(IInStream *inStream, @@ -810,26 +878,26 @@ HRESULT OpenAsArc_Name(const UString &relPath, const UString &arcFormat // , bool showErrorMessage ); - HRESULT OpenAsArc_Index(int index, const wchar_t *type /* = NULL */ + HRESULT OpenAsArc_Index(unsigned index, const wchar_t *type /* = NULL */ // , bool showErrorMessage ); - void OpenItemInArchive(int index, bool tryInternal, bool tryExternal, + void OpenItemInArchive(unsigned index, bool tryInternal, bool tryExternal, bool editMode, bool useEditor, const wchar_t *type = NULL); HRESULT OnOpenItemChanged(UInt32 index, const wchar_t *fullFilePath, bool usePassword, const UString &password); LRESULT OnOpenItemChanged(LPARAM lParam); bool IsVirus_Message(const UString &name); - void OpenItem(int index, bool tryInternal, bool tryExternal, const wchar_t *type = NULL); + void OpenItem(unsigned index, bool tryInternal, bool tryExternal, const wchar_t *type = NULL); void EditItem(bool useEditor); - void EditItem(int index, bool useEditor); + void EditItem(unsigned index, bool useEditor); void RenameFile(); void ChangeComment(); void SetListViewMode(UInt32 index); - UInt32 GetListViewMode() const { return _ListViewMode; } + UInt32 GetListViewMode() const { return _listViewMode; } PROPID GetSortID() const { return _sortID; } void ChangeFlatMode(); @@ -848,16 +916,21 @@ void AddToArchive(); - void GetFilePaths(const CRecordVector &indices, UStringVector &paths, bool allowFolders = false); + int FindDir_InOperatedList(const CRecordVector &indices) const; + void GetFilePaths(const CRecordVector &indices, UStringVector &paths) const; void ExtractArchives(); void TestArchives(); + HRESULT CopyTo(CCopyToOptions &options, const CRecordVector &indices, UStringVector *messages, - bool &usePassword, UString &password); + bool &usePassword, UString &password, + const UStringVector *filePaths = NULL); - HRESULT CopyTo(CCopyToOptions &options, const CRecordVector &indices, UStringVector *messages) + HRESULT CopyTo(CCopyToOptions &options, + const CRecordVector &indices, + UStringVector *messages) { bool usePassword = false; UString password; @@ -870,17 +943,29 @@ return CopyTo(options, indices, messages, usePassword, password); } + HRESULT CopyFsItems(CCopyToOptions &options, + const UStringVector &filePaths, + UStringVector *messages) + { + bool usePassword = false; + UString password; + CRecordVector indices; + return CopyTo(options, indices, messages, usePassword, password, &filePaths); + } + + HRESULT CopyFrom(bool moveMode, const UString &folderPrefix, const UStringVector &filePaths, bool showErrorMessages, UStringVector *messages); - void CopyFromNoAsk(const UStringVector &filePaths); - void CopyFromAsk(const UStringVector &filePaths); - - // empty folderPath means create new Archive to path of first fileName. - void DropObject(IDataObject * dataObject, const UString &folderPath); + void CopyFromNoAsk(bool moveMode, const UStringVector &filePaths); - // empty folderPath means create new Archive to path of first fileName. - void CompressDropFiles(const UStringVector &fileNames, const UString &folderPath); + void CompressDropFiles( + const UStringVector &filePaths, + const UString &folderPath, + bool createNewArchive, + bool moveMode, + UInt32 sourceFlags, + UInt32 &targetFlags); void RefreshTitle(bool always = false) { _panelCallback->RefreshTitle(always); } void RefreshTitleAlways() { RefreshTitle(true); } @@ -892,14 +977,14 @@ { void *_data; public: - CMyBuffer(): _data(0) {} + CMyBuffer(): _data(NULL) {} operator void *() { return _data; } bool Allocate(size_t size) { - if (_data != 0) + if (_data) return false; _data = ::MidAlloc(size); - return _data != 0; + return _data != NULL; } ~CMyBuffer() { ::MidFree(_data); } }; @@ -919,7 +1004,7 @@ throw 9387173; _needExit = true; _numActiveThreads = 0; - }; + } ~CExitEventLauncher() { Exit(true); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelItemOpen.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelItemOpen.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelItemOpen.cpp 2022-06-06 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelItemOpen.cpp 2023-03-20 12:00:00.000000000 +0000 @@ -68,7 +68,7 @@ { HANDLE _handle; public: - CProcessSnapshot(): _handle(INVALID_HANDLE_VALUE) {}; + CProcessSnapshot(): _handle(INVALID_HANDLE_VALUE) {} ~CProcessSnapshot() { Close(); } bool Close() @@ -136,7 +136,7 @@ void SetFromExtension(const char *ext) // ext must be low case { ProgNames.Clear(); - for (unsigned i = 0; i < ARRAY_SIZE(g_Progs); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Progs); i++) if (FindExtProg(g_Progs[i].Ext, ext)) { ProgNames.Add(g_Progs[i].Prog); @@ -220,22 +220,25 @@ const unsigned maxPath = 1024; WCHAR temp[maxPath + 1]; - const char *func_name = "GetProcessImageFileNameW"; - Func_GetProcessImageFileNameW my_func = (Func_GetProcessImageFileNameW) - (void *)::GetProcAddress(::GetModuleHandleA("kernel32.dll"), func_name); + const char *func_name = + "GetProcessImageFileNameW"; + Func_GetProcessImageFileNameW my_func = Z7_GET_PROC_ADDRESS( + Func_GetProcessImageFileNameW, ::GetModuleHandleA("kernel32.dll"), func_name); if (!my_func) { if (!g_Psapi_dll_module) g_Psapi_dll_module = LoadLibraryW(L"Psapi.dll"); if (g_Psapi_dll_module) - my_func = (Func_GetProcessImageFileNameW)(void *)::GetProcAddress(g_Psapi_dll_module, func_name); + my_func = Z7_GET_PROC_ADDRESS( + Func_GetProcessImageFileNameW, g_Psapi_dll_module, func_name); } if (my_func) { - // DWORD num = GetProcessImageFileNameW(hProcess, temp, maxPath); - DWORD num = my_func(hProcess, temp, maxPath); + const DWORD num = + // GetProcessImageFileNameW(hProcess, temp, maxPath); + my_func(hProcess, temp, maxPath); if (num != 0) path = temp; } @@ -318,11 +321,13 @@ void SetMainProcess(HANDLE h) { #ifndef UNDER_CE - - Func_GetProcessId func = (Func_GetProcessId)(void *)::GetProcAddress(::GetModuleHandleA("kernel32.dll"), "GetProcessId"); + const + Func_GetProcessId func = Z7_GET_PROC_ADDRESS( + Func_GetProcessId, ::GetModuleHandleA("kernel32.dll"), + "GetProcessId"); if (func) { - DWORD id = func(h); + const DWORD id = func(h); if (id != 0) _ids.AddToUniqueSorted(id); } @@ -462,7 +467,7 @@ else { if (!folderLink.FileInfo.Find(folderLink.FilePath)) - return ::GetLastError(); + return GetLastError_noZero_HRESULT(); if (folderLink.FileInfo.IsDir()) return S_FALSE; folderLink.IsVirtual = false; @@ -471,14 +476,14 @@ folderLink.VirtualPath = virtualFilePath; CFfpOpen ffp; - HRESULT res = ffp.OpenFileFolderPlugin(inStream, + const HRESULT res = ffp.OpenFileFolderPlugin(inStream, folderLink.FilePath.IsEmpty() ? us2fs(virtualFilePath) : folderLink.FilePath, arcFormat, GetParent()); openRes.Encrypted = ffp.Encrypted; openRes.ErrorMessage = ffp.ErrorMessage; - RINOK(res); + RINOK(res) folderLink.Password = ffp.Password; folderLink.UsePassword = ffp.Encrypted; @@ -571,7 +576,7 @@ } -HRESULT CPanel::OpenAsArc_Index(int index, const wchar_t *type +HRESULT CPanel::OpenAsArc_Index(unsigned index, const wchar_t *type // , bool showErrorMessage ) { @@ -653,36 +658,13 @@ " mak clw csproj vcproj sln dsp dsw" " "; -static bool FindExt(const char *p, const UString &name) -{ - int dotPos = name.ReverseFind_Dot(); - if (dotPos < 0 || dotPos == (int)name.Len() - 1) - return false; - - AString s; - for (unsigned pos = dotPos + 1;; pos++) - { - wchar_t c = name[pos]; - if (c == 0) - break; - if (c >= 0x80) - return false; - s += (char)MyCharLower_Ascii((char)c); - } - for (unsigned i = 0; p[i] != 0;) - { - unsigned j; - for (j = i; p[j] != ' '; j++); - if (s.Len() == j - i && memcmp(p + i, (const char *)s, s.Len()) == 0) - return true; - i = j + 1; - } - return false; -} +// bool FindExt(const char *p, const UString &name, AString &s); +bool FindExt(const char *p, const UString &name, CStringFinder &finder); static bool DoItemAlwaysStart(const UString &name) { - return FindExt(kStartExtensions, name); + CStringFinder finder; + return FindExt(kStartExtensions, name, finder); } UString GetQuotedString(const UString &s); @@ -754,10 +736,10 @@ UStringVector params; params.Add(path); - HRESULT res = StartAppWithParams(command, params, process); - if (res != SZ_OK) + const WRes res = StartAppWithParams(command, params, process); + if (res != 0) ::MessageBoxW(window, LangString(IDS_CANNOT_START_EDITOR), L"7-Zip", MB_OK | MB_ICONSTOP); - return res; + return HRESULT_FROM_WIN32(res); } @@ -772,7 +754,7 @@ } CRecordVector indices; - panel.GetSelectedItemsIndices(indices); + panel.Get_ItemIndices_Selected(indices); UString path1, path2; if (indices.Size() == 2) @@ -792,7 +774,7 @@ path1 = panel.GetItemFullPath(indices[0]); CRecordVector indices2; - destPanel.GetSelectedItemsIndices(indices2); + destPanel.Get_ItemIndices_Selected(indices2); if (indices2.Size() == 1) path2 = destPanel.GetItemFullPath(indices2[0]); else @@ -820,19 +802,19 @@ params.Add(path1); params.Add(path2); - HRESULT res; + WRes res; { CProcess process; res = StartAppWithParams(command, params, process); } - if (res == SZ_OK) + if (res == 0) return; ::MessageBoxW(_window, LangString(IDS_CANNOT_START_EDITOR), L"7-Zip", MB_OK | MB_ICONSTOP); } #ifndef _UNICODE -typedef BOOL (WINAPI * ShellExecuteExWP)(LPSHELLEXECUTEINFOW lpExecInfo); +typedef BOOL (WINAPI * Func_ShellExecuteExW)(LPSHELLEXECUTEINFOW lpExecInfo); #endif static HRESULT StartApplication(const UString &dir, const UString &path, HWND window, CProcess &process) @@ -844,7 +826,7 @@ int dot = path2.ReverseFind_Dot(); int separ = path2.ReverseFind_PathSepar(); if (dot < 0 || dot < separ) - path2 += '.'; + path2.Add_Dot(); } #endif @@ -862,12 +844,15 @@ execInfo.lpParameters = NULL; execInfo.lpDirectory = dir.IsEmpty() ? NULL : (LPCWSTR)dir; execInfo.nShow = SW_SHOWNORMAL; - execInfo.hProcess = 0; - ShellExecuteExWP shellExecuteExW = (ShellExecuteExWP) - (void *)::GetProcAddress(::GetModuleHandleW(L"shell32.dll"), "ShellExecuteExW"); - if (!shellExecuteExW) + execInfo.hProcess = NULL; + const + Func_ShellExecuteExW + f_ShellExecuteExW = Z7_GET_PROC_ADDRESS( + Func_ShellExecuteExW, ::GetModuleHandleW(L"shell32.dll"), + "ShellExecuteExW"); + if (!f_ShellExecuteExW) return 0; - shellExecuteExW(&execInfo); + f_ShellExecuteExW(&execInfo); result = (UINT32)(UINT_PTR)execInfo.hInstApp; process.Attach(execInfo.hProcess); } @@ -895,7 +880,7 @@ #endif ; execInfo.nShow = SW_SHOWNORMAL; - execInfo.hProcess = 0; + execInfo.hProcess = NULL; ::ShellExecuteEx(&execInfo); result = (UINT32)(UINT_PTR)execInfo.hInstApp; process.Attach(execInfo.hProcess); @@ -927,7 +912,7 @@ StartApplication(dir, path, window, process); } -void CPanel::EditItem(int index, bool useEditor) +void CPanel::EditItem(unsigned index, bool useEditor) { if (!_parentFolders.IsEmpty()) { @@ -939,7 +924,7 @@ } -void CPanel::OpenFolderExternal(int index) +void CPanel::OpenFolderExternal(unsigned index) { UString prefix = GetFsPath(); UString path = prefix; @@ -1010,9 +995,10 @@ } if (i != name2.Len()) { + CStringFinder finder; UString name3 = name2; name3.DeleteFrom(i); - if (FindExt(kExeExtensions, name3)) + if (FindExt(kExeExtensions, name3, finder)) isVirus = true; } } @@ -1025,13 +1011,13 @@ if (!isSpaceError) { - int pos1 = s.Find(L'('); + const int pos1 = s.Find(L'('); if (pos1 >= 0) { - int pos2 = s.Find(L')', pos1 + 1); + const int pos2 = s.Find(L')', (unsigned)pos1 + 1); if (pos2 >= 0) { - s.Delete(pos1, pos2 + 1 - pos1); + s.Delete((unsigned)pos1, (unsigned)pos2 + 1 - (unsigned)pos1); if (pos1 > 0 && s[pos1 - 1] == ' ' && s[pos1] == '.') s.Delete(pos1 - 1); } @@ -1050,10 +1036,10 @@ } -void CPanel::OpenItem(int index, bool tryInternal, bool tryExternal, const wchar_t *type) +void CPanel::OpenItem(unsigned index, bool tryInternal, bool tryExternal, const wchar_t *type) { CDisableTimerProcessing disableTimerProcessing(*this); - UString name = GetItemRelPath2(index); + const UString name = GetItemRelPath2(index); if (tryExternal) if (IsVirus_Message(name)) @@ -1096,7 +1082,7 @@ class CThreadCopyFrom: public CProgressThreadVirt { - HRESULT ProcessVirt(); + HRESULT ProcessVirt() Z7_override; public: UString FullPath; UInt32 ItemIndex; @@ -1133,7 +1119,7 @@ t.UpdateCallbackSpec->Password = password; - RINOK(t.Create(GetItemName(index), (HWND)*this)); + RINOK(t.Create(GetItemName(index), (HWND)*this)) return t.Result; } @@ -1292,7 +1278,7 @@ if (firstPass && indices.Size() == 1) { - DWORD curTime = GetTickCount() - startTime; + const DWORD curTime = GetTickCount() - startTime; /* if (curTime > 5 * 1000) @@ -1312,7 +1298,7 @@ DEBUG_PRINT_NUM(" -- firstPass -- time = ", curTime) } - processes.DisableWait(indices[waitResult]); + processes.DisableWait(indices[(unsigned)waitResult]); } firstPass = false; @@ -1324,7 +1310,7 @@ } - DWORD curTime = GetTickCount() - startTime; + const DWORD curTime = GetTickCount() - startTime; DEBUG_PRINT_NUM("after time = ", curTime) @@ -1444,15 +1430,14 @@ */ /* -class CBufSeqOutStream_WithFile: - public ISequentialOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CBufSeqOutStream_WithFile + , ISequentialOutStream +) Byte *_buffer; size_t _size; size_t _pos; - size_t _fileWritePos; bool fileMode; public: @@ -1478,9 +1463,6 @@ HRESULT FlushToFile(); size_t GetPos() const { return _pos; } - - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); }; static const UInt32 kBlockSize = ((UInt32)1 << 31); @@ -1565,7 +1547,7 @@ alwaysStart(name) : external */ -void CPanel::OpenItemInArchive(int index, bool tryInternal, bool tryExternal, bool editMode, bool useEditor, const wchar_t *type) +void CPanel::OpenItemInArchive(unsigned index, bool tryInternal, bool tryExternal, bool editMode, bool useEditor, const wchar_t *type) { // we don't want to change hash data here if (IsHashFolder()) @@ -1830,7 +1812,7 @@ // win7 / win10 work so for some extensions (pdf, html ..); DEBUG_PRINT("#### (HANDLE)process == 0"); // return; - if (res != SZ_OK) + if (res != S_OK) return; } @@ -1839,7 +1821,7 @@ tpi->FileIndex = index; tpi->RelPath = relPath; - if ((HANDLE)process != 0) + if ((HANDLE)process) tpi->Processes.SetMainProcess(process.Detach()); ::CThread th; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelItems.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelItems.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelItems.cpp 2022-01-23 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelItems.cpp 2023-04-21 08:00:00.000000000 +0000 @@ -41,7 +41,7 @@ return true; } -static int GetColumnWidth(PROPID propID, VARTYPE /* varType */) +static unsigned GetColumnWidth(PROPID propID, VARTYPE /* varType */) { switch (propID) { @@ -216,7 +216,7 @@ item.IsVisible = isVisible; item.Width = columnInfo.Width; if (isVisible) - item.Order = order++; + item.Order = (int)(order++); continue; } } @@ -225,14 +225,14 @@ { CPropColumn &item = _columns[i]; if (item.IsVisible && item.Order < 0) - item.Order = order++; + item.Order = (int)(order++); } for (i = 0; i < _columns.Size(); i++) { CPropColumn &item = _columns[i]; if (item.Order < 0) - item.Order = order++; + item.Order = (int)(order++); } CPropColumns newColumns; @@ -285,14 +285,14 @@ { const CPropColumn &prop = newColumns[i]; if (prop.Order < (int)newColumns.Size() && columns[prop.Order] == -1) - columns[prop.Order] = i; + columns[prop.Order] = (int)i; else orderError = true; } for (;;) { - unsigned numColumns = _visibleColumns.Size(); + const unsigned numColumns = _visibleColumns.Size(); if (numColumns == 0) break; DeleteColumn(numColumns - 1); @@ -319,14 +319,14 @@ void CPanel::AddColumn(const CPropColumn &prop) { - const int index = _visibleColumns.Size(); + const unsigned index = _visibleColumns.Size(); LV_COLUMNW column; column.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM | LVCF_ORDER; - column.cx = prop.Width; + column.cx = (int)prop.Width; column.fmt = GetColumnAlign(prop.ID, prop.Type); - column.iOrder = index; // must be <= _listView.ItemCount - column.iSubItem = index; // must be <= _listView.ItemCount + column.iOrder = (int)index; // must be <= _listView.ItemCount + column.iSubItem = (int)index; // must be <= _listView.ItemCount column.pszText = const_cast((const wchar_t *)prop.Name); _visibleColumns.Add(prop); @@ -346,7 +346,7 @@ void CPanel::GetSelectedNames(UStringVector &selectedNames) { CRecordVector indices; - GetSelectedItemsIndices(indices); + Get_ItemIndices_Selected(indices); selectedNames.ClearAndReserve(indices.Size()); FOR_VECTOR (i, indices) selectedNames.AddInReserved(GetItemRelPath(indices[i])); @@ -364,7 +364,7 @@ item.mask = LVIF_TEXT | LVIF_PARAM; if (!_listView.GetItem(&item)) continue; - int realIndex = GetRealIndex(item); + const unsigned realIndex = GetRealIndex(item); if (realIndex == kParentIndex) continue; if (_selectedStatusVector[realIndex]) @@ -384,7 +384,7 @@ { if (s.FocusedItem >= 0) { - int realIndex = GetRealItemIndex(s.FocusedItem); + const unsigned realIndex = GetRealItemIndex(s.FocusedItem); if (realIndex != kParentIndex) { s.FocusedName = GetItemRelPath(realIndex); @@ -422,10 +422,11 @@ } */ -HRESULT CPanel::RefreshListCtrl_SaveFocused() +HRESULT CPanel::RefreshListCtrl_SaveFocused(bool onTimer) { CSelectedState state; SaveSelectedState(state); + state.CalledFromTimer = onTimer; return RefreshListCtrl(state); } @@ -437,7 +438,7 @@ _listView.SetItemState(index, state, state); if (!_mySelectMode && select) { - int realIndex = GetRealItemIndex(index); + const unsigned realIndex = GetRealItemIndex(index); if (realIndex != kParentIndex) _selectedStatusVector[realIndex] = true; } @@ -464,6 +465,9 @@ HRESULT CPanel::RefreshListCtrl(const CSelectedState &state) { + m_DropHighlighted_SelectionIndex = -1; + m_DropHighlighted_SubFolderName.Empty(); + if (!_folder) return S_OK; @@ -474,7 +478,8 @@ */ _dontShowMode = false; - LoadFullPathAndShow(); + if (!state.CalledFromTimer) + LoadFullPathAndShow(); // OutputDebugStringA("=======\n"); // OutputDebugStringA("s1 \n"); CDisableTimerProcessing timerProcessing(*this); @@ -506,11 +511,13 @@ // m_Files.Clear(); + /* if (!_folder) { // throw 1; SetToRootFolder(); } + */ _headerToolBar.EnableButton(kParentFolderID, !IsRootFolder()); @@ -530,16 +537,44 @@ } */ + _isDirVector.Clear(); // DWORD tickCount1 = GetTickCount(); - RINOK(_folder->LoadItems()); + IFolderFolder *folder = _folder; + RINOK(_folder->LoadItems()) // DWORD tickCount2 = GetTickCount(); - RINOK(InitColumns()); - // OutputDebugString(TEXT("Start Dir\n")); + RINOK(InitColumns()) + UInt32 numItems; _folder->GetNumberOfItems(&numItems); + { + NCOM::CPropVariant prop; + _isDirVector.ClearAndSetSize(numItems); + bool *vec = (bool *)&_isDirVector.Front(); + HRESULT hres = S_OK; + unsigned i; + for (i = 0; i < numItems; i++) + { + hres = folder->GetProperty(i, kpidIsDir, &prop); + if (hres != S_OK) + break; + bool v = false; + if (prop.vt == VT_BOOL) + v = VARIANT_BOOLToBool(prop.boolVal); + else if (prop.vt != VT_EMPTY) + break; + vec[i] = v; + } + if (i != numItems) + { + _isDirVector.Clear(); + if (hres == S_OK) + hres = E_FAIL; + } + RINOK(hres) + } - bool showDots = _showDots && !IsRootFolder(); + const bool showDots = _showDots && !IsRootFolder(); _listView.SetItemCount(numItems + (showDots ? 1 : 0)); @@ -582,20 +617,20 @@ if (showDots) { - UString itemName (".."); + const UString itemName (".."); item.iItem = listViewItemCount; if (itemName == state.FocusedName) cursorIndex = listViewItemCount; item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE; int subItem = 0; item.iSubItem = subItem++; - item.lParam = kParentIndex; + item.lParam = (LPARAM)(int)kParentIndex; #ifdef USE_EMBED_ITEM item.pszText = const_cast((const wchar_t *)itemName); #else item.pszText = LPSTR_TEXTCALLBACKW; #endif - UInt32 attrib = FILE_ATTRIBUTE_DIRECTORY; + const UInt32 attrib = FILE_ATTRIBUTE_DIRECTORY; item.iImage = _extToIconMap.GetIconIndex(attrib, itemName); if (item.iImage < 0) item.iImage = 0; @@ -671,7 +706,7 @@ item.iItem = listViewItemCount; item.iSubItem = subItem++; - item.lParam = i; + item.lParam = (LPARAM)i; /* int finish = nameLen - 4; @@ -731,7 +766,7 @@ UInt32 attrib = 0; { NCOM::CPropVariant prop; - RINOK(_folder->GetProperty(i, kpidAttrib, &prop)); + RINOK(_folder->GetProperty(i, kpidAttrib, &prop)) if (prop.vt == VT_UI4) attrib = prop.ulVal; } @@ -844,7 +879,7 @@ } -void CPanel::GetSelectedItemsIndices(CRecordVector &indices) const +void CPanel::Get_ItemIndices_Selected(CRecordVector &indices) const { indices.Clear(); /* @@ -858,46 +893,49 @@ HeapSort(&indices.Front(), indices.Size()); */ const bool *v = &_selectedStatusVector.Front(); - unsigned size = _selectedStatusVector.Size(); + const unsigned size = _selectedStatusVector.Size(); for (unsigned i = 0; i < size; i++) if (v[i]) indices.Add(i); } -void CPanel::GetOperatedItemIndices(CRecordVector &indices) const +void CPanel::Get_ItemIndices_Operated(CRecordVector &indices) const { - GetSelectedItemsIndices(indices); + Get_ItemIndices_Selected(indices); if (!indices.IsEmpty()) return; if (_listView.GetSelectedCount() == 0) return; - int focusedItem = _listView.GetFocusedItem(); + const int focusedItem = _listView.GetFocusedItem(); if (focusedItem >= 0) { if (_listView.IsItemSelected(focusedItem)) { - int realIndex = GetRealItemIndex(focusedItem); + const unsigned realIndex = GetRealItemIndex(focusedItem); if (realIndex != kParentIndex) indices.Add(realIndex); } } } -void CPanel::GetAllItemIndices(CRecordVector &indices) const +void CPanel::Get_ItemIndices_All(CRecordVector &indices) const { indices.Clear(); UInt32 numItems; - if (_folder->GetNumberOfItems(&numItems) == S_OK) - for (UInt32 i = 0; i < numItems; i++) - indices.Add(i); + if (_folder->GetNumberOfItems(&numItems) != S_OK) + return; + indices.ClearAndSetSize(numItems); + UInt32 *vec = (UInt32 *)&indices.Front(); + for (UInt32 i = 0; i < numItems; i++) + vec[i] = i; } -void CPanel::GetOperatedIndicesSmart(CRecordVector &indices) const +void CPanel::Get_ItemIndices_OperSmart(CRecordVector &indices) const { - GetOperatedItemIndices(indices); + Get_ItemIndices_Operated(indices); if (indices.IsEmpty() || (indices.Size() == 1 && indices[0] == (UInt32)(Int32)-1)) - GetAllItemIndices(indices); + Get_ItemIndices_All(indices); } /* @@ -907,14 +945,14 @@ int numItems = _listView.GetItemCount(); for (int i = 0; i < numItems; i++) { - int realIndex = GetRealItemIndex(i); + const unsigned realIndex = GetRealItemIndex(i); if (realIndex >= 0) if (_selectedStatusVector[realIndex]) indices.Add(i); } if (indices.IsEmpty()) { - int focusedItem = _listView.GetFocusedItem(); + const int focusedItem = _listView.GetFocusedItem(); if (focusedItem >= 0) indices.Add(focusedItem); } @@ -931,7 +969,7 @@ { bool needRefresh = false; CRecordVector indices; - GetOperatedItemIndices(indices); + Get_ItemIndices_Operated(indices); FOR_VECTOR (i, indices) { UInt32 index = indices[i]; @@ -952,10 +990,10 @@ } - int focusedItem = _listView.GetFocusedItem(); + const int focusedItem = _listView.GetFocusedItem(); if (focusedItem < 0) return; - int realIndex = GetRealItemIndex(focusedItem); + const unsigned realIndex = GetRealItemIndex(focusedItem); if (realIndex == kParentIndex) return; if (!IsItem_Folder(realIndex)) @@ -964,10 +1002,10 @@ void CPanel::OpenFocusedItemAsInternal(const wchar_t *type) { - int focusedItem = _listView.GetFocusedItem(); + const int focusedItem = _listView.GetFocusedItem(); if (focusedItem < 0) return; - int realIndex = GetRealItemIndex(focusedItem); + const unsigned realIndex = GetRealItemIndex(focusedItem); if (IsItem_Folder(realIndex)) OpenFolder(realIndex); else @@ -977,17 +1015,17 @@ void CPanel::OpenSelectedItems(bool tryInternal) { CRecordVector indices; - GetOperatedItemIndices(indices); + Get_ItemIndices_Operated(indices); if (indices.Size() > 20) { MessageBox_Error_LangID(IDS_TOO_MANY_ITEMS); return; } - int focusedItem = _listView.GetFocusedItem(); + const int focusedItem = _listView.GetFocusedItem(); if (focusedItem >= 0) { - int realIndex = GetRealItemIndex(focusedItem); + const unsigned realIndex = GetRealItemIndex(focusedItem); if (realIndex == kParentIndex && (tryInternal || indices.Size() == 0) && _listView.IsItemSelected(focusedItem)) indices.Insert(0, realIndex); } @@ -1016,7 +1054,7 @@ } } -UString CPanel::GetItemName(int itemIndex) const +UString CPanel::GetItemName(unsigned itemIndex) const { if (itemIndex == kParentIndex) return L".."; @@ -1028,7 +1066,7 @@ return prop.bstrVal; } -UString CPanel::GetItemName_for_Copy(int itemIndex) const +UString CPanel::GetItemName_for_Copy(unsigned itemIndex) const { if (itemIndex == kParentIndex) return L".."; @@ -1048,7 +1086,7 @@ return Get_Correct_FsFile_Name(s); } -void CPanel::GetItemName(int itemIndex, UString &s) const +void CPanel::GetItemName(unsigned itemIndex, UString &s) const { if (itemIndex == kParentIndex) { @@ -1063,7 +1101,7 @@ s.SetFromBstr(prop.bstrVal); } -UString CPanel::GetItemPrefix(int itemIndex) const +UString CPanel::GetItemPrefix(unsigned itemIndex) const { if (itemIndex == kParentIndex) return UString(); @@ -1076,12 +1114,12 @@ return prefix; } -UString CPanel::GetItemRelPath(int itemIndex) const +UString CPanel::GetItemRelPath(unsigned itemIndex) const { return GetItemPrefix(itemIndex) + GetItemName(itemIndex); } -UString CPanel::GetItemRelPath2(int itemIndex) const +UString CPanel::GetItemRelPath2(unsigned itemIndex) const { UString s = GetItemRelPath(itemIndex); #if defined(_WIN32) && !defined(UNDER_CE) @@ -1094,7 +1132,50 @@ return s; } -UString CPanel::GetItemFullPath(int itemIndex) const + +void CPanel::Add_ItemRelPath2_To_String(unsigned itemIndex, UString &s) const +{ + if (itemIndex == kParentIndex) + { + s += ".."; + return; + } + + const unsigned start = s.Len(); + NCOM::CPropVariant prop; + if (_folder->GetProperty(itemIndex, kpidPrefix, &prop) != S_OK) + throw 2723400; + if (prop.vt == VT_BSTR) + s += prop.bstrVal; + + const wchar_t *name = NULL; + unsigned nameLen = 0; + + if (_folderGetItemName) + _folderGetItemName->GetItemName(itemIndex, &name, &nameLen); + if (name) + s += name; + else + { + prop.Clear(); + if (_folder->GetProperty(itemIndex, kpidName, &prop) != S_OK) + throw 2723400; + if (prop.vt != VT_BSTR) + throw 2723401; + s += prop.bstrVal; + } + + #if defined(_WIN32) && !defined(UNDER_CE) + if (s.Len() - start == 2 && NFile::NName::IsDrivePath2(s.Ptr(start))) + { + if (IsFSDrivesFolder() && !IsDeviceDrivesPrefix()) + s.Add_PathSepar(); + } + #endif +} + + +UString CPanel::GetItemFullPath(unsigned itemIndex) const { return GetFsPath() + GetItemRelPath2(itemIndex); } @@ -1111,28 +1192,30 @@ throw 2723401; } -bool CPanel::IsItem_Deleted(int itemIndex) const +bool CPanel::IsItem_Deleted(unsigned itemIndex) const { if (itemIndex == kParentIndex) return false; return GetItem_BoolProp(itemIndex, kpidIsDeleted); } -bool CPanel::IsItem_Folder(int itemIndex) const +bool CPanel::IsItem_Folder(unsigned itemIndex) const { if (itemIndex == kParentIndex) return true; + if (itemIndex < _isDirVector.Size()) + return _isDirVector[itemIndex]; return GetItem_BoolProp(itemIndex, kpidIsDir); } -bool CPanel::IsItem_AltStream(int itemIndex) const +bool CPanel::IsItem_AltStream(unsigned itemIndex) const { if (itemIndex == kParentIndex) return false; return GetItem_BoolProp(itemIndex, kpidIsAltStream); } -UInt64 CPanel::GetItem_UInt64Prop(int itemIndex, PROPID propID) const +UInt64 CPanel::GetItem_UInt64Prop(unsigned itemIndex, PROPID propID) const { if (itemIndex == kParentIndex) return 0; @@ -1145,7 +1228,7 @@ return 0; } -UInt64 CPanel::GetItemSize(int itemIndex) const +UInt64 CPanel::GetItemSize(unsigned itemIndex) const { if (itemIndex == kParentIndex) return 0; @@ -1169,7 +1252,7 @@ if (!_listView.GetColumn(i, &winColumnInfo)) throw 1; prop.Order = winColumnInfo.iOrder; - prop.Width = winColumnInfo.cx; + prop.Width = (UInt32)(Int32)winColumnInfo.cx; } CListViewInfo viewInfo; @@ -1247,22 +1330,22 @@ menu.AppendItem(flags, kCommandStart + i, prop.Name); } - int menuResult = menu.Track(TPM_LEFTALIGN | TPM_RETURNCMD | TPM_NONOTIFY, x, y, _listView); + const int menuResult = menu.Track(TPM_LEFTALIGN | TPM_RETURNCMD | TPM_NONOTIFY, x, y, _listView); if (menuResult >= kCommandStart && menuResult <= kCommandStart + (int)_columns.Size()) { - int index = menuResult - kCommandStart; + const unsigned index = (unsigned)(menuResult - kCommandStart); CPropColumn &prop = _columns[index]; prop.IsVisible = !prop.IsVisible; if (prop.IsVisible) { - prop.Order = _visibleColumns.Size(); + prop.Order = (int)_visibleColumns.Size(); AddColumn(prop); } else { - int visibleIndex = _visibleColumns.FindItem_for_PropID(prop.ID); + const int visibleIndex = _visibleColumns.FindItem_for_PropID(prop.ID); if (visibleIndex >= 0) { /* @@ -1277,15 +1360,15 @@ _sortID = kpidName; _ascending = true; } - DeleteColumn(visibleIndex); + DeleteColumn((unsigned)visibleIndex); } } } } -void CPanel::OnReload() +void CPanel::OnReload(bool onTimer) { - HRESULT res = RefreshListCtrl_SaveFocused(); + const HRESULT res = RefreshListCtrl_SaveFocused(onTimer); if (res != S_OK) MessageBox_Error_HRESULT(res); } @@ -1304,5 +1387,5 @@ return; if (wasChanged == 0) return; - OnReload(); + OnReload(true); // onTimer } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelKey.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelKey.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelKey.cpp 2020-09-29 07:35:01.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelKey.cpp 2023-03-20 12:00:00.000000000 +0000 @@ -29,9 +29,9 @@ static int FindVKeyPropIDPair(WORD vKey) { - for (unsigned i = 0; i < ARRAY_SIZE(g_VKeyPropIDPairs); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_VKeyPropIDPairs); i++) if (g_VKeyPropIDPairs[i].VKey == vKey) - return i; + return (int)i; return -1; } @@ -43,17 +43,18 @@ _panelCallback->OnTab(); return false; } - bool alt = IsKeyDown(VK_MENU); - bool ctrl = IsKeyDown(VK_CONTROL); - // bool leftCtrl = IsKeyDown(VK_LCONTROL); - bool rightCtrl = IsKeyDown(VK_RCONTROL); - bool shift = IsKeyDown(VK_SHIFT); + const bool alt = IsKeyDown(VK_MENU); + const bool ctrl = IsKeyDown(VK_CONTROL); + // const bool leftCtrl = IsKeyDown(VK_LCONTROL); + const bool rightCtrl = IsKeyDown(VK_RCONTROL); + const bool shift = IsKeyDown(VK_SHIFT); result = 0; - if (keyDownInfo->wVKey >= '0' && keyDownInfo->wVKey <= '9' && + if (keyDownInfo->wVKey >= '0' && + keyDownInfo->wVKey <= '9' && (rightCtrl || alt)) { - int index = keyDownInfo->wVKey - '0'; + const unsigned index = (unsigned)(keyDownInfo->wVKey - '0'); if (shift) { SetBookmark(index); @@ -67,7 +68,8 @@ } if ((keyDownInfo->wVKey == VK_F2 || - keyDownInfo->wVKey == VK_F1) && alt && !ctrl && !shift) + keyDownInfo->wVKey == VK_F1) + && alt && !ctrl && !shift) { _panelCallback->SetFocusToPath(keyDownInfo->wVKey == VK_F1 ? 0 : 1); return true; @@ -80,7 +82,7 @@ if (keyDownInfo->wVKey >= VK_F3 && keyDownInfo->wVKey <= VK_F12 && ctrl) { - int index = FindVKeyPropIDPair(keyDownInfo->wVKey); + const int index = FindVKeyPropIDPair(keyDownInfo->wVKey); if (index >= 0) SortItemsWithPropID(g_VKeyPropIDPairs[index].PropID); } @@ -313,6 +315,14 @@ return true; } return false; + case 'W': + if (ctrl) + { + // SendMessage(); + PostMessage(g_HWND, WM_COMMAND, IDCLOSE, 0); + return true; + } + return false; case 'Z': if (ctrl) { @@ -326,7 +336,7 @@ case '4': if (ctrl) { - int styleIndex = keyDownInfo->wVKey - '1'; + const unsigned styleIndex = (unsigned)(keyDownInfo->wVKey - '1'); SetListViewMode(styleIndex); return true; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelListNotify.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelListNotify.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelListNotify.cpp 2021-10-01 12:25:26.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelListNotify.cpp 2023-01-19 19:00:00.000000000 +0000 @@ -289,8 +289,8 @@ const void *data; UInt32 dataSize; UInt32 propType; - RINOK(_folderRawProps->GetRawProp(realIndex, propID, &data, &dataSize, &propType)); - unsigned limit = item.cchTextMax - 1; + RINOK(_folderRawProps->GetRawProp(realIndex, propID, &data, &dataSize, &propType)) + const unsigned limit = (unsigned)item.cchTextMax - 1; if (dataSize == 0) { text[0] = 0; @@ -425,11 +425,11 @@ if (name) { unsigned dest = 0; - unsigned limit = item.cchTextMax - 1; + const unsigned limit = (unsigned)item.cchTextMax - 1; for (unsigned i = 0; dest < limit;) { - wchar_t c = name[i++]; + const wchar_t c = name[i++]; if (c == 0) break; text[dest++] = c; @@ -488,10 +488,10 @@ if (name) { unsigned dest = 0; - unsigned limit = item.cchTextMax - 1; + const unsigned limit = (unsigned)item.cchTextMax - 1; for (unsigned i = 0; dest < limit;) { - wchar_t c = name[i++]; + const wchar_t c = name[i++]; if (c == 0) break; text[dest++] = c; @@ -502,7 +502,7 @@ } } - HRESULT res = _folder->GetProperty(realIndex, propID, &prop); + const HRESULT res = _folder->GetProperty(realIndex, propID, &prop); if (res != S_OK) { @@ -517,7 +517,7 @@ } else if (prop.vt == VT_BSTR) { - unsigned limit = item.cchTextMax - 1; + const unsigned limit = (unsigned)item.cchTextMax - 1; const wchar_t *src = prop.bstrVal; unsigned i; for (i = 0; i < limit; i++) @@ -535,10 +535,10 @@ char temp[64]; ConvertPropertyToShortString2(temp, prop, propID, _timestampLevel); unsigned i; - unsigned limit = item.cchTextMax - 1; + const unsigned limit = (unsigned)item.cchTextMax - 1; for (i = 0; i < limit; i++) { - wchar_t c = (Byte)temp[i]; + const wchar_t c = (Byte)temp[i]; if (c == 0) break; text[i] = c; @@ -555,11 +555,11 @@ void CPanel::OnItemChanged(NMLISTVIEW *item) { - int index = (int)item->lParam; + const unsigned index = (unsigned)item->lParam; if (index == kParentIndex) return; - bool oldSelected = (item->uOldState & LVIS_SELECTED) != 0; - bool newSelected = (item->uNewState & LVIS_SELECTED) != 0; + const bool oldSelected = (item->uOldState & LVIS_SELECTED) != 0; + const bool newSelected = (item->uNewState & LVIS_SELECTED) != 0; // Don't change this code. It works only with such check if (oldSelected != newSelected) _selectedStatusVector[index] = newSelected; @@ -712,7 +712,13 @@ } case LVN_BEGINDRAG: { - OnDrag((LPNMLISTVIEW)header); + OnDrag((LPNMLISTVIEW)header, false); + Post_Refresh_StatusBar(); + break; + } + case LVN_BEGINRDRAG: + { + OnDrag((LPNMLISTVIEW)header, true); Post_Refresh_StatusBar(); break; } @@ -739,7 +745,7 @@ lplvcd->clrTextBk = GetBkColorForItem(lplvcd->nmcd.dwItemSpec, lplvcd->nmcd.lItemlParam); */ - int realIndex = (int)lplvcd->nmcd.lItemlParam; + const unsigned realIndex = (unsigned)lplvcd->nmcd.lItemlParam; lplvcd->clrTextBk = _listView.GetBkColor(); if (_mySelectMode) { @@ -793,40 +799,44 @@ // DWORD dw = GetTickCount(); CRecordVector indices; - GetOperatedItemIndices(indices); - - wchar_t temp[32]; - ConvertUInt32ToString(indices.Size(), temp); - wcscat(temp, L" / "); - ConvertUInt32ToString(_selectedStatusVector.Size(), temp + wcslen(temp)); + Get_ItemIndices_Operated(indices); - // UString s1 = MyFormatNew(g_App.LangString_N_SELECTED_ITEMS, NumberToString(indices.Size())); - // UString s1 = MyFormatNew(IDS_N_SELECTED_ITEMS, NumberToString(indices.Size())); - _statusBar.SetText(0, MyFormatNew(g_App.LangString_N_SELECTED_ITEMS, temp)); - // _statusBar.SetText(0, MyFormatNew(IDS_N_SELECTED_ITEMS, NumberToString(indices.Size()))); + { + UString s; + s.Add_UInt32(indices.Size()); + s += " / "; + s.Add_UInt32(_selectedStatusVector.Size()); - wchar_t selectSizeString[32]; - selectSizeString[0] = 0; + // UString s1 = MyFormatNew(g_App.LangString_N_SELECTED_ITEMS, NumberToString(indices.Size())); + // UString s1 = MyFormatNew(IDS_N_SELECTED_ITEMS, NumberToString(indices.Size())); + _statusBar.SetText(0, MyFormatNew(g_App.LangString_N_SELECTED_ITEMS, s)); + // _statusBar.SetText(0, MyFormatNew(IDS_N_SELECTED_ITEMS, NumberToString(indices.Size()))); + } - if (indices.Size() > 0) { - // for (unsigned ttt = 0; ttt < 1000; ttt++) { - UInt64 totalSize = 0; - FOR_VECTOR (i, indices) - totalSize += GetItemSize(indices[i]); - ConvertSizeToString(totalSize, selectSizeString); - // } + wchar_t selectSizeString[32]; + selectSizeString[0] = 0; + + if (indices.Size() > 0) + { + // for (unsigned ttt = 0; ttt < 1000; ttt++) { + UInt64 totalSize = 0; + FOR_VECTOR (i, indices) + totalSize += GetItemSize(indices[i]); + ConvertSizeToString(totalSize, selectSizeString); + // } + } + _statusBar.SetText(1, selectSizeString); } - _statusBar.SetText(1, selectSizeString); - int focusedItem = _listView.GetFocusedItem(); + const int focusedItem = _listView.GetFocusedItem(); wchar_t sizeString[32]; sizeString[0] = 0; wchar_t dateString[32]; dateString[0] = 0; if (focusedItem >= 0 && _listView.GetSelectedCount() > 0) { - int realIndex = GetRealItemIndex(focusedItem); + const unsigned realIndex = GetRealItemIndex(focusedItem); if (realIndex != kParentIndex) { ConvertSizeToString(GetItemSize(realIndex), sizeString); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelMenu.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelMenu.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelMenu.cpp 2022-04-28 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelMenu.cpp 2023-03-20 12:00:00.000000000 +0000 @@ -20,8 +20,10 @@ #include "MyLoadMenu.h" #include "PropertyName.h" -#include "resource.h" #include "PropertyNameRes.h" +#include "resource.h" + +// #define SHOW_DEBUG_PANEL_MENU using namespace NWindows; @@ -32,13 +34,33 @@ static const UINT kSevenZipStartMenuID = kMenuCmdID_Plugin_Start; static const UINT kSystemStartMenuID = kMenuCmdID_Plugin_Start + 400; + +#ifdef SHOW_DEBUG_PANEL_MENU +static void Print_Ptr(void *p, const char *s) +{ + char temp[32]; + ConvertUInt64ToHex((UInt64)(void *)p, temp); + AString m; + m += temp; + m.Add_Space(); + m += s; + OutputDebugStringA(m); +} +#define ODS(sz) { Print_Ptr(this, sz); } +#define ODS_U(s) { OutputDebugStringW(s); } +#else +#define ODS(sz) +#define ODS_U(s) +#endif + + void CPanel::InvokeSystemCommand(const char *command) { NCOM::CComInitializer comInitializer; if (!IsFsOrPureDrivesFolder()) return; CRecordVector operatedIndices; - GetOperatedItemIndices(operatedIndices); + Get_ItemIndices_Operated(operatedIndices); if (operatedIndices.IsEmpty()) return; CMyComPtr contextMenu; @@ -173,7 +195,7 @@ // message.SelectFirst = false; CRecordVector operatedIndices; - GetOperatedItemIndices(operatedIndices); + Get_ItemIndices_Operated(operatedIndices); if (operatedIndices.Size() == 1) { @@ -346,7 +368,7 @@ UInt32 numProps; if (getProps->GetArcNumProps(level, &numProps) == S_OK) { - const int kNumSpecProps = ARRAY_SIZE(kSpecProps); + const int kNumSpecProps = Z7_ARRAY_SIZE(kSpecProps); AddSeparator(message); @@ -357,7 +379,7 @@ VARTYPE vt; if (i < 0) propID = kSpecProps[i + kNumSpecProps]; - else if (getProps->GetArcPropInfo(level, i, &name, &propID, &vt) != S_OK) + else if (getProps->GetArcPropInfo(level, (UInt32)i, &name, &propID, &vt) != S_OK) continue; NCOM::CPropVariant prop; if (getProps->GetArcProp(level, propID, &prop) != S_OK) @@ -369,12 +391,12 @@ if (level2 < numLevels - 1) { - UInt32 level = numLevels - 1 - level2; + const UInt32 level = numLevels - 1 - level2; UInt32 numProps; if (getProps->GetArcNumProps2(level, &numProps) == S_OK) { AddSeparatorSmall(message); - for (Int32 i = 0; i < (Int32)numProps; i++) + for (UInt32 i = 0; i < numProps; i++) { CMyComBSTR name; PROPID propID; @@ -393,11 +415,11 @@ { // we ERROR message for NonOpen level bool needSep = true; - const int kNumSpecProps = ARRAY_SIZE(kSpecProps); + const int kNumSpecProps = Z7_ARRAY_SIZE(kSpecProps); for (Int32 i = -(int)kNumSpecProps; i < 0; i++) { CMyComBSTR name; - PROPID propID = kSpecProps[i + kNumSpecProps]; + const PROPID propID = kSpecProps[i + kNumSpecProps]; NCOM::CPropVariant prop; if (getProps->GetArcProp(numLevels, propID, &prop) != S_OK) continue; @@ -440,7 +462,7 @@ */ UString s; CRecordVector indices; - GetSelectedItemsIndices(indices); + Get_ItemIndices_Selected(indices); FOR_VECTOR (i, indices) { if (i != 0) @@ -486,15 +508,25 @@ }; +static HRESULT ShellFolder_ParseDisplayName(IShellFolder *shellFolder, + HWND hwnd, const UString &path, LPITEMIDLIST *ppidl) +{ + ULONG eaten = 0; + return shellFolder->ParseDisplayName(hwnd, NULL, + path.Ptr_non_const(), &eaten, ppidl, NULL); +} + + HRESULT CPanel::CreateShellContextMenu( const CRecordVector &operatedIndices, CMyComPtr &systemContextMenu) { + ODS("==== CPanel::CreateShellContextMenu"); systemContextMenu.Release(); - const UString folderPath = GetFsPath(); + UString folderPath = GetFsPath(); CMyComPtr desktopFolder; - RINOK(::SHGetDesktopFolder(&desktopFolder)); + RINOK(::SHGetDesktopFolder(&desktopFolder)) if (!desktopFolder) { // ShowMessage("Failed to get Desktop folder"); @@ -502,24 +534,37 @@ } CFolderPidls pidls; - DWORD eaten; - + // NULL is allowed for parentHWND in ParseDisplayName() + const HWND parentHWND_for_ParseDisplayName = GetParent(); // if (folderPath.IsEmpty()), then ParseDisplayName returns pidls of "My Computer" - RINOK(desktopFolder->ParseDisplayName( - GetParent(), NULL, folderPath.Ptr_non_const(), - &eaten, &pidls.parent, NULL)); + /* win10: ParseDisplayName() supports folder path with tail slash + ParseDisplayName() returns { + E_INVALIDARG : path with super path prefix "\\\\?\\" + ERROR_FILE_NOT_FOUND : path for network share (\\server\path1\long path2") larger than MAX_PATH + } */ + const HRESULT res = ShellFolder_ParseDisplayName(desktopFolder, + parentHWND_for_ParseDisplayName, + folderPath, &pidls.parent); + if (res != S_OK) + { + ODS_U(folderPath); + if (res != E_INVALIDARG) + return res; + if (!NFile::NName::If_IsSuperPath_RemoveSuperPrefix(folderPath)) + return res; + RINOK(ShellFolder_ParseDisplayName(desktopFolder, + parentHWND_for_ParseDisplayName, + folderPath, &pidls.parent)) + } + if (!pidls.parent) + return E_FAIL; /* - STRRET pName; - res = desktopFolder->GetDisplayNameOf(pidls.parent, SHGDN_NORMAL, &pName); - WCHAR dir[MAX_PATH]; - if (!SHGetPathFromIDListW(pidls.parent, dir)) - dir[0] = 0; + UString path2; + NShell::GetPathFromIDList(pidls.parent, path2); + ODS_U(path2); */ - if (!pidls.parent) - return E_FAIL; - if (operatedIndices.IsEmpty()) { // how to get IContextMenu, if there are no selected files? @@ -549,28 +594,37 @@ CMyComPtr parentFolder; RINOK(desktopFolder->BindToObject(pidls.parent, - NULL, IID_IShellFolder, (void**)&parentFolder)); + NULL, IID_IShellFolder, (void**)&parentFolder)) if (!parentFolder) - { - // ShowMessage("Invalid file name"); return E_FAIL; - } + + ODS("==== CPanel::CreateShellContextMenu pidls START"); pidls.items.ClearAndReserve(operatedIndices.Size()); + UString fileName; FOR_VECTOR (i, operatedIndices) { - LPITEMIDLIST pidl; - const UString fileName = GetItemRelPath2(operatedIndices[i]); - RINOK(parentFolder->ParseDisplayName(GetParent(), 0, - fileName.Ptr_non_const(), &eaten, &pidl, 0)); + fileName.Empty(); + Add_ItemRelPath2_To_String(operatedIndices[i], fileName); + /* ParseDisplayName() in win10 returns: + E_INVALIDARG : if empty name, or path with dots only: "." , ".." + HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) : if there is no such file + */ + LPITEMIDLIST pidl = NULL; + RINOK(ShellFolder_ParseDisplayName(parentFolder, + parentHWND_for_ParseDisplayName, + fileName, &pidl)) + if (!pidl) + return E_FAIL; pidls.items.AddInReserved(pidl); } - - // Get IContextMenu for items - RINOK(parentFolder->GetUIObjectOf(GetParent(), pidls.items.Size(), - (LPCITEMIDLIST *)(void *)&pidls.items.Front(), IID_IContextMenu, 0, (void**)&systemContextMenu)); - + ODS("==== CPanel::CreateShellContextMenu pidls END"); + // Get IContextMenu for items + RINOK(parentFolder->GetUIObjectOf(GetParent(), + pidls.items.Size(), (LPCITEMIDLIST *)(void *)&pidls.items.Front(), + IID_IContextMenu, NULL, (void**)&systemContextMenu)) + ODS("==== CPanel::CreateShellContextMenu GetUIObjectOf finished"); if (!systemContextMenu) { // ShowMessage("Unable to get context menu interface"); @@ -579,14 +633,11 @@ return S_OK; } + // #define SHOW_DEBUG_FM_CTX_MENU #ifdef SHOW_DEBUG_FM_CTX_MENU -#include - -// #include Common/IntToString.h" - static void PrintHex(UString &s, UInt32 v) { char sz[32]; @@ -597,16 +648,14 @@ static void PrintContextStr(UString &s, IContextMenu *ctxm, unsigned i, unsigned id, const char *name) { s += " | "; - name = name; - // s += name; - // s += ": "; - + s += name; + s += ": "; UString s1; { char buf[256]; buf[0] = 0; - HRESULT res = ctxm->GetCommandString(i, id, - NULL, buf, ARRAY_SIZE(buf) - 1); + const HRESULT res = ctxm->GetCommandString(i, id, + NULL, buf, Z7_ARRAY_SIZE(buf) - 1); if (res != S_OK) { PrintHex(s1, res); @@ -614,13 +663,12 @@ } s1 += GetUnicodeString(buf); } - UString s2; { wchar_t buf2[256]; buf2[0] = 0; - HRESULT res = ctxm->GetCommandString(i, id | GCS_UNICODE, - NULL, (char *)buf2, ARRAY_SIZE(buf2) - 1); + const HRESULT res = ctxm->GetCommandString(i, id | GCS_UNICODE, + NULL, (char *)buf2, Z7_ARRAY_SIZE(buf2) - sizeof(wchar_t)); if (res != S_OK) { PrintHex(s2, res); @@ -628,7 +676,6 @@ } s2 += buf2; } - s += s1; if (s2.Compare(s1) != 0) { @@ -637,7 +684,6 @@ } } - static void PrintAllContextItems(IContextMenu *ctxm, unsigned num) { for (unsigned i = 0; i < num; i++) @@ -645,35 +691,18 @@ UString s; s.Add_UInt32(i); s += ": "; - - /* - UString valid; - { - char name[256]; - HRESULT res = ctxm->GetCommandString(i, GCS_VALIDATEA, - NULL, name, ARRAY_SIZE(name) - 1); - - if (res == S_OK) - { - // valid = "valid"; - } - else if (res == S_FALSE) - valid = "non-valid"; - else - PrintHex(valid, res); - } - s += valid; - */ - PrintContextStr(s, ctxm, i, GCS_VALIDATEA, "valid"); - PrintContextStr(s, ctxm, i, GCS_VERBA, "v"); - PrintContextStr(s, ctxm, i, GCS_HELPTEXTA, "h"); + PrintContextStr(s, ctxm, i, GCS_VERBA, "verb"); + PrintContextStr(s, ctxm, i, GCS_HELPTEXTA, "helptext"); OutputDebugStringW(s); } } + #endif + void CPanel::CreateSystemMenu(HMENU menuSpec, + bool showExtendedVerbs, const CRecordVector &operatedIndices, CMyComPtr &systemContextMenu) { @@ -722,19 +751,13 @@ CMenuDestroyer menuDestroyer(popupMenu); if (!popupMenu.CreatePopup()) throw 210503; - - HMENU hMenu = popupMenu; - - DWORD Flags = CMF_EXPLORE; - // Optionally the shell will show the extended - // context menu on some operating systems when - // the shift key is held down at the time the - // context menu is invoked. The following is - // commented out but you can uncommnent this - // line to show the extended context menu. - // Flags |= 0x00000080; - HRESULT res = systemContextMenu->QueryContextMenu(hMenu, 0, kSystemStartMenuID, 0x7FFF, Flags); - + const HMENU hMenu = popupMenu; + DWORD flags = CMF_EXPLORE; + if (showExtendedVerbs) + flags |= Z7_WIN_CMF_EXTENDEDVERBS; + ODS("=== systemContextMenu->QueryContextMenu START"); + const HRESULT res = systemContextMenu->QueryContextMenu(hMenu, 0, kSystemStartMenuID, 0x7FFF, flags); + ODS("=== systemContextMenu->QueryContextMenu END"); if (SUCCEEDED(res)) { #ifdef SHOW_DEBUG_FM_CTX_MENU @@ -779,11 +802,13 @@ void CPanel::CreateFileMenu(HMENU menuSpec) { - CreateFileMenu(menuSpec, _sevenZipContextMenu, _systemContextMenu, true); + CreateFileMenu(menuSpec, _sevenZipContextMenu, _systemContextMenu, true); // programMenu } void CPanel::CreateSevenZipMenu(HMENU menuSpec, + bool showExtendedVerbs, const CRecordVector &operatedIndices, + int firstDirIndex, CMyComPtr &sevenZipContextMenu) { sevenZipContextMenu.Release(); @@ -802,22 +827,23 @@ if (contextMenu.QueryInterface(IID_IInitContextMenu, &initContextMenu) != S_OK) return; */ - UString currentFolderUnicode = GetFsPath(); - UStringVector names; - unsigned i; - for (i = 0; i < operatedIndices.Size(); i++) - names.Add(currentFolderUnicode + GetItemRelPath2(operatedIndices[i])); - CRecordVector namePointers; - for (i = 0; i < operatedIndices.Size(); i++) - namePointers.Add(names[i]); - - // NFile::NDirectory::MySetCurrentDirectory(currentFolderUnicode); - if (contextMenuSpec->InitContextMenu(currentFolderUnicode, &namePointers.Front(), - operatedIndices.Size()) == S_OK) + ODS("=== FileName List Add START") + // for (unsigned y = 0; y < 10000; y++, contextMenuSpec->_fileNames.Clear()) + GetFilePaths(operatedIndices, contextMenuSpec->_fileNames); + ODS("=== FileName List Add END") + contextMenuSpec->Init_For_7zFM(); + contextMenuSpec->_attribs.FirstDirIndex = firstDirIndex; { - HRESULT res = contextMenu->QueryContextMenu(menu, 0, kSevenZipStartMenuID, - kSystemStartMenuID - 1, 0); - bool sevenZipMenuCreated = SUCCEEDED(res); + DWORD flags = CMF_EXPLORE; + if (showExtendedVerbs) + flags |= Z7_WIN_CMF_EXTENDEDVERBS; + const HRESULT res = contextMenu->QueryContextMenu(menu, + 0, // indexMenu + kSevenZipStartMenuID, // first + kSystemStartMenuID - 1, // last + flags); + ODS("=== contextMenu->QueryContextMenu END") + const bool sevenZipMenuCreated = SUCCEEDED(res); if (sevenZipMenuCreated) { // if (res != 0) @@ -834,7 +860,6 @@ { // MessageBox_Error_HRESULT_Caption(res, L"QueryContextMenu"); } - // int code = HRESULT_CODE(res); // int nextItemID = code; } @@ -917,19 +942,22 @@ sevenZipContextMenu.Release(); systemContextMenu.Release(); + const bool showExtendedVerbs = IsKeyDown(VK_SHIFT); + CRecordVector operatedIndices; - GetOperatedItemIndices(operatedIndices); + Get_ItemIndices_Operated(operatedIndices); + const int firstDirIndex = FindDir_InOperatedList(operatedIndices); CMenu menu; menu.Attach(menuSpec); if (!IsArcFolder()) { - CreateSevenZipMenu(menu, operatedIndices, sevenZipContextMenu); + CreateSevenZipMenu(menu, showExtendedVerbs, operatedIndices, firstDirIndex, sevenZipContextMenu); // CreateSystemMenu is very slow if you call it inside ZIP archive with big number of files // Windows probably can parse items inside ZIP archive. if (g_App.ShowSystemMenu) - CreateSystemMenu(menu, operatedIndices, systemContextMenu); + CreateSystemMenu(menu, showExtendedVerbs, operatedIndices, systemContextMenu); } /* @@ -937,19 +965,13 @@ menu.AppendItem(MF_SEPARATOR, 0, (LPCTSTR)0); */ - unsigned i; - for (i = 0; i < operatedIndices.Size(); i++) - if (IsItem_Folder(operatedIndices[i])) - break; - bool allAreFiles = (i == operatedIndices.Size()); - CFileMenu fm; fm.readOnly = IsThereReadOnlyFolder(); fm.isHashFolder = IsHashFolder(); fm.isFsFolder = Is_IO_FS_Folder(); fm.programMenu = programMenu; - fm.allAreFiles = allAreFiles; + fm.allAreFiles = (firstDirIndex == -1); fm.numItems = operatedIndices.Size(); fm.isAltStreamsSupported = false; @@ -961,7 +983,7 @@ { if (operatedIndices.Size() <= 1) { - Int32 realIndex = -1; + UInt32 realIndex = (UInt32)(Int32)-1; if (operatedIndices.Size() == 1) realIndex = operatedIndices[0]; Int32 val = 0; @@ -977,7 +999,7 @@ fm.isAltStreamsSupported = IsFolder_with_FsItems(); } - fm.Load(menu, menu.GetItemCount()); + fm.Load(menu, (unsigned)menu.GetItemCount()); } bool CPanel::InvokePluginCommand(unsigned id) @@ -987,6 +1009,7 @@ #if defined(_MSC_VER) && !defined(UNDER_CE) #define use_CMINVOKECOMMANDINFOEX +/* CMINVOKECOMMANDINFOEX depends from (_WIN32_IE >= 0x0400) */ #endif bool CPanel::InvokePluginCommand(unsigned id, @@ -1096,7 +1119,7 @@ */ CRecordVector operatedIndices; - GetOperatedItemIndices(operatedIndices); + Get_ItemIndices_Operated(operatedIndices); // negative x,y are possible for multi-screen modes. // x=-1 && y=-1 for keyboard call (SHIFT+F10 and others). @@ -1130,9 +1153,9 @@ CMyComPtr sevenZipContextMenu; CMyComPtr systemContextMenu; - CreateFileMenu(menu, sevenZipContextMenu, systemContextMenu, false); + CreateFileMenu(menu, sevenZipContextMenu, systemContextMenu, false); // programMenu - unsigned id = menu.Track(TPM_LEFTALIGN + const unsigned id = (unsigned)menu.Track(TPM_LEFTALIGN #ifndef UNDER_CE | TPM_RIGHTBUTTON #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelOperations.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelOperations.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelOperations.cpp 2022-07-15 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelOperations.cpp 2023-03-20 12:00:00.000000000 +0000 @@ -24,9 +24,6 @@ using namespace NFile; using namespace NName; -#define MY_CAST_FUNC (void(*)()) -// #define MY_CAST_FUNC - #ifndef _UNICODE extern bool g_IsNT; #endif @@ -40,7 +37,7 @@ class CThreadFolderOperations: public CProgressThreadVirt { - HRESULT ProcessVirt(); + HRESULT ProcessVirt() Z7_override; public: EFolderOpType OpType; UString Name; @@ -58,7 +55,7 @@ HRESULT CThreadFolderOperations::ProcessVirt() { NCOM::CComInitializer comInitializer; - switch (OpType) + switch ((int)OpType) { case FOLDER_TYPE_CREATE_FOLDER: return FolderOperations->CreateFolder(Name, UpdateCallback); @@ -94,7 +91,7 @@ MainTitle = "7-Zip"; // LangString(IDS_APP_TITLE); MainAddTitle = progressTitle + L' '; - RINOK(Create(progressTitle, MainWindow)); + RINOK(Create(progressTitle, MainWindow)) return Result; } @@ -116,7 +113,7 @@ { CDisableTimerProcessing disableTimerProcessing(*this); CRecordVector indices; - GetOperatedItemIndices(indices); + Get_ItemIndices_Operated(indices); if (indices.IsEmpty()) return; CSelectedState state; @@ -141,7 +138,7 @@ fo.hwnd = GetParent(); fo.wFunc = FO_DELETE; fo.pFrom = (const CHAR *)buffer; - fo.pTo = 0; + fo.pTo = NULL; fo.fFlags = 0; if (toRecycleBin) fo.fFlags |= FOF_ALLOWUNDO; @@ -150,8 +147,8 @@ // fo.fFlags |= FOF_SILENT; // fo.fFlags |= FOF_WANTNUKEWARNING; fo.fAnyOperationsAborted = FALSE; - fo.hNameMappings = 0; - fo.lpszProgressTitle = 0; + fo.hNameMappings = NULL; + fo.lpszProgressTitle = NULL; /* int res = */ ::SHFileOperationA(&fo); } else @@ -184,23 +181,24 @@ fo.hwnd = GetParent(); fo.wFunc = FO_DELETE; fo.pFrom = (const WCHAR *)buffer; - fo.pTo = 0; + fo.pTo = NULL; fo.fFlags = 0; if (toRecycleBin) fo.fFlags |= FOF_ALLOWUNDO; fo.fAnyOperationsAborted = FALSE; - fo.hNameMappings = 0; - fo.lpszProgressTitle = 0; + fo.hNameMappings = NULL; + fo.lpszProgressTitle = NULL; // int res; #ifdef _UNICODE /* res = */ ::SHFileOperationW(&fo); #else - Func_SHFileOperationW shFileOperationW = (Func_SHFileOperationW) - MY_CAST_FUNC - ::GetProcAddress(::GetModuleHandleW(L"shell32.dll"), "SHFileOperationW"); - if (!shFileOperationW) + Func_SHFileOperationW + f_SHFileOperationW = Z7_GET_PROC_ADDRESS( + Func_SHFileOperationW, ::GetModuleHandleW(L"shell32.dll"), + "SHFileOperationW"); + if (!f_SHFileOperationW) return; - /* res = */ shFileOperationW(&fo); + /* res = */ f_SHFileOperationW(&fo); #endif } } @@ -225,7 +223,7 @@ UString messageParam; if (indices.Size() == 1) { - int index = indices[0]; + const unsigned index = indices[0]; messageParam = GetItemRelPath2(index); if (IsItem_Folder(index)) { @@ -262,7 +260,7 @@ BOOL CPanel::OnBeginLabelEdit(LV_DISPINFOW * lpnmh) { - int realIndex = GetRealIndex(lpnmh->item); + const unsigned realIndex = GetRealIndex(lpnmh->item); if (realIndex == kParentIndex) return TRUE; if (IsThereReadOnlyFolder()) @@ -314,7 +312,7 @@ SaveSelectedState(_selectedState); - int realIndex = GetRealIndex(lpnmh->item); + const unsigned realIndex = GetRealIndex(lpnmh->item); if (realIndex == kParentIndex) return FALSE; const UString prefix = GetItemPrefix(realIndex); @@ -454,14 +452,14 @@ newName = correctName; } - HRESULT result = _folderOperations->CreateFile(newName, 0); + const HRESULT result = _folderOperations->CreateFile(newName, NULL); if (result != S_OK) { MessageBox_Error_HRESULT_Caption(result, LangString(IDS_CREATE_FILE_ERROR)); // MessageBoxErrorForUpdate(result, IDS_CREATE_FILE_ERROR); return; } - int pos = newName.Find(WCHAR_PATH_SEPARATOR); + const int pos = newName.Find(WCHAR_PATH_SEPARATOR); if (pos >= 0) newName.DeleteFrom((unsigned)pos); if (!_mySelectMode) @@ -488,10 +486,10 @@ if (!CheckBeforeUpdate(IDS_COMMENT)) return; CDisableTimerProcessing disableTimerProcessing2(*this); - int index = _listView.GetFocusedItem(); + const int index = _listView.GetFocusedItem(); if (index < 0) return; - int realIndex = GetRealItemIndex(index); + const unsigned realIndex = GetRealItemIndex(index); if (realIndex == kParentIndex) return; CSelectedState state; @@ -506,7 +504,7 @@ else if (propVariant.vt != VT_EMPTY) return; } - UString name = GetItemRelPath2(realIndex); + const UString name = GetItemRelPath2(realIndex); CComboDialog dlg; dlg.Title = name; dlg.Title += " : "; @@ -518,7 +516,7 @@ NCOM::CPropVariant propVariant (dlg.Value); CDisableNotify disableNotify(*this); - HRESULT result = _folderOperations->SetProperty(realIndex, kpidComment, &propVariant, NULL); + const HRESULT result = _folderOperations->SetProperty(realIndex, kpidComment, &propVariant, NULL); if (result != S_OK) { if (result == E_NOINTERFACE) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelSelect.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelSelect.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelSelect.cpp 2021-01-24 14:01:52.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelSelect.cpp 2023-03-20 12:00:00.000000000 +0000 @@ -15,7 +15,7 @@ { if (!_mySelectMode) return; - int focusedItem = _listView.GetFocusedItem(); + const int focusedItem = _listView.GetFocusedItem(); if (focusedItem < 0) return; if (!_selectionIsDefined) @@ -26,7 +26,7 @@ int numItems = _listView.GetItemCount(); for (int i = 0; i < numItems; i++) { - int realIndex = GetRealItemIndex(i); + const unsigned realIndex = GetRealItemIndex(i); if (realIndex == kParentIndex) continue; if (i >= startItem && i <= finishItem) @@ -44,10 +44,10 @@ { if (!_mySelectMode) return; - int focusedItem = _listView.GetFocusedItem(); + const int focusedItem = _listView.GetFocusedItem(); if (focusedItem < 0) return; - int realIndex = GetRealItemIndex(focusedItem); + const unsigned realIndex = GetRealItemIndex(focusedItem); if (_selectionIsDefined) { @@ -84,11 +84,11 @@ // _listView.SetItemState_Selected(focusedItem); */ - int focusedItem = _listView.GetFocusedItem(); + const int focusedItem = _listView.GetFocusedItem(); if (focusedItem < 0) return; - int realIndex = GetRealItemIndex(focusedItem); + const unsigned realIndex = GetRealItemIndex(focusedItem); if (realIndex != kParentIndex) { bool isSelected = !_selectedStatusVector[realIndex]; @@ -109,10 +109,10 @@ /* void CPanel::OnUpWithShift() { - int focusedItem = _listView.GetFocusedItem(); + const int focusedItem = _listView.GetFocusedItem(); if (focusedItem < 0) return; - int index = GetRealItemIndex(focusedItem); + const int index = GetRealItemIndex(focusedItem); if (index == kParentIndex) return; _selectedStatusVector[index] = !_selectedStatusVector[index]; @@ -121,10 +121,10 @@ void CPanel::OnDownWithShift() { - int focusedItem = _listView.GetFocusedItem(); + const int focusedItem = _listView.GetFocusedItem(); if (focusedItem < 0) return; - int index = GetRealItemIndex(focusedItem); + const int index = GetRealItemIndex(focusedItem); if (index == kParentIndex) return; _selectedStatusVector[index] = !_selectedStatusVector[index]; @@ -141,7 +141,7 @@ int numItems = _listView.GetItemCount(); for (int i = 0; i < numItems; i++) { - int realIndex = GetRealItemIndex(i); + const unsigned realIndex = GetRealItemIndex(i); if (realIndex != kParentIndex) _listView.SetItemState_Selected(i, _selectedStatusVector[realIndex]); } @@ -168,10 +168,10 @@ void CPanel::SelectByType(bool selectMode) { - int focusedItem = _listView.GetFocusedItem(); + const int focusedItem = _listView.GetFocusedItem(); if (focusedItem < 0) return; - int realIndex = GetRealItemIndex(focusedItem); + const unsigned realIndex = GetRealItemIndex(focusedItem); UString name = GetItemName(realIndex); bool isItemFolder = IsItem_Folder(realIndex); @@ -214,10 +214,12 @@ { if (!_mySelectMode) { + /* unsigned numSelected = 0; FOR_VECTOR (i, _selectedStatusVector) if (_selectedStatusVector[i]) numSelected++; + */ // 17.02: fixed : now we invert item even, if single item is selected /* if (numSelected == 1) @@ -225,7 +227,7 @@ int focused = _listView.GetFocusedItem(); if (focused >= 0) { - int realIndex = GetRealItemIndex(focused); + const unsigned realIndex = GetRealItemIndex(focused); if (realIndex >= 0) if (_selectedStatusVector[realIndex]) _selectedStatusVector[realIndex] = false; @@ -251,7 +253,7 @@ { // CPanel::OnItemChanged notify for LVIS_SELECTED change doesn't work here. Why? // so we change _selectedStatusVector[realIndex] here. - int realIndex = GetRealItemIndex(focused); + const unsigned realIndex = GetRealItemIndex(focused); if (realIndex != kParentIndex) _selectedStatusVector[realIndex] = true; _listView.SetItemState_Selected(focused); @@ -273,19 +275,19 @@ if ((itemActivate->uKeyFlags & LVKF_SHIFT) != 0) { // int focusedIndex = _listView.GetFocusedItem(); - int focusedIndex = _startGroupSelect; + const int focusedIndex = _startGroupSelect; if (focusedIndex < 0) return; - int startItem = MyMin(focusedIndex, indexInList); - int finishItem = MyMax(focusedIndex, indexInList); + const int startItem = MyMin(focusedIndex, indexInList); + const int finishItem = MyMax(focusedIndex, indexInList); - int numItems = _listView.GetItemCount(); + const int numItems = _listView.GetItemCount(); for (int i = 0; i < numItems; i++) { - int realIndex = GetRealItemIndex(i); + const unsigned realIndex = GetRealItemIndex(i); if (realIndex == kParentIndex) continue; - bool selected = (i >= startItem && i <= finishItem); + const bool selected = (i >= startItem && i <= finishItem); if (_selectedStatusVector[realIndex] != selected) { _selectedStatusVector[realIndex] = selected; @@ -301,7 +303,7 @@ #ifndef UNDER_CE if ((itemActivate->uKeyFlags & LVKF_CONTROL) != 0) { - int realIndex = GetRealItemIndex(indexInList); + const unsigned realIndex = GetRealItemIndex(indexInList); if (realIndex != kParentIndex) { _selectedStatusVector[realIndex] = !_selectedStatusVector[realIndex]; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelSort.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelSort.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelSort.cpp 2021-01-22 21:26:18.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelSort.cpp 2023-01-19 20:00:00.000000000 +0000 @@ -52,8 +52,8 @@ static int CompareFileNames_Le16(const Byte *s1, unsigned size1, const Byte *s2, unsigned size2) { - size1 &= ~1; - size2 &= ~1; + size1 &= ~1u; + size2 &= ~1u; for (unsigned i = 0;; i += 2) { if (i >= size1) @@ -76,8 +76,8 @@ static inline const wchar_t *GetExtensionPtr(const UString &name) { - int dotPos = name.ReverseFind_Dot(); - return name.Ptr((dotPos < 0) ? name.Len() : dotPos); + const int dotPos = name.ReverseFind_Dot(); + return name.Ptr(dotPos < 0 ? name.Len() : (unsigned)dotPos); } void CPanel::SetSortRawStatus() @@ -142,9 +142,9 @@ // if (panel->_sortIndex == 0) case kpidName: { - const UString name1 = panel->GetItemName((int)lParam1); - const UString name2 = panel->GetItemName((int)lParam2); - int res = CompareFileNames_ForFolderList(name1, name2); + const UString name1 = panel->GetItemName((unsigned)lParam1); + const UString name2 = panel->GetItemName((unsigned)lParam2); + const int res = CompareFileNames_ForFolderList(name1, name2); /* if (res != 0 || !panel->_flatMode) return res; @@ -156,8 +156,8 @@ } case kpidExtension: { - const UString name1 = panel->GetItemName((int)lParam1); - const UString name2 = panel->GetItemName((int)lParam2); + const UString name1 = panel->GetItemName((unsigned)lParam1); + const UString name2 = panel->GetItemName((unsigned)lParam2); return CompareFileNames_ForFolderList( GetExtensionPtr(name1), GetExtensionPtr(name2)); @@ -186,18 +186,18 @@ int CALLBACK CompareItems(LPARAM lParam1, LPARAM lParam2, LPARAM lpData) { if (lpData == 0) return 0; - if (lParam1 == kParentIndex) return -1; - if (lParam2 == kParentIndex) return 1; + if (lParam1 == (int)kParentIndex) return -1; + if (lParam2 == (int)kParentIndex) return 1; CPanel *panel = (CPanel*)lpData; - bool isDir1 = panel->IsItem_Folder((int)lParam1); - bool isDir2 = panel->IsItem_Folder((int)lParam2); + const bool isDir1 = panel->IsItem_Folder((unsigned)lParam1); + const bool isDir2 = panel->IsItem_Folder((unsigned)lParam2); if (isDir1 && !isDir2) return -1; if (isDir2 && !isDir1) return 1; - int result = CompareItems2(lParam1, lParam2, lpData); + const int result = CompareItems2(lParam1, lParam2, lpData); return panel->_ascending ? result: (-result); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelSplitFile.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelSplitFile.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PanelSplitFile.cpp 2020-05-25 07:58:58.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PanelSplitFile.cpp 2023-03-20 10:00:00.000000000 +0000 @@ -30,7 +30,7 @@ { UString UnchangedPart; UString ChangedPart; - CVolSeqName(): ChangedPart("000") {}; + CVolSeqName(): ChangedPart("000") {} void SetNumDigits(UInt64 numVolumes) { @@ -64,13 +64,13 @@ { for (int i = (int)ChangedPart.Len() - 1; i >= 0; i--) { - wchar_t c = ChangedPart[i]; + const wchar_t c = ChangedPart[i]; if (c != L'9') { - ChangedPart.ReplaceOneCharAtPos(i, (wchar_t)(c + 1)); + ChangedPart.ReplaceOneCharAtPos((unsigned)i, (wchar_t)(c + 1)); break; } - ChangedPart.ReplaceOneCharAtPos(i, L'0'); + ChangedPart.ReplaceOneCharAtPos((unsigned)i, L'0'); if (i == 0) ChangedPart.InsertAtFront(L'1'); } @@ -79,7 +79,7 @@ class CThreadSplit: public CProgressThreadVirt { - HRESULT ProcessVirt(); + HRESULT ProcessVirt() Z7_override; public: FString FilePath; FString VolBasePath; @@ -142,7 +142,7 @@ { NIO::CInFile inFile; if (!inFile.Open(FilePath)) - return GetLastError(); + return GetLastError_noZero_HRESULT(); CPreAllocOutFile outFile; @@ -155,7 +155,7 @@ UInt64 length; if (!inFile.GetLength(length)) - return GetLastError(); + return GetLastError_noZero_HRESULT(); CProgressSync &sync = Sync; sync.Set_NumBytesTotal(length); @@ -181,7 +181,7 @@ } UInt32 processedSize; if (!inFile.Read(buffer, needSize, processedSize)) - return GetLastError(); + return GetLastError_noZero_HRESULT(); if (processedSize == 0) return S_OK; needSize = processedSize; @@ -189,12 +189,12 @@ if (outFile.Written == 0) { FString name = VolBasePath; - name += '.'; + name.Add_Dot(); name += us2fs(seqName.GetNextName()); sync.Set_FilePath(fs2us(name)); if (!outFile.File.Create(name, false)) { - HRESULT res = GetLastError(); + const HRESULT res = GetLastError_noZero_HRESULT(); AddErrorPath(name); return res; } @@ -209,7 +209,7 @@ } if (!outFile.Write(buffer, needSize, processedSize)) - return GetLastError(); + return GetLastError_noZero_HRESULT(); if (needSize != processedSize) throw g_Message_FileWriteError; @@ -225,7 +225,7 @@ if (pos - prev >= ((UInt32)1 << 22) || outFile.Written == 0) { - RINOK(sync.Set_NumBytesCur(pos)); + RINOK(sync.Set_NumBytesCur(pos)) prev = pos; } } @@ -234,7 +234,7 @@ void CApp::Split() { - int srcPanelIndex = GetFocusedPanelIndex(); + const unsigned srcPanelIndex = GetFocusedPanelIndex(); CPanel &srcPanel = Panels[srcPanelIndex]; if (!srcPanel.Is_IO_FS_Folder()) { @@ -242,7 +242,7 @@ return; } CRecordVector indices; - srcPanel.GetOperatedItemIndices(indices); + srcPanel.Get_ItemIndices_Operated(indices); if (indices.IsEmpty()) return; if (indices.Size() != 1) @@ -250,7 +250,7 @@ srcPanel.MessageBox_Error_LangID(IDS_SELECT_ONE_FILE); return; } - int index = indices[0]; + const unsigned index = indices[0]; if (srcPanel.IsItem_Folder(index)) { srcPanel.MessageBox_Error_LangID(IDS_SELECT_ONE_FILE); @@ -258,7 +258,7 @@ } const UString itemName = srcPanel.GetItemName(index); - UString srcPath = srcPanel.GetFsPath() + srcPanel.GetItemPrefix(index); + const UString srcPath = srcPanel.GetFsPath() + srcPanel.GetItemPrefix(index); UString path = srcPath; unsigned destPanelIndex = (NumPanels <= 1) ? srcPanelIndex : (1 - srcPanelIndex); CPanel &destPanel = Panels[destPanelIndex]; @@ -297,7 +297,7 @@ NName::NormalizeDirPathPrefix(path); if (!CreateComplexDir(us2fs(path))) { - DWORD lastError = ::GetLastError(); + const HRESULT lastError = GetLastError_noZero_HRESULT(); srcPanel.MessageBox_Error_2Lines_Message_HRESULT(MyFormatNew(IDS_CANNOT_CREATE_FOLDER, path), lastError); return; } @@ -308,8 +308,8 @@ CProgressDialog &progressDialog = spliter; - UString progressWindowTitle ("7-Zip"); // LangString(IDS_APP_TITLE, 0x03000000); - UString title = LangString(IDS_SPLITTING); + const UString progressWindowTitle ("7-Zip"); // LangString(IDS_APP_TITLE, 0x03000000); + const UString title = LangString(IDS_SPLITTING); progressDialog.ShowCompressionInfo = false; @@ -344,7 +344,7 @@ class CThreadCombine: public CProgressThreadVirt { - HRESULT ProcessVirt(); + HRESULT ProcessVirt() Z7_override; public: FString InputDirPrefix; FStringVector Names; @@ -357,7 +357,7 @@ NIO::COutFile outFile; if (!outFile.Create(OutputPath, false)) { - HRESULT res = GetLastError(); + const HRESULT res = GetLastError_noZero_HRESULT(); AddErrorPath(OutputPath); return res; } @@ -376,7 +376,7 @@ const FString nextName = InputDirPrefix + Names[i]; if (!inFile.Open(nextName)) { - HRESULT res = GetLastError(); + const HRESULT res = GetLastError_noZero_HRESULT(); AddErrorPath(nextName); return res; } @@ -386,23 +386,23 @@ UInt32 processedSize; if (!inFile.Read(buffer, kBufSize, processedSize)) { - HRESULT res = GetLastError(); + const HRESULT res = GetLastError_noZero_HRESULT(); AddErrorPath(nextName); return res; } if (processedSize == 0) break; - UInt32 needSize = processedSize; + const UInt32 needSize = processedSize; if (!outFile.Write(buffer, needSize, processedSize)) { - HRESULT res = GetLastError(); + const HRESULT res = GetLastError_noZero_HRESULT(); AddErrorPath(OutputPath); return res; } if (needSize != processedSize) throw g_Message_FileWriteError; pos += processedSize; - RINOK(sync.Set_NumBytesCur(pos)); + RINOK(sync.Set_NumBytesCur(pos)) } } return S_OK; @@ -418,7 +418,7 @@ void CApp::Combine() { - int srcPanelIndex = GetFocusedPanelIndex(); + const unsigned srcPanelIndex = GetFocusedPanelIndex(); CPanel &srcPanel = Panels[srcPanelIndex]; if (!srcPanel.IsFSFolder()) { @@ -426,10 +426,10 @@ return; } CRecordVector indices; - srcPanel.GetOperatedItemIndices(indices); + srcPanel.Get_ItemIndices_Operated(indices); if (indices.IsEmpty()) return; - int index = indices[0]; + const unsigned index = indices[0]; if (indices.Size() != 1 || srcPanel.IsItem_Folder(index)) { srcPanel.MessageBox_Error_LangID(IDS_COMBINE_SELECT_ONE_FILE); @@ -510,7 +510,7 @@ NName::NormalizeDirPathPrefix(path); if (!CreateComplexDir(us2fs(path))) { - DWORD lastError = ::GetLastError(); + const HRESULT lastError = GetLastError_noZero_HRESULT(); srcPanel.MessageBox_Error_2Lines_Message_HRESULT(MyFormatNew(IDS_CANNOT_CREATE_FOLDER, path), lastError); return; } @@ -537,8 +537,8 @@ CProgressDialog &progressDialog = combiner; progressDialog.ShowCompressionInfo = false; - UString progressWindowTitle ("7-Zip"); // LangString(IDS_APP_TITLE, 0x03000000); - UString title = LangString(IDS_COMBINING); + const UString progressWindowTitle ("7-Zip"); // LangString(IDS_APP_TITLE, 0x03000000); + const UString title = LangString(IDS_COMBINING); progressDialog.MainWindow = _window; progressDialog.MainTitle = progressWindowTitle; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PasswordDialog.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PasswordDialog.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PasswordDialog.cpp 2013-02-22 17:33:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PasswordDialog.cpp 2023-03-06 16:00:00.000000000 +0000 @@ -4,11 +4,11 @@ #include "PasswordDialog.h" -#ifdef LANG +#ifdef Z7_LANG #include "LangUtils.h" #endif -#ifdef LANG +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { IDT_PASSWORD_ENTER, @@ -30,9 +30,9 @@ bool CPasswordDialog::OnInit() { - #ifdef LANG + #ifdef Z7_LANG LangSetWindowText(*this, IDD_PASSWORD); - LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); + LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs)); #endif _passwordEdit.Attach(GetItem(IDE_PASSWORD_PASSWORD)); CheckButton(IDX_PASSWORD_SHOW, ShowPassword); @@ -40,7 +40,7 @@ return CModalDialog::OnInit(); } -bool CPasswordDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CPasswordDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { if (buttonID == IDX_PASSWORD_SHOW) { diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PasswordDialog.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PasswordDialog.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PasswordDialog.h 2013-01-17 10:24:08.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PasswordDialog.h 2023-01-28 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // PasswordDialog.h -#ifndef __PASSWORD_DIALOG_H -#define __PASSWORD_DIALOG_H +#ifndef ZIP7_INC_PASSWORD_DIALOG_H +#define ZIP7_INC_PASSWORD_DIALOG_H #include "../../../Windows/Control/Dialog.h" #include "../../../Windows/Control/Edit.h" @@ -12,9 +12,9 @@ { NWindows::NControl::CEdit _passwordEdit; - virtual void OnOK(); - virtual bool OnInit(); - virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); + virtual void OnOK() Z7_override; + virtual bool OnInit() Z7_override; + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; void SetTextSpec(); void ReadControls(); public: @@ -22,7 +22,7 @@ bool ShowPassword; CPasswordDialog(): ShowPassword(false) {} - INT_PTR Create(HWND parentWindow = 0) { return CModalDialog::Create(IDD_PASSWORD, parentWindow); } + INT_PTR Create(HWND parentWindow = NULL) { return CModalDialog::Create(IDD_PASSWORD, parentWindow); } }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PluginInterface.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PluginInterface.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PluginInterface.h 2015-02-09 11:09:56.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PluginInterface.h 2023-02-01 18:00:00.000000000 +0000 @@ -1,31 +1,32 @@ // PluginInterface.h -#ifndef __PLUGIN_INTERFACE_H -#define __PLUGIN_INTERFACE_H +#ifndef ZIP7_INC_PLUGIN_INTERFACE_H +#define ZIP7_INC_PLUGIN_INTERFACE_H /* -#include "../../../Common/Types.h" +#include "../../../../C/7zTypes.h" #include "../../IDecl.h" -#define PLUGIN_INTERFACE(i, x) DECL_INTERFACE(i, 0x0A, x) +#define Z7_IFACE_CONSTR_PLUGIN(i, n) \ + Z7_DECL_IFACE_7ZIP(i, 0x0A, n) \ + { Z7_IFACE_COM7_PURE(i) }; -PLUGIN_INTERFACE(IInitContextMenu, 0x00) -{ - STDMETHOD(InitContextMenu)(const wchar_t *folder, const wchar_t * const *names, UInt32 numFiles) PURE; -}; - -PLUGIN_INTERFACE(IPluginOptionsCallback, 0x01) -{ - STDMETHOD(GetProgramFolderPath)(BSTR *value) PURE; - STDMETHOD(GetProgramPath)(BSTR *value) PURE; - STDMETHOD(GetRegistryCUPath)(BSTR *value) PURE; -}; - -PLUGIN_INTERFACE(IPluginOptions, 0x02) -{ - STDMETHOD(PluginOptions)(HWND hWnd, IPluginOptionsCallback *callback) PURE; - // STDMETHOD(GetFileExtensions)(BSTR *extensions) PURE; -}; -*/ +#define Z7_IFACEM_IInitContextMenu(x) \ + x(InitContextMenu(const wchar_t *folder, const wchar_t * const *names, UInt32 numFiles)) \ + +Z7_IFACE_CONSTR_PLUGIN(IInitContextMenu, 0x00) + +#define Z7_IFACEM_IPluginOptionsCallback(x) \ + x(GetProgramFolderPath(BSTR *value)) \ + x(GetProgramPath(BSTR *value)) \ + x(GetRegistryCUPath(BSTR *value)) \ +Z7_IFACE_CONSTR_PLUGIN(IPluginOptionsCallback, 0x01) + +#define Z7_IFACEM_IPluginOptions(x) \ + x(PluginOptions(HWND hWnd, IPluginOptionsCallback *callback)) \ + // x(GetFileExtensions(BSTR *extensions)) + +Z7_IFACE_CONSTR_PLUGIN(IPluginOptions, 0x02) +*/ #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PluginLoader.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PluginLoader.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PluginLoader.h 2013-11-23 17:49:34.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PluginLoader.h 2023-03-20 11:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // PluginLoader.h -#ifndef __PLUGIN_LOADER_H -#define __PLUGIN_LOADER_H +#ifndef ZIP7_INC_PLUGIN_LOADER_H +#define ZIP7_INC_PLUGIN_LOADER_H #include "../../../Windows/DLL.h" @@ -12,15 +12,18 @@ public: HRESULT CreateManager(REFGUID clsID, IFolderManager **manager) { - Func_CreateObject createObject = (Func_CreateObject)GetProc("CreateObject"); + const + Func_CreateObject createObject = Z7_GET_PROC_ADDRESS( + Func_CreateObject, Get_HMODULE(), + "CreateObject"); if (!createObject) - return GetLastError(); + return GetLastError_noZero_HRESULT(); return createObject(&clsID, &IID_IFolderManager, (void **)manager); } HRESULT LoadAndCreateManager(CFSTR filePath, REFGUID clsID, IFolderManager **manager) { if (!Load(filePath)) - return GetLastError(); + return GetLastError_noZero_HRESULT(); return CreateManager(clsID, manager); } }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ProgramLocation.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ProgramLocation.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ProgramLocation.h 2011-02-25 09:32:13.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ProgramLocation.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,6 +1,6 @@ // ProgramLocation.h -#ifndef __PROGRAM_LOCATION_H -#define __PROGRAM_LOCATION_H +#ifndef ZIP7_INC_PROGRAM_LOCATION_H +#define ZIP7_INC_PROGRAM_LOCATION_H #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ProgressDialog2.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ProgressDialog2.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ProgressDialog2.cpp 2021-09-03 12:13:46.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ProgressDialog2.cpp 2023-04-13 10:00:00.000000000 +0000 @@ -2,6 +2,10 @@ #include "StdAfx.h" +#ifdef Z7_OLD_WIN_SDK +#include +#endif + #include "../../../Common/IntToString.h" #include "../../../Common/StringConvert.h" @@ -43,7 +47,7 @@ static const DWORD kPauseSleepTime = 100; -#ifdef LANG +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { @@ -67,19 +71,19 @@ #endif -#define UNDEFINED_VAL ((UInt64)(Int64)-1) -#define INIT_AS_UNDEFINED(v) v = UNDEFINED_VAL; -#define IS_UNDEFINED_VAL(v) ((v) == UNDEFINED_VAL) -#define IS_DEFINED_VAL(v) ((v) != UNDEFINED_VAL) +#define UNDEFINED_VAL ((UInt64)(Int64)-1) +#define INIT_AS_UNDEFINED(v) v = UNDEFINED_VAL; +#define IS_UNDEFINED_VAL(v) ((v) == UNDEFINED_VAL) +#define IS_DEFINED_VAL(v) ((v) != UNDEFINED_VAL) CProgressSync::CProgressSync(): _stopped(false), _paused(false), _bytesProgressMode(true), + _isDir(false), _totalBytes(UNDEFINED_VAL), _completedBytes(0), _totalFiles(UNDEFINED_VAL), _curFiles(0), _inSize(UNDEFINED_VAL), - _outSize(UNDEFINED_VAL), - _isDir(false) + _outSize(UNDEFINED_VAL) {} #define CHECK_STOP if (_stopped) return E_ABORT; if (!_paused) return S_OK; @@ -228,7 +232,7 @@ AddError_Message(s); } -void CProgressSync::AddError_Code_Name(DWORD systemError, const wchar_t *name) +void CProgressSync::AddError_Code_Name(HRESULT systemError, const wchar_t *name) { UString s = NError::MyFormatMessage(systemError); if (systemError == 0) @@ -262,20 +266,20 @@ throw 1334987; if (_createDialogEvent.Create() != S_OK) throw 1334987; - #ifdef __ITaskbarList3_INTERFACE_DEFINED__ + // #ifdef __ITaskbarList3_INTERFACE_DEFINED__ CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER, IID_ITaskbarList3, (void**)&_taskbarList); if (_taskbarList) _taskbarList->HrInit(); - #endif + // #endif } -#ifndef _SFX +#ifndef Z7_SFX CProgressDialog::~CProgressDialog() { - #ifdef __ITaskbarList3_INTERFACE_DEFINED__ + // #ifdef __ITaskbarList3_INTERFACE_DEFINED__ SetTaskbarProgressState(TBPF_NOPROGRESS); - #endif + // #endif AddToTitle(L""); } void CProgressDialog::AddToTitle(LPCWSTR s) @@ -292,7 +296,7 @@ void CProgressDialog::SetTaskbarProgressState() { - #ifdef __ITaskbarList3_INTERFACE_DEFINED__ + // #ifdef __ITaskbarList3_INTERFACE_DEFINED__ if (_taskbarList && _hwndForTaskbar) { TBPFLAG tbpFlags; @@ -302,7 +306,7 @@ tbpFlags = _errorsWereDisplayed ? TBPF_ERROR: TBPF_NORMAL; SetTaskbarProgressState(tbpFlags); } - #endif + // #endif } static const unsigned kTitleFileNameSizeLimit = 36; @@ -331,23 +335,23 @@ if (!_hwndForTaskbar) _hwndForTaskbar = *this; - INIT_AS_UNDEFINED(_progressBar_Range); - INIT_AS_UNDEFINED(_progressBar_Pos); + INIT_AS_UNDEFINED(_progressBar_Range) + INIT_AS_UNDEFINED(_progressBar_Pos) - INIT_AS_UNDEFINED(_prevPercentValue); - INIT_AS_UNDEFINED(_prevElapsedSec); - INIT_AS_UNDEFINED(_prevRemainingSec); + INIT_AS_UNDEFINED(_prevPercentValue) + INIT_AS_UNDEFINED(_prevElapsedSec) + INIT_AS_UNDEFINED(_prevRemainingSec) - INIT_AS_UNDEFINED(_prevSpeed); + INIT_AS_UNDEFINED(_prevSpeed) _prevSpeed_MoveBits = 0; _prevTime = ::GetTickCount(); _elapsedTime = 0; - INIT_AS_UNDEFINED(_totalBytes_Prev); - INIT_AS_UNDEFINED(_processed_Prev); - INIT_AS_UNDEFINED(_packed_Prev); - INIT_AS_UNDEFINED(_ratio_Prev); + INIT_AS_UNDEFINED(_totalBytes_Prev) + INIT_AS_UNDEFINED(_processed_Prev) + INIT_AS_UNDEFINED(_packed_Prev) + INIT_AS_UNDEFINED(_ratio_Prev) _filesStr_Prev.Empty(); _filesTotStr_Prev.Empty(); @@ -362,9 +366,9 @@ _wasCreated = true; _dialogCreatedEvent.Set(); - #ifdef LANG - LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); - LangSetDlgItems_Colon(*this, kLangIDs_Colon, ARRAY_SIZE(kLangIDs_Colon)); + #ifdef Z7_LANG + LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs)); + LangSetDlgItems_Colon(*this, kLangIDs_Colon, Z7_ARRAY_SIZE(kLangIDs_Colon)); #endif CWindow window(GetItem(IDB_PROGRESS_BACKGROUND)); @@ -453,12 +457,12 @@ InvalidateRect(NULL); - int xSizeClient = xSize - mx * 2; + const int xSizeClient = xSize - mx * 2; { - int i; + unsigned i; for (i = 800; i > 40; i = i * 9 / 10) - if (Units_To_Pixels_X(i) <= xSizeClient) + if (Units_To_Pixels_X((int)i) <= xSizeClient) break; _numReduceSymbols = i / 4; } @@ -473,7 +477,7 @@ int mx2 = mx; for (;; mx2--) { - int bSize2 = bSizeX * 3 + mx2 * 2; + const int bSize2 = bSizeX * 3 + mx2 * 2; if (bSize2 <= xSizeClient) break; if (mx2 < 5) @@ -488,7 +492,7 @@ { RECT r; GetClientRectOfItem(IDL_PROGRESS_MESSAGES, r); - int y = r.top; + const int y = r.top; int ySize2 = yPos - my - y; const int kMinYSize = _buttonSizeY + _buttonSizeY * 3 / 4; int xx = xSize - mx * 2; @@ -519,13 +523,13 @@ labelSize = Units_To_Pixels_X(MY_PROGRESS_LABEL_UNITS_MIN); valueSize = Units_To_Pixels_X(MY_PROGRESS_VAL_UNITS); padSize = Units_To_Pixels_X(MY_PROGRESS_PAD_UNITS); - int requiredSize = (labelSize + valueSize) * 2 + padSize; + const int requiredSize = (labelSize + valueSize) * 2 + padSize; int gSize; { if (requiredSize < xSizeClient) { - int incr = (xSizeClient - requiredSize) / 3; + const int incr = (xSizeClient - requiredSize) / 3; labelSize += incr; } else @@ -540,7 +544,7 @@ labelSize = gSize - valueSize; yPos = my; - for (unsigned i = 0; i < ARRAY_SIZE(kIDs); i += 2) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(kIDs); i += 2) { int x = mx; const unsigned kNumColumn1Items = 5 * 2; @@ -566,7 +570,7 @@ if (range == _progressBar_Range) return; _progressBar_Range = range; - INIT_AS_UNDEFINED(_progressBar_Pos); + INIT_AS_UNDEFINED(_progressBar_Pos) _progressConv.Init(range); m_ProgressBar.SetRange32(0, _progressConv.Count(range)); } @@ -578,10 +582,10 @@ pos - _progressBar_Pos >= (_progressBar_Range >> 10)) { m_ProgressBar.SetPos(_progressConv.Count(pos)); - #ifdef __ITaskbarList3_INTERFACE_DEFINED__ + // #ifdef __ITaskbarList3_INTERFACE_DEFINED__ if (_taskbarList && _hwndForTaskbar) _taskbarList->SetProgressValue(_hwndForTaskbar, pos, _progressBar_Range); - #endif + // #endif _progressBar_Pos = pos; } } @@ -603,10 +607,10 @@ else { UInt32 hours32 = (UInt32)hours; - UINT_TO_STR_2(hours32); + UINT_TO_STR_2(hours32) } - *s++ = ':'; UINT_TO_STR_2(minutes); - *s++ = ':'; UINT_TO_STR_2(seconds); + *s++ = ':'; UINT_TO_STR_2(minutes) + *s++ = ':'; UINT_TO_STR_2(seconds) *s = 0; } @@ -627,7 +631,7 @@ } } -void CProgressDialog::ShowSize(int id, UInt64 val, UInt64 &prev) +void CProgressDialog::ShowSize(unsigned id, UInt64 val, UInt64 &prev) { if (val == prev) return; @@ -771,7 +775,7 @@ { if (IS_DEFINED_VAL(_prevRemainingSec)) { - INIT_AS_UNDEFINED(_prevRemainingSec); + INIT_AS_UNDEFINED(_prevRemainingSec) SetItemText(IDT_PROGRESS_REMAINING_VAL, L""); } } @@ -790,8 +794,9 @@ } } { - UInt64 elapsedTime = (_elapsedTime == 0) ? 1 : _elapsedTime; - UInt64 v = (progressCompleted * 1000) / elapsedTime; + const UInt64 elapsedTime = (_elapsedTime == 0) ? 1 : _elapsedTime; + // 22.02: progressCompleted can be for number of files + UInt64 v = (completed * 1000) / elapsedTime; Byte c = 0; unsigned moveBits = 0; if (v >= ((UInt64)10000 << 10)) { moveBits = 20; c = 'M'; } @@ -957,7 +962,7 @@ CWaitCursor waitCursor; HANDLE h[] = { thread, _createDialogEvent }; - DWORD res2 = WaitForMultipleObjects(ARRAY_SIZE(h), h, FALSE, kCreateDelay); + const DWORD res2 = WaitForMultipleObjects(Z7_ARRAY_SIZE(h), h, FALSE, kCreateDelay); if (res2 == WAIT_OBJECT_0 && !Sync.ThereIsMessage()) return 0; } @@ -979,9 +984,9 @@ bool CProgressDialog::OnExternalCloseMessage() { // it doesn't work if there is MessageBox. - #ifdef __ITaskbarList3_INTERFACE_DEFINED__ + // #ifdef __ITaskbarList3_INTERFACE_DEFINED__ SetTaskbarProgressState(TBPF_NOPROGRESS); - #endif + // #endif // AddToTitle(L"Finished "); // SetText(L"Finished2 "); @@ -1088,7 +1093,7 @@ } s.Add_Space(); - #ifndef _SFX + #ifndef Z7_SFX { unsigned len = s.Len(); s += MainAddTitle; @@ -1150,9 +1155,9 @@ if (needNumber) ConvertUInt32ToString(_numMessages + 1, sz); const unsigned itemIndex = _messageStrings.Size(); // _messageList.GetItemCount(); - if (_messageList.InsertItem((int)itemIndex, sz) == (int)itemIndex) + if (_messageList.InsertItem(itemIndex, sz) == (int)itemIndex) { - _messageList.SetSubItem((int)itemIndex, 1, message); + _messageList.SetSubItem(itemIndex, 1, message); _messageStrings.Add(message); } } @@ -1163,12 +1168,12 @@ bool needNumber = true; while (!s.IsEmpty()) { - int pos = s.Find(L'\n'); + const int pos = s.Find(L'\n'); if (pos < 0) break; - AddMessageDirect(s.Left(pos), needNumber); + AddMessageDirect(s.Left((unsigned)pos), needNumber); needNumber = false; - s.DeleteFrontal(pos + 1); + s.DeleteFrontal((unsigned)pos + 1); } AddMessageDirect(s, needNumber); _numMessages++; @@ -1210,7 +1215,7 @@ } -bool CProgressDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CProgressDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -1340,7 +1345,7 @@ index = listView.GetNextSelectedItem(index); if (index < 0) break; - vector.Add(index); + vector.Add((unsigned)index); } } @@ -1352,7 +1357,7 @@ UString s; unsigned numIndexes = indexes.Size(); if (numIndexes == 0) - numIndexes = _messageList.GetItemCount(); + numIndexes = (unsigned)_messageList.GetItemCount(); for (unsigned i = 0; i < numIndexes; i++) { @@ -1391,7 +1396,9 @@ HRESULT CProgressThreadVirt::Create(const UString &title, HWND parentWindow) { NWindows::CThread thread; - RINOK(thread.Create(MyThreadFunction, this)); + const WRes wres = thread.Create(MyThreadFunction, this); + if (wres != 0) + return HRESULT_FROM_WIN32(wres); CProgressDialog::Create(title, thread, parentWindow); return S_OK; } @@ -1417,7 +1424,7 @@ catch(int v) { m = "Error #"; - m.Add_UInt32(v); + m.Add_UInt32((unsigned)v); } catch(...) { m = "Error"; } if (Result != E_ABORT) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ProgressDialog2.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ProgressDialog2.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ProgressDialog2.h 2021-08-04 17:25:48.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ProgressDialog2.h 2023-04-12 12:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ProgressDialog2.h -#ifndef __PROGRESS_DIALOG_2_H -#define __PROGRESS_DIALOG_2_H +#ifndef ZIP7_INC_PROGRESS_DIALOG_2_H +#define ZIP7_INC_PROGRESS_DIALOG_2_H #include "../../../Common/MyCom.h" @@ -36,6 +36,7 @@ public: bool _bytesProgressMode; + bool _isDir; UInt64 _totalBytes; UInt64 _completedBytes; UInt64 _totalFiles; @@ -46,7 +47,6 @@ UString _titleFileName; UString _status; UString _filePath; - bool _isDir; UStringVector Messages; CProgressFinalMessage FinalMessage; @@ -96,7 +96,8 @@ void AddError_Message(const wchar_t *message); void AddError_Message_Name(const wchar_t *message, const wchar_t *name); - void AddError_Code_Name(DWORD systemError, const wchar_t *name); + // void AddError_Code_Name(DWORD systemError, const wchar_t *name); + void AddError_Code_Name(HRESULT systemError, const wchar_t *name); bool ThereIsMessage() const { return !Messages.IsEmpty() || FinalMessage.ThereIsMessage(); } }; @@ -151,12 +152,12 @@ NWindows::NControl::CProgressBar m_ProgressBar; NWindows::NControl::CListView _messageList; - int _numMessages; + unsigned _numMessages; UStringVector _messageStrings; - #ifdef __ITaskbarList3_INTERFACE_DEFINED__ + // #ifdef __ITaskbarList3_INTERFACE_DEFINED__ CMyComPtr _taskbarList; - #endif + // #endif HWND _hwndForTaskbar; UInt32 _prevTime; @@ -196,29 +197,29 @@ bool _externalCloseMessageWasReceived; - #ifdef __ITaskbarList3_INTERFACE_DEFINED__ + // #ifdef __ITaskbarList3_INTERFACE_DEFINED__ void SetTaskbarProgressState(TBPFLAG tbpFlags) { if (_taskbarList && _hwndForTaskbar) _taskbarList->SetProgressState(_hwndForTaskbar, tbpFlags); } - #endif + // #endif void SetTaskbarProgressState(); void UpdateStatInfo(bool showAll); - bool OnTimer(WPARAM timerID, LPARAM callback); void SetProgressRange(UInt64 range); void SetProgressPos(UInt64 pos); - virtual bool OnInit(); - virtual bool OnSize(WPARAM wParam, int xSize, int ySize); - virtual void OnCancel(); - virtual void OnOK(); - virtual bool OnNotify(UINT /* controlID */, LPNMHDR header); + virtual bool OnTimer(WPARAM timerID, LPARAM callback) Z7_override; + virtual bool OnInit() Z7_override; + virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override; + virtual void OnCancel() Z7_override; + virtual void OnOK() Z7_override; + virtual bool OnNotify(UINT /* controlID */, LPNMHDR header) Z7_override; void CopyToClipboard(); NWindows::NSynchronization::CManualResetEvent _createDialogEvent; NWindows::NSynchronization::CManualResetEvent _dialogCreatedEvent; - #ifndef _SFX + #ifndef Z7_SFX void AddToTitle(LPCWSTR string); #endif @@ -226,11 +227,11 @@ void SetPriorityText(); void OnPauseButton(); void OnPriorityButton(); - bool OnButtonClicked(int buttonID, HWND buttonHWND); - bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam); + bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; + bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam) Z7_override; void SetTitleText(); - void ShowSize(int id, UInt64 val, UInt64 &prev); + void ShowSize(unsigned id, UInt64 val, UInt64 &prev); void UpdateMessagesDialog(); @@ -252,10 +253,10 @@ int IconID; HWND MainWindow; - #ifndef _SFX + #ifndef Z7_SFX UString MainTitle; UString MainAddTitle; - ~CProgressDialog(); + ~CProgressDialog() Z7_DESTRUCTOR_override; #endif CProgressDialog(); @@ -265,7 +266,7 @@ _dialogCreatedEvent.Lock(); } - INT_PTR Create(const UString &title, NWindows::CThread &thread, HWND wndParent = 0); + INT_PTR Create(const UString &title, NWindows::CThread &thread, HWND wndParent = NULL); /* how it works: @@ -306,7 +307,7 @@ void Process(); void AddErrorPath(const FString &path) { ErrorPaths.Add(path); } - HRESULT Create(const UString &title, HWND parentWindow = 0); + HRESULT Create(const UString &title, HWND parentWindow = NULL); CProgressThreadVirt(): Result(E_FAIL), ThreadFinishedOK(false) {} CProgressMessageBoxPair &GetMessagePair(bool isError) { return isError ? FinalMessage.ErrorMessage : FinalMessage.OkMessage; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ProgressDialog.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ProgressDialog.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ProgressDialog.cpp 2021-07-15 10:25:40.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ProgressDialog.cpp 2023-03-20 11:00:00.000000000 +0000 @@ -15,7 +15,7 @@ static const UINT_PTR kTimerID = 3; static const UINT kTimerElapse = 100; -#ifdef LANG +#ifdef Z7_LANG #include "LangUtils.h" #endif @@ -32,7 +32,7 @@ return S_OK; } -#ifndef _SFX +#ifndef Z7_SFX CProgressDialog::~CProgressDialog() { AddToTitle(L""); @@ -45,15 +45,17 @@ #endif +#define UNDEFINED_VAL ((UInt64)(Int64)-1) + bool CProgressDialog::OnInit() { - _range = (UInt64)(Int64)-1; - _prevPercentValue = -1; + _range = UNDEFINED_VAL; + _prevPercentValue = UNDEFINED_VAL; _wasCreated = true; _dialogCreatedEvent.Set(); - #ifdef LANG + #ifdef Z7_LANG LangSetDlgItems(*this, NULL, 0); #endif @@ -114,7 +116,7 @@ if (total == 0) total = 1; - int percentValue = (int)(completed * 100 / total); + const UInt64 percentValue = completed * 100 / total; if (percentValue != _prevPercentValue) { wchar_t s[64]; @@ -122,7 +124,7 @@ UString title = s; title += "% "; SetText(title + _title); - #ifndef _SFX + #ifndef Z7_SFX AddToTitle(title + MainAddTitle); #endif _prevPercentValue = percentValue; @@ -159,7 +161,7 @@ return CModalDialog::OnMessage(message, wParam, lParam); } -bool CProgressDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CProgressDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ProgressDialog.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ProgressDialog.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ProgressDialog.h 2021-01-02 17:37:38.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ProgressDialog.h 2023-03-20 18:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ProgressDialog.h -#ifndef __PROGRESS_DIALOG_H -#define __PROGRESS_DIALOG_H +#ifndef ZIP7_INC_PROGRESS_DIALOG_H +#define ZIP7_INC_PROGRESS_DIALOG_H #include "../../../Windows/Synchronization.h" #include "../../../Windows/Thread.h" @@ -85,24 +85,27 @@ UInt64 _range; NWindows::NControl::CProgressBar m_ProgressBar; - int _prevPercentValue; + UInt64 _prevPercentValue; bool _wasCreated; bool _needClose; bool _inCancelMessageBox; bool _externalCloseMessageWasReceived; - bool OnTimer(WPARAM timerID, LPARAM callback); + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; + virtual bool OnTimer(WPARAM timerID, LPARAM callback) Z7_override; + virtual bool OnInit() Z7_override; + virtual void OnCancel() Z7_override; + virtual void OnOK() Z7_override; + virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam) Z7_override; + void SetRange(UInt64 range); void SetPos(UInt64 pos); - virtual bool OnInit(); - virtual void OnCancel(); - virtual void OnOK(); + NWindows::NSynchronization::CManualResetEvent _dialogCreatedEvent; - #ifndef _SFX + #ifndef Z7_SFX void AddToTitle(LPCWSTR string); #endif - bool OnButtonClicked(int buttonID, HWND buttonHWND); void WaitCreating() { _dialogCreatedEvent.Lock(); } void CheckNeedClose(); @@ -111,7 +114,7 @@ CProgressSync Sync; int IconID; - #ifndef _SFX + #ifndef Z7_SFX HWND MainWindow; UString MainTitle; UString MainAddTitle; @@ -119,8 +122,8 @@ #endif CProgressDialog(): _timer(0) - #ifndef _SFX - ,MainWindow(0) + #ifndef Z7_SFX + ,MainWindow(NULL) #endif { IconID = -1; @@ -133,7 +136,7 @@ throw 1334987; } - INT_PTR Create(const UString &title, NWindows::CThread &thread, HWND wndParent = 0) + INT_PTR Create(const UString &title, NWindows::CThread &thread, HWND wndParent = NULL) { _title = title; INT_PTR res = CModalDialog::Create(IDD_PROGRESS, wndParent); @@ -146,8 +149,6 @@ kCloseMessage = WM_APP + 1 }; - virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam); - void ProcessWasFinished() { WaitCreating(); @@ -155,7 +156,7 @@ PostMsg(kCloseMessage); else _needClose = true; - }; + } }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PropertyName.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PropertyName.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PropertyName.h 2013-01-17 10:12:48.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PropertyName.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // PropertyName.h -#ifndef __PROPERTY_NAME_H -#define __PROPERTY_NAME_H +#ifndef ZIP7_INC_PROPERTY_NAME_H +#define ZIP7_INC_PROPERTY_NAME_H #include "../../../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PropertyName.rc 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PropertyName.rc --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PropertyName.rc 2022-04-27 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PropertyName.rc 2022-11-05 14:00:00.000000000 +0000 @@ -104,4 +104,6 @@ IDS_PROP_GROUP_ID "Group ID" IDS_PROP_DEVICE_MAJOR "Device Major" IDS_PROP_DEVICE_MINOR "Device Minor" + IDS_PROP_DEV_MAJOR "Dev Major" + IDS_PROP_DEV_MINOR "Dev Minor" END diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PropertyNameRes.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PropertyNameRes.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/PropertyNameRes.h 2022-04-01 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/PropertyNameRes.h 2022-11-05 14:00:00.000000000 +0000 @@ -100,3 +100,5 @@ #define IDS_PROP_GROUP_ID 1100 #define IDS_PROP_DEVICE_MAJOR 1101 #define IDS_PROP_DEVICE_MINOR 1102 +#define IDS_PROP_DEV_MAJOR 1103 +#define IDS_PROP_DEV_MINOR 1104 diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/RegistryAssociations.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/RegistryAssociations.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/RegistryAssociations.cpp 2017-03-24 16:12:27.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/RegistryAssociations.cpp 2023-01-19 19:00:00.000000000 +0000 @@ -65,18 +65,18 @@ UString value; if (iconKey.QueryValue(NULL, value) == ERROR_SUCCESS) { - int pos = value.ReverseFind(L','); + const int pos = value.ReverseFind(L','); IconPath = value; if (pos >= 0) { const wchar_t *end; - Int32 index = ConvertStringToInt32((const wchar_t *)value + pos + 1, &end); + const Int32 index = ConvertStringToInt32((const wchar_t *)value + pos + 1, &end); if (*end == 0) { // 9.31: if there is no icon index, we use -1. Is it OK? if (pos != (int)value.Len() - 1) IconIndex = (int)index; - IconPath.SetFrom(value, pos); + IconPath.SetFrom(value, (unsigned)pos); } } } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/RegistryAssociations.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/RegistryAssociations.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/RegistryAssociations.h 2013-01-17 10:00:59.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/RegistryAssociations.h 2023-01-10 18:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // RegistryAssociations.h -#ifndef __REGISTRY_ASSOCIATIONS_H -#define __REGISTRY_ASSOCIATIONS_H +#ifndef ZIP7_INC_REGISTRY_ASSOCIATIONS_H +#define ZIP7_INC_REGISTRY_ASSOCIATIONS_H #include "../../../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/RegistryPlugins.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/RegistryPlugins.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/RegistryPlugins.cpp 2021-01-26 11:59:25.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/RegistryPlugins.cpp 2023-01-30 18:00:00.000000000 +0000 @@ -2,138 +2,144 @@ #include "StdAfx.h" +/* #include "../../../Windows/DLL.h" #include "../../../Windows/FileFind.h" #include "../../../Windows/PropVariant.h" #include "IFolder.h" +*/ #include "RegistryPlugins.h" -using namespace NWindows; -using namespace NFile; +// using namespace NWindows; +// using namespace NFile; /* -static LPCTSTR const kLMBasePath = TEXT("Software\\7-Zip\\FM"); +typedef UINT32 (WINAPI * Func_GetPluginProperty)(PROPID propID, PROPVARIANT *value); -static LPCTSTR const kPluginsKeyName = TEXT("Plugins"); -static LPCTSTR const kPluginsOpenClassIDValue = TEXT("CLSID"); -static LPCTSTR const kPluginsOptionsClassIDValue = TEXT("Options"); -static LPCTSTR const kPluginsTypeValue = TEXT("Type"); - -static CSysString GetFileFolderPluginsKeyName() -{ - return CSysString(kLMBasePath) + CSysString(TEXT('\\')) + - CSysString(kPluginsKeyName); -} - -*/ - -typedef UINT32 (WINAPI * GetPluginPropertyFunc)(PROPID propID, PROPVARIANT *value); - -static bool ReadPluginInfo(CPluginInfo &pluginInfo, bool needCheckDll) +static bool ReadPluginInfo(CPluginInfo &plugin, bool needCheckDll) { if (needCheckDll) { NDLL::CLibrary lib; - if (!lib.LoadEx(pluginInfo.FilePath, LOAD_LIBRARY_AS_DATAFILE)) + if (!lib.LoadEx(plugin.FilePath, LOAD_LIBRARY_AS_DATAFILE)) return false; } NDLL::CLibrary lib; - if (!lib.Load(pluginInfo.FilePath)) + if (!lib.Load(plugin.FilePath)) return false; - GetPluginPropertyFunc getPluginProperty = (GetPluginPropertyFunc)lib.GetProc("GetPluginProperty"); - if (getPluginProperty == NULL) + const + Func_GetPluginProperty + f_GetPluginProperty = ZIP7_GET_PROC_ADDRESS( + Func_GetPluginProperty, lib.Get_HMODULE(), + "GetPluginProperty"); + if (!f_GetPluginProperty) return false; - + NCOM::CPropVariant prop; - if (getPluginProperty(NPlugin::kName, &prop) != S_OK) + if (f_GetPluginProperty(NPlugin::kType, &prop) != S_OK) + return false; + if (prop.vt == VT_EMPTY) + plugin.Type = kPluginTypeFF; + else if (prop.vt == VT_UI4) + plugin.Type = (EPluginType)prop.ulVal; + else + return false; + prop.Clear(); + + if (f_GetPluginProperty(NPlugin::kName, &prop) != S_OK) return false; if (prop.vt != VT_BSTR) return false; - pluginInfo.Name = prop.bstrVal; + plugin.Name = prop.bstrVal; prop.Clear(); - if (getPluginProperty(NPlugin::kClassID, &prop) != S_OK) + if (f_GetPluginProperty(NPlugin::kClassID, &prop) != S_OK) return false; if (prop.vt == VT_EMPTY) - pluginInfo.ClassIDDefined = false; + plugin.ClassID_Defined = false; else if (prop.vt != VT_BSTR) return false; else { - pluginInfo.ClassIDDefined = true; - pluginInfo.ClassID = *(const GUID *)(const void *)prop.bstrVal; + plugin.ClassID_Defined = true; + plugin.ClassID = *(const GUID *)(const void *)prop.bstrVal; } prop.Clear(); + return true; +*/ - if (getPluginProperty(NPlugin::kOptionsClassID, &prop) != S_OK) +/* +{ + if (f_GetPluginProperty(NPlugin::kOptionsClassID, &prop) != S_OK) return false; if (prop.vt == VT_EMPTY) - pluginInfo.OptionsClassIDDefined = false; + plugin.OptionsClassID_Defined = false; else if (prop.vt != VT_BSTR) return false; else { - pluginInfo.OptionsClassIDDefined = true; - pluginInfo.OptionsClassID = *(const GUID *)(const void *)prop.bstrVal; + plugin.OptionsClassID_Defined = true; + plugin.OptionsClassID = *(const GUID *)(const void *)prop.bstrVal; } - prop.Clear(); - - if (getPluginProperty(NPlugin::kType, &prop) != S_OK) - return false; - if (prop.vt == VT_EMPTY) - pluginInfo.Type = kPluginTypeFF; - else if (prop.vt == VT_UI4) - pluginInfo.Type = (EPluginType)prop.ulVal; - else - return false; - return true; } +*/ -void ReadPluginInfoList(CObjectVector &plugins) -{ - plugins.Clear(); + /* + { + // very old 7-zip used agent plugin in "7-zip.dll" + // but then agent code was moved to 7zfm. + // so now we don't need to load "7-zip.dll" here + CPluginInfo plugin; + plugin.FilePath = baseFolderPrefix + FTEXT("7-zip.dll"); + if (::ReadPluginInfo(plugin, false)) + if (plugin.Type == kPluginTypeFF) + plugins.Add(plugin); + } + */ + /* + FString folderPath = NDLL::GetModuleDirPrefix(); + folderPath += "Plugins" STRING_PATH_SEPARATOR; + NFind::CEnumerator enumerator; + enumerator.SetDirPrefix(folderPath); + NFind::CFileInfo fi; + while (enumerator.Next(fi)) + { + if (fi.IsDir()) + continue; + CPluginInfo plugin; + plugin.FilePath = folderPath + fi.Name; + if (::ReadPluginInfo(plugin, true)) + if (plugin.Type == kPluginTypeFF) + plugins.Add(plugin); + } + */ - FString baseFolderPrefix = NDLL::GetModuleDirPrefix(); - { - CPluginInfo pluginInfo; - pluginInfo.FilePath = baseFolderPrefix + FTEXT("7-zip.dll"); - if (::ReadPluginInfo(pluginInfo, false)) - plugins.Add(pluginInfo); - } - FString folderPath = baseFolderPrefix; - folderPath += "Plugins" STRING_PATH_SEPARATOR; - NFind::CEnumerator enumerator; - enumerator.SetDirPrefix(folderPath); - NFind::CFileInfo fileInfo; - while (enumerator.Next(fileInfo)) - { - if (fileInfo.IsDir()) - continue; - CPluginInfo pluginInfo; - pluginInfo.FilePath = folderPath + fileInfo.Name; - if (::ReadPluginInfo(pluginInfo, true)) - plugins.Add(pluginInfo); - } -} - -void ReadFileFolderPluginInfoList(CObjectVector &plugins) -{ + /* ReadPluginInfoList(plugins); for (unsigned i = 0; i < plugins.Size();) if (plugins[i].Type != kPluginTypeFF) plugins.Delete(i); else i++; + */ + +/* +void ReadFileFolderPluginInfoList(CObjectVector &plugins) +{ + plugins.Clear(); + { + } + { - CPluginInfo p; + CPluginInfo &plugin = plugins.AddNew(); // p.FilePath.Empty(); - p.Type = kPluginTypeFF; - p.Name = "7-Zip"; - // p.ClassID = CLSID_CAgentArchiveHandler; - p.ClassIDDefined = true; - // p.OptionsClassID; - p.OptionsClassIDDefined = false; - plugins.Add(p); + plugin.Type = kPluginTypeFF; + plugin.Name = "7-Zip"; + // plugin.ClassID = CLSID_CAgentArchiveHandler; + // plugin.ClassID_Defined = true; + // plugin.ClassID_Defined = false; + // plugin.OptionsClassID_Defined = false; } } +*/ diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/RegistryPlugins.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/RegistryPlugins.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/RegistryPlugins.h 2013-01-17 10:01:20.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/RegistryPlugins.h 2023-01-30 20:00:00.000000000 +0000 @@ -1,10 +1,11 @@ // RegistryPlugins.h -#ifndef __REGISTRY_PLUGINS_H -#define __REGISTRY_PLUGINS_H +#ifndef ZIP7_INC_REGISTRY_PLUGINS_H +#define ZIP7_INC_REGISTRY_PLUGINS_H #include "../../../Common/MyString.h" +/* enum EPluginType { kPluginTypeFF = 0 @@ -12,21 +13,17 @@ struct CPluginInfo { - FString FilePath; EPluginType Type; - UString Name; - CLSID ClassID; - CLSID OptionsClassID; - bool ClassIDDefined; - bool OptionsClassIDDefined; - - // CSysString Extension; - // CSysString AddExtension; - // bool UpdateEnabled; - // bool KeepName; + // bool ClassID_Defined; + // bool OptionsClassID_Defined; + // FString FilePath; + // UString Name; + // CLSID ClassID; + // CLSID OptionsClassID; }; -void ReadPluginInfoList(CObjectVector &plugins); -void ReadFileFolderPluginInfoList(CObjectVector &plugins); +// void ReadPluginInfoList(CObjectVector &plugins); +// void ReadFileFolderPluginInfoList(CObjectVector &plugins); +*/ #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/RegistryUtils.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/RegistryUtils.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/RegistryUtils.cpp 2021-01-22 15:12:37.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/RegistryUtils.cpp 2023-02-01 08:00:00.000000000 +0000 @@ -137,6 +137,11 @@ { ShowDots = false; ShowRealFileIcons = false; + /* if (FullRow == false), we can use mouse click on another columns + to select group of files. We need to implement additional + way to select files in any column as in Explorer. + Then we can enable (FullRow == true) default mode. */ + // FullRow = true; FullRow = false; ShowGrid = false; SingleClick = false; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/RegistryUtils.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/RegistryUtils.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/RegistryUtils.h 2021-01-21 18:19:29.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/RegistryUtils.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // RegistryUtils.h -#ifndef __REGISTRY_UTILS_H -#define __REGISTRY_UTILS_H +#ifndef ZIP7_INC_REGISTRY_UTILS_H +#define ZIP7_INC_REGISTRY_UTILS_H #include "../../../Common/MyTypes.h" #include "../../../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/resource.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/resource.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/resource.h 2021-01-22 10:20:20.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/resource.h 2023-04-01 11:00:00.000000000 +0000 @@ -26,6 +26,14 @@ #define IDM_SHA1 104 #define IDM_SHA256 105 + +#define IDM_FILE 500 +#define IDM_EDIT 501 +#define IDM_VIEW 502 +#define IDM_FAVORITES 503 +#define IDM_TOOLS 504 +#define IDM_HELP 505 + #define IDM_OPEN 540 #define IDM_OPEN_INSIDE 541 #define IDM_OPEN_OUTSIDE 542 @@ -90,8 +98,10 @@ #define IDM_VIEW_TOOLBARS_LARGE_BUTTONS 752 #define IDM_VIEW_TOOLBARS_SHOW_BUTTONS_TEXT 753 +#define IDM_VIEW_TIME_POPUP 760 #define IDM_VIEW_TIME 761 +#define IDM_ADD_TO_FAVORITES 800 #define IDS_BOOKMARK 801 #define IDM_OPTIONS 900 diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/resource.rc 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/resource.rc --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/resource.rc 2020-05-25 07:51:33.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/resource.rc 2023-05-11 17:00:00.000000000 +0000 @@ -12,10 +12,27 @@ // VK_F7, IDM_CREATE_FOLDER, VIRTKEY, NOINVERT END +// for MENUEX: +// /* +#define MY_MENUITEM_SEPARATOR MENUITEM "", 0, MFT_SEPARATOR +#define MY_MFT_MENUBREAK MFT_MENUBREAK +#define MY_MFT_MENUBARBREAK MFT_MENUBARBREAK +#define MY_MFS_CHECKED MFT_STRING, MFS_CHECKED +#define MY_MENUITEM_ID(x) , x +// */ + +// for MENU: +/* +#define MY_MENUITEM_SEPARATOR MENUITEM SEPARATOR +#define MY_MFT_MENUBREAK MENUBREAK +#define MY_MFT_MENUBARBREAK MENUBARBREAK +#define MY_MFS_CHECKED CHECKED +#define MY_MENUITEM_ID(x) +*/ -IDM_MENU MENU +IDM_MENU MENUEX BEGIN - POPUP "&File" + POPUP "&File" MY_MENUITEM_ID(IDM_FILE) BEGIN MENUITEM "&Open\tEnter", IDM_OPEN MENUITEM "Open &Inside\tCtrl+PgDn", IDM_OPEN_INSIDE @@ -24,19 +41,19 @@ MENUITEM "Open O&utside\tShift+Enter", IDM_OPEN_OUTSIDE MENUITEM "&View\tF3", IDM_FILE_VIEW MENUITEM "&Edit\tF4", IDM_FILE_EDIT - MENUITEM SEPARATOR + MY_MENUITEM_SEPARATOR MENUITEM "Rena&me\tF2", IDM_RENAME MENUITEM "&Copy To...\tF5", IDM_COPY_TO MENUITEM "&Move To...\tF6", IDM_MOVE_TO MENUITEM "&Delete\tDel", IDM_DELETE - MENUITEM SEPARATOR + MY_MENUITEM_SEPARATOR MENUITEM "&Split file...", IDM_SPLIT MENUITEM "Com&bine files...", IDM_COMBINE - MENUITEM SEPARATOR + MY_MENUITEM_SEPARATOR MENUITEM "P&roperties\tAlt+Enter", IDM_PROPERTIES MENUITEM "Comme&nt...\tCtrl+Z", IDM_COMMENT // MENUITEM "Calculate checksum", IDM_CRC - POPUP "CRC" + POPUP "CRC" MY_MENUITEM_ID(0) BEGIN MENUITEM "CRC-32", IDM_CRC32 MENUITEM "CRC-64", IDM_CRC64 @@ -45,55 +62,56 @@ MENUITEM "*", IDM_HASH_ALL END MENUITEM "Di&ff", IDM_DIFF - MENUITEM SEPARATOR + MY_MENUITEM_SEPARATOR MENUITEM "Create Folder\tF7", IDM_CREATE_FOLDER MENUITEM "Create File\tCtrl+N", IDM_CREATE_FILE - MENUITEM SEPARATOR + MY_MENUITEM_SEPARATOR MENUITEM "&Link...", IDM_LINK MENUITEM "&Alternate streams", IDM_ALT_STREAMS - MENUITEM SEPARATOR + MY_MENUITEM_SEPARATOR MENUITEM "E&xit\tAlt+F4", IDCLOSE END - POPUP "&Edit" + POPUP "&Edit" MY_MENUITEM_ID(IDM_EDIT) BEGIN // MENUITEM "Cu&t\tCtrl+X", IDM_EDIT_CUT, GRAYED // MENUITEM "&Copy\tCtrl+C", IDM_EDIT_COPY, GRAYED // MENUITEM "&Paste\tCtrl+V", IDM_EDIT_PASTE, GRAYED - // MENUITEM SEPARATOR + // MY_MENUITEM_SEPARATOR MENUITEM "Select &All\tShift+[Grey +]", IDM_SELECT_ALL MENUITEM "Deselect All\tShift+[Grey -]", IDM_DESELECT_ALL MENUITEM "&Invert Selection\tGrey *", IDM_INVERT_SELECTION MENUITEM "Select...\tGrey +", IDM_SELECT MENUITEM "Deselect...\tGrey -", IDM_DESELECT + MENUITEM "", 0, MY_MFT_MENUBARBREAK MENUITEM "Select by Type\tAlt+[Grey+]", IDM_SELECT_BY_TYPE MENUITEM "Deselect by Type\tAlt+[Grey -]", IDM_DESELECT_BY_TYPE END - POPUP "&View" + POPUP "&View" MY_MENUITEM_ID(IDM_VIEW) BEGIN MENUITEM "Lar&ge Icons\tCtrl+1", IDM_VIEW_LARGE_ICONS MENUITEM "S&mall Icons\tCtrl+2", IDM_VIEW_SMALL_ICONS MENUITEM "&List\tCtrl+3", IDM_VIEW_LIST - MENUITEM "&Details\tCtrl+4", IDM_VIEW_DETAILS, CHECKED - MENUITEM SEPARATOR + MENUITEM "&Details\tCtrl+4", IDM_VIEW_DETAILS, MY_MFS_CHECKED + MY_MENUITEM_SEPARATOR MENUITEM "Name\tCtrl+F3", IDM_VIEW_ARANGE_BY_NAME MENUITEM "Type\tCtrl+F4", IDM_VIEW_ARANGE_BY_TYPE MENUITEM "Date\tCtrl+F5", IDM_VIEW_ARANGE_BY_DATE MENUITEM "Size\tCtrl+F6", IDM_VIEW_ARANGE_BY_SIZE MENUITEM "Unsorted\tCtrl+F7", IDM_VIEW_ARANGE_NO_SORT - MENUITEM SEPARATOR + MY_MENUITEM_SEPARATOR MENUITEM "Flat View", IDM_VIEW_FLAT_VIEW MENUITEM "&2 Panels\tF9", IDM_VIEW_TWO_PANELS - POPUP "2017" + POPUP "2017" MY_MENUITEM_ID(IDM_VIEW_TIME_POPUP) BEGIN MENUITEM "Time", IDM_VIEW_TIME END - POPUP "Toolbars" + POPUP "Toolbars" MY_MENUITEM_ID(IDM_VIEW_TOOLBARS) BEGIN MENUITEM "Archive Toolbar", IDM_VIEW_ARCHIVE_TOOLBAR MENUITEM "Standard Toolbar", IDM_VIEW_STANDARD_TOOLBAR - MENUITEM SEPARATOR + MY_MENUITEM_SEPARATOR MENUITEM "Large Buttons", IDM_VIEW_TOOLBARS_LARGE_BUTTONS MENUITEM "Show Buttons Text", IDM_VIEW_TOOLBARS_SHOW_BUTTONS_TEXT END @@ -107,29 +125,29 @@ // MENUITEM "Show deleted files", IDM_VIEW_SHOW_DELETED END - POPUP "F&avorites" + POPUP "F&avorites" MY_MENUITEM_ID(IDM_FAVORITES) BEGIN - POPUP "&Add folder to Favorites as" + POPUP "&Add folder to Favorites as" MY_MENUITEM_ID(IDM_ADD_TO_FAVORITES) BEGIN - MENUITEM SEPARATOR + MY_MENUITEM_SEPARATOR END - MENUITEM SEPARATOR + MY_MENUITEM_SEPARATOR END - POPUP "&Tools" + POPUP "&Tools" MY_MENUITEM_ID(IDM_TOOLS) BEGIN MENUITEM "&Options...", IDM_OPTIONS - MENUITEM SEPARATOR + MY_MENUITEM_SEPARATOR MENUITEM "&Benchmark", IDM_BENCHMARK #ifdef UNDER_CE MENUITEM "Benchmark 2", IDM_BENCHMARK2 #endif #ifndef UNDER_CE END - POPUP "&Help" + POPUP "&Help" MY_MENUITEM_ID(IDM_HELP) BEGIN MENUITEM "&Contents...\tF1", IDM_HELP_CONTENTS #endif - MENUITEM SEPARATOR + MY_MENUITEM_SEPARATOR MENUITEM "&About 7-Zip...", IDM_ABOUT END END @@ -172,7 +190,7 @@ IDS_VIRUS "The file looks like a virus (the file name contains long spaces in name)." IDS_MESSAGE_UNSUPPORTED_OPERATION_FOR_LONG_PATH_FOLDER "The operation cannot be called from a folder that has a long path." IDS_SELECT_ONE_FILE "You must select one file" - IDS_SELECT_FILES "You must select one or more files" + // IDS_SELECT_FILES "You must select one or more files" IDS_TOO_MANY_ITEMS "Too many items" IDS_COPY "Copy" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/RootFolder.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/RootFolder.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/RootFolder.cpp 2021-01-22 21:24:20.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/RootFolder.cpp 2023-04-23 09:00:00.000000000 +0000 @@ -4,7 +4,11 @@ #include "../../../Common/MyWindows.h" +#if defined(__MINGW32__) || defined(__MINGW64__) +#include +#else #include +#endif #include "../../../Common/StringConvert.h" @@ -96,19 +100,19 @@ #endif } -STDMETHODIMP CRootFolder::LoadItems() +Z7_COM7F_IMF(CRootFolder::LoadItems()) { Init(); return S_OK; } -STDMETHODIMP CRootFolder::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CRootFolder::GetNumberOfItems(UInt32 *numItems)) { *numItems = kNumRootFolderItems; return S_OK; } -STDMETHODIMP CRootFolder::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CRootFolder::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; switch (propID) @@ -120,28 +124,31 @@ return S_OK; } -typedef BOOL (WINAPI *SHGetSpecialFolderPathWp)(HWND hwnd, LPWSTR pszPath, int csidl, BOOL fCreate); -typedef BOOL (WINAPI *SHGetSpecialFolderPathAp)(HWND hwnd, LPSTR pszPath, int csidl, BOOL fCreate); +typedef BOOL (WINAPI *Func_SHGetSpecialFolderPathW)(HWND hwnd, LPWSTR pszPath, int csidl, BOOL fCreate); +typedef BOOL (WINAPI *Func_SHGetSpecialFolderPathA)(HWND hwnd, LPSTR pszPath, int csidl, BOOL fCreate); static UString GetMyDocsPath() { UString us; WCHAR s[MAX_PATH + 1]; - SHGetSpecialFolderPathWp getW = (SHGetSpecialFolderPathWp) - #ifdef UNDER_CE - My_GetProcAddress(GetModuleHandle(TEXT("coredll.dll")), "SHGetSpecialFolderPath"); - #else - My_GetProcAddress(GetModuleHandle(TEXT("shell32.dll")), "SHGetSpecialFolderPathW"); - #endif - if (getW && getW(0, s, CSIDL_PERSONAL, FALSE)) +#ifdef UNDER_CE + #define shell_name TEXT("coredll.dll") +#else + #define shell_name TEXT("shell32.dll") +#endif + Func_SHGetSpecialFolderPathW getW = Z7_GET_PROC_ADDRESS( + Func_SHGetSpecialFolderPathW, GetModuleHandle(shell_name), + "SHGetSpecialFolderPathW"); + if (getW && getW(NULL, s, CSIDL_PERSONAL, FALSE)) us = s; #ifndef _UNICODE else { - SHGetSpecialFolderPathAp getA = (SHGetSpecialFolderPathAp) - (void *)::GetProcAddress(::GetModuleHandleA("shell32.dll"), "SHGetSpecialFolderPathA"); + Func_SHGetSpecialFolderPathA getA = Z7_GET_PROC_ADDRESS( + Func_SHGetSpecialFolderPathA, ::GetModuleHandleA("shell32.dll"), + "SHGetSpecialFolderPathA"); CHAR s2[MAX_PATH + 1]; - if (getA && getA(0, s2, CSIDL_PERSONAL, FALSE)) + if (getA && getA(NULL, s2, CSIDL_PERSONAL, FALSE)) us = GetUnicodeString(s2); } #endif @@ -149,7 +156,7 @@ return us; } -STDMETHODIMP CRootFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder) +Z7_COM7F_IMF(CRootFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder)) { *resultFolder = NULL; CMyComPtr subFolder; @@ -165,7 +172,7 @@ { CNetFolder *netFolderSpec = new CNetFolder; subFolder = netFolderSpec; - netFolderSpec->Init(0, 0, _names[ROOT_INDEX_NETWORK] + WCHAR_PATH_SEPARATOR); + netFolderSpec->Init(NULL, NULL, _names[ROOT_INDEX_NETWORK] + WCHAR_PATH_SEPARATOR); } else if (index == ROOT_INDEX_DOCUMENTS) { @@ -174,7 +181,7 @@ { NFsFolder::CFSFolder *fsFolderSpec = new NFsFolder::CFSFolder; subFolder = fsFolderSpec; - RINOK(fsFolderSpec->Init(us2fs(s))); + RINOK(fsFolderSpec->Init(us2fs(s))) } } #else @@ -202,9 +209,9 @@ return path.IsPrefixedBy(name); } -STDMETHODIMP CRootFolder::BindToFolder(const wchar_t *name, IFolderFolder **resultFolder) +Z7_COM7F_IMF(CRootFolder::BindToFolder(const wchar_t *name, IFolderFolder **resultFolder)) { - *resultFolder = 0; + *resultFolder = NULL; UString name2 = name; name2.Trim(); @@ -259,7 +266,8 @@ subFolder = folderSpec; folderSpec->Init(false, true); } - else if (name2.Back() == ':') + else if (name2.Back() == ':' + && (name2.Len() != 2 || !NFile::NName::IsDrivePath2(name2))) { NAltStreamsFolder::CAltStreamsFolder *folderSpec = new NAltStreamsFolder::CAltStreamsFolder; subFolder = folderSpec; @@ -291,15 +299,15 @@ return S_OK; } -STDMETHODIMP CRootFolder::BindToParentFolder(IFolderFolder **resultFolder) +Z7_COM7F_IMF(CRootFolder::BindToParentFolder(IFolderFolder **resultFolder)) { - *resultFolder = 0; + *resultFolder = NULL; return S_OK; } IMP_IFolderFolder_Props(CRootFolder) -STDMETHODIMP CRootFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CRootFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; switch (propID) @@ -311,7 +319,7 @@ return S_OK; } -STDMETHODIMP CRootFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex) +Z7_COM7F_IMF(CRootFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex)) { *iconIndex = _iconIndices[index]; return S_OK; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/RootFolder.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/RootFolder.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/RootFolder.h 2014-09-17 11:03:46.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/RootFolder.h 2023-04-01 11:00:00.000000000 +0000 @@ -1,26 +1,23 @@ // RootFolder.h -#ifndef __ROOT_FOLDER_H -#define __ROOT_FOLDER_H +#ifndef ZIP7_INC_ROOT_FOLDER_H +#define ZIP7_INC_ROOT_FOLDER_H +#include "../../../Common/MyCom.h" #include "../../../Common/MyString.h" #include "IFolder.h" const unsigned kNumRootFolderItems_Max = 4; -class CRootFolder: - public IFolderFolder, - public IFolderGetSystemIconIndex, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_2( + CRootFolder + , IFolderFolder + , IFolderGetSystemIconIndex +) UString _names[kNumRootFolderItems_Max]; int _iconIndices[kNumRootFolderItems_Max]; - public: - MY_UNKNOWN_IMP1(IFolderGetSystemIconIndex) - INTERFACE_FolderFolder(;) - STDMETHOD(GetSystemIconIndex)(UInt32 index, Int32 *iconIndex); void Init(); }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SettingsPage.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SettingsPage.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SettingsPage.cpp 2021-11-17 19:25:14.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SettingsPage.cpp 2023-03-19 17:00:00.000000000 +0000 @@ -20,6 +20,7 @@ using namespace NWindows; +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { IDX_SETTINGS_SHOW_DOTS, @@ -32,6 +33,7 @@ IDX_SETTINGS_LARGE_PAGES // , IDT_COMPRESS_MEMORY }; +#endif #define kSettingsTopic "FM/options.htm#settings" @@ -112,7 +114,9 @@ _memCombo.Attach(GetItem(IDC_SETTINGS_MEM)); */ - LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); +#ifdef Z7_LANG + LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs)); +#endif CFmSettings st; st.Load(); @@ -225,7 +229,7 @@ { if (IsLargePageSupported()) { - bool enable = IsButtonCheckedBool(IDX_SETTINGS_LARGE_PAGES); + const bool enable = IsButtonCheckedBool(IDX_SETTINGS_LARGE_PAGES); NSecurity::EnablePrivilege_LockMemory(enable); SaveLockMemoryEnable(enable); } @@ -301,7 +305,7 @@ } /* -bool CSettingsPage::OnCommand(int code, int itemID, LPARAM param) +bool CSettingsPage::OnCommand(unsigned code, unsigned itemID, LPARAM param) { if (code == CBN_SELCHANGE) { @@ -319,7 +323,7 @@ } */ -bool CSettingsPage::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CSettingsPage::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SettingsPage.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SettingsPage.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SettingsPage.h 2021-11-17 17:47:24.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SettingsPage.h 2023-03-20 10:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // SettingsPage.h -#ifndef __SETTINGS_PAGE_H -#define __SETTINGS_PAGE_H +#ifndef ZIP7_INC_SETTINGS_PAGE_H +#define ZIP7_INC_SETTINGS_PAGE_H #include "../../../Windows/Control/PropertyPage.h" #include "../../../Windows/Control/ComboBox.h" @@ -22,11 +22,11 @@ */ // void EnableSubItems(); - // bool OnCommand(int code, int itemID, LPARAM param); - bool OnButtonClicked(int buttonID, HWND buttonHWND); - virtual bool OnInit(); - virtual void OnNotifyHelp(); - virtual LONG OnApply(); + // bool OnCommand(unsigned code, unsigned itemID, LPARAM param) Z7_override; + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; + virtual bool OnInit() Z7_override; + virtual void OnNotifyHelp() Z7_override; + virtual LONG OnApply() Z7_override; public: }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SplitDialog.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SplitDialog.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SplitDialog.cpp 2017-02-03 11:11:28.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SplitDialog.cpp 2023-03-20 10:00:00.000000000 +0000 @@ -4,9 +4,7 @@ #include "../../../Windows/FileName.h" -#ifdef LANG #include "LangUtils.h" -#endif #include "BrowseDialog.h" #include "CopyDialogRes.h" @@ -16,7 +14,7 @@ using namespace NWindows; -#ifdef LANG +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { IDT_SPLIT_PATH, @@ -27,9 +25,9 @@ bool CSplitDialog::OnInit() { - #ifdef LANG + #ifdef Z7_LANG LangSetWindowText(*this, IDD_SPLIT); - LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); + LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs)); #endif _pathCombo.Attach(GetItem(IDC_SPLIT_PATH)); _volumeCombo.Attach(GetItem(IDC_SPLIT_VOLUME)); @@ -75,7 +73,7 @@ return false; } -bool CSplitDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CSplitDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -91,7 +89,7 @@ UString currentPath; _pathCombo.GetText(currentPath); // UString title = "Specify a location for output folder"; - UString title = LangString(IDS_SET_FOLDER); + const UString title = LangString(IDS_SET_FOLDER); UString resultPath; if (!MyBrowseForFolder(*this, title, currentPath, resultPath)) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SplitDialog.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SplitDialog.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SplitDialog.h 2013-01-17 10:18:13.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SplitDialog.h 2023-01-28 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // SplitDialog.h -#ifndef __SPLIT_DIALOG_H -#define __SPLIT_DIALOG_H +#ifndef ZIP7_INC_SPLIT_DIALOG_H +#define ZIP7_INC_SPLIT_DIALOG_H #include "../../../Windows/Control/Dialog.h" #include "../../../Windows/Control/ComboBox.h" @@ -12,16 +12,16 @@ { NWindows::NControl::CComboBox _pathCombo; NWindows::NControl::CComboBox _volumeCombo; - virtual void OnOK(); - virtual bool OnInit(); - virtual bool OnSize(WPARAM wParam, int xSize, int ySize); - virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); + virtual void OnOK() Z7_override; + virtual bool OnInit() Z7_override; + virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override; + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; void OnButtonSetPath(); public: UString FilePath; UString Path; CRecordVector VolumeSizes; - INT_PTR Create(HWND parentWindow = 0) + INT_PTR Create(HWND parentWindow = NULL) { return CModalDialog::Create(IDD_SPLIT, parentWindow); } }; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SplitUtils.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SplitUtils.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SplitUtils.cpp 2017-02-15 09:27:59.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SplitUtils.cpp 2023-03-06 16:00:00.000000000 +0000 @@ -74,7 +74,7 @@ void AddVolumeItems(NWindows::NControl::CComboBox &combo) { - for (unsigned i = 0; i < ARRAY_SIZE(k_Sizes); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_Sizes); i++) combo.AddString(CSysString(k_Sizes[i])); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SplitUtils.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SplitUtils.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SplitUtils.h 2013-02-20 11:02:08.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SplitUtils.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // SplitUtils.h -#ifndef __SPLIT_UTILS_H -#define __SPLIT_UTILS_H +#ifndef ZIP7_INC_SPLIT_UTILS_H +#define ZIP7_INC_SPLIT_UTILS_H #include "../../../Common/MyTypes.h" #include "../../../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/StdAfx.h 2021-03-05 12:15:55.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/StdAfx.h 2023-04-07 10:00:00.000000000 +0000 @@ -1,21 +1,83 @@ -// stdafx.h +// StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H -/* we used 0x0400 for Windows NT supporting (MENUITEMINFOW) - But now menu problem is fixed. So it's OK to use 0x0500 (Windows 2000) */ +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif + +#include "../../../../C/Compiler.h" +Z7_DIAGNOSCTIC_IGNORE_BEGIN_RESERVED_MACRO_IDENTIFIER +#ifndef _WIN32_WINNT // #define _WIN32_WINNT 0x0400 #define _WIN32_WINNT 0x0500 +// #define _WIN32_WINNT 0x0600 +// #define _WIN32_WINNT 0x0A00 +#endif +#ifndef WINVER #define WINVER _WIN32_WINNT +#endif +// #define _WIN32_IE 0x400 // for debug +Z7_DIAGNOSCTIC_IGNORE_END_RESERVED_MACRO_IDENTIFIER #include "../../../Common/Common.h" +#include "../../../Common/MyWindows.h" -// #include "../../../Common/MyWindows.h" +#endif -// #include -// #include -// #include +/* +WINVER and _WIN32_WINNT +MSVC6 / 2003sdk: +{ + doesn't set _WIN32_WINNT + if WINVER is not set sets WINVER to value: + 0x0400 : MSVC6 + 0x0501 : Windows Server 2003 PSDK / 2003 R2 PSDK +} + +SDK for Win7 (and later) +{ + sets _WIN32_WINNT if it's not set. + sets WINVER if it's not set. + includes that does: +#if !defined(_WIN32_WINNT) && !defined(_CHICAGO_) + #define _WIN32_WINNT 0x0601 // in win7 sdk + #define _WIN32_WINNT 0x0A00 // in win10 sdk +#endif +#ifndef WINVER + #ifdef _WIN32_WINNT + #define WINVER _WIN32_WINNT + else + #define WINVER 0x0601 // in win7 sdk + #define WINVER 0x0A00 // in win10 sdk + endif #endif +} + +Some GUI structures defined by windows will be larger, +If (_WIN32_WINNT) value is larger. + +Also if we send sizeof(win_gui_struct) to some windows function, +and we compile that code with big (_WIN32_WINNT) value, +the window function in old Windows can fail, if that old Windows +doesn't understand new big version of (win_gui_struct) compiled +with big (_WIN32_WINNT) value. + +So it's better to define smallest (_WIN32_WINNT) value here. +In 7-Zip FM we use some functions that require (_WIN32_WINNT == 0x0500). +So it's simpler to define (_WIN32_WINNT == 0x0500) here. +If we define (_WIN32_WINNT == 0x0400) here, we need some manual +declarations for functions and macros that require (0x0500) functions. +Also libs must contain these (0x0500+) functions. + +Some code in 7-zip FM uses also CommCtrl.h structures +that depend from (_WIN32_IE) value. But default +(_WIN32_IE) value from probably is OK for us. +So we don't set _WIN32_IE here. +default _WIN32_IE value set by : + 0x501 2003sdk + 0xa00 win10 sdk +*/ diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/StringUtils.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/StringUtils.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/StringUtils.cpp 2017-02-06 19:35:37.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/StringUtils.cpp 2023-03-20 10:00:00.000000000 +0000 @@ -24,35 +24,9 @@ } } -void SplitString(const UString &srcString, UStringVector &destStrings) -{ - destStrings.Clear(); - unsigned len = srcString.Len(); - if (len == 0) - return; - UString s; - for (unsigned i = 0; i < len; i++) - { - wchar_t c = srcString[i]; - if (c == ' ') - { - if (!s.IsEmpty()) - { - destStrings.Add(s); - s.Empty(); - } - } - else - s += c; - } - if (!s.IsEmpty()) - destStrings.Add(s); -} - /* UString JoinStrings(const UStringVector &srcStrings) { - UString s; FOR_VECTOR (i, srcStrings) { diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/StringUtils.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/StringUtils.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/StringUtils.h 2013-01-17 10:34:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/StringUtils.h 2023-01-30 09:00:00.000000000 +0000 @@ -1,13 +1,11 @@ // StringUtils.h -#ifndef __STRING_UTILS_H -#define __STRING_UTILS_H +#ifndef ZIP7_INC_STRING_UTILS_H +#define ZIP7_INC_STRING_UTILS_H #include "../../../Common/MyString.h" void SplitStringToTwoStrings(const UString &src, UString &dest1, UString &dest2); - -void SplitString(const UString &srcString, UStringVector &destStrings); -UString JoinStrings(const UStringVector &srcStrings); +// UString JoinStrings(const UStringVector &srcStrings); #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SysIconUtils.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SysIconUtils.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SysIconUtils.cpp 2022-07-15 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SysIconUtils.cpp 2023-03-20 10:00:00.000000000 +0000 @@ -10,10 +10,11 @@ #include "SysIconUtils.h" +#if defined(__MINGW32__) || defined(__MINGW64__) +#include +#else #include - -#define MY_CAST_FUNC (void(*)()) -// #define MY_CAST_FUNC +#endif #ifndef _UNICODE extern bool g_IsNT; @@ -21,49 +22,55 @@ int GetIconIndexForCSIDL(int csidl) { - LPITEMIDLIST pidl = 0; + LPITEMIDLIST pidl = NULL; SHGetSpecialFolderLocation(NULL, csidl, &pidl); if (pidl) { SHFILEINFO shellInfo; - SHGetFileInfo((LPCTSTR)(const void *)(pidl), FILE_ATTRIBUTE_NORMAL, - &shellInfo, sizeof(shellInfo), - SHGFI_PIDL | SHGFI_SYSICONINDEX); - IMalloc *pMalloc; + shellInfo.iIcon = 0; + const DWORD_PTR res = SHGetFileInfo((LPCTSTR)(const void *)(pidl), FILE_ATTRIBUTE_NORMAL, + &shellInfo, sizeof(shellInfo), + SHGFI_PIDL | SHGFI_SYSICONINDEX); + /* + IMalloc *pMalloc; SHGetMalloc(&pMalloc); if (pMalloc) { pMalloc->Free(pidl); pMalloc->Release(); } - return shellInfo.iIcon; + */ + // we use OLE2.dll function here + CoTaskMemFree(pidl); + if (res) + return shellInfo.iIcon; } return 0; } #ifndef _UNICODE -typedef int (WINAPI * Func_SHGetFileInfoW)(LPCWSTR pszPath, DWORD attrib, SHFILEINFOW *psfi, UINT cbFileInfo, UINT uFlags); +typedef DWORD_PTR (WINAPI * Func_SHGetFileInfoW)(LPCWSTR pszPath, DWORD attrib, SHFILEINFOW *psfi, UINT cbFileInfo, UINT uFlags); -static struct CSHGetFileInfoInit +static struct C_SHGetFileInfo_Init { - Func_SHGetFileInfoW shGetFileInfoW; - CSHGetFileInfoInit() + Func_SHGetFileInfoW f_SHGetFileInfoW; + C_SHGetFileInfo_Init() { - shGetFileInfoW = (Func_SHGetFileInfoW) - MY_CAST_FUNC - ::GetProcAddress(::GetModuleHandleW(L"shell32.dll"), "SHGetFileInfoW"); + f_SHGetFileInfoW = Z7_GET_PROC_ADDRESS( + Func_SHGetFileInfoW, ::GetModuleHandleW(L"shell32.dll"), + "SHGetFileInfoW"); } -} g_SHGetFileInfoInit; +} g_SHGetFileInfo_Init; #endif -static DWORD_PTR MySHGetFileInfoW(LPCWSTR pszPath, DWORD attrib, SHFILEINFOW *psfi, UINT cbFileInfo, UINT uFlags) +static DWORD_PTR My_SHGetFileInfoW(LPCWSTR pszPath, DWORD attrib, SHFILEINFOW *psfi, UINT cbFileInfo, UINT uFlags) { #ifdef _UNICODE return SHGetFileInfo #else - if (g_SHGetFileInfoInit.shGetFileInfoW == 0) + if (!g_SHGetFileInfo_Init.f_SHGetFileInfoW) return 0; - return g_SHGetFileInfoInit.shGetFileInfoW + return g_SHGetFileInfo_Init.f_SHGetFileInfoW #endif (pszPath, attrib, psfi, cbFileInfo, uFlags); } @@ -74,7 +81,7 @@ if (!g_IsNT) { SHFILEINFO shellInfo; - DWORD_PTR res = ::SHGetFileInfo(fs2fas(path), FILE_ATTRIBUTE_NORMAL | attrib, &shellInfo, + const DWORD_PTR res = ::SHGetFileInfo(fs2fas(path), FILE_ATTRIBUTE_NORMAL | attrib, &shellInfo, sizeof(shellInfo), SHGFI_USEFILEATTRIBUTES | SHGFI_SYSICONINDEX); iconIndex = shellInfo.iIcon; return res; @@ -83,7 +90,7 @@ #endif { SHFILEINFOW shellInfo; - DWORD_PTR res = ::MySHGetFileInfoW(fs2us(path), FILE_ATTRIBUTE_NORMAL | attrib, &shellInfo, + const DWORD_PTR res = ::My_SHGetFileInfoW(fs2us(path), FILE_ATTRIBUTE_NORMAL | attrib, &shellInfo, sizeof(shellInfo), SHGFI_USEFILEATTRIBUTES | SHGFI_SYSICONINDEX); iconIndex = shellInfo.iIcon; return res; @@ -110,7 +117,7 @@ { SHFILEINFOW shellInfo; shellInfo.szTypeName[0] = 0; - DWORD_PTR res = ::MySHGetFileInfoW(fileName, FILE_ATTRIBUTE_NORMAL | attrib, &shellInfo, + DWORD_PTR res = ::My_SHGetFileInfoW(fileName, FILE_ATTRIBUTE_NORMAL | attrib, &shellInfo, sizeof(shellInfo), SHGFI_USEFILEATTRIBUTES | SHGFI_SYSICONINDEX | SHGFI_TYPENAME); if (typeName) *typeName = shellInfo.szTypeName; @@ -120,15 +127,15 @@ } */ -static int FindInSorted_Attrib(const CRecordVector &vect, DWORD attrib, int &insertPos) +static int FindInSorted_Attrib(const CRecordVector &vect, DWORD attrib, unsigned &insertPos) { unsigned left = 0, right = vect.Size(); while (left != right) { - unsigned mid = (left + right) / 2; - DWORD midAttrib = vect[mid].Attrib; + const unsigned mid = (left + right) / 2; + const DWORD midAttrib = vect[mid].Attrib; if (attrib == midAttrib) - return mid; + return (int)mid; if (attrib < midAttrib) right = mid; else @@ -138,15 +145,15 @@ return -1; } -static int FindInSorted_Ext(const CObjectVector &vect, const wchar_t *ext, int &insertPos) +static int FindInSorted_Ext(const CObjectVector &vect, const wchar_t *ext, unsigned &insertPos) { unsigned left = 0, right = vect.Size(); while (left != right) { - unsigned mid = (left + right) / 2; - int compare = MyStringCompareNoCase(ext, vect[mid].Ext); + const unsigned mid = (left + right) / 2; + const int compare = MyStringCompareNoCase(ext, vect[mid].Ext); if (compare == 0) - return mid; + return (int)mid; if (compare < 0) right = mid; else @@ -162,11 +169,11 @@ unsigned i; for (i = 0;; i++) { - wchar_t c = fileName[i]; + const wchar_t c = fileName[i]; if (c == 0) break; if (c == '.') - dotPos = i; + dotPos = (int)i; } /* @@ -181,12 +188,12 @@ if ((attrib & FILE_ATTRIBUTE_DIRECTORY) != 0 || dotPos < 0) { - int insertPos = 0; - int index = FindInSorted_Attrib(_attribMap, attrib, insertPos); + unsigned insertPos = 0; + const int index = FindInSorted_Attrib(_attribMap, attrib, insertPos); if (index >= 0) { // if (typeName) *typeName = _attribMap[index].TypeName; - return _attribMap[index].IconIndex; + return _attribMap[(unsigned)index].IconIndex; } CAttribIconPair pair; GetRealIconIndex( @@ -211,8 +218,8 @@ } const wchar_t *ext = fileName + dotPos + 1; - int insertPos = 0; - int index = FindInSorted_Ext(_extMap, ext, insertPos); + unsigned insertPos = 0; + const int index = FindInSorted_Ext(_extMap, ext, insertPos); if (index >= 0) { const CExtIconPair &pa = _extMap[index]; @@ -222,7 +229,7 @@ for (i = 0;; i++) { - wchar_t c = ext[i]; + const wchar_t c = ext[i]; if (c == 0) break; if (c < L'0' || c > L'9') @@ -257,3 +264,15 @@ return GetIconIndex(attrib, fileName, NULL); } */ + +HIMAGELIST GetSysImageList(bool smallIcons) +{ + SHFILEINFO shellInfo; + return (HIMAGELIST)SHGetFileInfo(TEXT(""), + FILE_ATTRIBUTE_NORMAL | + FILE_ATTRIBUTE_DIRECTORY, + &shellInfo, sizeof(shellInfo), + SHGFI_USEFILEATTRIBUTES | + SHGFI_SYSICONINDEX | + (smallIcons ? SHGFI_SMALLICON : SHGFI_ICON)); +} diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SysIconUtils.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SysIconUtils.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SysIconUtils.h 2021-01-26 12:18:46.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SysIconUtils.h 2023-01-11 11:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // SysIconUtils.h -#ifndef __SYS_ICON_UTILS_H -#define __SYS_ICON_UTILS_H +#ifndef ZIP7_INC_SYS_ICON_UTILS_H +#define ZIP7_INC_SYS_ICON_UTILS_H #include "../../../Common/MyWindows.h" @@ -50,13 +50,6 @@ DWORD_PTR GetRealIconIndex(CFSTR path, DWORD attrib, int &iconIndex); int GetIconIndexForCSIDL(int csidl); -inline HIMAGELIST GetSysImageList(bool smallIcons) -{ - SHFILEINFO shellInfo; - return (HIMAGELIST)SHGetFileInfo(TEXT(""), - FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_DIRECTORY, - &shellInfo, sizeof(shellInfo), - SHGFI_USEFILEATTRIBUTES | SHGFI_SYSICONINDEX | (smallIcons ? SHGFI_SMALLICON : SHGFI_ICON)); -} +HIMAGELIST GetSysImageList(bool smallIcons); #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SystemPage.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SystemPage.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SystemPage.cpp 2021-01-24 10:13:44.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SystemPage.cpp 2023-03-20 10:00:00.000000000 +0000 @@ -4,7 +4,11 @@ #include "../../../Common/MyWindows.h" +#if defined(__MINGW32__) || defined(__MINGW64__) +#include +#else #include +#endif #include "../../../Common/Defs.h" #include "../../../Common/StringConvert.h" @@ -25,10 +29,12 @@ extern bool g_IsNT; #endif +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { IDT_SYSTEM_ASSOCIATE }; +#endif #define kSystemTopic "FM/options.htm#system" @@ -44,7 +50,7 @@ else return ProgramKey; return CSysString (s); -}; +} int CSystemPage::AddIcon(const UString &iconPath, int iconIndex) @@ -62,19 +68,19 @@ #else // we expand path from REG_EXPAND_SZ registry item. UString path; - DWORD size = MAX_PATH + 10; - DWORD needLen = ::ExpandEnvironmentStringsW(iconPath, path.GetBuf(size + 2), size); + const DWORD size = MAX_PATH + 10; + const DWORD needLen = ::ExpandEnvironmentStringsW(iconPath, path.GetBuf(size + 2), size); path.ReleaseBuf_CalcLen(size); if (needLen == 0 || needLen >= size) path = iconPath; - int num = ExtractIconExW(path, iconIndex, NULL, &hicon, 1); + const UINT num = ExtractIconExW(path, iconIndex, NULL, &hicon, 1); if (num != 1 || !hicon) #endif return -1; _imageList.AddIcon(hicon); DestroyIcon(hicon); - return _numIcons++; + return (int)(_numIcons++); } @@ -84,7 +90,7 @@ _listView.SetSubItem(listIndex, group + 1, assoc.Pair[group].GetString()); LVITEMW newItem; memset(&newItem, 0, sizeof(newItem)); - newItem.iItem = listIndex; + newItem.iItem = (int)listIndex; newItem.mask = LVIF_IMAGE; newItem.iImage = assoc.GetIconIndex(); _listView.SetItem(&newItem); @@ -151,7 +157,9 @@ { _needSave = false; - LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); +#ifdef Z7_LANG + LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs)); +#endif _listView.Attach(GetItem(IDL_SYSTEM_ASSOCIATE)); _listView.SetUnicodeFormat(); @@ -221,9 +229,9 @@ const CExtPlugins &extInfo = _extDB.Exts[i]; LVITEMW item; - item.iItem = i; + item.iItem = (int)i; item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE; - item.lParam = i; + item.lParam = (LPARAM)i; item.iSubItem = 0; // ListView always uses internal iImage that is 0 by default? // so we always use LVIF_IMAGE. @@ -245,9 +253,9 @@ texts[g] = mi.GetString(); } item.iImage = assoc.GetIconIndex(); - int itemIndex = _listView.InsertItem(&item); + const int itemIndex = _listView.InsertItem(&item); for (g = 0; g < NUM_EXT_GROUPS; g++) - _listView.SetSubItem(itemIndex, 1 + g, texts[g]); + _listView.SetSubItem((unsigned)itemIndex, 1 + g, texts[g]); _items.Add(assoc); } @@ -334,7 +342,7 @@ } -bool CSystemPage::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CSystemPage::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -379,7 +387,7 @@ if (item->iSubItem >= 1 && item->iSubItem <= 2) { CUIntVector indices; - indices.Add(item->iItem); + indices.Add((unsigned)item->iItem); ChangeState(item->iSubItem < 2 ? 0 : 1, indices); } } @@ -414,7 +422,7 @@ int itemIndex = -1; while ((itemIndex = _listView.GetNextSelectedItem(itemIndex)) != -1) - indices.Add(itemIndex); + indices.Add((unsigned)itemIndex); if (indices.IsEmpty()) FOR_VECTOR (i, _items) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SystemPage.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SystemPage.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/SystemPage.h 2020-09-29 16:17:49.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/SystemPage.h 2023-01-28 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // SystemPage.h -#ifndef __SYSTEM_PAGE_H -#define __SYSTEM_PAGE_H +#ifndef ZIP7_INC_SYSTEM_PAGE_H +#define ZIP7_INC_SYSTEM_PAGE_H #include "../../../Windows/Control/ImageList.h" #include "../../../Windows/Control/ListView.h" @@ -49,7 +49,7 @@ } } OldState = State; - }; + } }; struct CAssoc @@ -116,11 +116,11 @@ CSystemPage(): WasChanged(false) {} - virtual bool OnInit(); - virtual void OnNotifyHelp(); - virtual bool OnNotify(UINT controlID, LPNMHDR lParam); - virtual LONG OnApply(); - virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); + virtual bool OnInit() Z7_override; + virtual void OnNotifyHelp() Z7_override; + virtual bool OnNotify(UINT controlID, LPNMHDR lParam) Z7_override; + virtual LONG OnApply() Z7_override; + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/TextPairs.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/TextPairs.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/TextPairs.cpp 2022-07-14 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/TextPairs.cpp 2023-03-16 13:00:00.000000000 +0000 @@ -100,9 +100,9 @@ static int ComparePairItems(void *const *a1, void *const *a2, void * /* param */) { return ComparePairItems(**(const CTextPair *const *)a1, **(const CTextPair *const *)a2); } -void CPairsStorage::Sort() { Pairs.Sort(ComparePairItems, 0); } +void CPairsStorage::Sort() { Pairs.Sort(ComparePairItems, NULL); } -int CPairsStorage::FindID(const UString &id, int &insertPos) const +int CPairsStorage::FindID(const UString &id, unsigned &insertPos) const { unsigned left = 0, right = Pairs.Size(); while (left != right) @@ -112,7 +112,7 @@ if (compResult == 0) { insertPos = mid; // to disable GCC warning - return mid; + return (int)mid; } if (compResult < 0) right = mid; @@ -125,13 +125,13 @@ int CPairsStorage::FindID(const UString &id) const { - int pos; + unsigned pos; return FindID(id, pos); } void CPairsStorage::AddPair(const CTextPair &pair) { - int insertPos; + unsigned insertPos; const int pos = FindID(pair.ID, insertPos); if (pos >= 0) Pairs[pos] = pair; @@ -143,7 +143,7 @@ { const int pos = FindID(id); if (pos >= 0) - Pairs.Delete(pos); + Pairs.Delete((unsigned)pos); } bool CPairsStorage::GetValue(const UString &id, UString &value) const @@ -185,7 +185,7 @@ text += pair.ID; if (multiWord) text += '\"'; - text += ' '; + text.Add_Space(); text += pair.Value; text += '\x0D'; text.Add_LF(); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/TextPairs.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/TextPairs.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/TextPairs.h 2014-07-05 10:49:22.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/TextPairs.h 2023-01-19 20:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // TextPairs.h -#ifndef __FM_TEXT_PAIRS_H -#define __FM_TEXT_PAIRS_H +#ifndef ZIP7_INC_FM_TEXT_PAIRS_H +#define ZIP7_INC_FM_TEXT_PAIRS_H #include "../../../Common/MyString.h" @@ -15,7 +15,7 @@ { CObjectVector Pairs; - int FindID(const UString &id, int &insertPos) const; + int FindID(const UString &id, unsigned &insertPos) const; int FindID(const UString &id) const; void Sort(); public: diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/UpdateCallback100.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/UpdateCallback100.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/UpdateCallback100.cpp 2015-03-21 09:01:49.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/UpdateCallback100.cpp 2023-01-28 17:00:00.000000000 +0000 @@ -9,50 +9,50 @@ #include "LangUtils.h" #include "UpdateCallback100.h" -STDMETHODIMP CUpdateCallback100Imp::ScanProgress(UInt64 /* numFolders */, UInt64 numFiles, UInt64 totalSize, const wchar_t *path, Int32 /* isDir */) +Z7_COM7F_IMF(CUpdateCallback100Imp::ScanProgress(UInt64 /* numFolders */, UInt64 numFiles, UInt64 totalSize, const wchar_t *path, Int32 /* isDir */)) { return ProgressDialog->Sync.ScanProgress(numFiles, totalSize, us2fs(path)); } -STDMETHODIMP CUpdateCallback100Imp::ScanError(const wchar_t *path, HRESULT errorCode) +Z7_COM7F_IMF(CUpdateCallback100Imp::ScanError(const wchar_t *path, HRESULT errorCode)) { ProgressDialog->Sync.AddError_Code_Name(errorCode, path); return S_OK; } -STDMETHODIMP CUpdateCallback100Imp::SetNumFiles(UInt64 numFiles) +Z7_COM7F_IMF(CUpdateCallback100Imp::SetNumFiles(UInt64 numFiles)) { return ProgressDialog->Sync.Set_NumFilesTotal(numFiles); } -STDMETHODIMP CUpdateCallback100Imp::SetTotal(UInt64 size) +Z7_COM7F_IMF(CUpdateCallback100Imp::SetTotal(UInt64 size)) { ProgressDialog->Sync.Set_NumBytesTotal(size); return S_OK; } -STDMETHODIMP CUpdateCallback100Imp::SetCompleted(const UInt64 *completed) +Z7_COM7F_IMF(CUpdateCallback100Imp::SetCompleted(const UInt64 *completed)) { return ProgressDialog->Sync.Set_NumBytesCur(completed); } -STDMETHODIMP CUpdateCallback100Imp::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) +Z7_COM7F_IMF(CUpdateCallback100Imp::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize)) { ProgressDialog->Sync.Set_Ratio(inSize, outSize); return S_OK; } -STDMETHODIMP CUpdateCallback100Imp::CompressOperation(const wchar_t *name) +Z7_COM7F_IMF(CUpdateCallback100Imp::CompressOperation(const wchar_t *name)) { return SetOperation_Base(NUpdateNotifyOp::kAdd, name, false); } -STDMETHODIMP CUpdateCallback100Imp::DeleteOperation(const wchar_t *name) +Z7_COM7F_IMF(CUpdateCallback100Imp::DeleteOperation(const wchar_t *name)) { return SetOperation_Base(NUpdateNotifyOp::kDelete, name, false); } -STDMETHODIMP CUpdateCallback100Imp::OperationResult(Int32 /* operationResult */) +Z7_COM7F_IMF(CUpdateCallback100Imp::OperationResult(Int32 /* operationResult */)) { ProgressDialog->Sync.Set_NumFilesCur(++NumFiles); return S_OK; @@ -60,7 +60,7 @@ void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, const wchar_t *fileName, UString &s); -HRESULT CUpdateCallback100Imp::ReportExtractResult(Int32 opRes, Int32 isEncrypted, const wchar_t *name) +Z7_COM7F_IMF(CUpdateCallback100Imp::ReportExtractResult(Int32 opRes, Int32 isEncrypted, const wchar_t *name)) { if (opRes != NArchive::NExtract::NOperationResult::kOK) { @@ -71,30 +71,30 @@ return S_OK; } -HRESULT CUpdateCallback100Imp::ReportUpdateOperation(UInt32 notifyOp, const wchar_t *name, Int32 isDir) +Z7_COM7F_IMF(CUpdateCallback100Imp::ReportUpdateOperation(UInt32 notifyOp, const wchar_t *name, Int32 isDir)) { return SetOperation_Base(notifyOp, name, IntToBool(isDir)); } -STDMETHODIMP CUpdateCallback100Imp::UpdateErrorMessage(const wchar_t *message) +Z7_COM7F_IMF(CUpdateCallback100Imp::UpdateErrorMessage(const wchar_t *message)) { ProgressDialog->Sync.AddError_Message(message); return S_OK; } -HRESULT CUpdateCallback100Imp::OpenFileError(const wchar_t *path, HRESULT errorCode) +Z7_COM7F_IMF(CUpdateCallback100Imp::OpenFileError(const wchar_t *path, HRESULT errorCode)) { ProgressDialog->Sync.AddError_Code_Name(errorCode, path); return S_OK; } -STDMETHODIMP CUpdateCallback100Imp::ReadingFileError(const wchar_t *path, HRESULT errorCode) +Z7_COM7F_IMF(CUpdateCallback100Imp::ReadingFileError(const wchar_t *path, HRESULT errorCode)) { ProgressDialog->Sync.AddError_Code_Name(errorCode, path); return S_OK; } -STDMETHODIMP CUpdateCallback100Imp::CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password) +Z7_COM7F_IMF(CUpdateCallback100Imp::CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password)) { *password = NULL; *passwordIsDefined = BoolToInt(PasswordIsDefined); @@ -103,17 +103,17 @@ return StringToBstr(Password, password); } -STDMETHODIMP CUpdateCallback100Imp::SetTotal(const UInt64 * /* files */, const UInt64 * /* bytes */) +Z7_COM7F_IMF(CUpdateCallback100Imp::SetTotal(const UInt64 * /* files */, const UInt64 * /* bytes */)) { return S_OK; } -STDMETHODIMP CUpdateCallback100Imp::SetCompleted(const UInt64 * /* files */, const UInt64 * /* bytes */) +Z7_COM7F_IMF(CUpdateCallback100Imp::SetCompleted(const UInt64 * /* files */, const UInt64 * /* bytes */)) { return ProgressDialog->Sync.CheckStop(); } -STDMETHODIMP CUpdateCallback100Imp::CryptoGetTextPassword(BSTR *password) +Z7_COM7F_IMF(CUpdateCallback100Imp::CryptoGetTextPassword(BSTR *password)) { *password = NULL; if (!PasswordIsDefined) diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/UpdateCallback100.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/UpdateCallback100.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/UpdateCallback100.h 2015-03-11 12:04:43.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/UpdateCallback100.h 2023-02-01 10:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // UpdateCallback100.h -#ifndef __UPDATE_CALLBACK100_H -#define __UPDATE_CALLBACK100_H +#ifndef ZIP7_INC_UPDATE_CALLBACK100_H +#define ZIP7_INC_UPDATE_CALLBACK100_H #include "../../../Common/MyCom.h" @@ -13,7 +13,7 @@ #include "ProgressDialog2.h" -class CUpdateCallback100Imp: +class CUpdateCallback100Imp Z7_final: public IFolderArchiveUpdateCallback, public IFolderArchiveUpdateCallback2, public IFolderScanProgress, @@ -24,11 +24,7 @@ public CUpdateCallbackGUI2, public CMyUnknownImp { -public: - - // CUpdateCallback100Imp() {} - - MY_UNKNOWN_IMP7( + Z7_COM_UNKNOWN_IMP_7( IFolderArchiveUpdateCallback, IFolderArchiveUpdateCallback2, IFolderScanProgress, @@ -37,16 +33,14 @@ IArchiveOpenCallback, ICompressProgressInfo) - INTERFACE_IProgress(;) - INTERFACE_IArchiveOpenCallback(;) - INTERFACE_IFolderArchiveUpdateCallback(;) - INTERFACE_IFolderArchiveUpdateCallback2(;) - INTERFACE_IFolderScanProgress(;) - - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); - - STDMETHOD(CryptoGetTextPassword)(BSTR *password); - STDMETHOD(CryptoGetTextPassword2)(Int32 *passwordIsDefined, BSTR *password); + Z7_IFACE_COM7_IMP(IProgress) + Z7_IFACE_COM7_IMP(IFolderArchiveUpdateCallback) + Z7_IFACE_COM7_IMP(IFolderArchiveUpdateCallback2) + Z7_IFACE_COM7_IMP(IFolderScanProgress) + Z7_IFACE_COM7_IMP(ICryptoGetTextPassword2) + Z7_IFACE_COM7_IMP(ICryptoGetTextPassword) + Z7_IFACE_COM7_IMP(IArchiveOpenCallback) + Z7_IFACE_COM7_IMP(ICompressProgressInfo) }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/VerCtrl.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/VerCtrl.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/VerCtrl.cpp 2021-12-15 07:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/VerCtrl.cpp 2023-03-06 16:00:00.000000000 +0000 @@ -149,7 +149,7 @@ } CRecordVector indices; - panel.GetSelectedItemsIndices(indices); + panel.Get_ItemIndices_Selected(indices); if (indices.Size() != 1) { @@ -223,7 +223,7 @@ if (!ParseNumberString(fi.Name, val)) continue; if ((Int32)val > maxVal) - maxVal = val; + maxVal = (Int32)val; } UInt32 next = (UInt32)maxVal + 1; @@ -320,7 +320,7 @@ const UInt64 k_Ntfs_prec = 10000000; UInt64 timeStamp = timeStampOriginal; const UInt32 k_precs[] = { 60 * 60, 60, 2, 1 }; - for (unsigned i = 0; i < ARRAY_SIZE(k_precs); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_precs); i++) { timeStamp = timeStampOriginal; const UInt64 prec = k_Ntfs_prec * k_precs[i]; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ViewSettings.cpp 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ViewSettings.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ViewSettings.cpp 2021-01-22 21:22:50.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ViewSettings.cpp 2023-01-19 20:00:00.000000000 +0000 @@ -36,7 +36,8 @@ #define Set32(p, v) SetUi32(((Byte *)p), v) #define SetBool(p, v) Set32(p, ((v) ? 1 : 0)) -#define Get32(p, dest) dest = GetUi32((const Byte *)p) +#define Get32(p, dest) dest = GetUi32((const Byte *)p); +#define Get32_LONG(p, dest) dest = (LONG)GetUi32((const Byte *)p); #define GetBool(p, dest) dest = (GetUi32(p) != 0); /* @@ -57,16 +58,16 @@ const UInt32 dataSize = kListViewHeaderSize + kColumnInfoSize * Columns.Size(); CByteArr buf(dataSize); - Set32(buf, kListViewVersion); - Set32(buf + 4, SortID); - SetBool(buf + 8, Ascending); + Set32(buf, kListViewVersion) + Set32(buf + 4, SortID) + SetBool(buf + 8, Ascending) FOR_VECTOR (i, Columns) { const CColumnInfo &column = Columns[i]; Byte *p = buf + kListViewHeaderSize + i * kColumnInfoSize; - Set32(p, column.PropID); - SetBool(p + 4, column.IsVisible); - Set32(p + 8, column.Width); + Set32(p, column.PropID) + SetBool(p + 4, column.IsVisible) + Set32(p + 8, column.Width) } { NSynchronization::CCriticalSectionLock lock(g_CS); @@ -92,11 +93,11 @@ if (size < kListViewHeaderSize) return; UInt32 version; - Get32(buf, version); + Get32(buf, version) if (version != kListViewVersion) return; - Get32(buf + 4, SortID); - GetBool(buf + 8, Ascending); + Get32(buf + 4, SortID) + GetBool(buf + 8, Ascending) IsLoaded = true; @@ -109,9 +110,9 @@ { CColumnInfo column; const Byte *p = buf + kListViewHeaderSize + i * kColumnInfoSize; - Get32(p, column.PropID); - GetBool(p + 4, column.IsVisible); - Get32(p + 8, column.Width); + Get32(p, column.PropID) + GetBool(p + 4, column.IsVisible) + Get32(p + 8, column.Width) Columns.AddInReserved(column); } } @@ -142,18 +143,18 @@ key.Create(HKEY_CURRENT_USER, kCUBasePath); { Byte buf[kWindowPositionHeaderSize]; - Set32(buf, rect.left); - Set32(buf + 4, rect.top); - Set32(buf + 8, rect.right); - Set32(buf + 12, rect.bottom); - SetBool(buf + 16, maximized); + Set32(buf, (UInt32)rect.left) + Set32(buf + 4, (UInt32)rect.top) + Set32(buf + 8, (UInt32)rect.right) + Set32(buf + 12, (UInt32)rect.bottom) + SetBool(buf + 16, maximized) key.SetValue(kPositionValueName, buf, kWindowPositionHeaderSize); } { Byte buf[kPanelsInfoHeaderSize]; - Set32(buf, numPanels); - Set32(buf + 4, currentPanel); - Set32(buf + 8, splitterPos); + Set32(buf, numPanels) + Set32(buf + 4, currentPanel) + Set32(buf + 8, splitterPos) key.SetValue(kPanelsInfoValueName, buf, kPanelsInfoHeaderSize); } } @@ -175,18 +176,18 @@ CByteBuffer buf; if (QueryBuf(key, kPositionValueName, buf, kWindowPositionHeaderSize)) { - Get32(buf, rect.left); - Get32(buf + 4, rect.top); - Get32(buf + 8, rect.right); - Get32(buf + 12, rect.bottom); - GetBool(buf + 16, maximized); + Get32_LONG(buf, rect.left) + Get32_LONG(buf + 4, rect.top) + Get32_LONG(buf + 8, rect.right) + Get32_LONG(buf + 12, rect.bottom) + GetBool(buf + 16, maximized) windowPosDefined = true; } if (QueryBuf(key, kPanelsInfoValueName, buf, kPanelsInfoHeaderSize)) { - Get32(buf, numPanels); - Get32(buf + 4, currentPanel); - Get32(buf + 8, splitterPos); + Get32(buf, numPanels) + Get32(buf + 4, currentPanel) + Get32(buf + 8, splitterPos) panelInfoDefined = true; } return; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ViewSettings.h 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ViewSettings.h --- 7zip-22.01+dfsg/CPP/7zip/UI/FileManager/ViewSettings.h 2015-11-12 10:52:46.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/FileManager/ViewSettings.h 2023-01-10 18:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ViewSettings.h -#ifndef __VIEW_SETTINGS_H -#define __VIEW_SETTINGS_H +#ifndef ZIP7_INC_VIEW_SETTINGS_H +#define ZIP7_INC_VIEW_SETTINGS_H #include "../../../Common/MyTypes.h" #include "../../../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/7zG.exe.manifest 7zip-23.01+dfsg/CPP/7zip/UI/GUI/7zG.exe.manifest --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/7zG.exe.manifest 2018-04-25 11:15:55.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/7zG.exe.manifest 2023-04-02 08:00:00.000000000 +0000 @@ -17,4 +17,7 @@ true + + +true diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/BenchmarkDialog.cpp 7zip-23.01+dfsg/CPP/7zip/UI/GUI/BenchmarkDialog.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/BenchmarkDialog.cpp 2021-12-21 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/BenchmarkDialog.cpp 2023-04-01 08:00:00.000000000 +0000 @@ -22,9 +22,7 @@ #include "../FileManager/DialogSize.h" #include "../FileManager/HelpUtils.h" -#ifdef LANG #include "../FileManager/LangUtils.h" -#endif #include "../../MyVersion.h" @@ -156,7 +154,7 @@ NeedPrint_Dec_1 = NeedPrint_Dec = NeedPrint_Tot = false; -}; +} struct CBenchProgressSync @@ -243,7 +241,7 @@ struct CThreadBenchmark { CBenchmarkDialog *BenchmarkDialog; - DECL_EXTERNAL_CODECS_LOC_VARS2; + DECL_EXTERNAL_CODECS_LOC_VARS_DECL // HRESULT Result; HRESULT Process(); @@ -290,15 +288,15 @@ Sync.Init(); } - virtual bool OnInit(); - virtual bool OnDestroy(); - virtual bool OnSize(WPARAM /* wParam */, int xSize, int ySize); - virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam); - virtual bool OnCommand(int code, int itemID, LPARAM lParam); - virtual void OnHelp(); - virtual void OnCancel(); - virtual bool OnTimer(WPARAM timerID, LPARAM callback); - virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); + virtual bool OnInit() Z7_override; + virtual bool OnDestroy() Z7_override; + virtual bool OnSize(WPARAM /* wParam */, int xSize, int ySize) Z7_override; + virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam) Z7_override; + virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM lParam) Z7_override; + virtual void OnHelp() Z7_override; + virtual void OnCancel() Z7_override; + virtual bool OnTimer(WPARAM timerID, LPARAM callback) Z7_override; + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; void Disable_Stop_Button(); void OnStopButton(); @@ -315,7 +313,7 @@ UInt32 GetNumberOfThreads(); size_t OnChangeDictionary(); - void SetItemText_Number(int itemID, UInt64 val, LPCTSTR post = NULL); + void SetItemText_Number(unsigned itemID, UInt64 val, LPCTSTR post = NULL); void Print_MemUsage(UString &s, UInt64 memUsage) const; bool IsMemoryUsageOK(UInt64 memUsage) const { return memUsage + (1 << 20) <= RamSize_Limit; } @@ -347,17 +345,17 @@ TotalMode(false) {} - ~CBenchmarkDialog(); + ~CBenchmarkDialog() Z7_DESTRUCTOR_override; - bool PostMsg_Finish(LPARAM param) + bool PostMsg_Finish(WPARAM wparam) { if ((HWND)*this) - return PostMsg(k_Message_Finished, param); + return PostMsg(k_Message_Finished, wparam); // the (HWND)*this is NULL only for some internal code failure return true; } - INT_PTR Create(HWND wndParent = 0) + INT_PTR Create(HWND wndParent = NULL) { BIG_DIALOG_SIZE(332, 228); return CModalDialog::Create(TotalMode ? IDD_BENCH_TOTAL : SIZED_DIALOG(IDD_BENCH), wndParent); @@ -385,13 +383,13 @@ UString HResultToMessage(HRESULT errorCode); -#ifdef LANG +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { IDT_BENCH_DICTIONARY, IDT_BENCH_MEMORY, IDT_BENCH_NUM_THREADS, - IDT_BENCH_SPEED, + IDT_BENCH_SIZE, IDT_BENCH_RATING_LABEL, IDT_BENCH_USAGE_LABEL, IDT_BENCH_RPU_LABEL, @@ -406,9 +404,9 @@ IDB_RESTART }; -static const UInt32 kLangIDs_Colon[] = +static const UInt32 kLangIDs_RemoveColon[] = { - IDT_BENCH_SIZE + IDT_BENCH_SPEED }; #endif @@ -439,18 +437,18 @@ { TCHAR s[16]; ConvertUInt32ToString(v, s); - int index = (int)cb.AddString(s); - cb.SetItemData(index, v); + const int index = (int)cb.AddString(s); + cb.SetItemData(index, (LPARAM)v); return index; } bool CBenchmarkDialog::OnInit() { - #ifdef LANG + #ifdef Z7_LANG LangSetWindowText(*this, IDD_BENCH); - LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); - // LangSetDlgItems_Colon(*this, kLangIDs_Colon, ARRAY_SIZE(kLangIDs_Colon)); + LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs)); + LangSetDlgItems_RemoveColon(*this, kLangIDs_RemoveColon, Z7_ARRAY_SIZE(kLangIDs_RemoveColon)); LangSetDlgItemText(*this, IDT_BENCH_CURRENT2, IDT_BENCH_CURRENT); LangSetDlgItemText(*this, IDT_BENCH_RESULTING2, IDT_BENCH_RESULTING); #endif @@ -486,7 +484,7 @@ NSystem::CProcessAffinity threadsInfo; threadsInfo.InitST(); - #ifndef _7ZIP_ST + #ifndef Z7_ST if (threadsInfo.Get() && threadsInfo.processAffinityMask != 0) numCPUs = threadsInfo.GetNumProcessThreads(); else @@ -531,7 +529,7 @@ if (numThreads == (UInt32)(Int32)-1) numThreads = numCPUs; if (numThreads > 1) - numThreads &= ~1; + numThreads &= ~(UInt32)1; const UInt32 kNumThreadsMax = (1 << 12); if (numThreads > kNumThreadsMax) numThreads = kNumThreadsMax; @@ -603,7 +601,7 @@ ConvertUInt32ToString(d, s); lstrcat(s, post); const int index = (int)m_Dictionary.AddString(s); - m_Dictionary.SetItemData(index, dict); + m_Dictionary.SetItemData(index, (LPARAM)dict); if (dict <= Sync.DictSize) cur = index; if (dict >= kMaxDicSize) @@ -711,18 +709,18 @@ s[0] = (wchar_t)('0' + (val) / 100); \ s[1] = (wchar_t)('0' + (val) % 100 / 10); \ s[2] = (wchar_t)('0' + (val) % 10); \ - s[3] = 0; } + s += 3; s[0] = 0; } -static void NumberToDot3(UInt64 val, WCHAR *s) +static WCHAR *NumberToDot3(UInt64 val, WCHAR *s) { - ConvertUInt64ToString(val / 1000, s); + s = ConvertUInt64ToString(val / 1000, s); const UInt32 rem = (UInt32)(val % 1000); - s += MyStringLen(s); *s++ = '.'; - UINT_TO_STR_3(s, rem); + UINT_TO_STR_3(s, rem) + return s; } -void CBenchmarkDialog::SetItemText_Number(int itemID, UInt64 val, LPCTSTR post) +void CBenchmarkDialog::SetItemText_Number(unsigned itemID, UInt64 val, LPCTSTR post) { TCHAR s[64]; ConvertUInt64ToString(val, s); @@ -758,7 +756,7 @@ UString s; Print_MemUsage(s, memUsage); - #ifdef _7ZIP_LARGE_PAGES + #ifdef Z7_LARGE_PAGES { AString s2; Add_LargePages_String(s2); @@ -875,7 +873,7 @@ const UInt32 numThreads = GetNumberOfThreads(); const UInt32 numPasses = (UInt32)m_NumPasses.GetItemData_of_CurSel(); - for (unsigned i = 0; i < ARRAY_SIZE(g_IDs); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_IDs); i++) SetItemText(g_IDs[i], kProcessingString); SetItemText_Empty(IDT_BENCH_LOG); @@ -916,7 +914,7 @@ { MyKillTimer(); MessageBoxError_Status(L"Can't create thread"); - }; + } return; } @@ -1000,19 +998,17 @@ WCHAR s[64]; - // GetTimeString(elapsedTime / 1000, s); - ConvertUInt32ToString(elapsedTime / 1000, s); + WCHAR *p = ConvertUInt32ToString(elapsedTime / 1000, s); if (_finishTime_WasSet) { - WCHAR *p = s + MyStringLen(s); *p++ = '.'; - UINT_TO_STR_3(p, elapsedTime % 1000); + UINT_TO_STR_3(p, elapsedTime % 1000) } - // NumberToDot3((UInt64)elapsedTime, s); + // p = NumberToDot3((UInt64)elapsedTime, s); - wcscat(s, L" s"); + MyStringCopy(p, L" s"); // if (WasStopped_in_GUI) wcscat(s, L" X"); // for debug @@ -1051,7 +1047,7 @@ if (rating32 != rating64) rating32 = (UInt32)(Int32)-1; return rating32; -}; +} static void AddUsageString(UString &s, const CTotalBenchRes &info) @@ -1088,7 +1084,7 @@ // s += " "; // s.Add_UInt32(GetRating(info)); Add_Dot3String(s, GetRating(info)); -}; +} static void AddRatingsLine(UString &s, const CTotalBenchRes &enc, const CTotalBenchRes &dec @@ -1127,8 +1123,7 @@ { // SetItemText_Number(controlID, GetMips(rating), kMIPS); WCHAR s[64]; - NumberToDot3(GetMips(rating), s); - MyStringCat(s, L" GIPS"); + MyStringCopy(NumberToDot3(GetMips(rating), s), L" GIPS"); SetItemText(controlID, s); } @@ -1391,7 +1386,7 @@ } -bool CBenchmarkDialog::OnCommand(int code, int itemID, LPARAM lParam) +bool CBenchmarkDialog::OnCommand(unsigned code, unsigned itemID, LPARAM lParam) { if (code == CBN_SELCHANGE && (itemID == IDC_BENCH_DICTIONARY || @@ -1405,7 +1400,7 @@ } -bool CBenchmarkDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CBenchmarkDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -1425,14 +1420,14 @@ // ---------- Benchmark Thread ---------- -struct CBenchCallback: public IBenchCallback +struct CBenchCallback Z7_final: public IBenchCallback { UInt64 dictionarySize; CBenchProgressSync *Sync; CBenchmarkDialog *BenchmarkDialog; - HRESULT SetEncodeResult(const CBenchInfo &info, bool final); - HRESULT SetDecodeResult(const CBenchInfo &info, bool final); + HRESULT SetEncodeResult(const CBenchInfo &info, bool final) Z7_override; + HRESULT SetDecodeResult(const CBenchInfo &info, bool final) Z7_override; }; HRESULT CBenchCallback::SetEncodeResult(const CBenchInfo &info, bool final) @@ -1494,14 +1489,14 @@ } -struct CBenchCallback2: public IBenchPrintCallback +struct CBenchCallback2 Z7_final: public IBenchPrintCallback { CBenchProgressSync *Sync; bool TotalMode; - void Print(const char *s); - void NewLine(); - HRESULT CheckBreak(); + void Print(const char *s) Z7_override; + void NewLine() Z7_override; + HRESULT CheckBreak() Z7_override; }; void CBenchCallback2::Print(const char *s) @@ -1528,12 +1523,12 @@ -struct CFreqCallback: public IBenchFreqCallback +struct CFreqCallback Z7_final: public IBenchFreqCallback { CBenchmarkDialog *BenchmarkDialog; - virtual HRESULT AddCpuFreq(unsigned numThreads, UInt64 freq, UInt64 usage); - virtual HRESULT FreqsFinished(unsigned numThreads); + virtual HRESULT AddCpuFreq(unsigned numThreads, UInt64 freq, UInt64 usage) Z7_override; + virtual HRESULT FreqsFinished(unsigned numThreads) Z7_override; }; HRESULT CFreqCallback::AddCpuFreq(unsigned numThreads, UInt64 freq, UInt64 usage) @@ -1839,7 +1834,7 @@ COneMethodInfo method; UInt32 numCPUs = 1; - #ifndef _7ZIP_ST + #ifndef Z7_ST numCPUs = NSystem::GetNumberOfProcessors(); #endif UInt32 numThreads = numCPUs; @@ -1860,8 +1855,8 @@ ParseNumberString(prop.Value, propVariant); if (name.IsPrefixedBy(L"mt")) { - #ifndef _7ZIP_ST - RINOK(ParseMtProp(name.Ptr(2), propVariant, numCPUs, numThreads)); + #ifndef Z7_ST + RINOK(ParseMtProp(name.Ptr(2), propVariant, numCPUs, numThreads)) if (numThreads != numCPUs) bd.Sync.NumThreads = numThreads; #endif @@ -1893,14 +1888,14 @@ if (method.Get_DicSize(dict)) bd.Sync.DictSize = dict; } - bd.Sync.Level = method.GetLevel(); + bd.Sync.Level = (int)method.GetLevel(); // Dummy(1000 * 1000 * 1); { CThreadBenchmark &benchmarker = bd._threadBenchmark; - #ifdef EXTERNAL_CODECS - benchmarker.__externalCodecs = __externalCodecs; + #ifdef Z7_EXTERNAL_CODECS + benchmarker._externalCodecs = _externalCodecs; #endif benchmarker.BenchmarkDialog = &bd; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/BenchmarkDialog.h 7zip-23.01+dfsg/CPP/7zip/UI/GUI/BenchmarkDialog.h --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/BenchmarkDialog.h 2021-07-15 13:03:08.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/BenchmarkDialog.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // BenchmarkDialog.h -#ifndef __BENCHMARK_DIALOG_H -#define __BENCHMARK_DIALOG_H +#ifndef ZIP7_INC_BENCHMARK_DIALOG_H +#define ZIP7_INC_BENCHMARK_DIALOG_H #include "../../Common/CreateCoder.h" #include "../../UI/Common/Property.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/CompressDialog.cpp 7zip-23.01+dfsg/CPP/7zip/UI/GUI/CompressDialog.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/CompressDialog.cpp 2022-07-14 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/CompressDialog.cpp 2023-06-19 12:00:00.000000000 +0000 @@ -29,14 +29,15 @@ extern bool g_IsNT; #endif -#ifdef LANG #include "../FileManager/LangUtils.h" -#endif #include "CompressDialogRes.h" #include "ExtractRes.h" +#include "resource2.h" + +// #define PRINT_PARAMS -#ifdef LANG +#ifdef Z7_LANG // #define IDS_OPTIONS 2100 @@ -88,6 +89,21 @@ static const UInt32 kLzmaMaxDictSize = (UInt32)15 << 28; +static const UINT k_Message_ArcChanged = WM_APP + 1; + +/* +static const UInt32 kZstd_MAX_DictSize = (UInt32)1 << MY_ZSTD_WINDOWLOG_MAX; +*/ + +/* The top value for windowLog_Chain: + (MY_ZSTD_CHAINLOG_MAX - 1): in BT mode + (MY_ZSTD_CHAINLOG_MAX) : in non-BT mode. But such big value is useless in most cases. + So we always reduce top value to (MY_ZSTD_CHAINLOG_MAX - 1) */ +/* +static const unsigned kMaxDictChain = MY_ZSTD_CHAINLOG_MAX - 1; +static const UInt32 kZstd_MAX_DictSize_Chain = (UInt32)1 << kMaxDictChain; +*/ + static LPCSTR const kExeExt = ".exe"; static const UInt32 g_Levels[] = @@ -114,6 +130,7 @@ kDeflate, kDeflate64, kPPMdZip, + // kZSTD, kSha256, kSha1, kCrc32, @@ -132,6 +149,7 @@ , "Deflate" , "Deflate64" , "PPMd" + // , "ZSTD" , "SHA256" , "SHA1" , "CRC32" @@ -148,6 +166,7 @@ kBZip2 , kDeflate , kDeflate64 + // , kZSTD , kCopy }; @@ -166,6 +185,7 @@ kBZip2, kLZMA, kPPMdZip + // , kZSTD }; static const EMethodID g_GZipMethods[] = @@ -183,6 +203,13 @@ kLZMA2 }; +/* +static const EMethodID g_ZstdMethods[] = +{ + kZSTD +}; +*/ + static const EMethodID g_SwfcMethods[] = { kDeflate @@ -236,7 +263,7 @@ bool SFX_() const { return (Flags & kFF_SFX) != 0; } }; -#define METHODS_PAIR(x) ARRAY_SIZE(x), x +#define METHODS_PAIR(x) Z7_ARRAY_SIZE(x), x static const CFormatInfo g_Formats[] = { @@ -282,6 +309,17 @@ METHODS_PAIR(g_XzMethods), kFF_Solid | kFF_MultiThread | kFF_MemUse }, + /* + { + "zstd", + // (1 << (MY_ZSTD_LEVEL_MAX + 1)) - 1, + (1 << (9 + 1)) - 1, + METHODS_PAIR(g_ZstdMethods), + // kFF_Solid | + kFF_MultiThread + | kFF_MemUse + }, + */ { "Swfc", (1 << 1) | (1 << 3) | (1 << 5) | (1 << 7) | (1 << 9), @@ -312,7 +350,7 @@ static bool IsMethodSupportedBySfx(int methodID) { - for (unsigned i = 0; i < ARRAY_SIZE(g_7zSfxMethods); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_7zSfxMethods); i++) if (methodID == g_7zSfxMethods[i]) return true; return false; @@ -370,10 +408,10 @@ || c.NumStreams != 1) continue; unsigned k; - for (k = 0; k < ARRAY_SIZE(g_7zMethods); k++) + for (k = 0; k < Z7_ARRAY_SIZE(g_7zMethods); k++) if (c.Name.IsEqualTo_Ascii_NoCase(kMethodsNames[g_7zMethods[k]])) break; - if (k != ARRAY_SIZE(g_7zMethods)) + if (k != Z7_ARRAY_SIZE(g_7zMethods)) continue; ExternalMethods.Add(c.Name); } @@ -383,9 +421,9 @@ bool CCompressDialog::OnInit() { - #ifdef LANG + #ifdef Z7_LANG LangSetWindowText(*this, IDD_COMPRESS); - LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); + LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs)); // LangSetDlgItemText(*this, IDB_COMPRESS_OPTIONS, IDS_OPTIONS); // IDG_COMPRESS_OPTIONS #endif @@ -420,10 +458,21 @@ _default_encryptionMethod_Index = -1; m_ArchivePath.Attach(GetItem(IDC_COMPRESS_ARCHIVE)); - m_Format.Attach(GetItem(IDC_COMPRESS_FORMAT)); + m_Format.Attach(GetItem(IDC_COMPRESS_FORMAT)); // that combo has CBS_SORT style in resources m_Level.Attach(GetItem(IDC_COMPRESS_LEVEL)); m_Method.Attach(GetItem(IDC_COMPRESS_METHOD)); m_Dictionary.Attach(GetItem(IDC_COMPRESS_DICTIONARY)); + + /* + { + RECT r; + GetClientRectOfItem(IDC_COMPRESS_DICTIONARY, r); + _dictionaryCombo_left = r.left; + } + */ + _dictionaryCombo_left = 0; // 230; + + // m_Dictionary_Chain.Attach(GetItem(IDC_COMPRESS_DICTIONARY2)); m_Order.Attach(GetItem(IDC_COMPRESS_ORDER)); m_Solid.Attach(GetItem(IDC_COMPRESS_SOLID)); m_NumThreads.Attach(GetItem(IDC_COMPRESS_THREADS)); @@ -444,13 +493,13 @@ UpdatePasswordControl(); { - bool needSetMain = (Info.FormatIndex < 0); + const bool needSetMain = (Info.FormatIndex < 0); FOR_VECTOR(i, ArcIndices) { - unsigned arcIndex = ArcIndices[i]; + const unsigned arcIndex = ArcIndices[i]; const CArcInfoEx &ai = (*ArcFormats)[arcIndex]; - int index = (int)m_Format.AddString(ai.Name); - m_Format.SetItemData(index, arcIndex); + const int index = (int)m_Format.AddString(ai.Name); + m_Format.SetItemData(index, (LPARAM)arcIndex); if (!needSetMain) { if (Info.FormatIndex == (int)arcIndex) @@ -460,7 +509,7 @@ if (i == 0 || ai.Name.IsEqualTo_NoCase(m_RegistryInfo.ArcType)) { m_Format.SetCurSel(index); - Info.FormatIndex = arcIndex; + Info.FormatIndex = (int)arcIndex; } } } @@ -477,10 +526,10 @@ for (unsigned i = 0; i < m_RegistryInfo.ArcPaths.Size() && i < kHistorySize; i++) m_ArchivePath.AddString(m_RegistryInfo.ArcPaths[i]); - AddComboItems(m_UpdateMode, k_UpdateMode_IDs, ARRAY_SIZE(k_UpdateMode_IDs), + AddComboItems(m_UpdateMode, k_UpdateMode_IDs, Z7_ARRAY_SIZE(k_UpdateMode_IDs), k_UpdateMode_Vals, Info.UpdateMode); - AddComboItems(m_PathMode, k_PathMode_IDs, ARRAY_SIZE(k_PathMode_IDs), + AddComboItems(m_PathMode, k_PathMode_IDs, Z7_ARRAY_SIZE(k_PathMode_IDs), k_PathMode_Vals, Info.PathMode); @@ -518,10 +567,10 @@ void CCompressDialog::UpdatePasswordControl() { - bool showPassword = IsShowPasswordChecked(); - TCHAR c = showPassword ? (TCHAR)0: TEXT('*'); - _password1Control.SetPasswordChar(c); - _password2Control.SetPasswordChar(c); + const bool showPassword = IsShowPasswordChecked(); + const TCHAR c = showPassword ? (TCHAR)0: TEXT('*'); + _password1Control.SetPasswordChar((WPARAM)c); + _password2Control.SetPasswordChar((WPARAM)c); UString password; _password1Control.GetText(password); _password1Control.SetText(password); @@ -532,7 +581,7 @@ _password2Control.Show_Bool(!showPassword); } -bool CCompressDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CCompressDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -703,13 +752,13 @@ bool CCompressDialog::IsSFX() { - CWindow sfxButton = GetItem(IDX_COMPRESS_SFX); - return sfxButton.IsEnabled() && IsButtonCheckedBool(IDX_COMPRESS_SFX); + return IsWindowEnabled(GetItem(IDX_COMPRESS_SFX)) + && IsButtonCheckedBool(IDX_COMPRESS_SFX); } static int GetExtDotPos(const UString &s) { - int dotPos = s.ReverseFind_Dot(); + const int dotPos = s.ReverseFind_Dot(); if (dotPos > s.ReverseFind_PathSepar() + 1) return dotPos; return -1; @@ -719,7 +768,7 @@ { UString fileName; m_ArchivePath.GetText(fileName); - int dotPos = GetExtDotPos(fileName); + const int dotPos = GetExtDotPos(fileName); if (IsSFX()) { if (dotPos >= 0) @@ -731,7 +780,7 @@ { if (dotPos >= 0) { - UString ext = fileName.Ptr(dotPos); + const UString ext = fileName.Ptr(dotPos); if (ext.IsEqualTo_Ascii_NoCase(kExeExt)) { fileName.DeleteFrom(dotPos); @@ -744,36 +793,38 @@ // CheckVolumeEnable(); } -bool CCompressDialog::GetFinalPath_Smart(UString &resPath) + +bool CCompressDialog::GetFinalPath_Smart(UString &resPath) const { + resPath.Empty(); UString name; m_ArchivePath.GetText(name); name.Trim(); - UString tempPath = name; - if (!IsAbsolutePath(name)) - { - UString newDirPrefix = DirPrefix; - if (newDirPrefix.IsEmpty()) - newDirPrefix = StartDirPrefix; - FString resultF; - if (!MyGetFullPathName(us2fs(newDirPrefix + name), resultF)) - return false; - tempPath = fs2us(resultF); - } - if (!SetArcPathFields(tempPath, name, false)) - return false; - FString resultF; - if (!MyGetFullPathName(us2fs(DirPrefix + name), resultF)) - return false; - resPath = fs2us(resultF); - return true; + FString fullPath; + UString dirPrefx = DirPrefix; + if (dirPrefx.IsEmpty()) + dirPrefx = StartDirPrefix; + const bool res = !dirPrefx.IsEmpty() ? + NName::GetFullPath(us2fs(dirPrefx), us2fs(name), fullPath): + NName::GetFullPath( us2fs(name), fullPath); + if (res) + resPath = fs2us(fullPath); + return res; +} + + +bool CCompressDialog::SetArcPathFields(const UString &path) +{ + UString name; + return SetArcPathFields(path, name, true); // always } + bool CCompressDialog::SetArcPathFields(const UString &path, UString &name, bool always) { FString resDirPrefix; FString resFileName; - bool res = GetFullPathAndSplit(us2fs(path), resDirPrefix, resFileName); + const bool res = GetFullPathAndSplit(us2fs(path), resDirPrefix, resFileName); if (res) { DirPrefix = fs2us(resDirPrefix); @@ -791,8 +842,26 @@ return res; } + static const wchar_t * const k_IncorrectPathMessage = L"Incorrect archive path"; +static void AddFilter(CObjectVector &filters, + const UString &description, const UString &ext) +{ + CBrowseFilterInfo &f = filters.AddNew(); + UString mask ("*."); + mask += ext; + f.Masks.Add(mask); + f.Description = description; + f.Description += " ("; + f.Description += mask; + f.Description += ")"; +} + + +static const char * const k_DontSave_Exts = + "xpi odt ods docx xlsx "; + void CCompressDialog::OnButtonSetArchive() { UString path; @@ -802,23 +871,133 @@ return; } - UString title = LangString(IDS_COMPRESS_SET_ARCHIVE_BROWSE); - UString filterDescription = LangString(IDS_OPEN_TYPE_ALL_FILES); - filterDescription += " (*.*)"; - UString resPath; - CurrentDirWasChanged = true; - if (!MyBrowseForFile(*this, title, - // DirPrefix.IsEmpty() ? NULL : (const wchar_t *)DirPrefix, - // NULL, - path, - filterDescription, - NULL, // L"*.*", - resPath)) + int filterIndex; + CObjectVector filters; + unsigned numFormats = 0; + + const bool isSFX = IsSFX(); + if (isSFX) + { + filterIndex = 0; + const UString ext ("exe"); + AddFilter(filters, ext, ext); + } + else + { + filterIndex = m_Format.GetCurSel(); + numFormats = (unsigned)m_Format.GetCount(); + + // filters [0, ... numFormats - 1] corresponds to items in m_Format combo + UString desc; + UStringVector masks; + CStringFinder finder; + + for (unsigned i = 0; i < numFormats; i++) + { + const CArcInfoEx &ai = (*ArcFormats)[(unsigned)m_Format.GetItemData(i)]; + CBrowseFilterInfo &f = filters.AddNew(); + f.Description = ai.Name; + f.Description += " ("; + bool needSpace_desc = false; + + FOR_VECTOR (k, ai.Exts) + { + const UString &ext = ai.Exts[k].Ext; + UString mask ("*."); + mask += ext; + + if (finder.FindWord_In_LowCaseAsciiList_NoCase(k_DontSave_Exts, ext)) + continue; + + f.Masks.Add(mask); + masks.Add(mask); + if (needSpace_desc) + f.Description.Add_Space(); + needSpace_desc = true; + f.Description += ext; + } + f.Description += ")"; + // we use only main ext in desc to reduce the size of list + if (i != 0) + desc.Add_Space(); + desc += ai.GetMainExt(); + } + + CBrowseFilterInfo &f = filters.AddNew(); + f.Description = LangString(IDT_COMPRESS_ARCHIVE); // IDS_ARCHIVES_COLON; + if (f.Description.IsEmpty()) + GetItemText(IDT_COMPRESS_ARCHIVE, f.Description); + f.Description.RemoveChar(L'&'); + // f.Description = "archive"; + f.Description += " ("; + f.Description += desc; + f.Description += ")"; + f.Masks = masks; + } + + AddFilter(filters, LangString(IDS_OPEN_TYPE_ALL_FILES), UString("*")); + if (filterIndex < 0) + filterIndex = (int)filters.Size() - 1; + + const UString title = LangString(IDS_COMPRESS_SET_ARCHIVE_BROWSE); + CBrowseInfo bi; + bi.lpstrTitle = title; + bi.SaveMode = true; + bi.FilterIndex = filterIndex; + bi.hwndOwner = *this; + bi.FilePath = path; + + if (!bi.BrowseForFile(filters)) + return; + + path = bi.FilePath; + + if (isSFX) + { + const int dotPos = GetExtDotPos(path); + if (dotPos >= 0) + path.DeleteFrom(dotPos); + path += kExeExt; + } + else + // if (bi.FilterIndex >= 0) + // if (bi.FilterIndex != filterIndex) + if ((unsigned)bi.FilterIndex < numFormats) + { + // archive format was confirmed. So we try to set format extension + bool needAddExt = true; + const CArcInfoEx &ai = (*ArcFormats)[(unsigned)m_Format.GetItemData((unsigned)bi.FilterIndex)]; + const int dotPos = GetExtDotPos(path); + if (dotPos >= 0) + { + const UString ext = path.Ptr(dotPos + 1); + if (ai.FindExtension(ext) >= 0) + needAddExt = false; + } + if (needAddExt) + { + if (path.IsEmpty() || path.Back() != '.') + path.Add_Dot(); + path += ai.GetMainExt(); + } + } + + SetArcPathFields(path); + + if (!isSFX) + if ((unsigned)bi.FilterIndex < numFormats) + if (bi.FilterIndex != m_Format.GetCurSel()) + { + m_Format.SetCurSel(bi.FilterIndex); + SaveOptionsInMem(); + FormatChanged(true); // isChanged return; - UString dummyName; - SetArcPathFields(resPath, dummyName, true); + } + + ArcPath_WasChanged(path); } + // in ExtractDialog.cpp extern void AddUniqueString(UStringVector &strings, const UString &srcString); @@ -826,7 +1005,7 @@ { for (unsigned i = 0; i < s.Len(); i++) { - wchar_t c = s[i]; + const wchar_t c = s[i]; if (c < 0x20 || c > 0x7F) return false; } @@ -844,6 +1023,7 @@ } +void SetErrorMessage_MemUsage(UString &s, UInt64 reqSize, UInt64 ramSize, UInt64 ramLimit, const UString &usageString); void SetErrorMessage_MemUsage(UString &s, UInt64 reqSize, UInt64 ramSize, UInt64 ramLimit, const UString &usageString) { s += "The operation was blocked by 7-Zip"; @@ -927,6 +1107,8 @@ } SaveOptionsInMem(); + + UStringVector arcPaths; { UString s; if (!GetFinalPath_Smart(s)) @@ -934,17 +1116,16 @@ ShowErrorMessage(*this, k_IncorrectPathMessage); return; } - - m_RegistryInfo.ArcPaths.Clear(); - AddUniqueString(m_RegistryInfo.ArcPaths, s); Info.ArcPath = s; + AddUniqueString(arcPaths, s); } - Info.UpdateMode = (NCompressDialog::NUpdateMode::EEnum)k_UpdateMode_Vals[m_UpdateMode.GetCurSel()];; + Info.UpdateMode = (NCompressDialog::NUpdateMode::EEnum)k_UpdateMode_Vals[m_UpdateMode.GetCurSel()]; Info.PathMode = (NWildcard::ECensorPathMode)k_PathMode_Vals[m_PathMode.GetCurSel()]; Info.Level = GetLevelSpec(); Info.Dict64 = GetDictSpec(); + // Info.Dict64_Chain = GetDictChainSpec(); Info.Order = GetOrderSpec(); Info.OrderMode = GetOrderMode(); Info.NumThreads = GetNumThreadsSpec(); @@ -975,7 +1156,7 @@ Info.Method = GetMethodSpec(); Info.EncryptionMethod = GetEncryptionMethodSpec(); - Info.FormatIndex = GetFormatIndex(); + Info.FormatIndex = (int)GetFormatIndex(); Info.SFXMode = IsSFX(); Info.OpenShareForWrite = IsButtonCheckedBool(IDX_COMPRESS_SHARED); Info.DeleteAfterCompressing = IsButtonCheckedBool(IDX_COMPRESS_DEL); @@ -1040,34 +1221,83 @@ } } - for (int i = 0; i < m_ArchivePath.GetCount(); i++) - { - UString sTemp; - m_ArchivePath.GetLBText(i, sTemp); - sTemp.Trim(); - AddUniqueString(m_RegistryInfo.ArcPaths, sTemp); - } - - if (m_RegistryInfo.ArcPaths.Size() > kHistorySize) - m_RegistryInfo.ArcPaths.DeleteBack(); - if (Info.FormatIndex >= 0) m_RegistryInfo.ArcType = (*ArcFormats)[Info.FormatIndex].Name; m_RegistryInfo.ShowPassword = IsShowPasswordChecked(); + FOR_VECTOR (i, m_RegistryInfo.ArcPaths) + { + if (arcPaths.Size() >= kHistorySize) + break; + AddUniqueString(arcPaths, m_RegistryInfo.ArcPaths[i]); + } + m_RegistryInfo.ArcPaths = arcPaths; + m_RegistryInfo.Save(); CModalDialog::OnOK(); } -#define kHelpTopic "fm/plugins/7-zip/add.htm" +#define kHelpTopic "fm/plugins/7-zip/add.htm" +#define kHelpTopic_Options "fm/plugins/7-zip/add.htm#options" void CCompressDialog::OnHelp() { ShowHelpWindow(kHelpTopic); } -bool CCompressDialog::OnCommand(int code, int itemID, LPARAM lParam) + +void CCompressDialog::ArcPath_WasChanged(const UString &path) +{ + const int dotPos = GetExtDotPos(path); + if (dotPos < 0) + return; + const UString ext = path.Ptr(dotPos + 1); + { + const CArcInfoEx &ai = Get_ArcInfoEx(); + if (ai.FindExtension(ext) >= 0) + return; + } + + const unsigned count = (unsigned)m_Format.GetCount(); + for (unsigned i = 0; i < count; i++) + { + const CArcInfoEx &ai = (*ArcFormats)[(unsigned)m_Format.GetItemData(i)]; + if (ai.FindExtension(ext) >= 0) + { + m_Format.SetCurSel(i); + SaveOptionsInMem(); + FormatChanged(true); // isChanged + return; + } + } +} + + +bool CCompressDialog::OnMessage(UINT message, WPARAM wParam, LPARAM lParam) +{ + switch (message) + { + case k_Message_ArcChanged: + { + // UString path; + // m_ArchivePath.GetText(path); + const int select = m_ArchivePath.GetCurSel(); + if ((unsigned)select < m_RegistryInfo.ArcPaths.Size()) + // if (path == m_RegistryInfo.ArcPaths[select]) + { + const UString &path = m_RegistryInfo.ArcPaths[select]; + SetArcPathFields(path); + // ArcPath_WasChanged(path); + } + return 0; + } + } + return CModalDialog::OnMessage(message, wParam, lParam); +} + + +bool CCompressDialog::OnCommand(unsigned code, unsigned itemID, LPARAM lParam) { if (code == CBN_SELCHANGE) { @@ -1075,21 +1305,21 @@ { case IDC_COMPRESS_ARCHIVE: { - // we can 't change m_ArchivePath in that handler ! - DirPrefix.Empty(); - SetItemText(IDT_COMPRESS_ARCHIVE_FOLDER, DirPrefix); - - /* - UString path; - m_ArchivePath.GetText(path); - m_ArchivePath.SetText(L""); - if (IsAbsolutePath(path)) + /* CBN_SELCHANGE is called before actual value of combo text will be changed. + So GetText() here returns old value (before change) of combo text. + So here we can change all controls except of m_ArchivePath. + */ + const int select = m_ArchivePath.GetCurSel(); + if ((unsigned)select < m_RegistryInfo.ArcPaths.Size()) { - UString fileName; - SetArcPathFields(path, fileName); - SetArchiveName(fileName); + // DirPrefix.Empty(); + // SetItemText(IDT_COMPRESS_ARCHIVE_FOLDER, DirPrefix); + const UString &path = m_RegistryInfo.ArcPaths[select]; + // SetArcPathFields(path); + ArcPath_WasChanged(path); + // we use PostMessage(k_Message_ArcChanged) here that later will change m_ArchivePath control + PostMsg(k_Message_ArcChanged); } - */ return true; } @@ -1106,7 +1336,17 @@ { Get_FormatOptions().ResetForLevelChange(); - SetMethod(); + SetMethod(); // call it if level changes method + + // call the following if level change keeps old method + /* + { + // try to keep old method + SetMethod(GetMethodID()); + MethodChanged(); + } + */ + SetSolidBlockSize(); SetNumThreads(); CheckSFXNameChange(); @@ -1128,6 +1368,7 @@ } case IDC_COMPRESS_DICTIONARY: + // case IDC_COMPRESS_DICTIONARY2: { /* we want to change the reported threads for Auto line and keep selected NumThreads option @@ -1142,6 +1383,7 @@ // SetSolidBlockSize(true); } + SetDictionary2(); SetSolidBlockSize(); SetNumThreads(); // we want to change the reported threads for Auto line only SetMemoryUsage(); @@ -1149,7 +1391,12 @@ } case IDC_COMPRESS_ORDER: + { + #ifdef PRINT_PARAMS + Print_Params(); + #endif return true; + } case IDC_COMPRESS_SOLID: { @@ -1199,7 +1446,7 @@ prevExtension = kExeExt; else { - prevExtension += '.'; + prevExtension.Add_Dot(); prevExtension += prevArchiverInfo.GetMainExt(); } const unsigned prevExtensionLen = prevExtension.Len(); @@ -1217,7 +1464,7 @@ void CCompressDialog::SetArchiveName(const UString &name) { UString fileName = name; - Info.FormatIndex = GetFormatIndex(); + Info.FormatIndex = (int)GetFormatIndex(); const CArcInfoEx &ai = (*ArcFormats)[Info.FormatIndex]; m_PrevFormat = Info.FormatIndex; if (ai.Flags_KeepName()) @@ -1238,7 +1485,7 @@ fileName += kExeExt; else { - fileName += '.'; + fileName.Add_Dot(); UString ext = ai.GetMainExt(); if (ai.Flags_HashHandler()) { @@ -1262,7 +1509,7 @@ { const NCompression::CFormatOptions &fo = m_RegistryInfo.Formats[i]; if (name.IsEqualTo_NoCase(GetUnicodeString(fo.FormatID))) - return i; + return (int)i; } return -1; } @@ -1270,14 +1517,14 @@ unsigned CCompressDialog::FindRegistryFormat_Always(const UString &name) { - int index = FindRegistryFormat(name); - if (index < 0) + const int index = FindRegistryFormat(name); + if (index >= 0) + return (unsigned)index; { NCompression::CFormatOptions fo; fo.FormatID = GetSystemString(name); - index = m_RegistryInfo.Formats.Add(fo); + return m_RegistryInfo.Formats.Add(fo); } - return index; } @@ -1288,10 +1535,10 @@ } -int CCompressDialog::GetStaticFormatIndex() +unsigned CCompressDialog::GetStaticFormatIndex() { const CArcInfoEx &ai = Get_ArcInfoEx(); - for (unsigned i = 0; i < ARRAY_SIZE(g_Formats); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Formats); i++) if (ai.Name.IsEqualTo_Ascii_NoCase(g_Formats[i].Name)) return i; return 0; // -1; @@ -1329,18 +1576,25 @@ } } + const bool isZstd = ai.Is_Zstd(); + for (unsigned i = 0; i < sizeof(UInt32) * 8; i++) { const UInt32 mask = (UInt32)1 << i; if ((fi.LevelsMask & mask) != 0) { - UInt32 langID = g_Levels[i]; + const UInt32 langID = g_Levels[i]; UString s; s.Add_UInt32(i); - s += " - "; - s += LangString(langID); - int index = (int)m_Level.AddString(s); - m_Level.SetItemData(index, i); + // if (fi.LevelsMask < (1 << (MY_ZSTD_LEVEL_MAX + 1)) - 1) + if (langID) + if (i != 0 || !isZstd) + { + s += " - "; + s += LangString(langID); + } + const int index = (int)m_Level.AddString(s); + m_Level.SetItemData(index, (LPARAM)i); } if (fi.LevelsMask <= mask) break; @@ -1354,12 +1608,11 @@ return cb.AddString((CSysString)s); } -// static const char *k_Auto = "- "; // "auto : "; +static const char *k_Auto_Prefix = "* "; static void Modify_Auto(AString &s) { - s.Insert(0, "* "); - // s += " -"; + s.Insert(0, k_Auto_Prefix); } void CCompressDialog::SetMethod2(int keepMethodId) @@ -1370,7 +1623,8 @@ const CArcInfoEx &ai = Get_ArcInfoEx(); if (GetLevel() == 0 && !ai.Flags_HashHandler()) { - if (!ai.Is_Tar()) + if (!ai.Is_Tar() && + !ai.Is_Zstd()) { MethodChanged(); return; @@ -1409,10 +1663,10 @@ { if (!is7z) break; - unsigned extIndex = m - fi.NumMethods; + const unsigned extIndex = m - fi.NumMethods; if (extIndex >= ExternalMethods.Size()) break; - methodID = ARRAY_SIZE(kMethodsNames) + extIndex; + methodID = (int)(Z7_ARRAY_SIZE(kMethodsNames) + extIndex); method = ExternalMethods[extIndex].Ptr(); } if (isSfx) @@ -1516,10 +1770,10 @@ UString s; if (methodId >= 0) { - if ((unsigned)methodId < ARRAY_SIZE(kMethodsNames)) + if ((unsigned)methodId < Z7_ARRAY_SIZE(kMethodsNames)) estimatedName = kMethodsNames[methodId]; else - estimatedName = ExternalMethods[methodId - ARRAY_SIZE(kMethodsNames)]; + estimatedName = ExternalMethods[(unsigned)methodId - (unsigned)Z7_ARRAY_SIZE(kMethodsNames)]; if (methodIdRaw >= 0) s = estimatedName; } @@ -1556,10 +1810,10 @@ return s; } -static const size_t k_Auto_Dict = (size_t)0 - 1; +static const size_t k_Auto_Dict = (size_t)0 - 1; -int CCompressDialog::AddDict2(size_t sizeReal, size_t sizeShow) +static int Combo_AddDict2(NWindows::NControl::CComboBox &cb, size_t sizeReal, size_t sizeShow) { char c = 0; unsigned moveBits = 0; @@ -1568,43 +1822,106 @@ AString s; s.Add_UInt64(sizeShow >> moveBits); s.Add_Space(); - if (moveBits != 0) + if (c != 0) s += c; s += 'B'; if (sizeReal == k_Auto_Dict) Modify_Auto(s); - const int index = (int)ComboBox_AddStringAscii(m_Dictionary, s); - m_Dictionary.SetItemData(index, sizeReal); + const int index = (int)ComboBox_AddStringAscii(cb, s); + cb.SetItemData(index, (LPARAM)sizeReal); return index; } +int CCompressDialog::AddDict2(size_t sizeReal, size_t sizeShow) +{ + return Combo_AddDict2(m_Dictionary, sizeReal, sizeShow); +} int CCompressDialog::AddDict(size_t size) { return AddDict2(size, size); } +/* +int CCompressDialog::AddDict_Chain(size_t size) +{ + return Combo_AddDict2(m_Dictionary_Chain, size, size); +} +*/ void CCompressDialog::SetDictionary2() { m_Dictionary.ResetContent(); + // m_Dictionary_Chain.ResetContent(); + // _auto_Dict = (UInt32)1 << 24; // we can use this dictSize to calculate _auto_Solid for unknown method for 7z - _auto_Dict = (UInt32)(Int32)-1; // for debug: + _auto_Dict = (UInt32)(Int32)-1; // for debug + // _auto_Dict_Chain = (UInt32)(Int32)-1; // for debug const CArcInfoEx &ai = Get_ArcInfoEx(); UInt32 defaultDict = (UInt32)(Int32)-1; + // UInt32 defaultDict_Chain = (UInt32)(Int32)-1; { const int index = FindRegistryFormat(ai.Name); if (index >= 0) { const NCompression::CFormatOptions &fo = m_RegistryInfo.Formats[index]; if (IsMethodEqualTo(fo.Method)) + { defaultDict = fo.Dictionary; + // defaultDict_Chain = fo.DictionaryChain; + } } } const int methodID = GetMethodID(); const UInt32 level = GetLevel2(); + + { + RECT r, rLabel; + GetClientRectOfItem(IDT_COMPRESS_DICTIONARY, rLabel); + GetClientRectOfItem(IDC_COMPRESS_DICTIONARY, r); + if (_dictionaryCombo_left == 0) + _dictionaryCombo_left = r.left; + + // bool showDict2; + int newLableRight; + int newDictLeft; + + /* + if (methodID == kZSTD) + { + showDict2 = true; + newDictLeft = _dictionaryCombo_left; + RECT r2; + GetClientRectOfItem(IDC_COMPRESS_DICTIONARY2, r2); + newLableRight = r2.left; + } + else + */ + { + // showDict2 = false; + RECT rBig; + GetClientRectOfItem(IDC_COMPRESS_METHOD, rBig); + newDictLeft= rBig.left; + newLableRight = newDictLeft; + } + + if (newLableRight != rLabel.right) + { + rLabel.right = newLableRight; + MoveItem_RECT(IDT_COMPRESS_DICTIONARY, rLabel); + InvalidateRect(&rLabel); + } + if (newDictLeft != r.left) + { + r.left = newDictLeft; + MoveItem_RECT(IDC_COMPRESS_DICTIONARY, r); + // InvalidateRect(&r); + } + // ShowItem_Bool(IDC_COMPRESS_DICTIONARY2, showDict2); + } + if (methodID < 0) return; @@ -1659,6 +1976,86 @@ m_Dictionary.SetCurSel(curSel); break; } + + /* + case kZSTD: + { + if (defaultDict != (UInt32)(Int32)-1 && + defaultDict > kZstd_MAX_DictSize) + defaultDict = kZstd_MAX_DictSize; + + if (defaultDict_Chain != (UInt32)(Int32)-1 && + defaultDict_Chain > kZstd_MAX_DictSize_Chain) + defaultDict_Chain = kZstd_MAX_DictSize_Chain; + + { + CZstdEncProps props; + ZstdEncProps_Init(&props); + // props.level_zstd = level; + props.level_7z = level; + ZstdEncProps_Set_WindowSize(&props, defaultDict != (UInt32)(Int32)-1 ? defaultDict: 0); + ZstdEncProps_NormalizeFull(&props); + _auto_Dict_Chain = (UInt32)1 << props.windowLog_Chain; + } + { + CZstdEncProps props; + ZstdEncProps_Init(&props); + // props.level_zstd = level; + props.level_7z = level; + ZstdEncProps_Set_WindowChainSize(&props, defaultDict_Chain != (UInt32)(Int32)-1 ? defaultDict_Chain: 0); + ZstdEncProps_NormalizeFull(&props); + _auto_Dict = (UInt32)1 << props.windowLog; + } + + // if there is collision of two window sizes, we reduce dict_Chain + if (defaultDict != (UInt32)(Int32)-1 && + defaultDict_Chain != (UInt32)(Int32)-1 && + defaultDict < defaultDict_Chain) + defaultDict_Chain = defaultDict; + + { + int curSel = AddDict2(k_Auto_Dict, _auto_Dict); + + // defaultDict = 12 << 10; // for debug + const UInt32 kWinStart = 18; + if (defaultDict != 0 && defaultDict < ((UInt32)1 << kWinStart)) + curSel = AddDict(defaultDict); + + for (unsigned i = kWinStart; i <= MY_ZSTD_WINDOWLOG_MAX; i++) + { + const size_t dict = (size_t)1 << i; + const int index = AddDict(dict); + if (defaultDict != (UInt32)(Int32)-1) + if (dict <= defaultDict || curSel <= 0) + curSel = index; + } + m_Dictionary.SetCurSel(curSel); + } + + { + int curSel = Combo_AddDict2(m_Dictionary_Chain, k_Auto_Dict, _auto_Dict_Chain); + + // defaultDict_Chain = 10 << 10; // for debug + const UInt32 kWinChainStart = 15; + if (defaultDict_Chain != 0 && defaultDict_Chain < ((UInt32)1 << kWinChainStart)) + curSel = AddDict_Chain(defaultDict_Chain); + + for (unsigned i = kWinChainStart; i <= kMaxDictChain; i++) + { + const size_t dict = (size_t)1 << i; + if (defaultDict != (UInt32)(Int32)-1 && dict > defaultDict) + break; + const int index = AddDict_Chain(dict); + if (defaultDict_Chain != (UInt32)(Int32)-1) + if (dict <= defaultDict_Chain || curSel <= 0) + curSel = index; + } + m_Dictionary_Chain.SetCurSel(curSel); + } + + break; + } + */ case kPPMd: { @@ -1795,8 +2192,8 @@ { char s[32]; ConvertUInt32ToString(size, s); - int index = (int)ComboBox_AddStringAscii(m_Order, s); - m_Order.SetItemData(index, size); + const int index = (int)ComboBox_AddStringAscii(m_Order, s); + m_Order.SetItemData(index, (LPARAM)size); return index; } @@ -1855,6 +2252,39 @@ break; } + /* + case kZSTD: + { + { + CZstdEncProps props; + ZstdEncProps_Init(&props); + // props.level_zstd = level; + props.level_7z = level; + ZstdEncProps_NormalizeFull(&props); + _auto_Order = props.targetLength; + if (props.strategy < ZSTD_strategy_btopt) + { + // ZSTD_strategy_fast uses targetLength to change fast level. + // targetLength probably is used only in ZSTD_strategy_btopt and higher + break; + } + } + int curSel = AddOrder_Auto(); + + for (unsigned i = 6; i <= 9 * 2; i++) + { + UInt32 order = ((UInt32)(2 + (i & 1)) << (i / 2)); + // if (order > 999) order = 999; + const int index = AddOrder(order); + if (defaultOrder != (UInt32)(Int32)-1) + if (order <= defaultOrder || curSel <= 0) + curSel = index; + } + m_Order.SetCurSel(curSel); + break; + } + */ + case kDeflate: case kDeflate64: { @@ -2051,8 +2481,8 @@ AString s; Add_Size(s, _auto_Solid); Modify_Auto(s); - int index = (int)ComboBox_AddStringAscii(m_Solid, s); - m_Solid.SetItemData(index, (UInt32)(Int32)-1); + const int index = (int)ComboBox_AddStringAscii(m_Solid, s); + m_Solid.SetItemData(index, (LPARAM)(UInt32)(Int32)-1); curSel = index; } @@ -2063,7 +2493,7 @@ if (is7z) LangString(IDS_COMPRESS_NON_SOLID, s); const int index = (int)m_Solid.AddString(s); - m_Solid.SetItemData(index, (UInt32)kSolidLog_NoSolid); + m_Solid.SetItemData(index, (LPARAM)(UInt32)kSolidLog_NoSolid); if (defaultBlockSize == kSolidLog_NoSolid) curSel = index; } @@ -2073,7 +2503,7 @@ AString s; Add_Size(s, (UInt64)1 << i); const int index = (int)ComboBox_AddStringAscii(m_Solid, s); - m_Solid.SetItemData(index, (UInt32)i); + m_Solid.SetItemData(index, (LPARAM)(UInt32)i); if (defaultBlockSize != (UInt32)(Int32)-1) if (i <= defaultBlockSize || index <= 1) curSel = index; @@ -2081,7 +2511,7 @@ { const int index = (int)m_Solid.AddString(LangString(IDS_COMPRESS_SOLID)); - m_Solid.SetItemData(index, kSolidLog_FullSolid); + m_Solid.SetItemData(index, (LPARAM)kSolidLog_FullSolid); if (defaultBlockSize == kSolidLog_FullSolid) curSel = index; } @@ -2090,6 +2520,43 @@ } +/* +static void ZstdEncProps_SetDictProps_From_CompressDialog(CZstdEncProps *props, CCompressDialog &cd) +{ + { + const UInt64 d64 = cd.GetDictSpec(); + UInt32 d32 = 0; // 0 is default for ZstdEncProps::windowLog + if (d64 != (UInt64)(Int64)-1) + { + d32 = (UInt32)d64; + if (d32 != d64) + d32 = (UInt32)(Int32)-2; + } + ZstdEncProps_Set_WindowSize(props, d32); + } + { + const UInt64 d64 = cd.GetDictChainSpec(); + UInt32 d32 = 0; // 0 is default for ZstdEncProps::windowLog_Chain + if (d64 != (UInt64)(Int64)-1) + { + d32 = (UInt32)d64; + if (d32 != d64) + d32 = (UInt32)(Int32)-2; + } + ZstdEncProps_Set_WindowChainSize(props, d32); + } +} + +static bool Is_Zstd_Mt_Supported() +{ + if (!GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "InitializeConditionVariable")) + return false; + return true; +} +*/ + +static const char *k_ST_Threads = " (ST)"; + void CCompressDialog::SetNumThreads2() { _auto_NumThreads = 1; @@ -2119,13 +2586,17 @@ } } + // const UInt32 num_ZSTD_threads_MAX = Is_Zstd_Mt_Supported() ? MY_ZSTDMT_NBWORKERS_MAX : 0; + UInt32 numAlgoThreadsMax = numHardwareThreads * 2; const int methodID = GetMethodID(); + switch (methodID) { case kLZMA: numAlgoThreadsMax = 2; break; case kLZMA2: numAlgoThreadsMax = 256; break; case kBZip2: numAlgoThreadsMax = 32; break; + // case kZSTD: numAlgoThreadsMax = num_ZSTD_threads_MAX; break; case kCopy: case kPPMd: case kDeflate: @@ -2150,7 +2621,10 @@ const UInt64 memUse_Limit = Get_MemUse_Bytes(); - if (autoThreads > 1 && _ramSize_Defined) + if (_ramSize_Defined) + if (autoThreads > 1 + // || (autoThreads == 0 && methodID == kZSTD) + ) { if (isZip) { @@ -2178,6 +2652,20 @@ } autoThreads = numBlockThreads * numThreads1; } + /* + else if (methodID == kZSTD) + { + if (num_ZSTD_threads_MAX != 0) + { + CZstdEncProps props; + ZstdEncProps_Init(&props); + // props.level_zstd = level; + props.level_7z = GetLevel2(); + ZstdEncProps_SetDictProps_From_CompressDialog(&props, *this); + autoThreads = ZstdEncProps_GetNumThreads_for_MemUsageLimit(&props, memUse_Limit, autoThreads); + } + } + */ } _auto_NumThreads = autoThreads; @@ -2186,8 +2674,9 @@ { AString s; s.Add_UInt32(autoThreads); + if (autoThreads == 0) s += k_ST_Threads; Modify_Auto(s); - int index = (int)ComboBox_AddStringAscii(m_NumThreads, s); + const int index = (int)ComboBox_AddStringAscii(m_NumThreads, s); m_NumThreads.SetItemData(index, (LPARAM)(INT_PTR)(-1)); // m_NumThreads.SetItemData(index, autoThreads); if (useAutoThreads) @@ -2195,12 +2684,16 @@ } if (numAlgoThreadsMax != autoThreads || autoThreads != 1) - for (UInt32 i = 1; i <= numHardwareThreads * 2 && i <= numAlgoThreadsMax; i++) + for (UInt32 i = + // (methodID == kZSTD) ? 0 : + 1; + i <= numHardwareThreads * 2 && i <= numAlgoThreadsMax; i++) { - char s[32]; - ConvertUInt32ToString(i, s); - int index = (int)ComboBox_AddStringAscii(m_NumThreads, s); - m_NumThreads.SetItemData(index, (UInt32)i); + AString s; + s.Add_UInt32(i); + if (i == 0) s += k_ST_Threads; + const int index = (int)ComboBox_AddStringAscii(m_NumThreads, s); + m_NumThreads.SetItemData(index, (LPARAM)(UInt32)i); if (!useAutoThreads && i == defaultValue) curSel = index; } @@ -2236,7 +2729,7 @@ s.Add_UInt64(val); s += '%'; if (isDefault) - sUser = "* "; + sUser = k_Auto_Prefix; else sRegistry = s; sUser += s; @@ -2247,7 +2740,7 @@ sRegistry = sUser; for (;;) { - int pos = sRegistry.Find(L' '); + const int pos = sRegistry.Find(L' '); if (pos < 0) break; sRegistry.Delete(pos); @@ -2258,7 +2751,7 @@ } const unsigned dataIndex = _memUse_Strings.Add(sRegistry); const int index = (int)m_MemUse.AddString(sUser); - m_MemUse.SetItemData(index, dataIndex); + m_MemUse.SetItemData(index, (LPARAM)dataIndex); return index; } @@ -2382,11 +2875,16 @@ return GetMemoryUsage_Dict_DecompMem(GetDict2(), decompressMemory); } + +/* +we could use that function to reduce the dictionary if small RAM UInt64 CCompressDialog::GetMemoryUsageComp_Threads_Dict(UInt32 numThreads, UInt64 dict64) { UInt64 decompressMemory; return GetMemoryUsage_Threads_Dict_DecompMem(numThreads, dict64, decompressMemory); } +*/ + UInt64 CCompressDialog::GetMemoryUsage_Dict_DecompMem(UInt64 dict64, UInt64 &decompressMemory) { @@ -2396,11 +2894,9 @@ UInt64 CCompressDialog::GetMemoryUsage_Threads_Dict_DecompMem(UInt32 numThreads, UInt64 dict64, UInt64 &decompressMemory) { decompressMemory = (UInt64)(Int64)-1; - if (dict64 == (UInt64)(Int64)-1) - return (UInt64)(Int64)-1; - UInt32 level = GetLevel2(); - if (level == 0) + const UInt32 level = GetLevel2(); + if (level == 0 && !Get_ArcInfoEx().Is_Zstd()) { decompressMemory = (1 << 20); return decompressMemory; @@ -2427,6 +2923,12 @@ } const int methodId = GetMethodID(); + + if (dict64 == (UInt64)(Int64)-1 + // && methodId != kZSTD + ) + return (UInt64)(Int64)-1; + switch (methodId) { @@ -2507,7 +3009,23 @@ decompressMemory = dict + (2 << 20); return size; } - + + /* + case kZSTD: + { + CZstdEncProps props; + ZstdEncProps_Init(&props); + // props.level_zstd = level; + props.level_7z = level; + props.nbWorkers = numThreads; + ZstdEncProps_SetDictProps_From_CompressDialog(&props, *this); + ZstdEncProps_NormalizeFull(&props); + size = ZstdEncProps_GetMemUsage(&props); + decompressMemory = (UInt64)1 << props.windowLog; + return size; + } + */ + case kPPMd: { decompressMemory = dict64 + (2 << 20); @@ -2613,8 +3131,109 @@ const UInt64 memUsage = GetMemoryUsage_DecompMem(decompressMem); PrintMemUsage(IDT_COMPRESS_MEMORY_VALUE, memUsage); PrintMemUsage(IDT_COMPRESS_MEMORY_DE_VALUE, decompressMem); + #ifdef PRINT_PARAMS + Print_Params(); + #endif } + + +#ifdef PRINT_PARAMS + +static const char kPropDelimeter = ' '; // ':' + +static void AddPropName(AString &s, const char *name) +{ + if (!s.IsEmpty()) + s += kPropDelimeter; + s += name; +} + +static void AddProp(AString &s, const char *name, unsigned v) +{ + AddPropName(s, name); + s.Add_UInt32(v); +} + +static void AddProp_switch(AString &s, const char *name, E_ZSTD_paramSwitch_e e) +{ + AddPropName(s, name); + s += e == k_ZSTD_ps_enable ? "" : "-"; +} + +static void PrintPropAsLog(AString &s, const char *name, size_t v) +{ + AddPropName(s, name); + for (unsigned i = 0; i < sizeof(size_t) * 8; i++) + { + if (((size_t)1 << i) == v) + { + s.Add_UInt32(i); + return; + } + } + char c = 'b'; + if ((v & 0x3FFFFFFF) == 0) { v >>= 30; c = 'G'; } + else if ((v & 0xFFFFF) == 0) { v >>= 20; c = 'M'; } + else if ((v & 0x3FF) == 0) { v >>= 10; c = 'K'; } + s.Add_UInt64(v); + s += c; +} + +static void ZstdEncProps_Print(CZstdEncProps *props, AString &s) +{ + if (props->level_zstd >= 0) + AddProp(s, "zx", props->level_zstd); + else + AddProp(s, "zf", -(props->level_zstd)); + AddProp(s, "a", props->strategy); + AddProp(s, "d", props->windowLog); + AddProp(s, "zclog", props->chainLog); + AddProp(s, "zhb", props->hashLog); + AddProp(s, "mml", props->minMatch); + AddProp(s, "mcb", props->searchLog); + AddProp(s, "fb", props->targetLength); + AddProp(s, "mt", props->nbWorkers); + PrintPropAsLog(s, "c", props->jobSize); + AddProp(s, "zov", props->overlapLog); + PrintPropAsLog(s, "ztps", props->targetPrefixSize); + AddProp_switch(s, "zmfr", props->useRowMatchFinder); + if (props->ldmParams.enableLdm == k_ZSTD_ps_enable) + { + AddProp_switch(s, "zle", props->ldmParams.enableLdm); + AddProp(s, "zlhb", props->ldmParams.hashLog); + AddProp(s, "zlbb", props->ldmParams.bucketSizeLog); + AddProp(s, "zlmml", props->ldmParams.minMatchLength); + AddProp(s, "zlhrb", props->ldmParams.hashRateLog); + } +} + +void CCompressDialog::Print_Params() +{ + { + CZstdEncProps props; + ZstdEncProps_Init(&props); + // props.level_zstd = level; + props.level_7z = GetLevel2(); + ZstdEncProps_SetDictProps_From_CompressDialog(&props, *this); + { + UInt32 order = GetOrderSpec(); + if (order != (UInt32)(Int32)-1) + props.targetLength = GetOrderSpec(); + } + props.nbWorkers = GetNumThreads2(); + // props.windowLog = 18; // for debug + ZstdEncProps_NormalizeFull(&props); + AString s; + ZstdEncProps_Print(&props, s); + SetItemTextA(IDT_COMPRESS_PARAMS_INFO, s); + } +} + +#endif // PRINT_PARAMS + + + void CCompressDialog::SetParams() { const CArcInfoEx &ai = Get_ArcInfoEx(); @@ -2663,6 +3282,24 @@ } fo.Dictionary = dict32; } + /* + { + const UInt64 dict64 = GetDictChainSpec(); + UInt32 dict32; + if (dict64 == (UInt64)(Int64)-1) + dict32 = (UInt32)(Int32)-1; + else + { + dict32 = (UInt32)dict64; + if (dict64 != dict32) + { + dict32 = (UInt32)(Int32)-2; + // dict32 = k_Zstd_MAX_DictSize; // it must be larger than threshold + } + } + fo.DictionaryChain = dict32; + } + */ fo.Order = GetOrderSpec(); fo.Method = GetMethodSpec(); @@ -2836,7 +3473,7 @@ else s.Add_UInt32(prec); const int index = (int)m_Prec.AddString(s); - m_Prec.SetItemData(index, writePrec); + m_Prec.SetItemData(index, (LPARAM)writePrec); return index; } @@ -2874,7 +3511,7 @@ // flags = (UInt32)1 << kTimePrec_Unix; s += ":"; - if (methodID >= 0 && (unsigned)methodID < ARRAY_SIZE(kMethodsNames)) + if (methodID >= 0 && (unsigned)methodID < Z7_ARRAY_SIZE(kMethodsNames)) s += kMethodsNames[methodID]; if (methodID == kPosix) { @@ -3038,7 +3675,7 @@ -#ifdef LANG +#ifdef Z7_LANG static const UInt32 kLangIDs_Options[] = { IDX_COMPRESS_NT_SYM_LINKS, @@ -3059,9 +3696,9 @@ bool COptionsDialog::OnInit() { - #ifdef LANG + #ifdef Z7_LANG LangSetWindowText(*this, IDB_COMPRESS_OPTIONS); // IDS_OPTIONS - LangSetDlgItems(*this, kLangIDs_Options, ARRAY_SIZE(kLangIDs_Options)); + LangSetDlgItems(*this, kLangIDs_Options, Z7_ARRAY_SIZE(kLangIDs_Options)); // LangSetDlgItemText(*this, IDB_COMPRESS_TIME_DEFAULT, IDB_COMPRESS_TIME_DEFAULT); // LangSetDlgItemText(*this, IDX_COMPRESS_TIME_DEFAULT, IDX_COMPRESS_TIME_DEFAULT); #endif @@ -3124,7 +3761,7 @@ } -bool COptionsDialog::OnCommand(int code, int itemID, LPARAM lParam) +bool COptionsDialog::OnCommand(unsigned code, unsigned itemID, LPARAM lParam) { if (code == CBN_SELCHANGE) { @@ -3142,7 +3779,7 @@ } -bool COptionsDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool COptionsDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -3179,5 +3816,5 @@ void COptionsDialog::OnHelp() { - ShowHelpWindow(kHelpTopic); + ShowHelpWindow(kHelpTopic_Options); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/CompressDialog.h 7zip-23.01+dfsg/CPP/7zip/UI/GUI/CompressDialog.h --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/CompressDialog.h 2022-04-18 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/CompressDialog.h 2023-01-28 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // CompressDialog.h -#ifndef __COMPRESS_DIALOG_H -#define __COMPRESS_DIALOG_H +#ifndef ZIP7_INC_COMPRESS_DIALOG_H +#define ZIP7_INC_COMPRESS_DIALOG_H #include "../../../Common/Wildcard.h" @@ -45,6 +45,7 @@ UInt32 Level; UString Method; UInt64 Dict64; + // UInt64 Dict64_Chain; bool OrderMode; UInt32 Order; UString Options; @@ -93,6 +94,7 @@ NumThreads = (UInt32)(Int32)-1; SolidIsSpecified = false; Dict64 = (UInt64)(Int64)(-1); + // Dict64_Chain = (UInt64)(Int64)(-1); OrderMode = false; Method.Empty(); Options.Empty(); @@ -144,12 +146,15 @@ NWindows::NControl::CComboBox m_Level; NWindows::NControl::CComboBox m_Method; NWindows::NControl::CComboBox m_Dictionary; + // NWindows::NControl::CComboBox m_Dictionary_Chain; NWindows::NControl::CComboBox m_Order; NWindows::NControl::CComboBox m_Solid; NWindows::NControl::CComboBox m_NumThreads; NWindows::NControl::CComboBox m_MemUse; NWindows::NControl::CComboBox m_Volume; + int _dictionaryCombo_left; + UStringVector _memUse_Strings; NWindows::NControl::CDialogChildControl m_Params; @@ -163,6 +168,7 @@ int _auto_MethodId; UInt32 _auto_Dict; // (UInt32)(Int32)-1 means unknown + UInt32 _auto_Dict_Chain; // (UInt32)(Int32)-1 means unknown UInt32 _auto_Order; UInt64 _auto_Solid; UInt32 _auto_NumThreads; @@ -201,7 +207,7 @@ void CheckSFXNameChange(); void SetArchiveName2(bool prevWasSFX); - int GetStaticFormatIndex(); + unsigned GetStaticFormatIndex(); void SetNearestSelectComboBox(NWindows::NControl::CComboBox &comboBox, UInt32 value); @@ -224,6 +230,7 @@ { SetDictionary2(); EnableMultiCombo(IDC_COMPRESS_DICTIONARY); + // EnableMultiCombo(IDC_COMPRESS_DICTIONARY2); SetOrder2(); EnableMultiCombo(IDC_COMPRESS_ORDER); } @@ -243,6 +250,7 @@ int AddDict2(size_t sizeReal, size_t sizeShow); int AddDict(size_t size); + // int AddDict_Chain(size_t size); void SetDictionary2(); @@ -254,6 +262,8 @@ UInt32 GetLevel2(); UInt64 GetDictSpec() { return GetComboValue_64(m_Dictionary, 1); } + // UInt64 GetDictChainSpec() { return GetComboValue_64(m_Dictionary_Chain, 1); } + UInt64 GetDict2() { UInt64 num = GetDictSpec(); @@ -319,6 +329,8 @@ void PrintMemUsage(UINT res, UInt64 value); void SetMemoryUsage(); + void Print_Params(); + void SetParams(); void SaveOptionsInMem(); @@ -328,7 +340,9 @@ unsigned GetFormatIndex(); bool SetArcPathFields(const UString &path, UString &name, bool always); - bool GetFinalPath_Smart(UString &resPath); + bool SetArcPathFields(const UString &path); + bool GetFinalPath_Smart(UString &resPath) const; + void ArcPath_WasChanged(const UString &newPath); void CheckSFXControlsEnable(); // void CheckVolumeEnable(); @@ -339,11 +353,12 @@ bool IsSFX(); void OnButtonSFX(); - virtual bool OnInit(); - virtual bool OnCommand(int code, int itemID, LPARAM lParam); - virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); - virtual void OnOK(); - virtual void OnHelp(); + virtual bool OnInit() Z7_override; + virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam) Z7_override; + virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM lParam) Z7_override; + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; + virtual void OnOK() Z7_override; + virtual void OnHelp() Z7_override; void MessageBoxError(LPCWSTR message) { @@ -361,15 +376,14 @@ NCompressDialog::CInfo Info; UString OriginalFileName; // for bzip2, gzip2 - bool CurrentDirWasChanged; - INT_PTR Create(HWND wndParent = 0) + INT_PTR Create(HWND wndParent = NULL) { BIG_DIALOG_SIZE(400, 320); return CModalDialog::Create(SIZED_DIALOG(IDD_COMPRESS), wndParent); } - CCompressDialog(): CurrentDirWasChanged(false) {}; + CCompressDialog() {} }; @@ -383,10 +397,10 @@ bool DefaultVal; CBoolPair BoolPair; - int Id; - int Set_Id; + unsigned Id; + unsigned Set_Id; - void SetIDs(int id, int set_Id) + void SetIDs(unsigned id, unsigned set_Id) { Id = id; Set_Id = set_Id; @@ -442,15 +456,15 @@ void On_CheckBoxSet_Prec_Clicked(); void On_CheckBoxSet_Clicked(const CBoolBox &bb); - virtual bool OnInit(); - virtual bool OnCommand(int code, int itemID, LPARAM lParam); - virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); - virtual void OnOK(); - virtual void OnHelp(); + virtual bool OnInit() Z7_override; + virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM lParam) Z7_override; + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; + virtual void OnOK() Z7_override; + virtual void OnHelp() Z7_override; public: - INT_PTR Create(HWND wndParent = 0) + INT_PTR Create(HWND wndParent = NULL) { BIG_DIALOG_SIZE(240, 232); return CModalDialog::Create(SIZED_DIALOG(IDD_COMPRESS_OPTIONS), wndParent); @@ -461,7 +475,7 @@ // , TimePrec(0) { Reset_TimePrec(); - }; + } }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/CompressDialog.rc 7zip-23.01+dfsg/CPP/7zip/UI/GUI/CompressDialog.rc --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/CompressDialog.rc 2022-04-21 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/CompressDialog.rc 2023-04-01 09:00:00.000000000 +0000 @@ -48,6 +48,11 @@ #define GROUP_Y_SIZE_ENCRYPT 128 #endif +// #define DICT_SIZE_SPACE 8 +// #define DICT_SIZE 54 +// #define DICT_x (g1x + g1xs - DICT_SIZE) +// #define DICT2_x (DICT_x - DICT_SIZE_SPACE - DICT_SIZE) + #define yPsw (yOpt + GROUP_Y_SIZE + 8) IDD_COMPRESS DIALOG 0, 0, xs, ys MY_MODAL_DIALOG_STYLE MY_FONT @@ -69,9 +74,14 @@ LTEXT "&Dictionary size:", IDT_COMPRESS_DICTIONARY, m, 104, g0xs, 8 COMBOBOX IDC_COMPRESS_DICTIONARY, g1x, 102, g1xs, 167, MY_COMBO + // LTEXT "&Dictionary size:", IDT_COMPRESS_DICTIONARY, m, 104, DICT_x - m, 16 // 8, SS_LEFTNOWORDWRAP + // LTEXT "", IDT_COMPRESS_PARAMS_INFO, m, 283, xs, MY_TEXT_NOPREFIX + // CTEXT "-", 0, DICT_x - DICT_SIZE_SPACE, 104, DICT_SIZE_SPACE, 8 + // COMBOBOX IDC_COMPRESS_DICTIONARY2, DICT2_x, 102, DICT_SIZE, 140, MY_COMBO + // COMBOBOX IDC_COMPRESS_DICTIONARY, DICT_x, 102, DICT_SIZE, 140, MY_COMBO LTEXT "&Word size:", IDT_COMPRESS_ORDER, m, 125, g0xs, 8 - COMBOBOX IDC_COMPRESS_ORDER, g1x, 123, g1xs, 141, MY_COMBO + COMBOBOX IDC_COMPRESS_ORDER, g1x, 123, g1xs, 140, MY_COMBO LTEXT "&Solid Block size:", IDT_COMPRESS_SOLID, m, 146, g0xs, 8 COMBOBOX IDC_COMPRESS_SOLID, g1x, 144, g1xs, 140, MY_COMBO diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/CompressDialogRes.h 7zip-23.01+dfsg/CPP/7zip/UI/GUI/CompressDialogRes.h --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/CompressDialogRes.h 2022-04-18 14:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/CompressDialogRes.h 2023-04-01 09:00:00.000000000 +0000 @@ -22,6 +22,7 @@ #define IDG_COMPRESS_NTFS 115 #define IDC_COMPRESS_PATH_MODE 116 #define IDC_COMPRESS_MEM_USE 117 +// #define IDC_COMPRESS_DICTIONARY2 118 #define IDE_COMPRESS_PASSWORD1 120 #define IDE_COMPRESS_PASSWORD2 121 @@ -32,6 +33,7 @@ // #define IDB_COMPRESS_OPTIONS 140 #define IDB_COMPRESS_OPTIONS 2100 #define IDT_COMPRESS_OPTIONS 141 +// #define IDT_COMPRESS_PARAMS_INFO 142 #define IDT_COMPRESS_PATH_MODE 3410 diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/ExtractDialog.cpp 7zip-23.01+dfsg/CPP/7zip/UI/GUI/ExtractDialog.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/ExtractDialog.cpp 2021-03-05 19:41:28.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/ExtractDialog.cpp 2023-03-19 17:00:00.000000000 +0000 @@ -9,7 +9,7 @@ #include "../../../Windows/FileDir.h" #include "../../../Windows/ResourceString.h" -#ifndef NO_REGISTRY +#ifndef Z7_NO_REGISTRY #include "../FileManager/HelpUtils.h" #endif @@ -28,7 +28,7 @@ extern HINSTANCE g_hInstance; -#ifndef _SFX +#ifndef Z7_SFX static const UInt32 kPathMode_IDs[] = { @@ -70,7 +70,7 @@ #endif -#ifdef LANG +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { @@ -87,23 +87,23 @@ // static const int kWildcardsButtonIndex = 2; -#ifndef NO_REGISTRY +#ifndef Z7_NO_REGISTRY static const unsigned kHistorySize = 16; #endif -#ifndef _SFX +#ifndef Z7_SFX // it's used in CompressDialog also void AddComboItems(NControl::CComboBox &combo, const UInt32 *langIDs, unsigned numItems, const int *values, int curVal); void AddComboItems(NControl::CComboBox &combo, const UInt32 *langIDs, unsigned numItems, const int *values, int curVal) { - int curSel = 0; + unsigned curSel = 0; for (unsigned i = 0; i < numItems; i++) { UString s = LangString(langIDs[i]); s.RemoveChar(L'&'); - int index = (int)combo.AddString(s); - combo.SetItemData(index, i); + const int index = (int)combo.AddString(s); + combo.SetItemData(index, (LPARAM)i); if (values[i] == curVal) curSel = i; } @@ -126,8 +126,8 @@ void CExtractDialog::GetButton_Bools(UINT id, CBoolPair &b1, CBoolPair &b2) { - bool val = IsButtonCheckedBool(id); - bool oldVal = GetBoolsVal(b1, b2); + const bool val = IsButtonCheckedBool(id); + const bool oldVal = GetBoolsVal(b1, b2); if (val != oldVal) b1.Def = b2.Def = true; b1.Val = b2.Val = val; @@ -137,7 +137,7 @@ bool CExtractDialog::OnInit() { - #ifdef LANG + #ifdef Z7_LANG { UString s; LangString_OnlyFromLangFile(IDD_EXTRACT, s); @@ -150,18 +150,18 @@ } SetText(s); // LangSetWindowText(*this, IDD_EXTRACT); - LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); + LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs)); } #endif - #ifndef _SFX + #ifndef Z7_SFX _passwordControl.Attach(GetItem(IDE_EXTRACT_PASSWORD)); _passwordControl.SetText(Password); _passwordControl.SetPasswordChar(TEXT('*')); _pathName.Attach(GetItem(IDE_EXTRACT_NAME)); #endif - #ifdef NO_REGISTRY + #ifdef Z7_NO_REGISTRY PathMode = NExtract::NPathMode::kFullPaths; OverwriteMode = NExtract::NOverwriteMode::kAsk; @@ -191,7 +191,7 @@ UString pathPrefix = DirPath; - #ifndef _SFX + #ifndef Z7_SFX if (_info.SplitDest.Val) { @@ -210,7 +210,7 @@ _path.SetText(pathPrefix); - #ifndef NO_REGISTRY + #ifndef Z7_NO_REGISTRY for (unsigned i = 0; i < _info.Paths.Size() && i < kHistorySize; i++) _path.AddString(_info.Paths[i]); #endif @@ -222,13 +222,13 @@ _path.SetCurSel(-1); */ - #ifndef _SFX + #ifndef Z7_SFX _pathMode.Attach(GetItem(IDC_EXTRACT_PATH_MODE)); _overwriteMode.Attach(GetItem(IDC_EXTRACT_OVERWRITE_MODE)); - AddComboItems(_pathMode, kPathMode_IDs, ARRAY_SIZE(kPathMode_IDs), kPathModeButtonsVals, PathMode); - AddComboItems(_overwriteMode, kOverwriteMode_IDs, ARRAY_SIZE(kOverwriteMode_IDs), kOverwriteButtonsVals, OverwriteMode); + AddComboItems(_pathMode, kPathMode_IDs, Z7_ARRAY_SIZE(kPathMode_IDs), kPathModeButtonsVals, PathMode); + AddComboItems(_overwriteMode, kOverwriteMode_IDs, Z7_ARRAY_SIZE(kOverwriteMode_IDs), kOverwriteButtonsVals, OverwriteMode); #endif @@ -243,7 +243,7 @@ return CModalDialog::OnInit(); } -#ifndef _SFX +#ifndef Z7_SFX void CExtractDialog::UpdatePasswordControl() { _passwordControl.SetPasswordChar(IsShowPasswordChecked() ? 0 : TEXT('*')); @@ -253,14 +253,14 @@ } #endif -bool CExtractDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CExtractDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { case IDB_EXTRACT_SET_PATH: OnButtonSetPath(); return true; - #ifndef _SFX + #ifndef Z7_SFX case IDX_EXTRACT_NAME_ENABLE: ShowItem_Bool(IDE_EXTRACT_NAME, IsButtonCheckedBool(IDX_EXTRACT_NAME_ENABLE)); return true; @@ -282,7 +282,7 @@ UString resultPath; if (!MyBrowseForFolder(*this, title, currentPath, resultPath)) return; - #ifndef NO_REGISTRY + #ifndef Z7_NO_REGISTRY _path.SetCurSel(-1); #endif _path.SetText(resultPath); @@ -299,7 +299,7 @@ void CExtractDialog::OnOK() { - #ifndef _SFX + #ifndef Z7_SFX int pathMode2 = kPathModeButtonsVals[_pathMode.GetCurSel()]; if (PathMode != NExtract::NPathMode::kCurPaths || pathMode2 != NExtract::NPathMode::kFullPaths) @@ -313,7 +313,7 @@ #endif - #ifndef NO_REGISTRY + #ifndef Z7_NO_REGISTRY // GetButton_Bools(IDX_EXTRACT_ALT_STREAMS, AltStreams, _info.AltStreams); GetButton_Bools(IDX_EXTRACT_NT_SECUR, NtSecurity, _info.NtSecurity); @@ -350,7 +350,7 @@ UString s; - #ifdef NO_REGISTRY + #ifdef Z7_NO_REGISTRY _path.GetText(s); @@ -371,9 +371,9 @@ s.Trim(); NName::NormalizeDirPathPrefix(s); - #ifndef _SFX + #ifndef Z7_SFX - bool splitDest = IsButtonCheckedBool(IDX_EXTRACT_NAME_ENABLE); + const bool splitDest = IsButtonCheckedBool(IDX_EXTRACT_NAME_ENABLE); if (splitDest) { UString pathName; @@ -392,9 +392,9 @@ DirPath = s; - #ifndef NO_REGISTRY + #ifndef Z7_NO_REGISTRY _info.Paths.Clear(); - #ifndef _SFX + #ifndef Z7_SFX AddUniqueString(_info.Paths, s); #endif for (int i = 0; i < _path.GetCount(); i++) @@ -411,7 +411,7 @@ CModalDialog::OnOK(); } -#ifndef NO_REGISTRY +#ifndef Z7_NO_REGISTRY #define kHelpTopic "fm/plugins/7-zip/extract.htm" void CExtractDialog::OnHelp() { diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/ExtractDialog.h 7zip-23.01+dfsg/CPP/7zip/UI/GUI/ExtractDialog.h --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/ExtractDialog.h 2014-06-13 08:28:35.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/ExtractDialog.h 2023-01-29 16:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ExtractDialog.h -#ifndef __EXTRACT_DIALOG_H -#define __EXTRACT_DIALOG_H +#ifndef ZIP7_INC_EXTRACT_DIALOG_H +#define ZIP7_INC_EXTRACT_DIALOG_H #include "ExtractDialogRes.h" @@ -12,7 +12,7 @@ #include "../FileManager/DialogSize.h" -#ifndef NO_REGISTRY +#ifndef Z7_NO_REGISTRY #include "../Common/ZipRegistry.h" #endif @@ -33,20 +33,20 @@ class CExtractDialog: public NWindows::NControl::CModalDialog { - #ifdef NO_REGISTRY + #ifdef Z7_NO_REGISTRY NWindows::NControl::CDialogChildControl _path; #else NWindows::NControl::CComboBox _path; #endif - #ifndef _SFX + #ifndef Z7_SFX NWindows::NControl::CEdit _pathName; NWindows::NControl::CEdit _passwordControl; NWindows::NControl::CComboBox _pathMode; NWindows::NControl::CComboBox _overwriteMode; #endif - #ifndef _SFX + #ifndef Z7_SFX // int GetFilesMode() const; void UpdatePasswordControl(); #endif @@ -55,13 +55,13 @@ void CheckButton_TwoBools(UINT id, const CBoolPair &b1, const CBoolPair &b2); void GetButton_Bools(UINT id, CBoolPair &b1, CBoolPair &b2); - virtual bool OnInit(); - virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); - virtual void OnOK(); + virtual bool OnInit() Z7_override; + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override; + virtual void OnOK() Z7_override; - #ifndef NO_REGISTRY + #ifndef Z7_NO_REGISTRY - virtual void OnHelp(); + virtual void OnHelp() Z7_override; NExtract::CInfo _info; @@ -76,7 +76,7 @@ UString DirPath; UString ArcPath; - #ifndef _SFX + #ifndef Z7_SFX UString Password; #endif bool PathMode_Force; @@ -84,16 +84,16 @@ NExtract::NPathMode::EEnum PathMode; NExtract::NOverwriteMode::EEnum OverwriteMode; - #ifndef _SFX + #ifndef Z7_SFX // CBoolPair AltStreams; CBoolPair NtSecurity; #endif CBoolPair ElimDup; - INT_PTR Create(HWND aWndParent = 0) + INT_PTR Create(HWND aWndParent = NULL) { - #ifdef _SFX + #ifdef Z7_SFX BIG_DIALOG_SIZE(240, 64); #else BIG_DIALOG_SIZE(300, 160); diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/ExtractGUI.cpp 7zip-23.01+dfsg/CPP/7zip/UI/GUI/ExtractGUI.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/ExtractGUI.cpp 2021-11-15 15:46:16.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/ExtractGUI.cpp 2023-03-03 12:00:00.000000000 +0000 @@ -36,7 +36,7 @@ static const wchar_t * const kIncorrectOutDir = L"Incorrect output directory path"; -#ifndef _SFX +#ifndef Z7_SFX static void AddValuePair(UString &s, UINT resourceID, UInt64 value, bool addColon = true) { @@ -60,10 +60,10 @@ class CThreadExtracting: public CProgressThreadVirt { - HRESULT ProcessVirt(); + HRESULT ProcessVirt() Z7_override; public: /* - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS const CExternalCodecs *externalCodecs; #endif */ @@ -78,19 +78,19 @@ const NWildcard::CCensorNode *WildcardCensor; const CExtractOptions *Options; - #ifndef _SFX + #ifndef Z7_SFX CHashBundle *HashBundle; - virtual void ProcessWasFinished_GuiVirt(); + virtual void ProcessWasFinished_GuiVirt() Z7_override; #endif - CMyComPtr ExtractCallback; + CMyComPtr FolderArchiveExtractCallback; UString Title; CPropNameValPairs Pairs; }; -#ifndef _SFX +#ifndef Z7_SFX void CThreadExtracting::ProcessWasFinished_GuiVirt() { if (HashBundle && !Pairs.IsEmpty()) @@ -102,7 +102,7 @@ { CDecompressStat Stat; - #ifndef _SFX + #ifndef Z7_SFX /* if (HashBundle) HashBundle->Init(); @@ -111,20 +111,21 @@ HRESULT res = Extract( /* - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS externalCodecs, #endif */ codecs, *FormatIndices, *ExcludedFormatIndices, *ArchivePaths, *ArchivePathsFull, - *WildcardCensor, *Options, ExtractCallbackSpec, ExtractCallback, - #ifndef _SFX + *WildcardCensor, *Options, + ExtractCallbackSpec, ExtractCallbackSpec, FolderArchiveExtractCallback, + #ifndef Z7_SFX HashBundle, #endif FinalMessage.ErrorMessage.Message, Stat); - #ifndef _SFX + #ifndef Z7_SFX if (res == S_OK && ExtractCallbackSpec->IsOK()) { if (HashBundle) @@ -172,7 +173,7 @@ UStringVector &archivePathsFull, const NWildcard::CCensorNode &wildcardCensor, CExtractOptions &options, - #ifndef _SFX + #ifndef Z7_SFX CHashBundle *hb, #endif bool showDialog, @@ -184,8 +185,8 @@ CThreadExtracting extracter; /* - #ifdef EXTERNAL_CODECS - extracter.externalCodecs = __externalCodecs; + #ifdef Z7_EXTERNAL_CODECS + extracter.externalCodecs = _externalCodecs; #endif */ extracter.codecs = codecs; @@ -222,7 +223,7 @@ if (archivePathsFull.Size() == 1) dialog.ArcPath = archivePathsFull[0]; - #ifndef _SFX + #ifndef Z7_SFX // dialog.AltStreams = options.NtOptions.AltStreams; dialog.NtSecurity = options.NtOptions.NtSecurity; if (extractCallback->PasswordIsDefined) @@ -238,7 +239,7 @@ options.PathMode = dialog.PathMode; options.ElimDup = dialog.ElimDup; - #ifndef _SFX + #ifndef Z7_SFX // options.NtOptions.AltStreams = dialog.AltStreams; options.NtOptions.NtSecurity = dialog.NtSecurity; extractCallback->Password = dialog.Password; @@ -258,7 +259,7 @@ { UString s = GetUnicodeString(NError::MyFormatMessage(GetLastError())); UString s2 = MyFormatNew(IDS_CANNOT_CREATE_FOLDER, - #ifdef LANG + #ifdef Z7_LANG 0x02000603, #endif options.OutputDir); @@ -275,7 +276,7 @@ extracter.Title = title; extracter.ExtractCallbackSpec = extractCallback; extracter.ExtractCallbackSpec->ProgressDialog = &extracter; - extracter.ExtractCallback = extractCallback; + extracter.FolderArchiveExtractCallback = extractCallback; extracter.ExtractCallbackSpec->Init(); extracter.CompressingMode = false; @@ -284,13 +285,13 @@ extracter.ArchivePathsFull = &archivePathsFull; extracter.WildcardCensor = &wildcardCensor; extracter.Options = &options; - #ifndef _SFX + #ifndef Z7_SFX extracter.HashBundle = hb; #endif extracter.IconID = IDI_ICON; - RINOK(extracter.Create(title, hwndParent)); + RINOK(extracter.Create(title, hwndParent)) messageWasDisplayed = extracter.ThreadFinishedOK && extracter.MessagesDisplayed; return extracter.Result; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/ExtractGUI.h 7zip-23.01+dfsg/CPP/7zip/UI/GUI/ExtractGUI.h --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/ExtractGUI.h 2021-09-21 17:00:29.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/ExtractGUI.h 2023-01-29 16:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // GUI/ExtractGUI.h -#ifndef __EXTRACT_GUI_H -#define __EXTRACT_GUI_H +#ifndef ZIP7_INC_EXTRACT_GUI_H +#define ZIP7_INC_EXTRACT_GUI_H #include "../Common/Extract.h" @@ -28,7 +28,7 @@ UStringVector &archivePathsFull, const NWildcard::CCensorNode &wildcardCensor, CExtractOptions &options, - #ifndef _SFX + #ifndef Z7_SFX CHashBundle *hb, #endif bool showDialog, diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/GUI.cpp 7zip-23.01+dfsg/CPP/7zip/UI/GUI/GUI.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/GUI.cpp 2022-05-18 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/GUI.cpp 2023-04-07 10:00:00.000000000 +0000 @@ -7,8 +7,11 @@ #endif #include "../../../Common/MyWindows.h" - +#if defined(__MINGW32__) || defined(__MINGW64__) +#include +#else #include +#endif #include "../../../Common/MyInitGuid.h" @@ -23,7 +26,7 @@ #include "../Common/ExitCode.h" #include "../FileManager/StringUtils.h" -#include "../FileManager/MyWindowsNew.h" +#include "../FileManager/LangUtils.h" #include "BenchmarkDialog.h" #include "ExtractGUI.h" @@ -34,7 +37,9 @@ using namespace NWindows; -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS +extern +const CExternalCodecs *g_ExternalCodecs_Ptr; const CExternalCodecs *g_ExternalCodecs_Ptr; #endif @@ -51,20 +56,23 @@ static DWORD GetDllVersion(LPCTSTR dllName) { DWORD dwVersion = 0; - HINSTANCE hinstDll = LoadLibrary(dllName); - if (hinstDll) + const HMODULE hmodule = LoadLibrary(dllName); + if (hmodule) { - DLLGETVERSIONPROC pDllGetVersion = (DLLGETVERSIONPROC)(void *)GetProcAddress(hinstDll, "DllGetVersion"); - if (pDllGetVersion) + const + DLLGETVERSIONPROC f_DllGetVersion = Z7_GET_PROC_ADDRESS( + DLLGETVERSIONPROC, hmodule, + "DllGetVersion"); + if (f_DllGetVersion) { DLLVERSIONINFO dvi; ZeroMemory(&dvi, sizeof(dvi)); dvi.cbSize = sizeof(dvi); - HRESULT hr = (*pDllGetVersion)(&dvi); + const HRESULT hr = (*f_DllGetVersion)(&dvi); if (SUCCEEDED(hr)) - dwVersion = MAKELONG(dvi.dwMinorVersion, dvi.dwMajorVersion); + dwVersion = (DWORD)MAKELONG(dvi.dwMinorVersion, dvi.dwMajorVersion); } - FreeLibrary(hinstDll); + FreeLibrary(hmodule); } return dwVersion; } @@ -100,9 +108,9 @@ return NExitCode::kMemoryError; } -static int ShowSysErrorMessage(DWORD errorCode) +static int ShowSysErrorMessage(HRESULT errorCode) { - if ((HRESULT)errorCode == E_OUTOFMEMORY) + if (errorCode == E_OUTOFMEMORY) return ShowMemErrorMessage(); ErrorMessage(HResultToMessage(errorCode)); return NExitCode::kFatalError; @@ -125,7 +133,7 @@ #endif if (commandStrings.Size() == 0) { - MessageBoxW(0, L"Specify command", L"7-Zip", 0); + MessageBoxW(NULL, L"Specify command", L"7-Zip", 0); return 0; } @@ -142,14 +150,14 @@ ThrowException_if_Error(codecs->Load()); Codecs_AddHashArcHandler(codecs); - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS { - g_ExternalCodecs_Ptr = &__externalCodecs; + g_ExternalCodecs_Ptr = &_externalCodecs; UString s; codecs->GetCodecsErrorMessage(s); if (!s.IsEmpty()) { - MessageBoxW(0, s, L"7-Zip", MB_ICONERROR); + MessageBoxW(NULL, s, L"7-Zip", MB_ICONERROR); } } @@ -162,7 +170,7 @@ || options.Command.IsFromUpdateGroup())) { - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS if (!codecs->MainDll_ErrorPath.IsEmpty()) { UString s ("7-Zip cannot load module: "); @@ -194,12 +202,12 @@ // excludedFormats.Sort(); } - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS if (isExtractGroupCommand || options.Command.IsFromUpdateGroup() || options.Command.CommandType == NCommandType::kHash || options.Command.CommandType == NCommandType::kBenchmark) - ThrowException_if_Error(__externalCodecs.Load()); + ThrowException_if_Error(_externalCodecs.Load()); #endif if (options.Command.CommandType == NCommandType::kBenchmark) @@ -227,7 +235,7 @@ CExtractCallbackImp *ecs = new CExtractCallbackImp; CMyComPtr extractCallback = ecs; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO ecs->PasswordIsDefined = options.PasswordEnabled; ecs->Password = options.Password; #endif @@ -241,13 +249,13 @@ eo.YesToAll = options.YesToAll; eo.TestMode = options.Command.IsTestCommand(); - #ifndef _SFX + #ifndef Z7_SFX eo.Properties = options.Properties; #endif bool messageWasDisplayed = false; - #ifndef _SFX + #ifndef Z7_SFX CHashBundle hb; CHashBundle *hb_ptr = NULL; @@ -289,7 +297,7 @@ ArchivePathsFullSorted, options.Censor.Pairs.Front().Head, eo, - #ifndef _SFX + #ifndef Z7_SFX hb_ptr, #endif options.ShowDialog, messageWasDisplayed, ecs); @@ -304,14 +312,14 @@ } else if (options.Command.IsFromUpdateGroup()) { - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO bool passwordIsDefined = options.PasswordEnabled && !options.Password.IsEmpty(); #endif CUpdateCallbackGUI callback; // callback.EnablePercents = options.EnablePercents; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO callback.PasswordIsDefined = passwordIsDefined; callback.AskPassword = options.PasswordEnabled && options.Password.IsEmpty(); callback.Password = options.Password; @@ -407,7 +415,9 @@ OleInitialize(NULL); #endif + #ifdef Z7_LANG LoadLangOneTime(); + #endif // setlocale(LC_COLLATE, ".ACP"); try @@ -456,7 +466,7 @@ catch(int v) { AString e ("Error: "); - e.Add_UInt32(v); + e.Add_UInt32((unsigned)v); ErrorMessage(e); return NExitCode::kFatalError; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/GUI.dsp 7zip-23.01+dfsg/CPP/7zip/UI/GUI/GUI.dsp --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/GUI.dsp 2022-05-18 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/GUI.dsp 2023-05-02 10:00:00.000000000 +0000 @@ -45,7 +45,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"stdafx.h" /FD /c -# ADD CPP /nologo /Gr /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_MBCS" /D "WIN32" /D "_WINDOWS" /D "LANG" /D "WIN_LONG_PATH" /D "EXTERNAL_CODECS" /D "SUPPORT_DEVICE_FILE" /D "_7ZIP_LARGE_PAGES" /FAcs /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /Gr /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_MBCS" /D "WIN32" /D "_WINDOWS" /D "Z7_LANG" /D "Z7_LONG_PATH" /D "Z7_EXTERNAL_CODECS" /D "Z7_DEVICE_FILE" /D "Z7_LARGE_PAGES" /FAcs /Yu"stdafx.h" /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "NDEBUG" @@ -72,7 +72,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c -# ADD CPP /nologo /Gr /MDd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_MBCS" /D "WIN32" /D "_WINDOWS" /D "LANG" /D "WIN_LONG_PATH" /D "EXTERNAL_CODECS" /D "SUPPORT_DEVICE_FILE" /D "_7ZIP_LARGE_PAGES" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /Gr /MDd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_MBCS" /D "WIN32" /D "_WINDOWS" /D "Z7_LANG" /D "Z7_LONG_PATH" /D "Z7_EXTERNAL_CODECS" /D "Z7_DEVICE_FILE" /D "Z7_LARGE_PAGES" /Yu"stdafx.h" /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "_DEBUG" @@ -99,7 +99,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"stdafx.h" /FD /c -# ADD CPP /nologo /Gr /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_UNICODE" /D "UNICODE" /D "WIN32" /D "_WINDOWS" /D "LANG" /D "WIN_LONG_PATH" /D "EXTERNAL_CODECS" /D "SUPPORT_DEVICE_FILE" /D "_7ZIP_LARGE_PAGES" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /Gr /MD /W4 /WX /GX /O1 /D "NDEBUG" /D "_UNICODE" /D "UNICODE" /D "WIN32" /D "_WINDOWS" /D "Z7_LANG" /D "Z7_LONG_PATH" /D "Z7_EXTERNAL_CODECS" /D "Z7_DEVICE_FILE" /D "Z7_LARGE_PAGES" /Yu"stdafx.h" /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "NDEBUG" @@ -127,7 +127,7 @@ # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c -# ADD CPP /nologo /Gr /MDd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_UNICODE" /D "UNICODE" /D "WIN32" /D "_WINDOWS" /D "LANG" /D "WIN_LONG_PATH" /D "EXTERNAL_CODECS" /D "SUPPORT_DEVICE_FILE" /D "_7ZIP_LARGE_PAGES" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /Gr /MDd /W4 /WX /Gm /GX /ZI /Od /D "_DEBUG" /D "_UNICODE" /D "UNICODE" /D "WIN32" /D "_WINDOWS" /D "Z7_LANG" /D "Z7_LONG_PATH" /D "Z7_EXTERNAL_CODECS" /D "Z7_DEVICE_FILE" /D "Z7_LARGE_PAGES" /Yu"stdafx.h" /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x419 /d "_DEBUG" @@ -485,10 +485,6 @@ # End Source File # Begin Source File -SOURCE=..\FileManager\FolderInterface.h -# End Source File -# Begin Source File - SOURCE=..\FileManager\FormatUtils.cpp # End Source File # Begin Source File @@ -669,6 +665,14 @@ # End Source File # Begin Source File +SOURCE=..\..\Common\MultiOutStream.cpp +# End Source File +# Begin Source File + +SOURCE=..\..\Common\MultiOutStream.h +# End Source File +# Begin Source File + SOURCE=..\..\Common\ProgressUtils.cpp # End Source File # Begin Source File @@ -777,6 +781,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\..\C\7zWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\..\..\C\Alloc.c # SUBTRACT CPP /YX /Yc /Yu # End Source File @@ -872,6 +880,14 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\Common.h +# End Source File +# Begin Source File + +SOURCE=..\..\..\..\C\Compiler.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\CRC.cpp # End Source File # Begin Source File @@ -928,6 +944,10 @@ # End Source File # Begin Source File +SOURCE=..\..\..\Common\MyWindows.h +# End Source File +# Begin Source File + SOURCE=..\..\..\Common\NewHandler.cpp # End Source File # Begin Source File @@ -1226,6 +1246,14 @@ SOURCE=..\..\ICoder.h # End Source File +# Begin Source File + +SOURCE=..\..\IDecl.h +# End Source File +# Begin Source File + +SOURCE=..\..\IStream.h +# End Source File # End Group # End Target # End Project diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/HashGUI.cpp 7zip-23.01+dfsg/CPP/7zip/UI/GUI/HashGUI.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/HashGUI.cpp 2021-11-15 16:00:43.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/HashGUI.cpp 2023-05-17 07:00:00.000000000 +0000 @@ -22,7 +22,7 @@ -class CHashCallbackGUI: public CProgressThreadVirt, public IHashCallbackUI +class CHashCallbackGUI Z7_final: public CProgressThreadVirt, public IHashCallbackUI { UInt64 NumFiles; bool _curIsFolder; @@ -31,24 +31,28 @@ CPropNameValPairs PropNameValPairs; - HRESULT ProcessVirt(); - virtual void ProcessWasFinished_GuiVirt(); + HRESULT ProcessVirt() Z7_override; + virtual void ProcessWasFinished_GuiVirt() Z7_override; public: const NWildcard::CCensor *censor; const CHashOptions *options; - DECL_EXTERNAL_CODECS_LOC_VARS2; + DECL_EXTERNAL_CODECS_LOC_VARS_DECL - CHashCallbackGUI() {} - ~CHashCallbackGUI() { } - - INTERFACE_IHashCallbackUI(;) + Z7_IFACE_IMP(IDirItemsCallback) + Z7_IFACE_IMP(IHashCallbackUI) + /* void AddErrorMessage(DWORD systemError, const wchar_t *name) { Sync.AddError_Code_Name(systemError, name); } + */ + void AddErrorMessage(HRESULT systemError, const wchar_t *name) + { + Sync.AddError_Code_Name(systemError, name); + } }; @@ -106,13 +110,13 @@ HRESULT CHashCallbackGUI::ScanError(const FString &path, DWORD systemError) { - AddErrorMessage(systemError, fs2us(path)); + AddErrorMessage(HRESULT_FROM_WIN32(systemError), fs2us(path)); return CheckBreak(); } HRESULT CHashCallbackGUI::FinishScanning(const CDirItemsStat &st) { - return ScanProgress(st, FString(), false); + return ScanProgress(st, FString(), false); // isDir } HRESULT CHashCallbackGUI::CheckBreak() @@ -158,7 +162,7 @@ { // if (systemError == ERROR_SHARING_VIOLATION) { - AddErrorMessage(systemError, fs2us(path)); + AddErrorMessage(HRESULT_FROM_WIN32(systemError), fs2us(path)); return S_FALSE; } // return systemError; @@ -305,8 +309,8 @@ bool &messageWasDisplayed) { CHashCallbackGUI t; - #ifdef EXTERNAL_CODECS - t.__externalCodecs = __externalCodecs; + #ifdef Z7_EXTERNAL_CODECS + t._externalCodecs = _externalCodecs; #endif t.censor = &censor; t.options = &options; @@ -319,7 +323,7 @@ t.MainAddTitle = title; t.MainAddTitle.Add_Space(); - RINOK(t.Create(title)); + RINOK(t.Create(title)) messageWasDisplayed = t.ThreadFinishedOK && t.MessagesDisplayed; return S_OK; } @@ -352,8 +356,8 @@ ShowHashResults(propPairs, hwnd); } - void CHashCallbackGUI::ProcessWasFinished_GuiVirt() { - ShowHashResults(PropNameValPairs, *this); + if (Result != E_ABORT) + ShowHashResults(PropNameValPairs, *this); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/HashGUI.h 7zip-23.01+dfsg/CPP/7zip/UI/GUI/HashGUI.h --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/HashGUI.h 2018-12-02 17:58:32.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/HashGUI.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // HashGUI.h -#ifndef __HASH_GUI_H -#define __HASH_GUI_H +#ifndef ZIP7_INC_HASH_GUI_H +#define ZIP7_INC_HASH_GUI_H #include "../Common/HashCalc.h" #include "../Common/Property.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/makefile 7zip-23.01+dfsg/CPP/7zip/UI/GUI/makefile --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/makefile 2021-10-07 18:27:19.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/makefile 2023-04-07 10:00:00.000000000 +0000 @@ -1,13 +1,13 @@ PROG = 7zG.exe CFLAGS = $(CFLAGS) \ - -DLANG \ - -DEXTERNAL_CODECS \ + -DZ7_LANG \ + -DZ7_EXTERNAL_CODECS \ !IFDEF UNDER_CE LIBS = $(LIBS) ceshell.lib Commctrl.lib !ELSE LIBS = $(LIBS) comctl32.lib htmlhelp.lib comdlg32.lib gdi32.lib -CFLAGS = $(CFLAGS) -DWIN_LONG_PATH -DSUPPORT_DEVICE_FILE -D_7ZIP_LARGE_PAGES +CFLAGS = $(CFLAGS) -DZ7_LONG_PATH -DZ7_LARGE_PAGES -DZ7_DEVICE_FILE !ENDIF GUI_OBJS = \ @@ -72,6 +72,7 @@ $O\FilterCoder.obj \ $O\LimitedStreams.obj \ $O\MethodProps.obj \ + $O\MultiOutStream.obj \ $O\ProgressUtils.obj \ $O\PropId.obj \ $O\StreamObjects.obj \ diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/StdAfx.h 7zip-23.01+dfsg/CPP/7zip/UI/GUI/StdAfx.h --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/StdAfx.h 2021-03-05 12:15:09.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/StdAfx.h 2023-03-06 18:00:00.000000000 +0000 @@ -1,21 +1,6 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H - -// #define _WIN32_WINNT 0x0400 -#define _WIN32_WINNT 0x0500 -#define WINVER _WIN32_WINNT - -#include "../../../Common/Common.h" - -// #include "../../../Common/MyWindows.h" - -// #include -// #include -// #include - -// #define printf(x) NO_PRINTF_(x) -// #define sprintf(x) NO_SPRINTF_(x) - +#if _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' #endif +#include "../FileManager/StdAfx.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/UpdateCallbackGUI2.cpp 7zip-23.01+dfsg/CPP/7zip/UI/GUI/UpdateCallbackGUI2.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/UpdateCallbackGUI2.cpp 2015-03-23 10:46:05.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/UpdateCallbackGUI2.cpp 2023-03-06 16:00:00.000000000 +0000 @@ -31,7 +31,7 @@ _lang_Removing = LangString(IDS_PROGRESS_REMOVE); _lang_Ops.Clear(); - for (unsigned i = 0; i < ARRAY_SIZE(k_UpdNotifyLangs); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_UpdNotifyLangs); i++) _lang_Ops.Add(LangString(k_UpdNotifyLangs[i])); } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/UpdateCallbackGUI2.h 7zip-23.01+dfsg/CPP/7zip/UI/GUI/UpdateCallbackGUI2.h --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/UpdateCallbackGUI2.h 2015-03-20 16:23:53.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/UpdateCallbackGUI2.h 2023-04-01 09:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // UpdateCallbackGUI2.h -#ifndef __UPDATE_CALLBACK_GUI2_H -#define __UPDATE_CALLBACK_GUI2_H +#ifndef ZIP7_INC_UPDATE_CALLBACK_GUI2_H +#define ZIP7_INC_UPDATE_CALLBACK_GUI2_H #include "../FileManager/ProgressDialog2.h" @@ -23,7 +23,6 @@ NumFiles(0) {} - // ~CUpdateCallbackGUI2(); void Init(); CProgressDialog *ProgressDialog; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/UpdateCallbackGUI.cpp 7zip-23.01+dfsg/CPP/7zip/UI/GUI/UpdateCallbackGUI.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/UpdateCallbackGUI.cpp 2021-09-29 17:10:03.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/UpdateCallbackGUI.cpp 2023-01-29 16:00:00.000000000 +0000 @@ -51,7 +51,7 @@ HRESULT CUpdateCallbackGUI::ScanError(const FString &path, DWORD systemError) { FailedFiles.Add(path); - ProgressDialog->Sync.AddError_Code_Name(systemError, fs2us(path)); + ProgressDialog->Sync.AddError_Code_Name(HRESULT_FROM_WIN32(systemError), fs2us(path)); return S_OK; } @@ -59,7 +59,7 @@ { CProgressSync &sync = ProgressDialog->Sync; RINOK(ProgressDialog->Sync.ScanProgress(st.NumFiles + st.NumAltStreams, - st.GetTotalBytes(), FString(), true)); + st.GetTotalBytes(), FString(), true)) sync.Set_Status(L""); return S_OK; } @@ -130,7 +130,7 @@ FailedFiles.Add(path); // if (systemError == ERROR_SHARING_VIOLATION) { - ProgressDialog->Sync.AddError_Code_Name(systemError, fs2us(path)); + ProgressDialog->Sync.AddError_Code_Name(HRESULT_FROM_WIN32(systemError), fs2us(path)); return S_FALSE; } // return systemError; @@ -209,7 +209,7 @@ return ProgressDialog->Sync.CheckStop(); } -#ifndef _NO_CRYPTO +#ifndef Z7_NO_CRYPTO HRESULT CUpdateCallbackGUI::Open_CryptoGetTextPassword(BSTR *password) { @@ -260,7 +260,7 @@ HRESULT CUpdateCallbackGUI::ReadingFileError(const FString &path, DWORD systemError) { FailedFiles.Add(path); - ProgressDialog->Sync.AddError_Code_Name(systemError, fs2us(path)); + ProgressDialog->Sync.AddError_Code_Name(HRESULT_FROM_WIN32(systemError), fs2us(path)); return S_OK; } diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/UpdateCallbackGUI.h 7zip-23.01+dfsg/CPP/7zip/UI/GUI/UpdateCallbackGUI.h --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/UpdateCallbackGUI.h 2015-03-11 10:09:27.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/UpdateCallbackGUI.h 2023-04-01 09:00:00.000000000 +0000 @@ -1,34 +1,31 @@ // UpdateCallbackGUI.h -#ifndef __UPDATE_CALLBACK_GUI_H -#define __UPDATE_CALLBACK_GUI_H +#ifndef ZIP7_INC_UPDATE_CALLBACK_GUI_H +#define ZIP7_INC_UPDATE_CALLBACK_GUI_H #include "../Common/Update.h" #include "../Common/ArchiveOpenCallback.h" #include "UpdateCallbackGUI2.h" -class CUpdateCallbackGUI: +class CUpdateCallbackGUI Z7_final: public IOpenCallbackUI, public IUpdateCallbackUI2, public CUpdateCallbackGUI2 { -public: - // CUpdateCallbackGUI(); - // ~CUpdateCallbackGUI(); + Z7_IFACE_IMP(IOpenCallbackUI) + Z7_IFACE_IMP(IUpdateCallbackUI) + Z7_IFACE_IMP(IDirItemsCallback) + Z7_IFACE_IMP(IUpdateCallbackUI2) +public: bool AskPassword; - - void Init(); + FStringVector FailedFiles; CUpdateCallbackGUI(): AskPassword(false) {} - - INTERFACE_IUpdateCallbackUI2(;) - INTERFACE_IOpenCallbackUI(;) - - FStringVector FailedFiles; + void Init(); }; #endif diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/UpdateGUI.cpp 7zip-23.01+dfsg/CPP/7zip/UI/GUI/UpdateGUI.cpp --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/UpdateGUI.cpp 2022-05-18 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/UpdateGUI.cpp 2023-03-29 10:00:00.000000000 +0000 @@ -37,7 +37,7 @@ class CThreadUpdating: public CProgressThreadVirt { - HRESULT ProcessVirt(); + HRESULT ProcessVirt() Z7_override; public: CCodecs *codecs; const CObjectVector *formatIndices; @@ -185,7 +185,7 @@ property.Name = s; else { - property.Name.SetFrom(s, index); + property.Name.SetFrom(s, (unsigned)index); property.Value = s.Ptr(index + 1); } properties.Add(property); @@ -222,6 +222,16 @@ name += (di.OrderMode ? "mem" : "d"); AddProp_Size(properties, name, di.Dict64); } + /* + if (di.Dict64_Chain != (UInt64)(Int64)-1) + { + AString name; + if (is7z) + name = "0"; + name += "dc"; + AddProp_Size(properties, name, di.Dict64_Chain); + } + */ if (di.Order != (UInt32)(Int32)-1) { AString name; @@ -287,17 +297,17 @@ static int FindActionSet(const NUpdateArchive::CActionSet &actionSet) { - for (unsigned i = 0; i < ARRAY_SIZE(g_UpdateMode_Pairs); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_UpdateMode_Pairs); i++) if (actionSet.IsEqualTo(*g_UpdateMode_Pairs[i].ActionSet)) - return i; + return (int)i; return -1; } static int FindUpdateMode(NCompressDialog::NUpdateMode::EEnum mode) { - for (unsigned i = 0; i < ARRAY_SIZE(g_UpdateMode_Pairs); i++) + for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_UpdateMode_Pairs); i++) if (mode == g_UpdateMode_Pairs[i].UpdateMode) - return i; + return (int)i; return -1; } @@ -365,10 +375,14 @@ } } - + + /* + // v23: we restore current dir in dialog code #if defined(_WIN32) && !defined(UNDER_CE) CCurrentDirRestorer curDirRestorer; #endif + */ + CCompressDialog dialog; NCompressDialog::CInfo &di = dialog.Info; dialog.ArcFormats = &codecs->Formats; @@ -453,9 +467,11 @@ if (di.PreserveATime.Def) options.PreserveATime = di.PreserveATime.Val; + /* #if defined(_WIN32) && !defined(UNDER_CE) curDirRestorer.NeedRestore = dialog.CurrentDirWasChanged; #endif + */ options.VolumesSizes = di.VolumeSizes; /* @@ -539,7 +555,7 @@ bool needSetPath = true; if (showDialog) { - RINOK(ShowDialog(codecs, censor.CensorPaths, options, callback, hwndParent)); + RINOK(ShowDialog(codecs, censor.CensorPaths, options, callback, hwndParent)) needSetPath = false; } if (options.SfxMode && options.SfxModule.IsEmpty()) @@ -582,7 +598,7 @@ tu.Options = &options; tu.IconID = IDI_ICON; - RINOK(tu.Create(title, hwndParent)); + RINOK(tu.Create(title, hwndParent)) messageWasDisplayed = tu.ThreadFinishedOK && tu.MessagesDisplayed; return tu.Result; diff -Nru 7zip-22.01+dfsg/CPP/7zip/UI/GUI/UpdateGUI.h 7zip-23.01+dfsg/CPP/7zip/UI/GUI/UpdateGUI.h --- 7zip-22.01+dfsg/CPP/7zip/UI/GUI/UpdateGUI.h 2014-05-06 09:20:17.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/UI/GUI/UpdateGUI.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // GUI/UpdateGUI.h -#ifndef __UPDATE_GUI_H -#define __UPDATE_GUI_H +#ifndef ZIP7_INC_UPDATE_GUI_H +#define ZIP7_INC_UPDATE_GUI_H #include "../Common/Update.h" diff -Nru 7zip-22.01+dfsg/CPP/7zip/warn_clang_mac.mak 7zip-23.01+dfsg/CPP/7zip/warn_clang_mac.mak --- 7zip-22.01+dfsg/CPP/7zip/warn_clang_mac.mak 2021-05-12 08:51:56.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/warn_clang_mac.mak 2023-05-06 05:00:00.000000000 +0000 @@ -1,39 +1,9 @@ -CFLAGS_WARN_CLANG_3_8_UNIQ = \ - -Wno-reserved-id-macro \ - -Wno-old-style-cast \ - -Wno-c++11-long-long \ - -Wno-unused-macros \ +CFLAGS_WARN = -Weverything -Wfatal-errors -Wno-poison-system-directories +CXX_STD_FLAGS = -std=c++98 +CXX_STD_FLAGS = -std=c++11 +CXX_STD_FLAGS = -std=c++14 +CXX_STD_FLAGS = -std=c++17 +CXX_STD_FLAGS = -std=c++20 +CXX_STD_FLAGS = -std=c++23 -CFLAGS_WARN_CLANG_3_8 = \ - $(CFLAGS_WARN_CLANG_3_8_UNIQ) \ - -Weverything \ - -Wno-extra-semi \ - -Wno-sign-conversion \ - -Wno-language-extension-token \ - -Wno-global-constructors \ - -Wno-non-virtual-dtor \ - -Wno-switch-enum \ - -Wno-covered-switch-default \ - -Wno-cast-qual \ - -Wno-padded \ - -Wno-exit-time-destructors \ - -Wno-weak-vtables \ - -CFLAGS_WARN_CLANG_12= $(CFLAGS_WARN_CLANG_3_8) \ - -Wno-extra-semi-stmt \ - -Wno-zero-as-null-pointer-constant \ - -Wno-deprecated-dynamic-exception-spec \ - -Wno-c++98-compat-pedantic \ - -Wno-atomic-implicit-seq-cst \ - -Wconversion \ - -Wno-sign-conversion \ - -Wno-suggest-override \ - -Wno-suggest-destructor-override \ - -CFLAGS_WARN_MAC = \ - -Wno-poison-system-directories \ - -Wno-c++11-long-long \ - -Wno-atomic-implicit-seq-cst \ - - -CFLAGS_WARN = $(CFLAGS_WARN_CLANG_12) $(CFLAGS_WARN_MAC) +CXX_STD_FLAGS = -std=c++11 diff -Nru 7zip-22.01+dfsg/CPP/7zip/warn_clang.mak 7zip-23.01+dfsg/CPP/7zip/warn_clang.mak --- 7zip-22.01+dfsg/CPP/7zip/warn_clang.mak 2021-04-28 11:21:35.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/warn_clang.mak 2023-05-06 05:00:00.000000000 +0000 @@ -1,37 +1,3 @@ -CFLAGS_WARN_CLANG_3_8_UNIQ = \ - -Wno-reserved-id-macro \ - -Wno-old-style-cast \ - -Wno-c++11-long-long \ - -Wno-unused-macros \ - -CFLAGS_WARN_CLANG_3_8 = \ - $(CFLAGS_WARN_CLANG_3_8_UNIQ) \ - -Weverything \ - -Wno-extra-semi \ - -Wno-sign-conversion \ - -Wno-language-extension-token \ - -Wno-global-constructors \ - -Wno-non-virtual-dtor \ - -Wno-switch-enum \ - -Wno-covered-switch-default \ - -Wno-cast-qual \ - -Wno-padded \ - -Wno-exit-time-destructors \ - -Wno-weak-vtables \ - -CFLAGS_WARN_CLANG_12= $(CFLAGS_WARN_CLANG_3_8) \ - -Wno-extra-semi-stmt \ - -Wno-zero-as-null-pointer-constant \ - -Wno-deprecated-dynamic-exception-spec \ - -Wno-c++98-compat-pedantic \ - -Wno-atomic-implicit-seq-cst \ - -Wconversion \ - -Wno-sign-conversion \ - -CFLAGS_WARN_1 = \ - -Wno-deprecated-copy-dtor \ - - - - -CFLAGS_WARN = $(CFLAGS_WARN_CLANG_12) $(CFLAGS_WARN_1) +CFLAGS_WARN = -Weverything -Wfatal-errors +# CXX_STD_FLAGS = -std=c++11 +# CXX_STD_FLAGS = diff -Nru 7zip-22.01+dfsg/CPP/7zip/warn_gcc.mak 7zip-23.01+dfsg/CPP/7zip/warn_gcc.mak --- 7zip-22.01+dfsg/CPP/7zip/warn_gcc.mak 2021-07-16 12:45:12.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/7zip/warn_gcc.mak 2023-05-06 05:00:00.000000000 +0000 @@ -1,57 +1,45 @@ -CFLAGS_WARN_GCC_4_5 = \ - -CFLAGS_WARN_GCC_6 = \ +CFLAGS_WARN_GCC_4_8 = \ -Waddress \ -Waggressive-loop-optimizations \ -Wattributes \ - -Wbool-compare \ -Wcast-align \ -Wcomment \ -Wdiv-by-zero \ - -Wduplicated-cond \ -Wformat-contains-nul \ -Winit-self \ -Wint-to-pointer-cast \ -Wunused \ -Wunused-macros \ +CFLAGS_WARN_GCC_6 = $(CFLAGS_WARN_GCC_4_8)\ + -Wbool-compare \ + -Wduplicated-cond \ + # -Wno-strict-aliasing -CFLAGS_WARN_GCC_9 = \ - -Waddress \ +CFLAGS_WARN_GCC_9 = $(CFLAGS_WARN_GCC_6)\ -Waddress-of-packed-member \ - -Waggressive-loop-optimizations \ - -Wattributes \ - -Wbool-compare \ -Wbool-operation \ - -Wcast-align \ -Wcast-align=strict \ - -Wcomment \ + -Wconversion \ -Wdangling-else \ - -Wdiv-by-zero \ -Wduplicated-branches \ - -Wduplicated-cond \ - -Wformat-contains-nul \ -Wimplicit-fallthrough=5 \ - -Winit-self \ -Wint-in-bool-context \ - -Wint-to-pointer-cast \ - -Wunused \ - -Wunused-macros \ - -Wconversion \ + -Wmaybe-uninitialized \ + -Wmisleading-indentation \ + -Wmissing-attributes +# In C: -Wsign-conversion enabled also by -Wconversion # -Wno-sign-conversion \ -CFLAGS_WARN_GCC_10 = $(CFLAGS_WARN_GCC_9) \ - -Wmaybe-uninitialized \ - -Wmisleading-indentation \ CFLAGS_WARN_GCC_PPMD_UNALIGNED = \ -Wno-strict-aliasing \ -CFLAGS_WARN = $(CFLAGS_WARN_GCC_9) \ - -# $(CFLAGS_WARN_GCC_PPMD_UNALIGNED) +# CFLAGS_WARN = $(CFLAGS_WARN_GCC_4_8) +CFLAGS_WARN = $(CFLAGS_WARN_GCC_9) - \ No newline at end of file +# CXX_STD_FLAGS = -std=c++11 +# CXX_STD_FLAGS = diff -Nru 7zip-22.01+dfsg/CPP/Build.mak 7zip-23.01+dfsg/CPP/Build.mak --- 7zip-22.01+dfsg/CPP/Build.mak 2021-04-29 08:41:29.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Build.mak 2023-05-01 10:00:00.000000000 +0000 @@ -4,6 +4,11 @@ CFLAGS = $(CFLAGS) -DUNICODE -D_UNICODE !ENDIF +!IF "$(CC)" != "clang-cl" +# for link time code generation: +# CFLAGS = $(CFLAGS) -GL +!ENDIF + !IFNDEF O !IFDEF PLATFORM O=$(PLATFORM) @@ -51,33 +56,22 @@ COMPL_ASM = $(MY_ML) -c -Fo$O/ $** !ENDIF -CFLAGS = $(CFLAGS) -nologo -c -Fo$O/ -W4 -WX -EHsc -Gy -GR- -GF +!IFDEF OLD_COMPILER +CFLAGS_WARN_LEVEL = -W4 +!ELSE +CFLAGS_WARN_LEVEL = -Wall +!ENDIF + +CFLAGS = $(CFLAGS) -nologo -c -Fo$O/ $(CFLAGS_WARN_LEVEL) -WX -EHsc -Gy -GR- -GF !IF "$(CC)" == "clang-cl" CFLAGS = $(CFLAGS) \ -Werror \ - -Wextra \ -Wall \ + -Wextra \ -Weverything \ - -Wno-extra-semi-stmt \ - -Wno-extra-semi \ - -Wno-zero-as-null-pointer-constant \ - -Wno-sign-conversion \ - -Wno-old-style-cast \ - -Wno-reserved-id-macro \ - -Wno-deprecated-dynamic-exception-spec \ - -Wno-language-extension-token \ - -Wno-global-constructors \ - -Wno-non-virtual-dtor \ - -Wno-deprecated-copy-dtor \ - -Wno-exit-time-destructors \ - -Wno-switch-enum \ - -Wno-covered-switch-default \ - -Wno-nonportable-system-include-path \ - -Wno-c++98-compat-pedantic \ - -Wno-cast-qual \ - -Wc++11-extensions \ + -Wfatal-errors \ !ENDIF @@ -92,8 +86,21 @@ CFLAGS = $(CFLAGS_COMMON) $(CFLAGS) + !IFNDEF OLD_COMPILER -CFLAGS = $(CFLAGS) -GS- -Zc:forScope -Zc:wchar_t + +CFLAGS = $(CFLAGS) -GS- -Zc:wchar_t +!IFDEF VCTOOLSVERSION +!IF "$(VCTOOLSVERSION)" >= "14.00" +!IF "$(CC)" != "clang-cl" +CFLAGS = $(CFLAGS) -Zc:throwingNew +!ENDIF +!ENDIF +!ELSE +# -Zc:forScope is default in VS2010. so we need it only for older versions +CFLAGS = $(CFLAGS) -Zc:forScope +!ENDIF + !IFNDEF UNDER_CE !IF "$(CC)" != "clang-cl" CFLAGS = $(CFLAGS) -MP4 @@ -102,10 +109,10 @@ # CFLAGS = $(CFLAGS) -arch:IA32 !ENDIF !ENDIF -!ELSE -CFLAGS = $(CFLAGS) + !ENDIF + !IFDEF MY_CONSOLE CFLAGS = $(CFLAGS) -D_CONSOLE !ENDIF @@ -123,7 +130,7 @@ !ENDIF CFLAGS_O2 = $(CFLAGS) -O2 -LFLAGS = $(LFLAGS) -nologo -OPT:REF -OPT:ICF +LFLAGS = $(LFLAGS) -nologo -OPT:REF -OPT:ICF -INCREMENTAL:NO !IFNDEF UNDER_CE LFLAGS = $(LFLAGS) /LARGEADDRESSAWARE @@ -140,6 +147,12 @@ # /BASE:0x400000 !ENDIF +!IF "$(PLATFORM)" == "arm64" +# we can get better compression ratio with ARM64 filter if we change alignment to 4096 +# LFLAGS = $(LFLAGS) /FILEALIGN:4096 +!ENDIF + + # !IF "$(PLATFORM)" == "x64" @@ -162,21 +175,23 @@ COMPL_O2 = $(CC) $(CFLAGS_O2) $** COMPL_PCH = $(CC) $(CFLAGS_O1) -Yc"StdAfx.h" -Fp$O/a.pch $** COMPL = $(CC) $(CFLAGS_O1) -Yu"StdAfx.h" -Fp$O/a.pch $** - -COMPLB = $(CC) $(CFLAGS_O1) -Yu"StdAfx.h" -Fp$O/a.pch $< -# COMPLB_O2 = $(CC) $(CFLAGS_O2) -Yu"StdAfx.h" -Fp$O/a.pch $< -COMPLB_O2 = $(CC) $(CFLAGS_O2) $< +COMPLB = $(CC) $(CFLAGS_O1) -Yu"StdAfx.h" -Fp$O/a.pch $< +COMPLB_O2 = $(CC) $(CFLAGS_O2) $< +# COMPLB_O2 = $(CC) $(CFLAGS_O2) -Yu"StdAfx.h" -Fp$O/a.pch $< CFLAGS_C_ALL = $(CFLAGS_O2) $(CFLAGS_C_SPEC) + CCOMPL_PCH = $(CC) $(CFLAGS_C_ALL) -Yc"Precomp.h" -Fp$O/a.pch $** CCOMPL_USE = $(CC) $(CFLAGS_C_ALL) -Yu"Precomp.h" -Fp$O/a.pch $** +CCOMPLB_USE = $(CC) $(CFLAGS_C_ALL) -Yu"Precomp.h" -Fp$O/a.pch $< CCOMPL = $(CC) $(CFLAGS_C_ALL) $** CCOMPLB = $(CC) $(CFLAGS_C_ALL) $< !IF "$(CC)" == "clang-cl" COMPL = $(COMPL) -FI StdAfx.h COMPLB = $(COMPLB) -FI StdAfx.h -CCOMPL_USE = $(CCOMPL_USE) -FI Precomp.h +CCOMPL_USE = $(CCOMPL_USE) -FI Precomp.h +CCOMPLB_USE = $(CCOMPLB_USE) -FI Precomp.h !ENDIF all: $(PROGPATH) @@ -189,6 +204,11 @@ $O/asm: if not exist "$O/asm" mkdir "$O/asm" +!IF "$(CC)" != "clang-cl" +# for link time code generation: +# LFLAGS = $(LFLAGS) -LTCG +!ENDIF + $(PROGPATH): $O $O/asm $(OBJS) $(DEF_FILE) link $(LFLAGS) -out:$(PROGPATH) $(OBJS) $(LIBS) @@ -198,3 +218,12 @@ !ENDIF $O\StdAfx.obj: $(*B).cpp $(COMPL_PCH) + +predef: empty.c + $(CCOMPL) /EP /Zc:preprocessor /PD +predef2: A.cpp + $(COMPL) -EP -Zc:preprocessor -PD +predef3: A.cpp + $(COMPL) -E -dM +predef4: A.cpp + $(COMPL_O2) -E diff -Nru 7zip-22.01+dfsg/CPP/Common/AutoPtr.h 7zip-23.01+dfsg/CPP/Common/AutoPtr.h --- 7zip-22.01+dfsg/CPP/Common/AutoPtr.h 2008-08-06 07:33:16.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/AutoPtr.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,13 +1,13 @@ // Common/AutoPtr.h -#ifndef __COMMON_AUTOPTR_H -#define __COMMON_AUTOPTR_H +#ifndef ZIP7_INC_COMMON_AUTOPTR_H +#define ZIP7_INC_COMMON_AUTOPTR_H template class CMyAutoPtr { T *_p; public: - CMyAutoPtr(T *p = 0) : _p(p) {} + CMyAutoPtr(T *p = NULL) : _p(p) {} CMyAutoPtr(CMyAutoPtr& p): _p(p.release()) {} CMyAutoPtr& operator=(CMyAutoPtr& p) { @@ -21,10 +21,10 @@ T* release() { T *tmp = _p; - _p = 0; + _p = NULL; return tmp; } - void reset(T* p = 0) + void reset(T* p = NULL) { if (p != _p) delete _p; diff -Nru 7zip-22.01+dfsg/CPP/Common/C_FileIO.h 7zip-23.01+dfsg/CPP/Common/C_FileIO.h --- 7zip-22.01+dfsg/CPP/Common/C_FileIO.h 2020-12-13 17:15:43.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/C_FileIO.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,6 +1,6 @@ // Common/C_FileIO.h -#ifndef __COMMON_C_FILEIO_H -#define __COMMON_C_FILEIO_H +#ifndef ZIP7_INC_COMMON_C_FILEIO_H +#define ZIP7_INC_COMMON_C_FILEIO_H #endif diff -Nru 7zip-22.01+dfsg/CPP/Common/CksumReg.cpp 7zip-23.01+dfsg/CPP/Common/CksumReg.cpp --- 7zip-22.01+dfsg/CPP/Common/CksumReg.cpp 2021-10-21 14:48:45.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/CksumReg.cpp 2023-03-24 11:00:00.000000000 +0000 @@ -7,35 +7,30 @@ #include "../Common/MyCom.h" #include "../7zip/Common/RegisterCodec.h" - #include "../7zip/Compress/BZip2Crc.h" -class CCksumHasher: - public IHasher, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CCksumHasher + , IHasher +) CBZip2Crc _crc; UInt64 _size; - Byte mtDummy[1 << 7]; - public: + // Byte _mtDummy[1 << 7]; CCksumHasher() { _crc.Init(0); _size = 0; } - - MY_UNKNOWN_IMP1(IHasher) - INTERFACE_IHasher(;) }; -STDMETHODIMP_(void) CCksumHasher::Init() throw() +Z7_COM7F_IMF2(void, CCksumHasher::Init()) { _crc.Init(0); _size = 0; } -STDMETHODIMP_(void) CCksumHasher::Update(const void *data, UInt32 size) throw() +Z7_COM7F_IMF2(void, CCksumHasher::Update(const void *data, UInt32 size)) { _size += size; CBZip2Crc crc = _crc; @@ -44,7 +39,7 @@ _crc = crc; } -STDMETHODIMP_(void) CCksumHasher::Final(Byte *digest) throw() +Z7_COM7F_IMF2(void, CCksumHasher::Final(Byte *digest)) { UInt64 size = _size; CBZip2Crc crc = _crc; @@ -54,7 +49,7 @@ size >>= 8; } const UInt32 val = crc.GetDigest(); - SetUi32(digest, val); + SetUi32(digest, val) } REGISTER_HASHER(CCksumHasher, 0x203, "CKSUM", 4) diff -Nru 7zip-22.01+dfsg/CPP/Common/CommandLineParser.h 7zip-23.01+dfsg/CPP/Common/CommandLineParser.h --- 7zip-22.01+dfsg/CPP/Common/CommandLineParser.h 2021-01-21 12:40:25.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/CommandLineParser.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Common/CommandLineParser.h -#ifndef __COMMON_COMMAND_LINE_PARSER_H -#define __COMMON_COMMAND_LINE_PARSER_H +#ifndef ZIP7_INC_COMMON_COMMAND_LINE_PARSER_H +#define ZIP7_INC_COMMON_COMMAND_LINE_PARSER_H #include "MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/Common/Common.h 7zip-23.01+dfsg/CPP/Common/Common.h --- 7zip-22.01+dfsg/CPP/Common/Common.h 2022-01-06 19:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/Common.h 2023-05-06 05:00:00.000000000 +0000 @@ -1,7 +1,13 @@ // Common.h -#ifndef __COMMON_COMMON_H -#define __COMMON_COMMON_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif + +#ifndef ZIP7_INC_COMMON_H +#define ZIP7_INC_COMMON_H + +#include "../../C/Compiler.h" /* This file is included to all cpp files in 7-Zip. @@ -16,42 +22,292 @@ you can change this h file or h files included in this file. */ -// compiler pragmas to disable some warnings -#include "../../C/Compiler.h" +#ifdef _MSC_VER + #pragma warning(disable : 4710) // function not inlined + // 'CUncopyable::CUncopyable': + #pragma warning(disable : 4514) // unreferenced inline function has been removed + #if _MSC_VER < 1300 + #pragma warning(disable : 4702) // unreachable code + #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 _MSC_VER < 1400 + #pragma warning(disable : 4511) // copy constructor could not be generated // #pragma warning(disable : 4512) // assignment operator could not be generated + #pragma warning(disable : 4512) // assignment operator could not be generated + #endif + #if _MSC_VER > 1400 && _MSC_VER <= 1900 + // #pragma warning(disable : 4996) + // strcat: This function or variable may be unsafe + // GetVersion was declared deprecated + #endif -// it's or code that defines windows things, if it's not _WIN32 -#include "MyWindows.h" +#if _MSC_VER > 1200 +// -Wall warnings -// NewHandler.h and NewHandler.cpp redefine operator new() to throw exceptions, if compiled with old MSVC compilers -#include "NewHandler.h" +#if _MSC_VER <= 1600 +#pragma warning(disable : 4917) // 'OLE_HANDLE' : a GUID can only be associated with a class, interface or namespace +#endif + +// #pragma warning(disable : 4061) // enumerator '' in switch of enum '' is not explicitly handled by a case label +// #pragma warning(disable : 4266) // no override available for virtual member function from base ''; function is hidden +#pragma warning(disable : 4625) // copy constructor was implicitly defined as deleted +#pragma warning(disable : 4626) // assignment operator was implicitly defined as deleted +#if _MSC_VER >= 1600 && _MSC_VER < 1920 +#pragma warning(disable : 4571) // Informational: catch(...) semantics changed since Visual C++ 7.1; structured exceptions (SEH) are no longer caught +#endif +#if _MSC_VER >= 1600 +#pragma warning(disable : 4365) // 'initializing' : conversion from 'int' to 'unsigned int', signed / unsigned mismatch +#endif +#if _MSC_VER < 1800 +// we disable the warning, if we don't use 'final' in class +#pragma warning(disable : 4265) // class has virtual functions, but destructor is not virtual +#endif + +#if _MSC_VER >= 1900 +#pragma warning(disable : 5026) // move constructor was implicitly defined as deleted +#pragma warning(disable : 5027) // move assignment operator was implicitly defined as deleted +#endif +#if _MSC_VER >= 1912 +#pragma warning(disable : 5039) // pointer or reference to potentially throwing function passed to 'extern "C"' function under - EHc.Undefined behavior may occur if this function throws an exception. +#endif +#if _MSC_VER >= 1925 +// #pragma warning(disable : 5204) // 'ISequentialInStream' : class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly +#endif +#if _MSC_VER >= 1934 +// #pragma warning(disable : 5264) // const variable is not used +#endif + +#endif // _MSC_VER > 1200 +#endif // _MSC_VER + + +#if defined(_MSC_VER) // && !defined(__clang__) +#define Z7_DECLSPEC_NOTHROW __declspec(nothrow) +#elif defined(__clang__) || defined(__GNUC__) +#define Z7_DECLSPEC_NOTHROW __attribute__((nothrow)) +#else +#define Z7_DECLSPEC_NOTHROW +#endif + +/* +#if defined (_MSC_VER) && _MSC_VER >= 1900 \ + || defined(__clang__) && __clang_major__ >= 6 \ + || defined(__GNUC__) && __GNUC__ >= 6 + #define Z7_noexcept noexcept +#else + #define Z7_noexcept throw() +#endif +*/ + + +#if defined(__clang__) +// noexcept, final, = delete +#pragma GCC diagnostic ignored "-Wc++98-compat" +#if __clang_major__ >= 4 +// throw() dynamic exception specifications are deprecated +#pragma GCC diagnostic ignored "-Wdeprecated-dynamic-exception-spec" +#endif +#pragma GCC diagnostic ignored "-Wold-style-cast" +#pragma GCC diagnostic ignored "-Wglobal-constructors" +#pragma GCC diagnostic ignored "-Wexit-time-destructors" + +// #pragma GCC diagnostic ignored "-Wunused-private-field" +// #pragma GCC diagnostic ignored "-Wnonportable-system-include-path" +// #pragma GCC diagnostic ignored "-Wsuggest-override" +// #pragma GCC diagnostic ignored "-Wsign-conversion" +// #pragma GCC diagnostic ignored "-Winconsistent-missing-override" +// #pragma GCC diagnostic ignored "-Wsuggest-destructor-override" +// #pragma GCC diagnostic ignored "-Wnon-virtual-dtor" +// #pragma GCC diagnostic ignored "-Wdeprecated-copy-with-user-provided-dtor" +// #pragma GCC diagnostic ignored "-Wdeprecated-copy-dtor" +// #ifndef _WIN32 +// #pragma GCC diagnostic ignored "-Wweak-vtables" +// #endif +/* +#if defined(Z7_GCC_VERSION) && (Z7_GCC_VERSION >= 40400) \ + || defined(Z7_CLANG_VERSION) && (Z7_CLANG_VERSION >= 30000) +// enumeration values not explicitly handled in switch +#pragma GCC diagnostic ignored "-Wswitch-enum" +#endif +*/ +#endif // __clang__ -#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#ifdef __GNUC__ +// #pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor" +#endif /* There is BUG in MSVC 6.0 compiler for operator new[]: It doesn't check overflow, when it calculates size in bytes for allocated array. - So we can use MY_ARRAY_NEW macro instead of new[] operator. */ + So we can use Z7_ARRAY_NEW macro instead of new[] operator. */ #if defined(_MSC_VER) && (_MSC_VER == 1200) && !defined(_WIN64) - #define MY_ARRAY_NEW(p, T, size) p = new T[((size) > (unsigned)0xFFFFFFFF / sizeof(T)) ? (unsigned)0xFFFFFFFF / sizeof(T) : (size)]; + #define Z7_ARRAY_NEW(p, T, size) p = new T[((size) > (unsigned)0xFFFFFFFF / sizeof(T)) ? (unsigned)0xFFFFFFFF / sizeof(T) : (size)]; #else - #define MY_ARRAY_NEW(p, T, size) p = new T[size]; + #define Z7_ARRAY_NEW(p, T, size) p = new T[size]; #endif #if (defined(__GNUC__) && (__GNUC__ >= 8)) - #define MY_ATTR_NORETURN __attribute__((noreturn)) + #define Z7_ATTR_NORETURN __attribute__((noreturn)) #elif (defined(__clang__) && (__clang_major__ >= 3)) #if __has_feature(cxx_attributes) - #define MY_ATTR_NORETURN [[noreturn]] + #define Z7_ATTR_NORETURN [[noreturn]] #else - #define MY_ATTR_NORETURN __attribute__ ((noreturn)) + #define Z7_ATTR_NORETURN __attribute__((noreturn)) #endif #elif (defined(_MSC_VER) && (_MSC_VER >= 1900)) - #define MY_ATTR_NORETURN [[noreturn]] + #define Z7_ATTR_NORETURN [[noreturn]] +#else + #define Z7_ATTR_NORETURN +#endif + + +// final in "GCC 4.7.0" +// In C++98 and C++03 code the alternative spelling __final can be used instead (this is a GCC extension.) + +#if defined (__cplusplus) && __cplusplus >= 201103L \ + || defined(_MSC_VER) && _MSC_VER >= 1800 \ + || defined(__clang__) && __clang_major__ >= 4 \ + /* || defined(__GNUC__) && __GNUC__ >= 9 */ + #define Z7_final final + #if defined(__clang__) && __cplusplus < 201103L + #pragma GCC diagnostic ignored "-Wc++11-extensions" + #endif +#elif defined (__cplusplus) && __cplusplus >= 199711L \ + && defined(__GNUC__) && __GNUC__ >= 4 && !defined(__clang__) + #define Z7_final __final #else - #define MY_ATTR_NORETURN + #define Z7_final + #if defined(__clang__) && __clang_major__ >= 4 \ + || defined(__GNUC__) && __GNUC__ >= 4 + #pragma GCC diagnostic ignored "-Wnon-virtual-dtor" + #pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor" + #endif #endif +#define Z7_class_final(c) class c Z7_final + + +#if defined (__cplusplus) && __cplusplus >= 201103L \ + || (defined(_MSC_VER) && _MSC_VER >= 1800) + #define Z7_CPP_IS_SUPPORTED_default + #define Z7_eq_delete = delete + // #define Z7_DECL_DEFAULT_COPY_CONSTRUCTOR_IF_SUPPORTED(c) c(const c& k) = default; +#else + #define Z7_eq_delete + // #define Z7_DECL_DEFAULT_COPY_CONSTRUCTOR_IF_SUPPORTED(c) #endif + + +#if defined(__cplusplus) && (__cplusplus >= 201103L) \ + || defined(_MSC_VER) && (_MSC_VER >= 1400) /* && (_MSC_VER != 1600) */ \ + || defined(__clang__) && __clang_major__ >= 4 + #if defined(_MSC_VER) && (_MSC_VER == 1600) /* && (_MSC_VER != 1600) */ + #pragma warning(disable : 4481) // nonstandard extension used: override specifier 'override' + #define Z7_DESTRUCTOR_override + #else + #define Z7_DESTRUCTOR_override override + #endif + #define Z7_override override +#else + #define Z7_override + #define Z7_DESTRUCTOR_override +#endif + + + +#define Z7_CLASS_NO_COPY(cls) \ + private: \ + cls(const cls &) Z7_eq_delete; \ + cls &operator=(const cls &) Z7_eq_delete; + +class CUncopyable +{ +protected: + CUncopyable() {} // allow constructor + // ~CUncopyable() {} + Z7_CLASS_NO_COPY(CUncopyable) +}; + +#define MY_UNCOPYABLE :private CUncopyable +// #define MY_UNCOPYABLE + + +typedef void (*Z7_void_Function)(void); + +#if defined(__clang__) || defined(__GNUC__) +#define Z7_CAST_FUNC(t, e) reinterpret_cast(reinterpret_cast(e)) +#else +#define Z7_CAST_FUNC(t, e) reinterpret_cast(reinterpret_cast(e)) +// #define Z7_CAST_FUNC(t, e) reinterpret_cast(e) +#endif + +#define Z7_GET_PROC_ADDRESS(func_type, hmodule, func_name) \ + Z7_CAST_FUNC(func_type, GetProcAddress(hmodule, func_name)) + +// || defined(__clang__) +// || defined(__GNUC__) + +#if defined(_MSC_VER) && (_MSC_VER >= 1400) +#define Z7_DECLSPEC_NOVTABLE __declspec(novtable) +#else +#define Z7_DECLSPEC_NOVTABLE +#endif + +#ifdef __clang__ +#define Z7_PURE_INTERFACES_BEGIN \ +_Pragma("GCC diagnostic push") \ +_Pragma("GCC diagnostic ignored \"-Wnon-virtual-dtor\"") +_Pragma("GCC diagnostic ignored \"-Wweak-vtables\"") +#define Z7_PURE_INTERFACES_END \ +_Pragma("GCC diagnostic pop") +#else +#define Z7_PURE_INTERFACES_BEGIN +#define Z7_PURE_INTERFACES_END +#endif + +// NewHandler.h and NewHandler.cpp redefine operator new() to throw exceptions, if compiled with old MSVC compilers +#include "NewHandler.h" + +/* +// #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#ifndef ARRAY_SIZE +#define ARRAY_SIZE(a) Z7_ARRAY_SIZE(a) +#endif +*/ + +#endif // ZIP7_INC_COMMON_H + + + +// #define Z7_REDEFINE_NULL + +#if defined(Z7_REDEFINE_NULL) /* && (!defined(__clang__) || defined(_MSC_VER)) */ + +// NULL is defined in +#include +#undef NULL + +#ifdef __cplusplus + #if defined (__cplusplus) && __cplusplus >= 201103L \ + || (defined(_MSC_VER) && _MSC_VER >= 1800) + #define NULL nullptr + #else + #define NULL 0 + #endif +#else + #define NULL ((void *)0) +#endif + +#else // Z7_REDEFINE_NULL + +#if defined(__clang__) && __clang_major__ >= 5 +#pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant" +#endif + +#endif // Z7_REDEFINE_NULL + +// for precompiler: +#include "MyWindows.h" diff -Nru 7zip-22.01+dfsg/CPP/Common/ComTry.h 7zip-23.01+dfsg/CPP/Common/ComTry.h --- 7zip-22.01+dfsg/CPP/Common/ComTry.h 2017-01-03 11:06:43.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/ComTry.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // ComTry.h -#ifndef __COM_TRY_H -#define __COM_TRY_H +#ifndef ZIP7_INC_COM_TRY_H +#define ZIP7_INC_COM_TRY_H #include "MyWindows.h" // #include "Exception.h" diff -Nru 7zip-22.01+dfsg/CPP/Common/CrcReg.cpp 7zip-23.01+dfsg/CPP/Common/CrcReg.cpp --- 7zip-22.01+dfsg/CPP/Common/CrcReg.cpp 2020-12-29 16:41:51.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/CrcReg.cpp 2023-03-16 20:00:00.000000000 +0000 @@ -11,42 +11,39 @@ EXTERN_C_BEGIN -typedef UInt32 (MY_FAST_CALL *CRC_FUNC)(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); extern CRC_FUNC g_CrcUpdate; -extern CRC_FUNC g_CrcUpdateT4; +// extern CRC_FUNC g_CrcUpdateT4; extern CRC_FUNC g_CrcUpdateT8; extern CRC_FUNC g_CrcUpdateT0_32; extern CRC_FUNC g_CrcUpdateT0_64; EXTERN_C_END -class CCrcHasher: - public IHasher, - public ICompressSetCoderProperties, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_2( + CCrcHasher + , IHasher + , ICompressSetCoderProperties +) UInt32 _crc; CRC_FUNC _updateFunc; - Byte mtDummy[1 << 7]; - + + Z7_CLASS_NO_COPY(CCrcHasher) + bool SetFunctions(UInt32 tSize); public: - CCrcHasher(): _crc(CRC_INIT_VAL) { SetFunctions(0); } + Byte _mtDummy[1 << 7]; // it's public to eliminate clang warning: unused private field - MY_UNKNOWN_IMP2(IHasher, ICompressSetCoderProperties) - INTERFACE_IHasher(;) - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); + CCrcHasher(): _crc(CRC_INIT_VAL) { SetFunctions(0); } }; bool CCrcHasher::SetFunctions(UInt32 tSize) { CRC_FUNC f = NULL; if (tSize == 0) f = g_CrcUpdate; - else if (tSize == 1) f = CrcUpdateT1; - else if (tSize == 4) f = g_CrcUpdateT4; + // else if (tSize == 1) f = CrcUpdateT1; + // else if (tSize == 4) f = g_CrcUpdateT4; else if (tSize == 8) f = g_CrcUpdateT8; else if (tSize == 32) f = g_CrcUpdateT0_32; else if (tSize == 64) f = g_CrcUpdateT0_64; @@ -60,13 +57,13 @@ return true; } -STDMETHODIMP CCrcHasher::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps) +Z7_COM7F_IMF(CCrcHasher::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps)) { for (UInt32 i = 0; i < numProps; i++) { - const PROPVARIANT &prop = coderProps[i]; if (propIDs[i] == NCoderPropID::kDefaultProp) { + const PROPVARIANT &prop = coderProps[i]; if (prop.vt != VT_UI4) return E_INVALIDARG; if (!SetFunctions(prop.ulVal)) @@ -76,20 +73,20 @@ return S_OK; } -STDMETHODIMP_(void) CCrcHasher::Init() throw() +Z7_COM7F_IMF2(void, CCrcHasher::Init()) { _crc = CRC_INIT_VAL; } -STDMETHODIMP_(void) CCrcHasher::Update(const void *data, UInt32 size) throw() +Z7_COM7F_IMF2(void, CCrcHasher::Update(const void *data, UInt32 size)) { _crc = _updateFunc(_crc, data, size, g_CrcTable); } -STDMETHODIMP_(void) CCrcHasher::Final(Byte *digest) throw() +Z7_COM7F_IMF2(void, CCrcHasher::Final(Byte *digest)) { - UInt32 val = CRC_GET_DIGEST(_crc); - SetUi32(digest, val); + const UInt32 val = CRC_GET_DIGEST(_crc); + SetUi32(digest, val) } REGISTER_HASHER(CCrcHasher, 0x1, "CRC32", 4) diff -Nru 7zip-22.01+dfsg/CPP/Common/Defs.h 7zip-23.01+dfsg/CPP/Common/Defs.h --- 7zip-22.01+dfsg/CPP/Common/Defs.h 2021-01-24 18:00:05.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/Defs.h 2023-03-24 09:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Common/Defs.h -#ifndef __COMMON_DEFS_H -#define __COMMON_DEFS_H +#ifndef ZIP7_INC_COMMON_DEFS_H +#define ZIP7_INC_COMMON_DEFS_H template inline T MyMin(T a, T b) { return a < b ? a : b; } template inline T MyMax(T a, T b) { return a > b ? a : b; } @@ -10,7 +10,7 @@ { return a == b ? 0 : (a < b ? -1 : 1); } inline int BoolToInt(bool v) { return (v ? 1 : 0); } -inline unsigned BoolToUInt(bool v) { return (v ? (unsigned)1 : (unsigned)0); } +inline unsigned BoolToUInt(bool v) { return (v ? 1u : 0u); } inline bool IntToBool(int v) { return (v != 0); } #endif diff -Nru 7zip-22.01+dfsg/CPP/Common/DynamicBuffer.h 7zip-23.01+dfsg/CPP/Common/DynamicBuffer.h --- 7zip-22.01+dfsg/CPP/Common/DynamicBuffer.h 2020-09-29 15:54:03.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/DynamicBuffer.h 2023-03-22 19:00:00.000000000 +0000 @@ -1,7 +1,11 @@ // Common/DynamicBuffer.h -#ifndef __COMMON_DYNAMIC_BUFFER_H -#define __COMMON_DYNAMIC_BUFFER_H +#ifndef ZIP7_INC_COMMON_DYNAMIC_BUFFER_H +#define ZIP7_INC_COMMON_DYNAMIC_BUFFER_H + +#include + +#include "Common.h" template class CDynamicBuffer { @@ -34,7 +38,7 @@ } public: - CDynamicBuffer(): _items(0), _size(0), _pos(0) {} + CDynamicBuffer(): _items(NULL), _size(0), _pos(0) {} // operator T *() { return _items; } operator const T *() const { return _items; } ~CDynamicBuffer() { delete []_items; } diff -Nru 7zip-22.01+dfsg/CPP/Common/DynLimBuf.cpp 7zip-23.01+dfsg/CPP/Common/DynLimBuf.cpp --- 7zip-22.01+dfsg/CPP/Common/DynLimBuf.cpp 2021-01-24 13:18:36.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/DynLimBuf.cpp 2022-12-15 20:00:00.000000000 +0000 @@ -7,7 +7,7 @@ CDynLimBuf::CDynLimBuf(size_t limit) throw() { - _chars = 0; + _chars = NULL; _pos = 0; _size = 0; _sizeLimit = limit; diff -Nru 7zip-22.01+dfsg/CPP/Common/DynLimBuf.h 7zip-23.01+dfsg/CPP/Common/DynLimBuf.h --- 7zip-22.01+dfsg/CPP/Common/DynLimBuf.h 2016-10-15 10:49:14.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/DynLimBuf.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Common/DynLimBuf.h -#ifndef __COMMON_DYN_LIM_BUF_H -#define __COMMON_DYN_LIM_BUF_H +#ifndef ZIP7_INC_COMMON_DYN_LIM_BUF_H +#define ZIP7_INC_COMMON_DYN_LIM_BUF_H #include diff -Nru 7zip-22.01+dfsg/CPP/Common/IntToString.cpp 7zip-23.01+dfsg/CPP/Common/IntToString.cpp --- 7zip-22.01+dfsg/CPP/Common/IntToString.cpp 2021-02-09 19:48:14.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/IntToString.cpp 2022-12-19 22:00:00.000000000 +0000 @@ -16,7 +16,7 @@ char * ConvertUInt32ToString(UInt32 val, char *s) throw() { - CONVERT_INT_TO_STR(char, 16); + CONVERT_INT_TO_STR(char, 16) } char * ConvertUInt64ToString(UInt64 val, char *s) throw() @@ -25,7 +25,7 @@ { return ConvertUInt32ToString((UInt32)val, s); } - CONVERT_INT_TO_STR(char, 24); + CONVERT_INT_TO_STR(char, 24) } void ConvertUInt64ToOct(UInt64 val, char *s) throw() @@ -102,7 +102,7 @@ { unsigned t = val & 0xF; val >>= 4; - s[i] = GET_HEX_CHAR(t);; + s[i] = GET_HEX_CHAR(t); } } @@ -121,7 +121,7 @@ wchar_t * ConvertUInt32ToString(UInt32 val, wchar_t *s) throw() { - CONVERT_INT_TO_STR(wchar_t, 16); + CONVERT_INT_TO_STR(wchar_t, 16) } wchar_t * ConvertUInt64ToString(UInt64 val, wchar_t *s) throw() @@ -130,7 +130,7 @@ { return ConvertUInt32ToString((UInt32)val, s); } - CONVERT_INT_TO_STR(wchar_t, 24); + CONVERT_INT_TO_STR(wchar_t, 24) } void ConvertInt64ToString(Int64 val, char *s) throw() diff -Nru 7zip-22.01+dfsg/CPP/Common/IntToString.h 7zip-23.01+dfsg/CPP/Common/IntToString.h --- 7zip-22.01+dfsg/CPP/Common/IntToString.h 2019-07-02 14:09:39.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/IntToString.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Common/IntToString.h -#ifndef __COMMON_INT_TO_STRING_H -#define __COMMON_INT_TO_STRING_H +#ifndef ZIP7_INC_COMMON_INT_TO_STRING_H +#define ZIP7_INC_COMMON_INT_TO_STRING_H #include "MyTypes.h" diff -Nru 7zip-22.01+dfsg/CPP/Common/Lang.cpp 7zip-23.01+dfsg/CPP/Common/Lang.cpp --- 7zip-22.01+dfsg/CPP/Common/Lang.cpp 2021-03-06 09:38:03.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/Lang.cpp 2023-05-16 10:00:00.000000000 +0000 @@ -12,85 +12,95 @@ { _ids.Clear(); _offsets.Clear(); + Comments.Clear(); delete []_text; - _text = 0; + _text = NULL; } -static const char * const kLangSignature = ";!@Lang2@!UTF-8!"; +static const char * const kLangSignature = ";!@Lang2@!UTF-8!\n"; bool CLang::OpenFromString(const AString &s2) { - UString s; - if (!ConvertUTF8ToUnicode(s2, s)) + UString su; + if (!ConvertUTF8ToUnicode(s2, su)) return false; - unsigned i = 0; - if (s.IsEmpty()) + if (su.IsEmpty()) return false; - if (s[0] == 0xFEFF) - i++; - - for (const char *p = kLangSignature;; i++) + const wchar_t *s = su; + const wchar_t *sLim = s + su.Len(); + if (*s == 0xFEFF) + s++; + for (const char *p = kLangSignature;; s++) { - Byte c = (Byte)(*p++); + const Byte c = (Byte)(*p++); if (c == 0) break; - if (s[i] != c) + if (*s != c) return false; } - _text = new wchar_t[s.Len() - i + 1]; - wchar_t *text = _text; + wchar_t *text = new wchar_t[(size_t)(sLim - s) + 1]; + _text = text; - Int32 id = -100; - UInt32 pos = 0; + UString comment; + Int32 id = -1024; + unsigned pos = 0; - while (i < s.Len()) + while (s != sLim) { - unsigned start = pos; + const unsigned start = pos; do { - wchar_t c = s[i++]; + wchar_t c = *s++; if (c == '\n') break; if (c == '\\') { - if (i == s.Len()) + if (s == sLim) return false; - c = s[i++]; + c = *s++; switch (c) { case '\n': return false; case 'n': c = '\n'; break; case 't': c = '\t'; break; - case '\\': c = '\\'; break; + case '\\': /* c = '\\'; */ break; default: text[pos++] = L'\\'; break; } } text[pos++] = c; } - while (i < s.Len()); + while (s != sLim); { unsigned j = start; for (; j < pos; j++) - if (text[j] != ' ') + if (text[j] != ' ' && text[j] != '\t') break; if (j == pos) { id++; + pos = start; continue; } } + + // start != pos + text[pos++] = 0; + if (text[start] == ';') { - pos = start; + comment = text + start; + comment.TrimRight(); + if (comment.Len() != 1) + Comments.Add(comment); id++; + pos = start; continue; } - - text[pos++] = 0; + const wchar_t *end; - UInt32 id32 = ConvertStringToUInt32(text + start, &end); + const UInt32 id32 = ConvertStringToUInt32(text + start, &end); if (*end == 0) { if (id32 > ((UInt32)1 << 30) || (Int32)id32 < id) @@ -134,7 +144,7 @@ char *p2 = p; for (unsigned i = 0; i < len; i++) { - char c = p[i]; + const char c = p[i]; if (c == 0) break; if (c != 0x0D) @@ -156,7 +166,7 @@ const wchar_t *CLang::Get(UInt32 id) const throw() { - int index = _ids.FindInSorted(id); + const int index = _ids.FindInSorted(id); if (index < 0) return NULL; return _text + (size_t)_offsets[(unsigned)index]; diff -Nru 7zip-22.01+dfsg/CPP/Common/Lang.h 7zip-23.01+dfsg/CPP/Common/Lang.h --- 7zip-22.01+dfsg/CPP/Common/Lang.h 2017-02-08 17:07:20.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/Lang.h 2023-05-16 10:00:00.000000000 +0000 @@ -1,23 +1,30 @@ // Common/Lang.h -#ifndef __COMMON_LANG_H -#define __COMMON_LANG_H +#ifndef ZIP7_INC_COMMON_LANG_H +#define ZIP7_INC_COMMON_LANG_H #include "MyString.h" class CLang { wchar_t *_text; - CRecordVector _ids; - CRecordVector _offsets; bool OpenFromString(const AString &s); public: - CLang(): _text(0) {} + CRecordVector _ids; + CRecordVector _offsets; + UStringVector Comments; + + CLang(): _text(NULL) {} ~CLang() { Clear(); } bool Open(CFSTR fileName, const char *id); void Clear() throw(); + bool IsEmpty() const { return _ids.IsEmpty(); } const wchar_t *Get(UInt32 id) const throw(); + const wchar_t *Get_by_index(unsigned index) const throw() + { + return _text + (size_t)_offsets[index]; + } }; #endif diff -Nru 7zip-22.01+dfsg/CPP/Common/ListFileUtils.cpp 7zip-23.01+dfsg/CPP/Common/ListFileUtils.cpp --- 7zip-22.01+dfsg/CPP/Common/ListFileUtils.cpp 2021-04-24 11:07:17.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/ListFileUtils.cpp 2023-02-01 17:00:00.000000000 +0000 @@ -66,7 +66,7 @@ if (fileSize >= ((UInt32)1 << 31) - 32) return false; UString u; - if (codePage == MY__CP_UTF16 || codePage == MY__CP_UTF16BE) + if (codePage == Z7_WIN_CP_UTF16 || codePage == Z7_WIN_CP_UTF16BE) { if ((fileSize & 1) != 0) return false; @@ -78,7 +78,7 @@ file.Close(); const unsigned num = (unsigned)fileSize / 2; wchar_t *p = u.GetBuf(num); - if (codePage == MY__CP_UTF16) + if (codePage == Z7_WIN_CP_UTF16) for (unsigned i = 0; i < num; i++) { wchar_t c = GetUi16(buf + (size_t)i * 2); diff -Nru 7zip-22.01+dfsg/CPP/Common/ListFileUtils.h 7zip-23.01+dfsg/CPP/Common/ListFileUtils.h --- 7zip-22.01+dfsg/CPP/Common/ListFileUtils.h 2018-08-04 13:04:27.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/ListFileUtils.h 2023-02-01 17:00:00.000000000 +0000 @@ -1,13 +1,13 @@ // Common/ListFileUtils.h -#ifndef __COMMON_LIST_FILE_UTILS_H -#define __COMMON_LIST_FILE_UTILS_H +#ifndef ZIP7_INC_COMMON_LIST_FILE_UTILS_H +#define ZIP7_INC_COMMON_LIST_FILE_UTILS_H #include "MyString.h" #include "MyTypes.h" -#define MY__CP_UTF16 1200 -#define MY__CP_UTF16BE 1201 +#define Z7_WIN_CP_UTF16 1200 +#define Z7_WIN_CP_UTF16BE 1201 // bool ReadNamesFromListFile(CFSTR fileName, UStringVector &strings, UINT codePage = CP_OEMCP); diff -Nru 7zip-22.01+dfsg/CPP/Common/MyBuffer2.h 7zip-23.01+dfsg/CPP/Common/MyBuffer2.h --- 7zip-22.01+dfsg/CPP/Common/MyBuffer2.h 2021-07-15 10:33:32.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyBuffer2.h 2023-03-15 16:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Common/MyBuffer2.h -#ifndef __COMMON_MY_BUFFER2_H -#define __COMMON_MY_BUFFER2_H +#ifndef ZIP7_INC_COMMON_MY_BUFFER2_H +#define ZIP7_INC_COMMON_MY_BUFFER2_H #include "../../C/Alloc.h" @@ -12,7 +12,7 @@ Byte *_data; size_t _size; - CLASS_NO_COPY(CMidBuffer) + Z7_CLASS_NO_COPY(CMidBuffer) public: CMidBuffer(): _data(NULL), _size(0) {} @@ -56,12 +56,37 @@ }; +class CAlignedBuffer1 +{ + Byte *_data; + + Z7_CLASS_NO_COPY(CAlignedBuffer1) + +public: + ~CAlignedBuffer1() + { + ISzAlloc_Free(&g_AlignedAlloc, _data); + } + + CAlignedBuffer1(size_t size) + { + _data = NULL; + _data = (Byte *)ISzAlloc_Alloc(&g_AlignedAlloc, size); + if (!_data) + throw 1; + } + + operator Byte *() { return _data; } + operator const Byte *() const { return _data; } +}; + + class CAlignedBuffer { Byte *_data; size_t _size; - CLASS_NO_COPY(CAlignedBuffer) + Z7_CLASS_NO_COPY(CAlignedBuffer) public: CAlignedBuffer(): _data(NULL), _size(0) {} diff -Nru 7zip-22.01+dfsg/CPP/Common/MyBuffer.h 7zip-23.01+dfsg/CPP/Common/MyBuffer.h --- 7zip-22.01+dfsg/CPP/Common/MyBuffer.h 2019-10-11 10:56:10.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyBuffer.h 2023-03-22 18:00:00.000000000 +0000 @@ -1,13 +1,15 @@ // Common/MyBuffer.h -#ifndef __COMMON_MY_BUFFER_H -#define __COMMON_MY_BUFFER_H +#ifndef ZIP7_INC_COMMON_MY_BUFFER_H +#define ZIP7_INC_COMMON_MY_BUFFER_H + +#include #include "Defs.h" #include "MyTypes.h" /* 7-Zip now uses CBuffer only as CByteBuffer. - So there is no need to use MY_ARRAY_NEW macro in CBuffer code. */ + So there is no need to use Z7_ARRAY_NEW macro in CBuffer code. */ template class CBuffer { @@ -20,16 +22,23 @@ if (_items) { delete []_items; - _items = 0; + _items = NULL; } _size = 0; } - CBuffer(): _items(0), _size(0) {}; - CBuffer(size_t size): _items(0), _size(0) { _items = new T[size]; _size = size; } - CBuffer(const CBuffer &buffer): _items(0), _size(0) + CBuffer(): _items(NULL), _size(0) {} + CBuffer(size_t size): _items(NULL), _size(0) + { + if (size != 0) + { + _items = new T[size]; + _size = size; + } + } + CBuffer(const CBuffer &buffer): _items(NULL), _size(0) { - size_t size = buffer._size; + const size_t size = buffer._size; if (size != 0) { _items = new T[size]; @@ -136,7 +145,7 @@ class CByteBuffer_Wipe: public CByteBuffer { - CLASS_NO_COPY(CByteBuffer_Wipe) + Z7_CLASS_NO_COPY(CByteBuffer_Wipe) public: // CByteBuffer_Wipe(): CBuffer() {} CByteBuffer_Wipe(size_t size): CBuffer(size) {} @@ -157,17 +166,17 @@ void Free() { delete []_items; - _items = 0; + _items = NULL; } - CObjArray(size_t size): _items(0) + CObjArray(size_t size): _items(NULL) { if (size != 0) { - MY_ARRAY_NEW(_items, T, size) + Z7_ARRAY_NEW(_items, T, size) // _items = new T[size]; } } - CObjArray(): _items(0) {}; + CObjArray(): _items(NULL) {} ~CObjArray() { delete []_items; } operator T *() { return _items; } @@ -176,8 +185,8 @@ void Alloc(size_t newSize) { delete []_items; - _items = 0; - MY_ARRAY_NEW(_items, T, newSize) + _items = NULL; + Z7_ARRAY_NEW(_items, T, newSize) // _items = new T[newSize]; } }; @@ -201,12 +210,12 @@ void Free() { delete []_items; - _items = 0; + _items = NULL; _size = 0; } - CObjArray2(): _items(0), _size(0) {}; + CObjArray2(): _items(NULL), _size(0) {} /* - CObjArray2(const CObjArray2 &buffer): _items(0), _size(0) + CObjArray2(const CObjArray2 &buffer): _items(NULL), _size(0) { size_t newSize = buffer._size; if (newSize != 0) @@ -221,7 +230,7 @@ } */ /* - CObjArray2(size_t size): _items(0), _size(0) + CObjArray2(size_t size): _items(NULL), _size(0) { if (size != 0) { @@ -247,7 +256,7 @@ T *newBuffer = NULL; if (size != 0) { - MY_ARRAY_NEW(newBuffer, T, size) + Z7_ARRAY_NEW(newBuffer, T, size) // newBuffer = new T[size]; } delete []_items; diff -Nru 7zip-22.01+dfsg/CPP/Common/MyCom.h 7zip-23.01+dfsg/CPP/Common/MyCom.h --- 7zip-22.01+dfsg/CPP/Common/MyCom.h 2022-03-27 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyCom.h 2023-04-01 13:00:00.000000000 +0000 @@ -1,15 +1,11 @@ // MyCom.h -#ifndef __MY_COM_H -#define __MY_COM_H +#ifndef ZIP7_INC_MY_COM_H +#define ZIP7_INC_MY_COM_H #include "MyWindows.h" #include "MyTypes.h" -#ifndef RINOK -#define RINOK(x) { HRESULT __result_ = (x); if (__result_ != S_OK) return __result_; } -#endif - template class CMyComPtr { @@ -72,6 +68,10 @@ } }; +#define Z7_DECL_CMyComPtr_QI_FROM(i, v, unk) \ + CMyComPtr v; (unk)->QueryInterface(IID_ ## i, (void **)&v); + + ////////////////////////////////////////////////////////// inline HRESULT StringToBstr(LPCOLESTR src, BSTR *bstr) @@ -83,7 +83,7 @@ class CMyComBSTR { BSTR m_str; - CLASS_NO_COPY(CMyComBSTR) + Z7_CLASS_NO_COPY(CMyComBSTR) public: CMyComBSTR(): m_str(NULL) {} ~CMyComBSTR() { ::SysFreeString(m_str); } @@ -174,7 +174,7 @@ class CMyComBSTR_Wipe: public CMyComBSTR { - CLASS_NO_COPY(CMyComBSTR_Wipe) + Z7_CLASS_NO_COPY(CMyComBSTR_Wipe) public: CMyComBSTR_Wipe(): CMyComBSTR() {} ~CMyComBSTR_Wipe() { Wipe_and_Free(); } @@ -185,123 +185,325 @@ /* If CMyUnknownImp doesn't use virtual destructor, the code size is smaller. But if some class_1 derived from CMyUnknownImp - uses MY_ADDREF_RELEASE and IUnknown::Release() + uses Z7_COM_ADDREF_RELEASE and IUnknown::Release() and some another class_2 is derived from class_1, then class_1 must use virtual destructor: virtual ~class_1(); In that case, class_1::Release() calls correct destructor of class_2. - - We use virtual ~CMyUnknownImp() to disable warning + We can use virtual ~CMyUnknownImp() to disable warning "class has virtual functions, but destructor is not virtual". - - also we can use virtual ~IUnknown() {} in MyWindows.h + Also we can use virtual ~IUnknown() {} in MyWindows.h */ class CMyUnknownImp { - CLASS_NO_COPY(CMyUnknownImp) -public: - ULONG __m_RefCount; - CMyUnknownImp(): __m_RefCount(0) {} + Z7_CLASS_NO_COPY(CMyUnknownImp) +protected: + ULONG _m_RefCount; + CMyUnknownImp(): _m_RefCount(0) {} #ifdef _WIN32 #if defined(__GNUC__) || defined(__clang__) - virtual // to disable GCC/CLANG varnings + // virtual ~CMyUnknownImp() {} // to disable GCC/CLANG varnings #endif #endif - ~CMyUnknownImp() {} }; -#define MY_QUERYINTERFACE_BEGIN STDMETHOD(QueryInterface) \ -(REFGUID iid, void **outObject) throw() { *outObject = NULL; +#define Z7_COM_QI_BEGIN \ + private: STDMETHOD(QueryInterface) (REFGUID iid, void **outObject) throw() Z7_override Z7_final \ + { *outObject = NULL; + +#define Z7_COM_QI_ENTRY(i) \ + else if (iid == IID_ ## i) \ + { i *ti = this; *outObject = ti; } +// { *outObject = (void *)(i *)this; } + +#define Z7_COM_QI_ENTRY_UNKNOWN_0 \ + if (iid == IID_IUnknown) \ + { IUnknown *tu = this; *outObject = tu; } + +#define Z7_COM_QI_ENTRY_UNKNOWN(i) \ + if (iid == IID_IUnknown) \ + { i *ti = this; IUnknown *tu = ti; *outObject = tu; } +// { *outObject = (void *)(IUnknown *)(i *)this; } + +#define Z7_COM_QI_BEGIN2(i) \ + Z7_COM_QI_BEGIN \ + Z7_COM_QI_ENTRY_UNKNOWN(i) \ + Z7_COM_QI_ENTRY(i) + +#define Z7_COM_QI_END \ + else return E_NOINTERFACE; \ + ++_m_RefCount; /* AddRef(); */ return S_OK; } + +#define Z7_COM_ADDREF_RELEASE \ + private: \ + STDMETHOD_(ULONG, AddRef)() throw() Z7_override Z7_final \ + { return ++_m_RefCount; } \ + STDMETHOD_(ULONG, Release)() throw() Z7_override Z7_final \ + { if (--_m_RefCount != 0) return _m_RefCount; delete this; return 0; } \ -#define MY_QUERYINTERFACE_ENTRY(i) else if (iid == IID_ ## i) \ - { *outObject = (void *)(i *)this; } - -#define MY_QUERYINTERFACE_ENTRY_UNKNOWN(i) if (iid == IID_IUnknown) \ - { *outObject = (void *)(IUnknown *)(i *)this; } - -#define MY_QUERYINTERFACE_BEGIN2(i) MY_QUERYINTERFACE_BEGIN \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i) \ - MY_QUERYINTERFACE_ENTRY(i) - -#define MY_QUERYINTERFACE_END else return E_NOINTERFACE; ++__m_RefCount; /* AddRef(); */ return S_OK; } - -#define MY_ADDREF_RELEASE \ -STDMETHOD_(ULONG, AddRef)() throw() { return ++__m_RefCount; } \ -STDMETHOD_(ULONG, Release)() { if (--__m_RefCount != 0) return __m_RefCount; \ - delete this; return 0; } - -#define MY_UNKNOWN_IMP_SPEC(i) \ - MY_QUERYINTERFACE_BEGIN \ +#define Z7_COM_UNKNOWN_IMP_SPEC(i) \ + Z7_COM_QI_BEGIN \ i \ - MY_QUERYINTERFACE_END \ - MY_ADDREF_RELEASE + Z7_COM_QI_END \ + Z7_COM_ADDREF_RELEASE -#define MY_UNKNOWN_IMP MY_QUERYINTERFACE_BEGIN \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(IUnknown) \ - MY_QUERYINTERFACE_END \ - MY_ADDREF_RELEASE - -#define MY_UNKNOWN_IMP1(i) MY_UNKNOWN_IMP_SPEC( \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i) \ - MY_QUERYINTERFACE_ENTRY(i) \ +#define Z7_COM_UNKNOWN_IMP_0 \ + Z7_COM_QI_BEGIN \ + Z7_COM_QI_ENTRY_UNKNOWN_0 \ + Z7_COM_QI_END \ + Z7_COM_ADDREF_RELEASE + +#define Z7_COM_UNKNOWN_IMP_1(i) \ + Z7_COM_UNKNOWN_IMP_SPEC( \ + Z7_COM_QI_ENTRY_UNKNOWN(i) \ + Z7_COM_QI_ENTRY(i) \ ) -#define MY_UNKNOWN_IMP2(i1, i2) MY_UNKNOWN_IMP_SPEC( \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ - MY_QUERYINTERFACE_ENTRY(i1) \ - MY_QUERYINTERFACE_ENTRY(i2) \ +#define Z7_COM_UNKNOWN_IMP_2(i1, i2) \ + Z7_COM_UNKNOWN_IMP_SPEC( \ + Z7_COM_QI_ENTRY_UNKNOWN(i1) \ + Z7_COM_QI_ENTRY(i1) \ + Z7_COM_QI_ENTRY(i2) \ ) -#define MY_UNKNOWN_IMP3(i1, i2, i3) MY_UNKNOWN_IMP_SPEC( \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ - MY_QUERYINTERFACE_ENTRY(i1) \ - MY_QUERYINTERFACE_ENTRY(i2) \ - MY_QUERYINTERFACE_ENTRY(i3) \ +#define Z7_COM_UNKNOWN_IMP_3(i1, i2, i3) \ + Z7_COM_UNKNOWN_IMP_SPEC( \ + Z7_COM_QI_ENTRY_UNKNOWN(i1) \ + Z7_COM_QI_ENTRY(i1) \ + Z7_COM_QI_ENTRY(i2) \ + Z7_COM_QI_ENTRY(i3) \ ) -#define MY_UNKNOWN_IMP4(i1, i2, i3, i4) MY_UNKNOWN_IMP_SPEC( \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ - MY_QUERYINTERFACE_ENTRY(i1) \ - MY_QUERYINTERFACE_ENTRY(i2) \ - MY_QUERYINTERFACE_ENTRY(i3) \ - MY_QUERYINTERFACE_ENTRY(i4) \ +#define Z7_COM_UNKNOWN_IMP_4(i1, i2, i3, i4) \ + Z7_COM_UNKNOWN_IMP_SPEC( \ + Z7_COM_QI_ENTRY_UNKNOWN(i1) \ + Z7_COM_QI_ENTRY(i1) \ + Z7_COM_QI_ENTRY(i2) \ + Z7_COM_QI_ENTRY(i3) \ + Z7_COM_QI_ENTRY(i4) \ ) -#define MY_UNKNOWN_IMP5(i1, i2, i3, i4, i5) MY_UNKNOWN_IMP_SPEC( \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ - MY_QUERYINTERFACE_ENTRY(i1) \ - MY_QUERYINTERFACE_ENTRY(i2) \ - MY_QUERYINTERFACE_ENTRY(i3) \ - MY_QUERYINTERFACE_ENTRY(i4) \ - MY_QUERYINTERFACE_ENTRY(i5) \ +#define Z7_COM_UNKNOWN_IMP_5(i1, i2, i3, i4, i5) \ + Z7_COM_UNKNOWN_IMP_SPEC( \ + Z7_COM_QI_ENTRY_UNKNOWN(i1) \ + Z7_COM_QI_ENTRY(i1) \ + Z7_COM_QI_ENTRY(i2) \ + Z7_COM_QI_ENTRY(i3) \ + Z7_COM_QI_ENTRY(i4) \ + Z7_COM_QI_ENTRY(i5) \ ) -#define MY_UNKNOWN_IMP6(i1, i2, i3, i4, i5, i6) MY_UNKNOWN_IMP_SPEC( \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ - MY_QUERYINTERFACE_ENTRY(i1) \ - MY_QUERYINTERFACE_ENTRY(i2) \ - MY_QUERYINTERFACE_ENTRY(i3) \ - MY_QUERYINTERFACE_ENTRY(i4) \ - MY_QUERYINTERFACE_ENTRY(i5) \ - MY_QUERYINTERFACE_ENTRY(i6) \ +#define Z7_COM_UNKNOWN_IMP_6(i1, i2, i3, i4, i5, i6) \ + Z7_COM_UNKNOWN_IMP_SPEC( \ + Z7_COM_QI_ENTRY_UNKNOWN(i1) \ + Z7_COM_QI_ENTRY(i1) \ + Z7_COM_QI_ENTRY(i2) \ + Z7_COM_QI_ENTRY(i3) \ + Z7_COM_QI_ENTRY(i4) \ + Z7_COM_QI_ENTRY(i5) \ + Z7_COM_QI_ENTRY(i6) \ ) -#define MY_UNKNOWN_IMP7(i1, i2, i3, i4, i5, i6, i7) MY_UNKNOWN_IMP_SPEC( \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ - MY_QUERYINTERFACE_ENTRY(i1) \ - MY_QUERYINTERFACE_ENTRY(i2) \ - MY_QUERYINTERFACE_ENTRY(i3) \ - MY_QUERYINTERFACE_ENTRY(i4) \ - MY_QUERYINTERFACE_ENTRY(i5) \ - MY_QUERYINTERFACE_ENTRY(i6) \ - MY_QUERYINTERFACE_ENTRY(i7) \ +#define Z7_COM_UNKNOWN_IMP_7(i1, i2, i3, i4, i5, i6, i7) \ + Z7_COM_UNKNOWN_IMP_SPEC( \ + Z7_COM_QI_ENTRY_UNKNOWN(i1) \ + Z7_COM_QI_ENTRY(i1) \ + Z7_COM_QI_ENTRY(i2) \ + Z7_COM_QI_ENTRY(i3) \ + Z7_COM_QI_ENTRY(i4) \ + Z7_COM_QI_ENTRY(i5) \ + Z7_COM_QI_ENTRY(i6) \ + Z7_COM_QI_ENTRY(i7) \ ) -const HRESULT k_My_HRESULT_WritingWasCut = 0x20000010; + +#define Z7_IFACES_IMP_UNK_1(i1) \ + Z7_COM_UNKNOWN_IMP_1(i1) \ + Z7_IFACE_COM7_IMP(i1) \ + +#define Z7_IFACES_IMP_UNK_2(i1, i2) \ + Z7_COM_UNKNOWN_IMP_2(i1, i2) \ + Z7_IFACE_COM7_IMP(i1) \ + Z7_IFACE_COM7_IMP(i2) \ + +#define Z7_IFACES_IMP_UNK_3(i1, i2, i3) \ + Z7_COM_UNKNOWN_IMP_3(i1, i2, i3) \ + Z7_IFACE_COM7_IMP(i1) \ + Z7_IFACE_COM7_IMP(i2) \ + Z7_IFACE_COM7_IMP(i3) \ + +#define Z7_IFACES_IMP_UNK_4(i1, i2, i3, i4) \ + Z7_COM_UNKNOWN_IMP_4(i1, i2, i3, i4) \ + Z7_IFACE_COM7_IMP(i1) \ + Z7_IFACE_COM7_IMP(i2) \ + Z7_IFACE_COM7_IMP(i3) \ + Z7_IFACE_COM7_IMP(i4) \ + +#define Z7_IFACES_IMP_UNK_5(i1, i2, i3, i4, i5) \ + Z7_COM_UNKNOWN_IMP_5(i1, i2, i3, i4, i5) \ + Z7_IFACE_COM7_IMP(i1) \ + Z7_IFACE_COM7_IMP(i2) \ + Z7_IFACE_COM7_IMP(i3) \ + Z7_IFACE_COM7_IMP(i4) \ + Z7_IFACE_COM7_IMP(i5) \ + +#define Z7_IFACES_IMP_UNK_6(i1, i2, i3, i4, i5, i6) \ + Z7_COM_UNKNOWN_IMP_6(i1, i2, i3, i4, i5, i6) \ + Z7_IFACE_COM7_IMP(i1) \ + Z7_IFACE_COM7_IMP(i2) \ + Z7_IFACE_COM7_IMP(i3) \ + Z7_IFACE_COM7_IMP(i4) \ + Z7_IFACE_COM7_IMP(i5) \ + Z7_IFACE_COM7_IMP(i6) \ + + +#define Z7_CLASS_IMP_COM_0(c) \ + Z7_class_final(c) : \ + public IUnknown, \ + public CMyUnknownImp { \ + Z7_COM_UNKNOWN_IMP_0 \ + private: + +#define Z7_CLASS_IMP_COM_1(c, i1) \ + Z7_class_final(c) : \ + public i1, \ + public CMyUnknownImp { \ + Z7_IFACES_IMP_UNK_1(i1) \ + private: + +#define Z7_CLASS_IMP_COM_2(c, i1, i2) \ + Z7_class_final(c) : \ + public i1, \ + public i2, \ + public CMyUnknownImp { \ + Z7_IFACES_IMP_UNK_2(i1, i2) \ + private: + +#define Z7_CLASS_IMP_COM_3(c, i1, i2, i3) \ + Z7_class_final(c) : \ + public i1, \ + public i2, \ + public i3, \ + public CMyUnknownImp { \ + Z7_IFACES_IMP_UNK_3(i1, i2, i3) \ + private: + +#define Z7_CLASS_IMP_COM_4(c, i1, i2, i3, i4) \ + Z7_class_final(c) : \ + public i1, \ + public i2, \ + public i3, \ + public i4, \ + public CMyUnknownImp { \ + Z7_IFACES_IMP_UNK_4(i1, i2, i3, i4) \ + private: + +#define Z7_CLASS_IMP_COM_5(c, i1, i2, i3, i4, i5) \ + Z7_class_final(c) : \ + public i1, \ + public i2, \ + public i3, \ + public i4, \ + public i5, \ + public CMyUnknownImp { \ + Z7_IFACES_IMP_UNK_5(i1, i2, i3, i4, i5) \ + private: + +#define Z7_CLASS_IMP_COM_6(c, i1, i2, i3, i4, i5, i6) \ + Z7_class_final(c) : \ + public i1, \ + public i2, \ + public i3, \ + public i4, \ + public i5, \ + public i6, \ + public CMyUnknownImp { \ + Z7_IFACES_IMP_UNK_6(i1, i2, i3, i4, i5, i6) \ + private: + + +/* +#define Z7_CLASS_IMP_NOQIB_0(c) \ + Z7_class_final(c) : \ + public IUnknown, \ + public CMyUnknownImp { \ + Z7_COM_UNKNOWN_IMP_0 \ + private: +*/ + +#define Z7_CLASS_IMP_NOQIB_1(c, i1) \ + Z7_class_final(c) : \ + public i1, \ + public CMyUnknownImp { \ + Z7_COM_UNKNOWN_IMP_0 \ + Z7_IFACE_COM7_IMP(i1) \ + private: + +#define Z7_CLASS_IMP_NOQIB_2(c, i1, i2) \ + Z7_class_final(c) : \ + public i1, \ + public i2, \ + public CMyUnknownImp { \ + Z7_COM_UNKNOWN_IMP_1(i2) \ + Z7_IFACE_COM7_IMP(i1) \ + Z7_IFACE_COM7_IMP(i2) \ + private: + +#define Z7_CLASS_IMP_NOQIB_3(c, i1, i2, i3) \ + Z7_class_final(c) : \ + public i1, \ + public i2, \ + public i3, \ + public CMyUnknownImp { \ + Z7_COM_UNKNOWN_IMP_2(i2, i3) \ + Z7_IFACE_COM7_IMP(i1) \ + Z7_IFACE_COM7_IMP(i2) \ + Z7_IFACE_COM7_IMP(i3) \ + private: + +#define Z7_CLASS_IMP_NOQIB_4(c, i1, i2, i3, i4) \ + Z7_class_final(c) : \ + public i1, \ + public i2, \ + public i3, \ + public i4, \ + public CMyUnknownImp { \ + Z7_COM_UNKNOWN_IMP_3(i2, i3, i4) \ + Z7_IFACE_COM7_IMP(i1) \ + Z7_IFACE_COM7_IMP(i2) \ + Z7_IFACE_COM7_IMP(i3) \ + Z7_IFACE_COM7_IMP(i4) \ + +/* +#define Z7_CLASS_IMP_NOQIB_5(c, i1, i2, i3, i4, i5) \ + Z7_class_final(c) : \ + public i1, \ + public i2, \ + public i3, \ + public i4, \ + public i5, \ + public CMyUnknownImp { \ + Z7_COM_UNKNOWN_IMP_4(i2, i3, i4, i5) \ + Z7_IFACE_COM7_IMP(i1) \ + Z7_IFACE_COM7_IMP(i2) \ + Z7_IFACE_COM7_IMP(i3) \ + Z7_IFACE_COM7_IMP(i4) \ + Z7_IFACE_COM7_IMP(i5) \ +*/ + + +#define Z7_CLASS_IMP_IInStream(c) \ + class c Z7_final : \ + public IInStream, \ + public CMyUnknownImp { \ + Z7_IFACES_IMP_UNK_2(ISequentialInStream, IInStream) \ + + +#define k_My_HRESULT_WritingWasCut 0x20000010 #endif diff -Nru 7zip-22.01+dfsg/CPP/Common/MyException.h 7zip-23.01+dfsg/CPP/Common/MyException.h --- 7zip-22.01+dfsg/CPP/Common/MyException.h 2007-06-21 09:19:59.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyException.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Common/Exception.h -#ifndef __COMMON_EXCEPTION_H -#define __COMMON_EXCEPTION_H +#ifndef ZIP7_INC_COMMON_EXCEPTION_H +#define ZIP7_INC_COMMON_EXCEPTION_H #include "MyWindows.h" diff -Nru 7zip-22.01+dfsg/CPP/Common/MyGuidDef.h 7zip-23.01+dfsg/CPP/Common/MyGuidDef.h --- 7zip-22.01+dfsg/CPP/Common/MyGuidDef.h 2020-08-29 09:11:44.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyGuidDef.h 2023-03-16 19:00:00.000000000 +0000 @@ -1,8 +1,12 @@ // Common/MyGuidDef.h +// #pragma message "Common/MyGuidDef.h" + #ifndef GUID_DEFINED #define GUID_DEFINED +// #pragma message "GUID_DEFINED" + #include "MyTypes.h" typedef struct { @@ -27,31 +31,33 @@ #ifdef __cplusplus inline int operator==(REFGUID g1, REFGUID g2) { - for (int i = 0; i < (int)sizeof(g1); i++) - if (((unsigned char *)&g1)[i] != ((unsigned char *)&g2)[i]) + for (unsigned i = 0; i < sizeof(g1); i++) + if (((const unsigned char *)&g1)[i] != ((const unsigned char *)&g2)[i]) return 0; return 1; } inline int operator!=(REFGUID g1, REFGUID g2) { return !(g1 == g2); } #endif +#endif // GUID_DEFINED + +#ifndef EXTERN_C #ifdef __cplusplus - #define MY_EXTERN_C extern "C" + #define EXTERN_C extern "C" #else - #define MY_EXTERN_C extern + #define EXTERN_C extern #endif - #endif - #ifdef DEFINE_GUID #undef DEFINE_GUID #endif #ifdef INITGUID #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ - MY_EXTERN_C const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } + EXTERN_C const GUID name; \ + EXTERN_C const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } #else #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ - MY_EXTERN_C const GUID name + EXTERN_C const GUID name #endif diff -Nru 7zip-22.01+dfsg/CPP/Common/MyInitGuid.h 7zip-23.01+dfsg/CPP/Common/MyInitGuid.h --- 7zip-22.01+dfsg/CPP/Common/MyInitGuid.h 2021-03-05 12:09:56.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyInitGuid.h 2023-03-24 09:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Common/MyInitGuid.h -#ifndef __COMMON_MY_INITGUID_H -#define __COMMON_MY_INITGUID_H +#ifndef ZIP7_INC_COMMON_MY_INITGUID_H +#define ZIP7_INC_COMMON_MY_INITGUID_H /* This file must be included only to one C++ file in project before @@ -19,31 +19,39 @@ Other: we define IID_IUnknown in this file */ -#ifdef __clang__ - #pragma clang diagnostic ignored "-Wmissing-variable-declarations" -#endif +// #include "Common.h" +/* vc6 without sdk needs before , + but it doesn't work in new msvc. + So we include full "MyWindows.h" instead of */ +// #include +#include "MyWindows.h" #ifdef _WIN32 +#ifdef __clang__ + // #pragma GCC diagnostic ignored "-Wmissing-variable-declarations" +#endif + #ifdef UNDER_CE #include #endif -#include +// for vc6 without sdk we must define INITGUID here +#define INITGUID +#include #ifdef UNDER_CE DEFINE_GUID(IID_IUnknown, 0x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); #endif -#else +#else // _WIN32 #define INITGUID #include "MyGuidDef.h" DEFINE_GUID(IID_IUnknown, 0x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); -#endif - +#endif // _WIN32 #endif diff -Nru 7zip-22.01+dfsg/CPP/Common/MyLinux.h 7zip-23.01+dfsg/CPP/Common/MyLinux.h --- 7zip-22.01+dfsg/CPP/Common/MyLinux.h 2022-02-26 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyLinux.h 2023-03-15 16:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // MyLinux.h -#ifndef __MY_LIN_LINUX_H -#define __MY_LIN_LINUX_H +#ifndef ZIP7_INC_COMMON_MY_LINUX_H +#define ZIP7_INC_COMMON_MY_LINUX_H // #include "../../C/7zTypes.h" diff -Nru 7zip-22.01+dfsg/CPP/Common/MyMap.cpp 7zip-23.01+dfsg/CPP/Common/MyMap.cpp --- 7zip-22.01+dfsg/CPP/Common/MyMap.cpp 2014-12-30 15:38:33.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyMap.cpp 2023-03-15 16:00:00.000000000 +0000 @@ -76,7 +76,7 @@ unsigned i = kNumBitsMax - 1; for (; GetSubBit(key, i) == GetSubBit(n.Key, i); i--); n.Len = (UInt16)(kNumBitsMax - (1 + i)); - unsigned newBit = GetSubBit(key, i); + const unsigned newBit = GetSubBit(key, i); n.Values[newBit] = value; n.Keys[newBit] = key; return false; @@ -91,7 +91,7 @@ bitPos -= n.Len; if (GetSubBits(key, bitPos, n.Len) != GetSubBits(n.Key, bitPos, n.Len)) { - unsigned i = n.Len - 1; + unsigned i = (unsigned)n.Len - 1; for (; GetSubBit(key, bitPos + i) == GetSubBit(n.Key, bitPos + i); i--); CNode e2(n); @@ -107,7 +107,7 @@ Nodes.Add(e2); return false; } - unsigned bit = GetSubBit(key, --bitPos); + const unsigned bit = GetSubBit(key, --bitPos); if (n.IsLeaf[bit]) { @@ -121,7 +121,7 @@ CNode e2; - unsigned newBit = GetSubBit(key, i); + const unsigned newBit = GetSubBit(key, i); e2.Values[newBit] = value; e2.Values[1 - newBit] = n.Values[bit]; e2.IsLeaf[newBit] = e2.IsLeaf[1 - newBit] = 1; diff -Nru 7zip-22.01+dfsg/CPP/Common/MyMap.h 7zip-23.01+dfsg/CPP/Common/MyMap.h --- 7zip-22.01+dfsg/CPP/Common/MyMap.h 2013-02-14 11:07:04.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyMap.h 2023-03-15 16:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // MyMap.h -#ifndef __COMMON_MYMAP_H -#define __COMMON_MYMAP_H +#ifndef ZIP7_INC_COMMON_MY_MAP_H +#define ZIP7_INC_COMMON_MY_MAP_H #include "MyTypes.h" #include "MyVector.h" diff -Nru 7zip-22.01+dfsg/CPP/Common/MyString.cpp 7zip-23.01+dfsg/CPP/Common/MyString.cpp --- 7zip-22.01+dfsg/CPP/Common/MyString.cpp 2022-02-21 06:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyString.cpp 2023-03-15 19:00:00.000000000 +0000 @@ -408,7 +408,7 @@ // MY_STRING_REALLOC(_chars, char, (size_t)newLimit + 1, (size_t)_len + 1); char *newBuf = MY_STRING_NEW_char((size_t)newLimit + 1); memcpy(newBuf, _chars, (size_t)_len + 1); - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; _limit = newLimit; } @@ -419,9 +419,10 @@ // MY_STRING_REALLOC(_chars, char, (size_t)newLimit + 1, 0); char *newBuf = MY_STRING_NEW_char((size_t)newLimit + 1); newBuf[0] = 0; - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; _limit = newLimit; + _len = 0; } void AString::SetStartLen(unsigned len) @@ -541,7 +542,7 @@ if (1 > _limit) { char *newBuf = MY_STRING_NEW_char(1 + 1); - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; _limit = 1; } @@ -558,7 +559,7 @@ if (len > _limit) { char *newBuf = MY_STRING_NEW_char((size_t)len + 1); - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; _limit = len; } @@ -575,7 +576,7 @@ if (len > _limit) { char *newBuf = MY_STRING_NEW_char((size_t)len + 1); - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; _limit = len; } @@ -600,7 +601,7 @@ if (len > _limit) { char *newBuf = MY_STRING_NEW_char((size_t)len + 1); - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; _limit = len; } @@ -624,7 +625,7 @@ if (len > _limit) { char *newBuf = MY_STRING_NEW_char((size_t)len + 1); - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; _limit = len; } @@ -641,6 +642,8 @@ void AString::Add_Space_if_NotEmpty() { if (!IsEmpty()) Add_Space(); } void AString::Add_LF() { operator+=('\n'); } void AString::Add_Slash() { operator+=('/'); } +void AString::Add_Dot() { operator+=('.'); } +void AString::Add_Minus() { operator+=('-'); } AString &AString::operator+=(const char *s) { @@ -694,7 +697,7 @@ if (len > _limit) { char *newBuf = MY_STRING_NEW_char((size_t)len + 1); - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; _limit = len; } @@ -766,7 +769,7 @@ const char *p = _chars + _len - 1; for (;;) { - char c = *p; + const char c = *p; if (IS_PATH_SEPAR(c)) return (int)(p - _chars); if (p == _chars) @@ -1001,7 +1004,7 @@ // MY_STRING_REALLOC(_chars, wchar_t, (size_t)newLimit + 1, (size_t)_len + 1); wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)newLimit + 1); wmemcpy(newBuf, _chars, _len + 1); - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; _limit = newLimit; } @@ -1012,14 +1015,15 @@ // MY_STRING_REALLOC(_chars, wchar_t, newLimit + 1, 0); wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)newLimit + 1); newBuf[0] = 0; - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; _limit = newLimit; + _len = 0; } void UString::SetStartLen(unsigned len) { - _chars = 0; + _chars = NULL; _chars = MY_STRING_NEW_wchar_t((size_t)len + 1); _len = len; _limit = len; @@ -1101,7 +1105,7 @@ UString::UString() { - _chars = 0; + _chars = NULL; _chars = MY_STRING_NEW_wchar_t(kStartStringCapacity); _len = 0; _limit = kStartStringCapacity - 1; @@ -1163,7 +1167,7 @@ if (1 > _limit) { wchar_t *newBuf = MY_STRING_NEW_wchar_t(1 + 1); - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; _limit = 1; } @@ -1180,7 +1184,7 @@ if (len > _limit) { wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1); - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; _limit = len; } @@ -1197,7 +1201,7 @@ if (len > _limit) { wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1); - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; _limit = len; } @@ -1211,7 +1215,7 @@ if (len > _limit) { wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1); - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; _limit = len; } @@ -1249,7 +1253,7 @@ if (len > _limit) { wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1); - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; _limit = len; } @@ -1289,7 +1293,7 @@ if (len > _limit) { wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1); - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; _limit = len; } @@ -1301,6 +1305,7 @@ return *this; } +void UString::Add_Dot() { operator+=(L'.'); } void UString::Add_Space() { operator+=(L' '); } void UString::Add_Space_if_NotEmpty() { if (!IsEmpty()) Add_Space(); } @@ -1393,31 +1398,26 @@ { if (_len == 0) return -1; - const wchar_t *p = _chars + _len - 1; - for (;;) + const wchar_t *p = _chars + _len; + do { - if (*p == c) + if (*(--p) == c) return (int)(p - _chars); - if (p == _chars) - return -1; - p--; } + while (p != _chars); + return -1; } int UString::ReverseFind_PathSepar() const throw() { - if (_len == 0) - return -1; - const wchar_t *p = _chars + _len - 1; - for (;;) + const wchar_t *p = _chars + _len; + while (p != _chars) { - wchar_t c = *p; + const wchar_t c = *(--p); if (IS_PATH_SEPAR(c)) return (int)(p - _chars); - if (p == _chars) - return -1; - p--; } + return -1; } void UString::TrimLeft() throw() @@ -1601,7 +1601,7 @@ // MY_STRING_REALLOC(_chars, wchar_t, newLimit + 1, 0); if (_chars) { - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = NULL; // _len = 0; } @@ -1651,7 +1651,7 @@ { wchar_t *newBuf = MY_STRING_NEW_wchar_t(1 + 1); if (_chars) - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; } _len = 1; @@ -1669,7 +1669,7 @@ { wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1); if (_chars) - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; } _len = len; @@ -1684,7 +1684,7 @@ { wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1); if (_chars) - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; } wchar_t *chars = _chars; @@ -1703,7 +1703,7 @@ { wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1); if (_chars) - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; } _len = len; @@ -1793,3 +1793,67 @@ } #endif // USE_UNICODE_FSTRING + + +bool CStringFinder::FindWord_In_LowCaseAsciiList_NoCase(const char *p, const wchar_t *str) +{ + _temp.Empty(); + for (;;) + { + const wchar_t c = *str++; + if (c == 0) + break; + if (c <= 0x20 || c > 0x7f) + return false; + _temp += (char)MyCharLower_Ascii((char)c); + } + + while (*p != 0) + { + const char *s2 = _temp.Ptr(); + char c, c2; + do + { + c = *p++; + c2 = *s2++; + } + while (c == c2); + + if (c == ' ') + { + if (c2 == 0) + return true; + continue; + } + + while (*p++ != ' '); + } + + return false; +} + + +void SplitString(const UString &srcString, UStringVector &destStrings) +{ + destStrings.Clear(); + unsigned len = srcString.Len(); + if (len == 0) + return; + UString s; + for (unsigned i = 0; i < len; i++) + { + const wchar_t c = srcString[i]; + if (c == ' ') + { + if (!s.IsEmpty()) + { + destStrings.Add(s); + s.Empty(); + } + } + else + s += c; + } + if (!s.IsEmpty()) + destStrings.Add(s); +} diff -Nru 7zip-22.01+dfsg/CPP/Common/MyString.h 7zip-23.01+dfsg/CPP/Common/MyString.h --- 7zip-22.01+dfsg/CPP/Common/MyString.h 2022-03-15 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyString.h 2023-03-15 20:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Common/MyString.h -#ifndef __COMMON_MY_STRING_H -#define __COMMON_MY_STRING_H +#ifndef ZIP7_INC_COMMON_MY_STRING_H +#define ZIP7_INC_COMMON_MY_STRING_H #include @@ -10,6 +10,7 @@ #include #endif +#include "Common.h" #include "MyWindows.h" #include "MyTypes.h" #include "MyVector.h" @@ -70,7 +71,7 @@ { for (;;) { - char c = *src; + const char c = *src; *dest = c; if (c == 0) return dest; @@ -79,6 +80,13 @@ } } +inline void MyStringCat(char *dest, const char *src) +{ + for (; *dest != 0; dest++); + while ((*dest++ = *src++) != 0); + // MyStringCopy(dest + MyStringLen(dest), src); +} + inline unsigned MyStringLen(const wchar_t *s) { unsigned i; @@ -93,7 +101,9 @@ inline void MyStringCat(wchar_t *dest, const wchar_t *src) { - MyStringCopy(dest + MyStringLen(dest), src); + for (; *dest != 0; dest++); + while ((*dest++ = *src++) != 0); + // MyStringCopy(dest + MyStringLen(dest), src); } @@ -102,7 +112,7 @@ { for (;;) { - wchar_t c = *src; + const wchar_t c = *src; *dest = c; if (c == 0) return dest; @@ -225,7 +235,7 @@ bool StringsAreEqualNoCase_Ascii(const wchar_t *s1, const char *s2) throw(); bool StringsAreEqualNoCase_Ascii(const wchar_t *s1, const wchar_t *s2) throw(); -#define MY_STRING_DELETE(_p_) delete []_p_; +#define MY_STRING_DELETE(_p_) { delete [](_p_); } // #define MY_STRING_DELETE(_p_) my_delete(_p_); @@ -312,7 +322,7 @@ explicit AString(char c); explicit AString(const char *s); AString(const AString &s); - ~AString() { MY_STRING_DELETE(_chars); } + ~AString() { MY_STRING_DELETE(_chars) } unsigned Len() const { return _len; } bool IsEmpty() const { return _len == 0; } @@ -322,6 +332,7 @@ char *Ptr_non_const() const { return _chars; } const char *Ptr() const { return _chars; } const char *Ptr(unsigned pos) const { return _chars + pos; } + const char *Ptr(int pos) const { return _chars + (unsigned)pos; } const char *RightPtr(unsigned num) const { return _chars + _len - num; } char Back() const { return _chars[(size_t)_len - 1]; } @@ -379,6 +390,8 @@ void Add_OptSpaced(const char *s); void Add_LF(); void Add_Slash(); + void Add_Dot(); + void Add_Minus(); void Add_PathSepar() { operator+=(CHAR_PATH_SEPARATOR); } AString &operator+=(const char *s); @@ -389,6 +402,10 @@ void AddFrom(const char *s, unsigned len); // no check void SetFrom(const char *s, unsigned len); // no check + void SetFrom(const char* s, int len) // no check + { + SetFrom(s, (unsigned)len); // no check + } void SetFrom_CalcLen(const char *s, unsigned len); AString Mid(unsigned startIndex, unsigned count) const { return AString(count, _chars + startIndex); } @@ -419,9 +436,13 @@ int Find(char c) const { return FindCharPosInString(_chars, c); } int Find(char c, unsigned startIndex) const { - int pos = FindCharPosInString(_chars + startIndex, c); + const int pos = FindCharPosInString(_chars + startIndex, c); return pos < 0 ? -1 : (int)startIndex + pos; } + int Find(char c, int startIndex) const + { + return Find(c, (unsigned)startIndex); + } int ReverseFind(char c) const throw(); int ReverseFind_Dot() const throw() { return ReverseFind('.'); } @@ -460,6 +481,11 @@ _chars[index] = 0; } } + void DeleteFrom(int index) + { + DeleteFrom((unsigned)index); + } + void Wipe_and_Empty() { @@ -474,7 +500,7 @@ class AString_Wipe: public AString { - CLASS_NO_COPY(AString_Wipe) + Z7_CLASS_NO_COPY(AString_Wipe) public: AString_Wipe(): AString() {} // AString_Wipe(const AString &s): AString(s) {} @@ -582,7 +608,7 @@ explicit UString(const AString &s); UString(const wchar_t *s); UString(const UString &s); - ~UString() { MY_STRING_DELETE(_chars); } + ~UString() { MY_STRING_DELETE(_chars) } unsigned Len() const { return _len; } bool IsEmpty() const { return _len == 0; } @@ -591,6 +617,7 @@ operator const wchar_t *() const { return _chars; } wchar_t *Ptr_non_const() const { return _chars; } const wchar_t *Ptr() const { return _chars; } + const wchar_t *Ptr(int pos) const { return _chars + (unsigned)pos; } const wchar_t *Ptr(unsigned pos) const { return _chars + pos; } const wchar_t *RightPtr(unsigned num) const { return _chars + _len - num; } wchar_t Back() const { return _chars[(size_t)_len - 1]; } @@ -599,6 +626,14 @@ wchar_t *GetBuf() { return _chars; } + /* + wchar_t *GetBuf_GetMaxAvail(unsigned &availBufLen) + { + availBufLen = _limit; + return _chars; + } + */ + wchar_t *GetBuf(unsigned minLen) { if (minLen > _limit) @@ -650,6 +685,7 @@ void Add_Space(); void Add_Space_if_NotEmpty(); void Add_LF(); + void Add_Dot(); void Add_PathSepar() { operator+=(WCHAR_PATH_SEPARATOR); } UString &operator+=(const wchar_t *s); @@ -662,6 +698,7 @@ UString Mid(unsigned startIndex, unsigned count) const { return UString(count, _chars + startIndex); } UString Left(unsigned count) const { return UString(count, *this); } + UString Left(int count) const { return Left((unsigned)count); } // void MakeUpper() { MyStringUpper(_chars); } // void MakeUpper() { MyStringUpper_Ascii(_chars); } @@ -720,10 +757,12 @@ void Replace(wchar_t oldChar, wchar_t newChar) throw(); void Replace(const UString &oldString, const UString &newString); + void Delete(int index) throw() { Delete((unsigned)index); } void Delete(unsigned index) throw(); void Delete(unsigned index, unsigned count) throw(); void DeleteFrontal(unsigned num) throw(); void DeleteBack() { _chars[--_len] = 0; } + void DeleteFrom(int index) { DeleteFrom((unsigned)index); } void DeleteFrom(unsigned index) { if (index < _len) @@ -746,7 +785,7 @@ class UString_Wipe: public UString { - CLASS_NO_COPY(UString_Wipe) + Z7_CLASS_NO_COPY(UString_Wipe) public: UString_Wipe(): UString() {} // UString_Wipe(const UString &s): UString(s) {} @@ -834,7 +873,7 @@ UString2(): _chars(NULL), _len(0) {} UString2(const wchar_t *s); UString2(const UString2 &s); - ~UString2() { if (_chars) MY_STRING_DELETE(_chars); } + ~UString2() { if (_chars) { MY_STRING_DELETE(_chars) } } unsigned Len() const { return _len; } bool IsEmpty() const { return _len == 0; } @@ -912,7 +951,7 @@ #ifdef USE_UNICODE_FSTRING - #define __FTEXT(quote) L##quote + #define MY_FTEXT(quote) L##quote typedef wchar_t FChar; typedef UString FString; @@ -923,9 +962,9 @@ FString fas2fs(const AString &s); AString fs2fas(const FChar *s); -#else +#else // USE_UNICODE_FSTRING - #define __FTEXT(quote) quote + #define MY_FTEXT(quote) quote typedef char FChar; @@ -979,9 +1018,9 @@ FString us2fs(const wchar_t *s); #define fs2fas(_x_) (_x_) -#endif +#endif // USE_UNICODE_FSTRING -#define FTEXT(quote) __FTEXT(quote) +#define FTEXT(quote) MY_FTEXT(quote) #define FCHAR_PATH_SEPARATOR FTEXT(CHAR_PATH_SEPARATOR) #define FSTRING_PATH_SEPARATOR FTEXT(STRING_PATH_SEPARATOR) @@ -993,6 +1032,18 @@ typedef CObjectVector FStringVector; + +class CStringFinder +{ + AString _temp; +public: + // list - is list of low case Ascii strings separated by space " ". + // the function returns true, if it can find exact word (str) in (list). + bool FindWord_In_LowCaseAsciiList_NoCase(const char *list, const wchar_t *str); +}; + +void SplitString(const UString &srcString, UStringVector &destStrings); + #endif @@ -1000,10 +1051,10 @@ #if defined(_WIN32) // #include // WCHAR_MAX is defined as ((wchar_t)-1) - #define _WCHART_IS_16BIT 1 + #define Z7_WCHART_IS_16BIT 1 #elif (defined(WCHAR_MAX) && (WCHAR_MAX <= 0xffff)) \ || (defined(__SIZEOF_WCHAR_T__) && (__SIZEOF_WCHAR_T__ == 2)) - #define _WCHART_IS_16BIT 1 + #define Z7_WCHART_IS_16BIT 1 #endif #if WCHAR_PATH_SEPARATOR == L'\\' diff -Nru 7zip-22.01+dfsg/CPP/Common/MyTypes.h 7zip-23.01+dfsg/CPP/Common/MyTypes.h --- 7zip-22.01+dfsg/CPP/Common/MyTypes.h 2021-10-20 14:26:28.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyTypes.h 2023-03-24 08:00:00.000000000 +0000 @@ -1,9 +1,10 @@ // Common/MyTypes.h -#ifndef __COMMON_MY_TYPES_H -#define __COMMON_MY_TYPES_H +#ifndef ZIP7_INC_COMMON_MY_TYPES_H +#define ZIP7_INC_COMMON_MY_TYPES_H #include "../../C/7zTypes.h" +#include "Common.h" typedef int HRes; @@ -33,20 +34,4 @@ } }; -#define CLASS_NO_COPY(cls) \ - private: \ - cls(const cls &); \ - cls &operator=(const cls &); - -class CUncopyable -{ -protected: - CUncopyable() {} // allow constructor - // ~CUncopyable() {} -CLASS_NO_COPY(CUncopyable) -}; - -#define MY_UNCOPYABLE :private CUncopyable -// #define MY_UNCOPYABLE - #endif diff -Nru 7zip-22.01+dfsg/CPP/Common/MyUnknown.h 7zip-23.01+dfsg/CPP/Common/MyUnknown.h --- 7zip-22.01+dfsg/CPP/Common/MyUnknown.h 2015-08-01 14:41:33.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyUnknown.h 2023-03-18 16:00:00.000000000 +0000 @@ -1,17 +1,8 @@ // MyUnknown.h -#ifndef __MY_UNKNOWN_H -#define __MY_UNKNOWN_H +#ifndef ZIP7_INC_MY_UNKNOWN_H +#define ZIP7_INC_MY_UNKNOWN_H #include "MyWindows.h" -/* -#ifdef _WIN32 -#include -#include -#else -#include "MyWindows.h" -#endif -*/ - #endif diff -Nru 7zip-22.01+dfsg/CPP/Common/MyVector.h 7zip-23.01+dfsg/CPP/Common/MyVector.h --- 7zip-22.01+dfsg/CPP/Common/MyVector.h 2022-03-27 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyVector.h 2023-03-24 09:00:00.000000000 +0000 @@ -1,10 +1,12 @@ // Common/MyVector.h -#ifndef __COMMON_MY_VECTOR_H -#define __COMMON_MY_VECTOR_H +#ifndef ZIP7_INC_COMMON_MY_VECTOR_H +#define ZIP7_INC_COMMON_MY_VECTOR_H #include +#include "Common.h" + const unsigned k_VectorSizeMax = ((unsigned)1 << 31) - 1; template @@ -22,7 +24,7 @@ void ReAllocForNewCapacity(const unsigned newCapacity) { T *p; - MY_ARRAY_NEW(p, T, newCapacity); + Z7_ARRAY_NEW(p, T, newCapacity) // p = new T[newCapacity]; if (_size != 0) memcpy(p, _items, (size_t)_size * sizeof(T)); @@ -53,7 +55,7 @@ const unsigned size = v.Size(); if (size != 0) { - // MY_ARRAY_NEW(_items, T, size) + // Z7_ARRAY_NEW(_items, T, size) _items = new T[size]; _size = size; _capacity = size; @@ -68,7 +70,7 @@ { if (size != 0) { - MY_ARRAY_NEW(_items, T, size) + Z7_ARRAY_NEW(_items, T, size) // _items = new T[size]; _capacity = size; } @@ -100,7 +102,7 @@ delete []_items; _items = NULL; _capacity = 0; - MY_ARRAY_NEW(_items, T, newCapacity) + Z7_ARRAY_NEW(_items, T, newCapacity) // _items = new T[newCapacity]; _capacity = newCapacity; } @@ -119,7 +121,7 @@ T *p = NULL; if (_size != 0) { - // MY_ARRAY_NEW(p, T, _size) + // Z7_ARRAY_NEW(p, T, _size) p = new T[_size]; memcpy(p, _items, (size_t)_size * sizeof(T)); } @@ -264,6 +266,8 @@ const T& operator[](unsigned index) const { return _items[index]; } T& operator[](unsigned index) { return _items[index]; } + const T& operator[](int index) const { return _items[(unsigned)index]; } + T& operator[](int index) { return _items[(unsigned)index]; } const T& Front() const { return _items[0]; } T& Front() { return _items[0]; } const T& Back() const { return _items[(size_t)_size - 1]; } @@ -497,6 +501,8 @@ const T& operator[](unsigned index) const { return *((T *)_v[index]); } T& operator[](unsigned index) { return *((T *)_v[index]); } + const T& operator[](int index) const { return *((T *)_v[(unsigned)index]); } + T& operator[](int index) { return *((T *)_v[(unsigned)index]); } const T& Front() const { return operator[](0); } T& Front() { return operator[](0); } const T& Back() const { return *(T *)_v.Back(); } @@ -604,6 +610,7 @@ delete (T *)_v[index]; _v.Delete(index); } + // void Delete(int index) { Delete((unsigned)index); } /* void Delete(unsigned index, unsigned num) diff -Nru 7zip-22.01+dfsg/CPP/Common/MyWindows.cpp 7zip-23.01+dfsg/CPP/Common/MyWindows.cpp --- 7zip-22.01+dfsg/CPP/Common/MyWindows.cpp 2021-04-01 11:17:26.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyWindows.cpp 2023-03-21 07:00:00.000000000 +0000 @@ -78,7 +78,7 @@ BSTR SysAllocString(const OLECHAR *s) { if (!s) - return 0; + return NULL; const OLECHAR *s2 = s; while (*s2 != 0) s2++; @@ -181,7 +181,7 @@ { UInt64 v = GET_TIME_64(fileTime); v = (UInt64)((Int64)v - (Int64)TIME_GetBias() * TICKS_PER_SEC); - SET_FILETIME(localFileTime, v); + SET_FILETIME(localFileTime, v) return TRUE; } @@ -189,7 +189,7 @@ { UInt64 v = GET_TIME_64(localFileTime); v = (UInt64)((Int64)v + (Int64)TIME_GetBias() * TICKS_PER_SEC); - SET_FILETIME(fileTime, v); + SET_FILETIME(fileTime, v) return TRUE; } @@ -203,7 +203,7 @@ t = tv.tv_sec * (UInt64)TICKS_PER_SEC + TICKS_1601_TO_1970; t += tv.tv_usec * 10; } - SET_FILETIME(ft, t); + SET_FILETIME(ft, t) } */ diff -Nru 7zip-22.01+dfsg/CPP/Common/MyWindows.h 7zip-23.01+dfsg/CPP/Common/MyWindows.h --- 7zip-22.01+dfsg/CPP/Common/MyWindows.h 2022-03-27 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyWindows.h 2023-04-08 10:00:00.000000000 +0000 @@ -1,16 +1,25 @@ // MyWindows.h -#ifndef __MY_WINDOWS_H -#define __MY_WINDOWS_H +#ifdef Z7_DEFINE_GUID +#undef Z7_DEFINE_GUID +#endif -#ifdef _WIN32 +#ifdef INITGUID + #define Z7_DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ + EXTERN_C const GUID name; \ + EXTERN_C const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } +#else + #define Z7_DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ + EXTERN_C const GUID name +#endif -#include -#ifdef UNDER_CE - #undef VARIANT_TRUE - #define VARIANT_TRUE ((VARIANT_BOOL)-1) -#endif +#ifndef ZIP7_INC_MY_WINDOWS_H +#define ZIP7_INC_MY_WINDOWS_H + +#ifdef _WIN32 + +#include "../../C/7zWindows.h" #else // _WIN32 @@ -18,11 +27,11 @@ #include // #include // for uintptr_t +#include "../../C/7zTypes.h" #include "MyGuidDef.h" // WINAPI is __stdcall in Windows-MSVC in windef.h #define WINAPI -#define EXTERN_C MY_EXTERN_C typedef char CHAR; typedef unsigned char UCHAR; @@ -103,31 +112,78 @@ #define STDAPI EXTERN_C HRESULT STDAPICALLTYPE -#define STDMETHOD_(t, f) virtual t STDMETHODCALLTYPE f -#define STDMETHOD(f) STDMETHOD_(HRESULT, f) -#define STDMETHODIMP_(type) type STDMETHODCALLTYPE -#define STDMETHODIMP STDMETHODIMP_(HRESULT) +#ifndef DECLSPEC_NOTHROW +#define DECLSPEC_NOTHROW Z7_DECLSPEC_NOTHROW +#endif + +#ifndef DECLSPEC_NOVTABLE +#define DECLSPEC_NOVTABLE Z7_DECLSPEC_NOVTABLE +#endif + +#ifndef COM_DECLSPEC_NOTHROW +#ifdef COM_STDMETHOD_CAN_THROW + #define COM_DECLSPEC_NOTHROW +#else + #define COM_DECLSPEC_NOTHROW DECLSPEC_NOTHROW +#endif +#endif + +#define DECLARE_INTERFACE(iface) struct DECLSPEC_NOVTABLE iface +#define DECLARE_INTERFACE_(iface, baseiface) struct DECLSPEC_NOVTABLE iface : public baseiface + +#define STDMETHOD_(t, f) virtual COM_DECLSPEC_NOTHROW t STDMETHODCALLTYPE f +#define STDMETHOD(f) STDMETHOD_(HRESULT, f) +#define STDMETHODIMP_(t) COM_DECLSPEC_NOTHROW t STDMETHODCALLTYPE +#define STDMETHODIMP STDMETHODIMP_(HRESULT) + #define PURE = 0 -#define MIDL_INTERFACE(x) struct +// #define MIDL_INTERFACE(x) struct + #ifdef __cplusplus +/* + p7zip and 7-Zip before v23 used virtual destructor in IUnknown, + if _WIN32 is not defined. + It used virtual destructor, because some compilers don't like virtual + interfaces without virtual destructor. + IUnknown in Windows (_WIN32) doesn't use virtual destructor in IUnknown. + We still can define Z7_USE_VIRTUAL_DESTRUCTOR_IN_IUNKNOWN here, + if we want to be compatible with old plugin interface of p7zip and 7-Zip before v23. + +v23: + In new 7-Zip v23 we try to be more compatible with original IUnknown from _WIN32. + So we do not define Z7_USE_VIRTUAL_DESTRUCTOR_IN_IUNKNOWN here, +*/ +// #define Z7_USE_VIRTUAL_DESTRUCTOR_IN_IUNKNOWN + +#ifdef Z7_USE_VIRTUAL_DESTRUCTOR_IN_IUNKNOWN +#if defined(__clang__) +#pragma GCC diagnostic ignored "-Winconsistent-missing-destructor-override" +#endif +#endif + +Z7_PURE_INTERFACES_BEGIN + DEFINE_GUID(IID_IUnknown, 0x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); struct IUnknown { - STDMETHOD(QueryInterface) (REFIID iid, void **outObject) PURE; - STDMETHOD_(ULONG, AddRef)() PURE; - STDMETHOD_(ULONG, Release)() PURE; + STDMETHOD(QueryInterface) (REFIID iid, void **outObject) =0; + STDMETHOD_(ULONG, AddRef)() =0; + STDMETHOD_(ULONG, Release)() =0; + #ifdef Z7_USE_VIRTUAL_DESTRUCTOR_IN_IUNKNOWN virtual ~IUnknown() {} - // We use virtual ~IUnknown() here for binary compatibility with 7z.so from p7zip + #endif }; typedef IUnknown *LPUNKNOWN; -#endif +Z7_PURE_INTERFACES_END + +#endif // __cplusplus #define VARIANT_TRUE ((VARIANT_BOOL)-1) #define VARIANT_FALSE ((VARIANT_BOOL)0) @@ -197,8 +253,8 @@ typedef tagVARIANT VARIANT; typedef VARIANT VARIANTARG; -MY_EXTERN_C HRESULT VariantClear(VARIANTARG *prop); -MY_EXTERN_C HRESULT VariantCopy(VARIANTARG *dest, const VARIANTARG *src); +EXTERN_C HRESULT VariantClear(VARIANTARG *prop); +EXTERN_C HRESULT VariantCopy(VARIANTARG *dest, const VARIANTARG *src); typedef struct tagSTATPROPSTG { @@ -207,19 +263,19 @@ VARTYPE vt; } STATPROPSTG; -MY_EXTERN_C BSTR SysAllocStringByteLen(LPCSTR psz, UINT len); -MY_EXTERN_C BSTR SysAllocStringLen(const OLECHAR *sz, UINT len); -MY_EXTERN_C BSTR SysAllocString(const OLECHAR *sz); -MY_EXTERN_C void SysFreeString(BSTR bstr); -MY_EXTERN_C UINT SysStringByteLen(BSTR bstr); -MY_EXTERN_C UINT SysStringLen(BSTR bstr); - -MY_EXTERN_C DWORD GetLastError(); -MY_EXTERN_C void SetLastError(DWORD dwCode); -MY_EXTERN_C LONG CompareFileTime(const FILETIME* ft1, const FILETIME* ft2); +EXTERN_C BSTR SysAllocStringByteLen(LPCSTR psz, UINT len); +EXTERN_C BSTR SysAllocStringLen(const OLECHAR *sz, UINT len); +EXTERN_C BSTR SysAllocString(const OLECHAR *sz); +EXTERN_C void SysFreeString(BSTR bstr); +EXTERN_C UINT SysStringByteLen(BSTR bstr); +EXTERN_C UINT SysStringLen(BSTR bstr); + +EXTERN_C DWORD GetLastError(); +EXTERN_C void SetLastError(DWORD dwCode); +EXTERN_C LONG CompareFileTime(const FILETIME* ft1, const FILETIME* ft2); -MY_EXTERN_C DWORD GetCurrentThreadId(); -MY_EXTERN_C DWORD GetCurrentProcessId(); +EXTERN_C DWORD GetCurrentThreadId(); +EXTERN_C DWORD GetCurrentProcessId(); #define MAX_PATH 1024 diff -Nru 7zip-22.01+dfsg/CPP/Common/MyXml.cpp 7zip-23.01+dfsg/CPP/Common/MyXml.cpp --- 7zip-22.01+dfsg/CPP/Common/MyXml.cpp 2021-01-24 13:22:01.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyXml.cpp 2023-03-15 16:00:00.000000000 +0000 @@ -81,7 +81,7 @@ const char * CXmlItem::ParseItem(const char *s, int numAllowedLevels) { - SKIP_SPACES(s); + SKIP_SPACES(s) const char *beg = s; for (;;) @@ -102,7 +102,7 @@ IsTag = true; s++; - SKIP_SPACES(s); + SKIP_SPACES(s) beg = s; for (;; s++) @@ -115,11 +115,11 @@ for (;;) { beg = s; - SKIP_SPACES(s); + SKIP_SPACES(s) if (*s == '/') { s++; - // SKIP_SPACES(s); + // SKIP_SPACES(s) if (*s != '>') return NULL; return s + 1; @@ -132,7 +132,7 @@ SubItems.Clear(); for (;;) { - SKIP_SPACES(s); + SKIP_SPACES(s) if (s[0] == '<' && s[1] == '/') break; CXmlItem &item = SubItems.AddNew(); @@ -168,11 +168,11 @@ return NULL; prop.Name.SetFrom(beg, (unsigned)(s - beg)); - SKIP_SPACES(s); + SKIP_SPACES(s) if (*s != '=') return NULL; s++; - SKIP_SPACES(s); + SKIP_SPACES(s) if (*s != '\"') return NULL; s++; @@ -194,7 +194,7 @@ static const char * SkipHeader(const char *s, const char *startString, const char *endString) { - SKIP_SPACES(s); + SKIP_SPACES(s) if (IsString1PrefixedByString2(s, startString)) { s = strstr(s, endString); @@ -215,7 +215,7 @@ FOR_VECTOR (i, Props) { const CXmlProp &prop = Props[i]; - s += ' '; + s.Add_Space(); s += prop.Name; s += '='; s += '\"'; @@ -228,7 +228,7 @@ { const CXmlItem &item = SubItems[i]; if (i != 0 && !SubItems[i - 1].IsTag) - s += ' '; + s.Add_Space(); item.AppendTo(s); } if (IsTag) @@ -248,7 +248,7 @@ s = Root.ParseItem(s, 1000); if (!s || !Root.IsTag) return false; - SKIP_SPACES(s); + SKIP_SPACES(s) return *s == 0; } diff -Nru 7zip-22.01+dfsg/CPP/Common/MyXml.h 7zip-23.01+dfsg/CPP/Common/MyXml.h --- 7zip-22.01+dfsg/CPP/Common/MyXml.h 2017-02-08 17:50:54.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/MyXml.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // MyXml.h -#ifndef __MY_XML_H -#define __MY_XML_H +#ifndef ZIP7_INC_MY_XML_H +#define ZIP7_INC_MY_XML_H #include "MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/Common/NewHandler.cpp 7zip-23.01+dfsg/CPP/Common/NewHandler.cpp --- 7zip-22.01+dfsg/CPP/Common/NewHandler.cpp 2022-03-27 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/NewHandler.cpp 2023-03-04 10:00:00.000000000 +0000 @@ -10,21 +10,23 @@ #ifndef DEBUG_MEMORY_LEAK -#ifdef _7ZIP_REDEFINE_OPERATOR_NEW +#ifdef Z7_REDEFINE_OPERATOR_NEW /* void * my_new(size_t size) { // void *p = ::HeapAlloc(::GetProcessHeap(), 0, size); + if (size == 0) + size = 1; void *p = ::malloc(size); - if (p == 0) + if (!p) throw CNewException(); return p; } void my_delete(void *p) throw() { - // if (p == 0) return; ::HeapFree(::GetProcessHeap(), 0, p); + // if (!p) return; ::HeapFree(::GetProcessHeap(), 0, p); ::free(p); } @@ -44,9 +46,21 @@ #endif operator new(size_t size) { + /* by C++ specification: + if (size == 0), operator new(size) returns non_NULL pointer. + If (operator new(0) returns NULL), it's out of specification. + but some calling code can work correctly even in this case too. */ + // if (size == 0) return NULL; // for debug only. don't use it + + /* malloc(0) returns non_NULL in main compilers, as we need here. + But specification also allows malloc(0) to return NULL. + So we change (size=0) to (size=1) here to get real non_NULL pointer */ + if (size == 0) + size = 1; // void *p = ::HeapAlloc(::GetProcessHeap(), 0, size); + // void *p = ::MyAlloc(size); // note: MyAlloc(0) returns NULL void *p = ::malloc(size); - if (p == 0) + if (!p) throw CNewException(); return p; } @@ -57,7 +71,8 @@ #endif operator delete(void *p) throw() { - // if (p == 0) return; ::HeapFree(::GetProcessHeap(), 0, p); + // if (!p) return; ::HeapFree(::GetProcessHeap(), 0, p); + // MyFree(p); ::free(p); } @@ -69,8 +84,10 @@ operator new[](size_t size) { // void *p = ::HeapAlloc(::GetProcessHeap(), 0, size); + if (size == 0) + size = 1; void *p = ::malloc(size); - if (p == 0) + if (!p) throw CNewException(); return p; } @@ -81,7 +98,7 @@ #endif operator delete[](void *p) throw() { - // if (p == 0) return; ::HeapFree(::GetProcessHeap(), 0, p); + // if (!p) return; ::HeapFree(::GetProcessHeap(), 0, p); ::free(p); } */ @@ -93,16 +110,43 @@ #include // #pragma init_seg(lib) +/* const int kDebugSize = 1000000; static void *a[kDebugSize]; -static int index = 0; +static int g_index = 0; + +class CC +{ +public: + CC() + { + for (int i = 0; i < kDebugSize; i++) + a[i] = 0; + } + ~CC() + { + printf("\nDestructor: %d\n", numAllocs); + for (int i = 0; i < kDebugSize; i++) + if (a[i] != 0) + return; + } +} g_CC; +*/ +#ifdef _WIN32 static bool wasInit = false; static CRITICAL_SECTION cs; +#endif static int numAllocs = 0; -void * __cdecl operator new(size_t size) + +void * +#ifdef _MSC_VER +__cdecl +#endif +operator new(size_t size) { + #ifdef _WIN32 if (!wasInit) { InitializeCriticalSection(&cs); @@ -114,53 +158,127 @@ int loc = numAllocs; void *p = HeapAlloc(GetProcessHeap(), 0, size); /* - if (index < kDebugSize) + if (g_index < kDebugSize) { - a[index] = p; - index++; + a[g_index] = p; + g_index++; } */ printf("Alloc %6d, size = %8u\n", loc, (unsigned)size); LeaveCriticalSection(&cs); - if (p == 0) + if (!p) throw CNewException(); return p; -} - -class CC -{ -public: - CC() - { - for (int i = 0; i < kDebugSize; i++) - a[i] = 0; - } - ~CC() + #else + numAllocs++; + int loc = numAllocs; + if (size == 0) + size = 1; + void *p = malloc(size); + /* + if (g_index < kDebugSize) { - printf("\nDestructor: %d\n", numAllocs); - for (int i = 0; i < kDebugSize; i++) - if (a[i] != 0) - return; + a[g_index] = p; + g_index++; } -} g_CC; - + */ + printf("Alloc %6d, size = %8u\n", loc, (unsigned)size); + if (!p) + throw CNewException(); + return p; + #endif +} -void __cdecl operator delete(void *p) +void +#ifdef _MSC_VER +__cdecl +#endif +operator delete(void *p) throw() { - if (p == 0) + if (!p) return; + #ifdef _WIN32 EnterCriticalSection(&cs); /* - for (int i = 0; i < index; i++) + for (int i = 0; i < g_index; i++) if (a[i] == p) a[i] = 0; */ HeapFree(GetProcessHeap(), 0, p); + if (numAllocs == 0) + numAllocs = numAllocs; // ERROR numAllocs--; + if (numAllocs == 0) + numAllocs = numAllocs; // OK: all objects were deleted printf("Free %d\n", numAllocs); LeaveCriticalSection(&cs); + #else + free(p); + numAllocs--; + printf("Free %d\n", numAllocs); + #endif +} + +/* +void * +#ifdef _MSC_VER +__cdecl +#endif +operator new[](size_t size) +{ + printf("operator_new[] : "); + return operator new(size); } +void +#ifdef _MSC_VER +__cdecl +#endif +operator delete(void *p, size_t sz) throw(); + +void +#ifdef _MSC_VER +__cdecl +#endif +operator delete(void *p, size_t sz) throw() +{ + if (!p) + return; + printf("operator_delete_size : size=%d : ", (unsigned)sz); + operator delete(p); +} + +void +#ifdef _MSC_VER +__cdecl +#endif +operator delete[](void *p) throw() +{ + if (!p) + return; + printf("operator_delete[] : "); + operator delete(p); +} + +void +#ifdef _MSC_VER +__cdecl +#endif +operator delete[](void *p, size_t sz) throw(); + +void +#ifdef _MSC_VER +__cdecl +#endif +operator delete[](void *p, size_t sz) throw() +{ + if (!p) + return; + printf("operator_delete_size[] : size=%d : ", (unsigned)sz); + operator delete(p); +} +*/ + #endif /* diff -Nru 7zip-22.01+dfsg/CPP/Common/NewHandler.h 7zip-23.01+dfsg/CPP/Common/NewHandler.h --- 7zip-22.01+dfsg/CPP/Common/NewHandler.h 2017-01-03 17:40:45.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/NewHandler.h 2023-03-16 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Common/NewHandler.h -#ifndef __COMMON_NEW_HANDLER_H -#define __COMMON_NEW_HANDLER_H +#ifndef ZIP7_INC_COMMON_NEW_HANDLER_H +#define ZIP7_INC_COMMON_NEW_HANDLER_H /* NewHandler.h and NewHandler.cpp allows to solve problem with compilers that @@ -10,6 +10,16 @@ This file must be included before any code that uses operators new() or delete() and you must compile and link "NewHandler.cpp", if you use some old MSVC compiler. +DOCs: + Since ISO C++98, operator new throws std::bad_alloc when memory allocation fails. + MSVC 6.0 returned a null pointer on an allocation failure. + Beginning in VS2002, operator new conforms to the standard and throws on failure. + + By default, the compiler also generates defensive null checks to prevent + these older-style allocators from causing an immediate crash on failure. + The /Zc:throwingNew option tells the compiler to leave out these null checks, + on the assumption that all linked memory allocators conform to the standard. + The operator new() in some MSVC versions doesn't throw exception std::bad_alloc. MSVC 6.0 (_MSC_VER == 1200) doesn't throw exception. The code produced by some another MSVC compilers also can be linked @@ -36,13 +46,13 @@ #endif -#if defined(_MSC_VER) && (_MSC_VER < 1900) +#if defined(_MSC_VER) && (_MSC_VER < 1600) // If you want to use default operator new(), you can disable the following line - #define _7ZIP_REDEFINE_OPERATOR_NEW + #define Z7_REDEFINE_OPERATOR_NEW #endif -#ifdef _7ZIP_REDEFINE_OPERATOR_NEW +#ifdef Z7_REDEFINE_OPERATOR_NEW // std::bad_alloc can require additional DLL dependency. // So we don't define CNewException as std::bad_alloc here. diff -Nru 7zip-22.01+dfsg/CPP/Common/Random.h 7zip-23.01+dfsg/CPP/Common/Random.h --- 7zip-22.01+dfsg/CPP/Common/Random.h 2015-11-13 16:43:16.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/Random.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Common/Random.h -#ifndef __COMMON_RANDOM_H -#define __COMMON_RANDOM_H +#ifndef ZIP7_INC_COMMON_RANDOM_H +#define ZIP7_INC_COMMON_RANDOM_H class CRandom { diff -Nru 7zip-22.01+dfsg/CPP/Common/Sha1Reg.cpp 7zip-23.01+dfsg/CPP/Common/Sha1Reg.cpp --- 7zip-22.01+dfsg/CPP/Common/Sha1Reg.cpp 2021-01-26 11:31:19.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/Sha1Reg.cpp 2023-03-16 20:00:00.000000000 +0000 @@ -9,13 +9,14 @@ #include "../7zip/Common/RegisterCodec.h" -class CSha1Hasher: - public IHasher, - public ICompressSetCoderProperties, - public CMyUnknownImp -{ - CAlignedBuffer _buf; - Byte mtDummy[1 << 7]; +Z7_CLASS_IMP_COM_2( + CSha1Hasher + , IHasher + , ICompressSetCoderProperties +) + CAlignedBuffer1 _buf; +public: + Byte _mtDummy[1 << 7]; CSha1 *Sha() { return (CSha1 *)(void *)(Byte *)_buf; } public: @@ -25,36 +26,32 @@ Sha1_SetFunction(Sha(), 0); Sha1_InitState(Sha()); } - - MY_UNKNOWN_IMP2(IHasher, ICompressSetCoderProperties) - INTERFACE_IHasher(;) - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); }; -STDMETHODIMP_(void) CSha1Hasher::Init() throw() +Z7_COM7F_IMF2(void, CSha1Hasher::Init()) { Sha1_InitState(Sha()); } -STDMETHODIMP_(void) CSha1Hasher::Update(const void *data, UInt32 size) throw() +Z7_COM7F_IMF2(void, CSha1Hasher::Update(const void *data, UInt32 size)) { Sha1_Update(Sha(), (const Byte *)data, size); } -STDMETHODIMP_(void) CSha1Hasher::Final(Byte *digest) throw() +Z7_COM7F_IMF2(void, CSha1Hasher::Final(Byte *digest)) { Sha1_Final(Sha(), digest); } -STDMETHODIMP CSha1Hasher::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps) +Z7_COM7F_IMF(CSha1Hasher::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps)) { unsigned algo = 0; for (UInt32 i = 0; i < numProps; i++) { - const PROPVARIANT &prop = coderProps[i]; if (propIDs[i] == NCoderPropID::kDefaultProp) { + const PROPVARIANT &prop = coderProps[i]; if (prop.vt != VT_UI4) return E_INVALIDARG; if (prop.ulVal > 2) diff -Nru 7zip-22.01+dfsg/CPP/Common/Sha256Reg.cpp 7zip-23.01+dfsg/CPP/Common/Sha256Reg.cpp --- 7zip-22.01+dfsg/CPP/Common/Sha256Reg.cpp 2021-01-26 11:15:51.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/Sha256Reg.cpp 2023-03-16 20:00:00.000000000 +0000 @@ -9,13 +9,14 @@ #include "../7zip/Common/RegisterCodec.h" -class CSha256Hasher: - public IHasher, - public ICompressSetCoderProperties, - public CMyUnknownImp -{ - CAlignedBuffer _buf; - Byte mtDummy[1 << 7]; +Z7_CLASS_IMP_COM_2( + CSha256Hasher + , IHasher + , ICompressSetCoderProperties +) + CAlignedBuffer1 _buf; +public: + Byte _mtDummy[1 << 7]; CSha256 *Sha() { return (CSha256 *)(void *)(Byte *)_buf; } public: @@ -25,36 +26,32 @@ Sha256_SetFunction(Sha(), 0); Sha256_InitState(Sha()); } - - MY_UNKNOWN_IMP2(IHasher, ICompressSetCoderProperties) - INTERFACE_IHasher(;) - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); }; -STDMETHODIMP_(void) CSha256Hasher::Init() throw() +Z7_COM7F_IMF2(void, CSha256Hasher::Init()) { Sha256_InitState(Sha()); } -STDMETHODIMP_(void) CSha256Hasher::Update(const void *data, UInt32 size) throw() +Z7_COM7F_IMF2(void, CSha256Hasher::Update(const void *data, UInt32 size)) { Sha256_Update(Sha(), (const Byte *)data, size); } -STDMETHODIMP_(void) CSha256Hasher::Final(Byte *digest) throw() +Z7_COM7F_IMF2(void, CSha256Hasher::Final(Byte *digest)) { Sha256_Final(Sha(), digest); } -STDMETHODIMP CSha256Hasher::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps) +Z7_COM7F_IMF(CSha256Hasher::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps)) { unsigned algo = 0; for (UInt32 i = 0; i < numProps; i++) { - const PROPVARIANT &prop = coderProps[i]; if (propIDs[i] == NCoderPropID::kDefaultProp) { + const PROPVARIANT &prop = coderProps[i]; if (prop.vt != VT_UI4) return E_INVALIDARG; if (prop.ulVal > 2) diff -Nru 7zip-22.01+dfsg/CPP/Common/StdAfx.h 7zip-23.01+dfsg/CPP/Common/StdAfx.h --- 7zip-22.01+dfsg/CPP/Common/StdAfx.h 2013-01-20 07:29:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H #include "Common.h" diff -Nru 7zip-22.01+dfsg/CPP/Common/StdInStream.cpp 7zip-23.01+dfsg/CPP/Common/StdInStream.cpp --- 7zip-22.01+dfsg/CPP/Common/StdInStream.cpp 2020-03-17 12:14:32.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/StdInStream.cpp 2023-03-16 19:00:00.000000000 +0000 @@ -14,10 +14,12 @@ // #define kReadErrorMessage "Error reading input stream" // #define kIllegalCharMessage "Illegal zero character in input stream" -#define kFileOpenMode TEXT("r") CStdInStream g_StdIn(stdin); +/* +#define kFileOpenMode TEXT("r") + bool CStdInStream::Open(LPCTSTR fileName) throw() { Close(); @@ -39,6 +41,7 @@ _streamIsOpen = (fclose(_stream) != 0); return !_streamIsOpen; } +*/ bool CStdInStream::ScanAStringUntilNewLine(AString &s) { diff -Nru 7zip-22.01+dfsg/CPP/Common/StdInStream.h 7zip-23.01+dfsg/CPP/Common/StdInStream.h --- 7zip-22.01+dfsg/CPP/Common/StdInStream.h 2020-03-17 12:02:20.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/StdInStream.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Common/StdInStream.h -#ifndef __COMMON_STD_IN_STREAM_H -#define __COMMON_STD_IN_STREAM_H +#ifndef ZIP7_INC_COMMON_STD_IN_STREAM_H +#define ZIP7_INC_COMMON_STD_IN_STREAM_H #include @@ -11,20 +11,22 @@ class CStdInStream { FILE *_stream; - bool _streamIsOpen; + // bool _streamIsOpen; public: int CodePage; CStdInStream(FILE *stream = NULL): _stream(stream), - _streamIsOpen(false), + // _streamIsOpen(false), CodePage(-1) - {}; + {} + /* ~CStdInStream() { Close(); } bool Open(LPCTSTR fileName) throw(); bool Close() throw(); + */ // returns: // false, if ZERO character in stream diff -Nru 7zip-22.01+dfsg/CPP/Common/StdOutStream.cpp 7zip-23.01+dfsg/CPP/Common/StdOutStream.cpp --- 7zip-22.01+dfsg/CPP/Common/StdOutStream.cpp 2020-03-17 12:07:17.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/StdOutStream.cpp 2023-03-16 19:00:00.000000000 +0000 @@ -11,11 +11,12 @@ #include "StringConvert.h" #include "UTFConvert.h" -#define kFileOpenMode "wt" - CStdOutStream g_StdOut(stdout); CStdOutStream g_StdErr(stderr); +/* +// #define kFileOpenMode "wt" + bool CStdOutStream::Open(const char *fileName) throw() { Close(); @@ -34,6 +35,7 @@ _streamIsOpen = false; return true; } +*/ bool CStdOutStream::Flush() throw() { @@ -73,7 +75,7 @@ static const wchar_t kReplaceChar = '_'; -void CStdOutStream::Normalize_UString__LF_Allowed(UString &s) +void CStdOutStream::Normalize_UString_LF_Allowed(UString &s) { unsigned len = s.Len(); wchar_t *d = s.GetBuf(); diff -Nru 7zip-22.01+dfsg/CPP/Common/StdOutStream.h 7zip-23.01+dfsg/CPP/Common/StdOutStream.h --- 7zip-22.01+dfsg/CPP/Common/StdOutStream.h 2020-03-17 12:13:18.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/StdOutStream.h 2023-03-16 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Common/StdOutStream.h -#ifndef __COMMON_STD_OUT_STREAM_H -#define __COMMON_STD_OUT_STREAM_H +#ifndef ZIP7_INC_COMMON_STD_OUT_STREAM_H +#define ZIP7_INC_COMMON_STD_OUT_STREAM_H #include @@ -11,26 +11,28 @@ class CStdOutStream { FILE *_stream; - bool _streamIsOpen; + // bool _streamIsOpen; public: bool IsTerminalMode; int CodePage; - CStdOutStream(FILE *stream = 0): + CStdOutStream(FILE *stream = NULL): _stream(stream), - _streamIsOpen(false), + // _streamIsOpen(false), IsTerminalMode(false), CodePage(-1) - {}; + {} - ~CStdOutStream() { Close(); } + // ~CStdOutStream() { Close(); } // void AttachStdStream(FILE *stream) { _stream = stream; _streamIsOpen = false; } // bool IsDefined() const { return _stream != NULL; } operator FILE *() { return _stream; } + /* bool Open(const char *fileName) throw(); bool Close() throw(); + */ bool Flush() throw(); CStdOutStream & operator<<(CStdOutStream & (* func)(CStdOutStream &)) @@ -60,7 +62,7 @@ void PrintUString(const UString &s, AString &temp); void Convert_UString_to_AString(const UString &src, AString &dest); - void Normalize_UString__LF_Allowed(UString &s); + void Normalize_UString_LF_Allowed(UString &s); void Normalize_UString(UString &s); void NormalizePrint_UString(const UString &s, UString &tempU, AString &tempA); diff -Nru 7zip-22.01+dfsg/CPP/Common/StringConvert.cpp 7zip-23.01+dfsg/CPP/Common/StringConvert.cpp --- 7zip-22.01+dfsg/CPP/Common/StringConvert.cpp 2021-05-03 09:51:38.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/StringConvert.cpp 2022-12-15 07:00:00.000000000 +0000 @@ -534,6 +534,7 @@ +#if !defined(_WIN32) || defined(ENV_HAVE_LOCALE) #ifdef _WIN32 #define U_to_A(a, b, c) UnicodeStringToMultiByte2 @@ -544,8 +545,6 @@ // #define A_to_U(a, b, c) MultiByteToUnicodeString2_Native(a, b) #endif -#if !defined(_WIN32) || defined(ENV_HAVE_LOCALE) - bool IsNativeUTF8() { UString u; diff -Nru 7zip-22.01+dfsg/CPP/Common/StringConvert.h 7zip-23.01+dfsg/CPP/Common/StringConvert.h --- 7zip-22.01+dfsg/CPP/Common/StringConvert.h 2021-04-23 17:49:50.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/StringConvert.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Common/StringConvert.h -#ifndef __COMMON_STRING_CONVERT_H -#define __COMMON_STRING_CONVERT_H +#ifndef ZIP7_INC_COMMON_STRING_CONVERT_H +#define ZIP7_INC_COMMON_STRING_CONVERT_H #include "MyString.h" #include "MyWindows.h" diff -Nru 7zip-22.01+dfsg/CPP/Common/StringToInt.h 7zip-23.01+dfsg/CPP/Common/StringToInt.h --- 7zip-22.01+dfsg/CPP/Common/StringToInt.h 2022-03-27 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/StringToInt.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Common/StringToInt.h -#ifndef __COMMON_STRING_TO_INT_H -#define __COMMON_STRING_TO_INT_H +#ifndef ZIP7_INC_COMMON_STRING_TO_INT_H +#define ZIP7_INC_COMMON_STRING_TO_INT_H #include "MyTypes.h" diff -Nru 7zip-22.01+dfsg/CPP/Common/TextConfig.cpp 7zip-23.01+dfsg/CPP/Common/TextConfig.cpp --- 7zip-22.01+dfsg/CPP/Common/TextConfig.cpp 2017-02-08 11:16:19.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/TextConfig.cpp 2023-03-16 18:00:00.000000000 +0000 @@ -15,7 +15,7 @@ AString result; for (finishPos = 0; ; finishPos++) { - char c = s[finishPos]; + const char c = s[finishPos]; if (IsDelimitChar(c) || c == '=') break; result += c; @@ -35,7 +35,7 @@ { for (; pos < s.Len(); pos++) { - char c = s[pos]; + const char c = s[pos]; if (!IsDelimitChar(c)) { if (c != ';') @@ -111,13 +111,13 @@ { FOR_VECTOR (i, pairs) if (pairs[i].ID.IsEqualTo(id)) - return i; + return (int)i; return -1; } UString GetTextConfigValue(const CObjectVector &pairs, const char *id) { - int index = FindTextConfigItem(pairs, id); + const int index = FindTextConfigItem(pairs, id); if (index < 0) return UString(); return pairs[index].String; diff -Nru 7zip-22.01+dfsg/CPP/Common/TextConfig.h 7zip-23.01+dfsg/CPP/Common/TextConfig.h --- 7zip-22.01+dfsg/CPP/Common/TextConfig.h 2017-02-07 17:25:23.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/TextConfig.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Common/TextConfig.h -#ifndef __COMMON_TEXT_CONFIG_H -#define __COMMON_TEXT_CONFIG_H +#ifndef ZIP7_INC_COMMON_TEXT_CONFIG_H +#define ZIP7_INC_COMMON_TEXT_CONFIG_H #include "MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/Common/UTFConvert.cpp 7zip-23.01+dfsg/CPP/Common/UTFConvert.cpp --- 7zip-22.01+dfsg/CPP/Common/UTFConvert.cpp 2021-05-01 12:00:27.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/UTFConvert.cpp 2023-05-03 11:00:00.000000000 +0000 @@ -8,17 +8,17 @@ #include "UTFConvert.h" -#ifndef _WCHART_IS_16BIT +#ifndef Z7_WCHART_IS_16BIT #ifndef __APPLE__ // we define it if the system supports files with non-utf8 symbols: - #define _UTF8_RAW_NON_UTF8_SUPPORTED + #define MY_UTF8_RAW_NON_UTF8_SUPPORTED #endif #endif /* - _UTF8_START(n) - is a base value for start byte (head), if there are (n) additional bytes after start byte + MY_UTF8_START(n) - is a base value for start byte (head), if there are (n) additional bytes after start byte - n : _UTF8_START(n) : Bits of code point + n : MY_UTF8_START(n) : Bits of code point 0 : 0x80 : : unused 1 : 0xC0 : 11 : @@ -30,13 +30,13 @@ 7 : 0xFF : */ -#define _UTF8_START(n) (0x100 - (1 << (7 - (n)))) +#define MY_UTF8_START(n) (0x100 - (1 << (7 - (n)))) -#define _UTF8_HEAD_PARSE2(n) \ - if (c < _UTF8_START((n) + 1)) \ - { numBytes = (n); val -= _UTF8_START(n); } +#define MY_UTF8_HEAD_PARSE2(n) \ + if (c < MY_UTF8_START((n) + 1)) \ + { numBytes = (n); val -= MY_UTF8_START(n); } -#ifndef _WCHART_IS_16BIT +#ifndef Z7_WCHART_IS_16BIT /* if (wchar_t is 32-bit), we can support large points in long UTF-8 sequence, @@ -46,30 +46,30 @@ (_UTF8_NUM_TAIL_BYTES_MAX == 6) : (36-bit hack) */ -#define _UTF8_NUM_TAIL_BYTES_MAX 5 +#define MY_UTF8_NUM_TAIL_BYTES_MAX 5 #endif /* -#define _UTF8_HEAD_PARSE \ +#define MY_UTF8_HEAD_PARSE \ UInt32 val = c; \ - _UTF8_HEAD_PARSE2(1) \ - else _UTF8_HEAD_PARSE2(2) \ - else _UTF8_HEAD_PARSE2(3) \ - else _UTF8_HEAD_PARSE2(4) \ - else _UTF8_HEAD_PARSE2(5) \ - #if _UTF8_NUM_TAIL_BYTES_MAX >= 6 - else _UTF8_HEAD_PARSE2(6) + MY_UTF8_HEAD_PARSE2(1) \ + else MY_UTF8_HEAD_PARSE2(2) \ + else MY_UTF8_HEAD_PARSE2(3) \ + else MY_UTF8_HEAD_PARSE2(4) \ + else MY_UTF8_HEAD_PARSE2(5) \ + #if MY_UTF8_NUM_TAIL_BYTES_MAX >= 6 + else MY_UTF8_HEAD_PARSE2(6) #endif */ -#define _UTF8_HEAD_PARSE_MAX_3_BYTES \ +#define MY_UTF8_HEAD_PARSE_MAX_3_BYTES \ UInt32 val = c; \ - _UTF8_HEAD_PARSE2(1) \ - else _UTF8_HEAD_PARSE2(2) \ - else { numBytes = 3; val -= _UTF8_START(3); } + MY_UTF8_HEAD_PARSE2(1) \ + else MY_UTF8_HEAD_PARSE2(2) \ + else { numBytes = 3; val -= MY_UTF8_START(3); } -#define _UTF8_RANGE(n) (((UInt32)1) << ((n) * 5 + 6)) +#define MY_UTF8_RANGE(n) (((UInt32)1) << ((n) * 5 + 6)) #define START_POINT_FOR_SURROGATE 0x10000 @@ -82,7 +82,7 @@ */ -#if defined(_WCHART_IS_16BIT) +#if defined(Z7_WCHART_IS_16BIT) #define UTF_ESCAPE_PLANE 0 @@ -102,7 +102,7 @@ #define UTF_ESCAPE_PLANE 0 /* - if (UTF_FLAG__FROM_UTF8__USE_ESCAPE is set) + if (Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE is set) { if (UTF_ESCAPE_PLANE is UTF_ESCAPE_PLANE_HIGH) { @@ -111,13 +111,13 @@ So we still need a way to extract 8-bit Escapes and BMP-Escapes-8 from same BMP-Escapes-16 stored in 7z. And if we want to restore any 8-bit from 7z archive, - we still must use UTF_FLAG__FROM_UTF8__BMP_ESCAPE_CONVERT for (utf-8 -> utf-16) + we still must use Z7_UTF_FLAG_FROM_UTF8_BMP_ESCAPE_CONVERT for (utf-8 -> utf-16) Also we need additional Conversions to tranform from utf-16 to utf-16-With-Escapes-21 } else (UTF_ESCAPE_PLANE == 0) { we must convert original 3-bytes utf-8 BMP-Escape point to sequence - of 3 BMP-Escape-16 points with UTF_FLAG__FROM_UTF8__BMP_ESCAPE_CONVERT + of 3 BMP-Escape-16 points with Z7_UTF_FLAG_FROM_UTF8_BMP_ESCAPE_CONVERT so we can extract original RAW-UTF-8 from UTFD-16 later. } } @@ -138,7 +138,7 @@ #define IS_LOW_SURROGATE_POINT(v) (((v) & (UInt32)0xfffffC00) == 0xdc00) -#define _ERROR_UTF8_CHECK \ +#define UTF_ERROR_UTF8_CHECK \ { NonUtf = true; continue; } void CUtf8Check::Check_Buf(const char *src, size_t size) throw() @@ -168,19 +168,19 @@ if (c < 0x80) continue; - if (c < 0xc0 + 2)// it's limit for 0x140000 unicode codes : win32 compatibility - _ERROR_UTF8_CHECK + if (c < 0xc0 + 2) // it's limit for 0x140000 unicode codes : win32 compatibility + UTF_ERROR_UTF8_CHECK unsigned numBytes; UInt32 val = c; - _UTF8_HEAD_PARSE2(1) - else _UTF8_HEAD_PARSE2(2) - else _UTF8_HEAD_PARSE2(4) - else _UTF8_HEAD_PARSE2(5) + MY_UTF8_HEAD_PARSE2(1) + else MY_UTF8_HEAD_PARSE2(2) + else MY_UTF8_HEAD_PARSE2(4) + else MY_UTF8_HEAD_PARSE2(5) else { - _ERROR_UTF8_CHECK + UTF_ERROR_UTF8_CHECK } unsigned pos = 0; @@ -206,7 +206,7 @@ if (pos == size) Truncated = true; else - _ERROR_UTF8_CHECK + UTF_ERROR_UTF8_CHECK } #ifdef UTF_ESCAPE_BASE @@ -268,7 +268,7 @@ return false; unsigned numBytes; - _UTF8_HEAD_PARSE + MY_UTF8_HEAD_PARSE else return false; @@ -285,7 +285,7 @@ } while (--numBytes); - if (val < _UTF8_RANGE(pos - 1)) + if (val < MY_UTF8_RANGE(pos - 1)) return false; if (val >= 0x110000) @@ -303,18 +303,18 @@ #define UTF_ESCAPE(c) \ - ((flags & UTF_FLAG__FROM_UTF8__USE_ESCAPE) ? \ + ((flags & Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE) ? \ UTF_ESCAPE_PLANE + UTF_ESCAPE_BASE + (c) : UTF_REPLACEMENT_CHAR) /* -#define _HARD_ERROR_UTF8 +#define UTF_HARD_ERROR_UTF8 { if (dest) dest[destPos] = (wchar_t)UTF_ESCAPE(c); \ destPos++; ok = false; continue; } */ // we ignore utf errors, and don't change (ok) variable! -#define _ERROR_UTF8 \ +#define UTF_ERROR_UTF8 \ { if (dest) dest[destPos] = (wchar_t)UTF_ESCAPE(c); \ destPos++; continue; } @@ -362,12 +362,12 @@ if (c < 0xc0 + 2 || c >= 0xf5) // it's limit for 0x140000 unicode codes : win32 compatibility { - _ERROR_UTF8 + UTF_ERROR_UTF8 } unsigned numBytes; - _UTF8_HEAD_PARSE_MAX_3_BYTES + MY_UTF8_HEAD_PARSE_MAX_3_BYTES unsigned pos = 0; do @@ -387,7 +387,7 @@ break; if (numBytes == 2) { - if (flags & UTF_FLAG__FROM_UTF8__SURROGATE_ERROR) + if (flags & Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR) if ((val & (0xF800 >> 6)) == (0xd800 >> 6)) break; } @@ -399,27 +399,27 @@ if (numBytes != 0) { - if ((flags & UTF_FLAG__FROM_UTF8__USE_ESCAPE) == 0) + if ((flags & Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE) == 0) { // the following code to emit the 0xfffd chars as win32 Utf8 function. // disable the folling line, if you need 0xfffd for each incorrect byte as in Escape mode src += pos; } - _ERROR_UTF8 + UTF_ERROR_UTF8 } /* - if (val < _UTF8_RANGE(pos - 1)) - _ERROR_UTF8 + if (val < MY_UTF8_RANGE(pos - 1)) + UTF_ERROR_UTF8 */ #ifdef UTF_ESCAPE_BASE - if ((flags & UTF_FLAG__FROM_UTF8__BMP_ESCAPE_CONVERT) + if ((flags & Z7_UTF_FLAG_FROM_UTF8_BMP_ESCAPE_CONVERT) && IS_ESCAPE_POINT(val, 0)) { // We will emit 3 utf16-Escape-16-21 points from one Escape-16 point (3 bytes) - _ERROR_UTF8 + UTF_ERROR_UTF8 } #endif @@ -434,11 +434,11 @@ if (val < START_POINT_FOR_SURROGATE) { /* - if ((flags & UTF_FLAG__FROM_UTF8__SURROGATE_ERROR) + if ((flags & Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR) && IS_SURROGATE_POINT(val)) { // We will emit 3 utf16-Escape-16-21 points from one Surrogate-16 point (3 bytes) - _ERROR_UTF8 + UTF_ERROR_UTF8 } */ if (dest) @@ -451,7 +451,7 @@ if (val >= 0x110000) { // We will emit utf16-Escape-16-21 point from each source byte - _ERROR_UTF8 + UTF_ERROR_UTF8 } */ if (dest) @@ -467,8 +467,8 @@ -#define _UTF8_HEAD(n, val) ((char)(_UTF8_START(n) + (val >> (6 * (n))))) -#define _UTF8_CHAR(n, val) ((char)(0x80 + (((val) >> (6 * (n))) & 0x3F))) +#define MY_UTF8_HEAD(n, val) ((char)(MY_UTF8_START(n) + (val >> (6 * (n))))) +#define MY_UTF8_CHAR(n, val) ((char)(0x80 + (((val) >> (6 * (n))) & 0x3F))) static size_t Utf16_To_Utf8_Calc(const wchar_t *src, const wchar_t *srcLim, unsigned flags) { @@ -483,7 +483,7 @@ if (val < 0x80) continue; - if (val < _UTF8_RANGE(1)) + if (val < MY_UTF8_RANGE(1)) { size++; continue; @@ -492,12 +492,12 @@ #ifdef UTF_ESCAPE_BASE #if UTF_ESCAPE_PLANE != 0 - if (flags & UTF_FLAG__TO_UTF8__PARSE_HIGH_ESCAPE) + if (flags & Z7_UTF_FLAG_TO_UTF8_PARSE_HIGH_ESCAPE) if (IS_ESCAPE_POINT(val, UTF_ESCAPE_PLANE)) continue; #endif - if (flags & UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE) + if (flags & Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE) if (IS_ESCAPE_POINT(val, 0)) continue; @@ -517,18 +517,18 @@ continue; } - #ifdef _WCHART_IS_16BIT + #ifdef Z7_WCHART_IS_16BIT size += 2; #else - if (val < _UTF8_RANGE(2)) size += 2; - else if (val < _UTF8_RANGE(3)) size += 3; - else if (val < _UTF8_RANGE(4)) size += 4; - else if (val < _UTF8_RANGE(5)) size += 5; + if (val < MY_UTF8_RANGE(2)) size += 2; + else if (val < MY_UTF8_RANGE(3)) size += 3; + else if (val < MY_UTF8_RANGE(4)) size += 4; + else if (val < MY_UTF8_RANGE(5)) size += 5; else - #if _UTF8_NUM_TAIL_BYTES_MAX >= 6 + #if MY_UTF8_NUM_TAIL_BYTES_MAX >= 6 size += 6; #else size += 3; @@ -554,10 +554,10 @@ continue; } - if (val < _UTF8_RANGE(1)) + if (val < MY_UTF8_RANGE(1)) { - dest[0] = _UTF8_HEAD(1, val); - dest[1] = _UTF8_CHAR(0, val); + dest[0] = MY_UTF8_HEAD(1, val); + dest[1] = MY_UTF8_CHAR(0, val); dest += 2; continue; } @@ -567,11 +567,11 @@ #if UTF_ESCAPE_PLANE != 0 /* if (wchar_t is 32-bit) - && (UTF_FLAG__TO_UTF8__PARSE_HIGH_ESCAPE is set) + && (Z7_UTF_FLAG_TO_UTF8_PARSE_HIGH_ESCAPE is set) && (point is virtual escape plane) we extract 8-bit byte from virtual HIGH-ESCAPE PLANE. */ - if (flags & UTF_FLAG__TO_UTF8__PARSE_HIGH_ESCAPE) + if (flags & Z7_UTF_FLAG_TO_UTF8_PARSE_HIGH_ESCAPE) if (IS_ESCAPE_POINT(val, UTF_ESCAPE_PLANE)) { *dest++ = (char)(val); @@ -579,10 +579,10 @@ } #endif // UTF_ESCAPE_PLANE != 0 - /* if (UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE is defined) + /* if (Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE is defined) we extract 8-bit byte from BMP-ESCAPE PLANE. */ - if (flags & UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE) + if (flags & Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE) if (IS_ESCAPE_POINT(val, 0)) { *dest++ = (char)(val); @@ -601,46 +601,46 @@ { src++; val = (((val - 0xd800) << 10) | (c2 - 0xdc00)) + 0x10000; - dest[0] = _UTF8_HEAD(3, val); - dest[1] = _UTF8_CHAR(2, val); - dest[2] = _UTF8_CHAR(1, val); - dest[3] = _UTF8_CHAR(0, val); + dest[0] = MY_UTF8_HEAD(3, val); + dest[1] = MY_UTF8_CHAR(2, val); + dest[2] = MY_UTF8_CHAR(1, val); + dest[3] = MY_UTF8_CHAR(0, val); dest += 4; continue; } } - if (flags & UTF_FLAG__TO_UTF8__SURROGATE_ERROR) + if (flags & Z7_UTF_FLAG_TO_UTF8_SURROGATE_ERROR) val = UTF_REPLACEMENT_CHAR; // WIN32 function does it } - #ifndef _WCHART_IS_16BIT - if (val < _UTF8_RANGE(2)) + #ifndef Z7_WCHART_IS_16BIT + if (val < MY_UTF8_RANGE(2)) #endif { - dest[0] = _UTF8_HEAD(2, val); - dest[1] = _UTF8_CHAR(1, val); - dest[2] = _UTF8_CHAR(0, val); + dest[0] = MY_UTF8_HEAD(2, val); + dest[1] = MY_UTF8_CHAR(1, val); + dest[2] = MY_UTF8_CHAR(0, val); dest += 3; continue; } - #ifndef _WCHART_IS_16BIT + #ifndef Z7_WCHART_IS_16BIT // we don't expect this case. so we can throw exception // throw 20210407; char b; unsigned numBits; - if (val < _UTF8_RANGE(3)) { numBits = 6 * 3; b = _UTF8_HEAD(3, val); } - else if (val < _UTF8_RANGE(4)) { numBits = 6 * 4; b = _UTF8_HEAD(4, val); } - else if (val < _UTF8_RANGE(5)) { numBits = 6 * 5; b = _UTF8_HEAD(5, val); } - #if _UTF8_NUM_TAIL_BYTES_MAX >= 6 - else { numBits = 6 * 6; b = (char)_UTF8_START(6); } + if (val < MY_UTF8_RANGE(3)) { numBits = 6 * 3; b = MY_UTF8_HEAD(3, val); } + else if (val < MY_UTF8_RANGE(4)) { numBits = 6 * 4; b = MY_UTF8_HEAD(4, val); } + else if (val < MY_UTF8_RANGE(5)) { numBits = 6 * 5; b = MY_UTF8_HEAD(5, val); } + #if MY_UTF8_NUM_TAIL_BYTES_MAX >= 6 + else { numBits = 6 * 6; b = (char)MY_UTF8_START(6); } #else else { val = UTF_REPLACEMENT_CHAR; - { numBits = 6 * 3; b = _UTF8_HEAD(3, val); } + { numBits = 6 * 3; b = MY_UTF8_HEAD(3, val); } } #endif @@ -675,11 +675,11 @@ static unsigned g_UTF8_To_Unicode_Flags = - UTF_FLAG__FROM_UTF8__USE_ESCAPE - #ifndef _WCHART_IS_16BIT - | UTF_FLAG__FROM_UTF8__SURROGATE_ERROR - #ifdef _UTF8_RAW_NON_UTF8_SUPPORTED - | UTF_FLAG__FROM_UTF8__BMP_ESCAPE_CONVERT + Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE + #ifndef Z7_WCHART_IS_16BIT + | Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR + #ifdef MY_UTF8_RAW_NON_UTF8_SUPPORTED + | Z7_UTF_FLAG_FROM_UTF8_BMP_ESCAPE_CONVERT #endif #endif ; @@ -729,13 +729,13 @@ unsigned g_Unicode_To_UTF8_Flags = - // UTF_FLAG__TO_UTF8__PARSE_HIGH_ESCAPE + // Z7_UTF_FLAG_TO_UTF8_PARSE_HIGH_ESCAPE 0 #ifndef _WIN32 - #ifdef _UTF8_RAW_NON_UTF8_SUPPORTED - | UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE + #ifdef MY_UTF8_RAW_NON_UTF8_SUPPORTED + | Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE #else - | UTF_FLAG__TO_UTF8__SURROGATE_ERROR; + | Z7_UTF_FLAG_TO_UTF8_SURROGATE_ERROR #endif #endif ; @@ -840,7 +840,7 @@ } */ -#ifndef _WCHART_IS_16BIT +#ifndef Z7_WCHART_IS_16BIT void Convert_UnicodeEsc16_To_UnicodeEscHigh #if UTF_ESCAPE_PLANE == 0 diff -Nru 7zip-22.01+dfsg/CPP/Common/UTFConvert.h 7zip-23.01+dfsg/CPP/Common/UTFConvert.h --- 7zip-22.01+dfsg/CPP/Common/UTFConvert.h 2021-04-26 08:40:27.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/UTFConvert.h 2023-03-15 20:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Common/UTFConvert.h -#ifndef __COMMON_UTF_CONVERT_H -#define __COMMON_UTF_CONVERT_H +#ifndef ZIP7_INC_COMMON_UTF_CONVERT_H +#define ZIP7_INC_COMMON_UTF_CONVERT_H #include "MyBuffer.h" #include "MyString.h" @@ -88,12 +88,12 @@ bool Check_UTF8_Buf(const char *src, size_t size, bool allowReduced) throw(); bool CheckUTF8_AString(const AString &s) throw(); -#define UTF_FLAG__FROM_UTF8__SURROGATE_ERROR (1 << 0) -#define UTF_FLAG__FROM_UTF8__USE_ESCAPE (1 << 1) -#define UTF_FLAG__FROM_UTF8__BMP_ESCAPE_CONVERT (1 << 2) +#define Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR (1 << 0) +#define Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE (1 << 1) +#define Z7_UTF_FLAG_FROM_UTF8_BMP_ESCAPE_CONVERT (1 << 2) /* -UTF_FLAG__FROM_UTF8__SURROGATE_ERROR +Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR if (flag is NOT set) { @@ -108,14 +108,14 @@ if (flag is set) { - if (UTF_FLAG__FROM_UTF8__USE_ESCAPE is defined) + if (Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE is defined) it generates ESCAPE for SINGLE-SURROGATE-8, - if (UTF_FLAG__FROM_UTF8__USE_ESCAPE is not defined) + if (Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE is not defined) it generates U+fffd for SINGLE-SURROGATE-8, } -UTF_FLAG__FROM_UTF8__USE_ESCAPE +Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE if (flag is NOT set) it generates (U+fffd) code for non-UTF-8 (invalid) characters @@ -126,7 +126,7 @@ And later we can restore original UTF-8-RAW characters from (ESCAPE-16-21) codes. } -UTF_FLAG__FROM_UTF8__BMP_ESCAPE_CONVERT +Z7_UTF_FLAG_FROM_UTF8_BMP_ESCAPE_CONVERT if (flag is NOT set) { @@ -146,9 +146,9 @@ WIN32: UTF-16-RAW -> UTF-8 (Archive) -> UTF-16-RAW { - set UTF_FLAG__FROM_UTF8__USE_ESCAPE - Do NOT set UTF_FLAG__FROM_UTF8__SURROGATE_ERROR - Do NOT set UTF_FLAG__FROM_UTF8__BMP_ESCAPE_CONVERT + set Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE + Do NOT set Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR + Do NOT set Z7_UTF_FLAG_FROM_UTF8_BMP_ESCAPE_CONVERT So we restore original SINGLE-SURROGATE-16 from single SINGLE-SURROGATE-8. } @@ -157,17 +157,17 @@ { we want restore original UTF-8-RAW sequence later from that ESCAPE-16. Set the flags: - UTF_FLAG__FROM_UTF8__SURROGATE_ERROR - UTF_FLAG__FROM_UTF8__USE_ESCAPE - UTF_FLAG__FROM_UTF8__BMP_ESCAPE_CONVERT + Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR + Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE + Z7_UTF_FLAG_FROM_UTF8_BMP_ESCAPE_CONVERT } MacOS: UTF-8-RAW -> UTF-16 (Intermediate / Archive) -> UTF-8-RAW { we want to restore correct UTF-8 without any BMP processing: Set the flags: - UTF_FLAG__FROM_UTF8__SURROGATE_ERROR - UTF_FLAG__FROM_UTF8__USE_ESCAPE + Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR + Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE } */ @@ -178,12 +178,12 @@ bool ConvertUTF8ToUnicode_Flags(const AString &src, UString &dest, unsigned flags = 0); bool ConvertUTF8ToUnicode(const AString &src, UString &dest); -#define UTF_FLAG__TO_UTF8__SURROGATE_ERROR (1 << 8) -#define UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE (1 << 9) -// #define UTF_FLAG__TO_UTF8__PARSE_HIGH_ESCAPE (1 << 10) +#define Z7_UTF_FLAG_TO_UTF8_SURROGATE_ERROR (1 << 8) +#define Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE (1 << 9) +// #define Z7_UTF_FLAG_TO_UTF8_PARSE_HIGH_ESCAPE (1 << 10) /* -UTF_FLAG__TO_UTF8__SURROGATE_ERROR +Z7_UTF_FLAG_TO_UTF8_SURROGATE_ERROR if (flag is NOT set) { @@ -193,7 +193,7 @@ In Linux : use-case-1: UTF-8 -> UTF-16 -> UTF-8 doesn't generate UTF-16 SINGLE-SURROGATE, - if (UTF_FLAG__FROM_UTF8__SURROGATE_ERROR) is used. + if (Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR) is used. use-case 2: UTF-16-7z (with SINGLE-SURROGATE from Windows) -> UTF-8 (Linux) will generate SINGLE-SURROGATE-UTF-8 here. } @@ -206,17 +206,17 @@ } -UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE +Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE if (flag is NOT set) it doesn't extract raw 8-bit symbol from Escape-Plane-16 if (flag is set) it extracts raw 8-bit symbol from Escape-Plane-16 in Linux we need some way to extract NON-UTF8 RAW 8-bits from BMP (UTF-16 7z archive): if (we use High-Escape-Plane), we can transfer BMP escapes to High-Escape-Plane. - if (we don't use High-Escape-Plane), we must use UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE. + if (we don't use High-Escape-Plane), we must use Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE. -UTF_FLAG__TO_UTF8__PARSE_HIGH_ESCAPE +Z7_UTF_FLAG_TO_UTF8_PARSE_HIGH_ESCAPE // that flag affects the code only if (wchar_t is 32-bit) // that mode with high-escape can be disabled now in UTFConvert.cpp if (flag is NOT set) @@ -228,19 +228,19 @@ WIN32 : UTF-16-RAW -> UTF-8 (archive) -> UTF-16-RAW { - Do NOT set UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE. - Do NOT set UTF_FLAG__TO_UTF8__SURROGATE_ERROR. + Do NOT set Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE. + Do NOT set Z7_UTF_FLAG_TO_UTF8_SURROGATE_ERROR. So we restore original UTF-16-RAW. } Linix : UTF-8 with Escapes -> UTF-16 (7z archive) -> UTF-8 with Escapes - set UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE to extract non-UTF from 7z archive - set UTF_FLAG__TO_UTF8__PARSE_HIGH_ESCAPE for intermediate UTF-16. + set Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE to extract non-UTF from 7z archive + set Z7_UTF_FLAG_TO_UTF8_PARSE_HIGH_ESCAPE for intermediate UTF-16. Note: high esacape mode can be ignored now in UTFConvert.cpp macOS: the system doesn't support incorrect UTF-8 in file names. - set UTF_FLAG__TO_UTF8__SURROGATE_ERROR + set Z7_UTF_FLAG_TO_UTF8_SURROGATE_ERROR */ extern unsigned g_Unicode_To_UTF8_Flags; @@ -261,7 +261,7 @@ bool Unicode_IsThere_Utf16SurrogateError(const UString &src); */ -#ifdef _WCHART_IS_16BIT +#ifdef Z7_WCHART_IS_16BIT #define Convert_UnicodeEsc16_To_UnicodeEscHigh(s) #else void Convert_UnicodeEsc16_To_UnicodeEscHigh(UString &s); diff -Nru 7zip-22.01+dfsg/CPP/Common/Wildcard.cpp 7zip-23.01+dfsg/CPP/Common/Wildcard.cpp --- 7zip-22.01+dfsg/CPP/Common/Wildcard.cpp 2021-12-26 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/Wildcard.cpp 2022-12-30 15:00:00.000000000 +0000 @@ -125,8 +125,8 @@ { for (;;) { - wchar_t m = *mask; - wchar_t c = *name; + const wchar_t m = *mask; + const wchar_t c = *name; if (m == 0) return (c == 0); if (m == '*') @@ -526,12 +526,10 @@ bool IsDriveColonName(const wchar_t *s) { - wchar_t c = s[0]; - return c != 0 - && s[1] == ':' - && s[2] == 0 - && ((c >= 'a' && c <= 'z') - || (c >= 'A' && c <= 'Z')); + unsigned c = s[0]; + c |= 0x20; + c -= 'a'; + return c <= (unsigned)('z' - 'a') && s[1] == ':' && s[2] == 0; } unsigned GetNumPrefixParts_if_DrivePath(UStringVector &pathParts) diff -Nru 7zip-22.01+dfsg/CPP/Common/Wildcard.h 7zip-23.01+dfsg/CPP/Common/Wildcard.h --- 7zip-22.01+dfsg/CPP/Common/Wildcard.h 2021-12-25 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/Wildcard.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Common/Wildcard.h -#ifndef __COMMON_WILDCARD_H -#define __COMMON_WILDCARD_H +#ifndef ZIP7_INC_COMMON_WILDCARD_H +#define ZIP7_INC_COMMON_WILDCARD_H #include "MyString.h" @@ -83,7 +83,7 @@ CCensorNode(): Parent(NULL) // , ExcludeDirItems(false) - {}; + {} CCensorNode(const UString &name, CCensorNode *parent): Parent(parent) diff -Nru 7zip-22.01+dfsg/CPP/Common/XzCrc64Reg.cpp 7zip-23.01+dfsg/CPP/Common/XzCrc64Reg.cpp --- 7zip-22.01+dfsg/CPP/Common/XzCrc64Reg.cpp 2016-04-06 10:23:14.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Common/XzCrc64Reg.cpp 2023-03-16 20:00:00.000000000 +0000 @@ -9,34 +9,31 @@ #include "../7zip/Common/RegisterCodec.h" -class CXzCrc64Hasher: - public IHasher, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CXzCrc64Hasher + , IHasher +) UInt64 _crc; - Byte mtDummy[1 << 7]; - public: - CXzCrc64Hasher(): _crc(CRC64_INIT_VAL) {} + Byte _mtDummy[1 << 7]; // it's public to eliminate clang warning: unused private field - MY_UNKNOWN_IMP1(IHasher) - INTERFACE_IHasher(;) + CXzCrc64Hasher(): _crc(CRC64_INIT_VAL) {} }; -STDMETHODIMP_(void) CXzCrc64Hasher::Init() throw() +Z7_COM7F_IMF2(void, CXzCrc64Hasher::Init()) { _crc = CRC64_INIT_VAL; } -STDMETHODIMP_(void) CXzCrc64Hasher::Update(const void *data, UInt32 size) throw() +Z7_COM7F_IMF2(void, CXzCrc64Hasher::Update(const void *data, UInt32 size)) { _crc = Crc64Update(_crc, data, size); } -STDMETHODIMP_(void) CXzCrc64Hasher::Final(Byte *digest) throw() +Z7_COM7F_IMF2(void, CXzCrc64Hasher::Final(Byte *digest)) { - UInt64 val = CRC64_GET_DIGEST(_crc); - SetUi64(digest, val); + const UInt64 val = CRC64_GET_DIGEST(_crc); + SetUi64(digest, val) } REGISTER_HASHER(CXzCrc64Hasher, 0x4, "CRC64", 8) diff -Nru 7zip-22.01+dfsg/CPP/Windows/Clipboard.h 7zip-23.01+dfsg/CPP/Windows/Clipboard.h --- 7zip-22.01+dfsg/CPP/Windows/Clipboard.h 2013-02-14 09:17:32.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Clipboard.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Clipboard.h -#ifndef __CLIPBOARD_H -#define __CLIPBOARD_H +#ifndef ZIP7_INC_CLIPBOARD_H +#define ZIP7_INC_CLIPBOARD_H #include "../Common/MyString.h" @@ -11,7 +11,7 @@ { bool m_Open; public: - CClipboard(): m_Open(false) {}; + CClipboard(): m_Open(false) {} ~CClipboard() { Close(); } bool Open(HWND wndNewOwner) throw(); bool Close() throw(); diff -Nru 7zip-22.01+dfsg/CPP/Windows/COM.h 7zip-23.01+dfsg/CPP/Windows/COM.h --- 7zip-22.01+dfsg/CPP/Windows/COM.h 2014-08-11 05:39:51.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/COM.h 2023-03-17 16:00:00.000000000 +0000 @@ -1,9 +1,9 @@ // Windows/COM.h -#ifndef __WINDOWS_COM_H -#define __WINDOWS_COM_H +#ifndef ZIP7_INC_WINDOWS_COM_H +#define ZIP7_INC_WINDOWS_COM_H -#include "../Common/MyString.h" +// #include "../Common/MyString.h" namespace NWindows { namespace NCOM { @@ -21,17 +21,18 @@ // it's single thread. Do we need multithread? CoInitialize(NULL); #endif - }; + } ~CComInitializer() { CoUninitialize(); } }; -class CStgMedium +/* +class CStgMedium2 { STGMEDIUM _object; -public: bool _mustBeReleased; - CStgMedium(): _mustBeReleased(false) {} - ~CStgMedium() { Free(); } +public: + CStgMedium2(): _mustBeReleased(false) {} + ~CStgMedium2() { Free(); } void Free() { if (_mustBeReleased) @@ -42,6 +43,21 @@ STGMEDIUM* operator->() { return &_object;} STGMEDIUM* operator&() { return &_object; } }; +*/ + +struct CStgMedium: public STGMEDIUM +{ + CStgMedium() + { + tymed = TYMED_NULL; // 0 + hGlobal = NULL; + pUnkForRelease = NULL; + } + ~CStgMedium() + { + ReleaseStgMedium(this); + } +}; #endif diff -Nru 7zip-22.01+dfsg/CPP/Windows/CommonDialog.cpp 7zip-23.01+dfsg/CPP/Windows/CommonDialog.cpp --- 7zip-22.01+dfsg/CPP/Windows/CommonDialog.cpp 2021-01-26 09:21:31.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/CommonDialog.cpp 2023-03-17 16:00:00.000000000 +0000 @@ -2,7 +2,7 @@ #include "StdAfx.h" -#include "../Common/MyWindows.h" +#include "../Common/MyBuffer.h" #ifdef UNDER_CE #include @@ -14,6 +14,7 @@ #include "CommonDialog.h" #include "Defs.h" +// #include "FileDir.h" #ifndef _UNICODE extern bool g_IsNT; @@ -21,61 +22,46 @@ namespace NWindows { -#ifndef _UNICODE - -class CDoubleZeroStringListA -{ - LPTSTR Buf; - unsigned Size; -public: - CDoubleZeroStringListA(LPSTR buf, unsigned size): Buf(buf), Size(size) {} - bool Add(LPCSTR s) throw(); - void Finish() { *Buf = 0; } -}; - -bool CDoubleZeroStringListA::Add(LPCSTR s) throw() -{ - unsigned len = MyStringLen(s) + 1; - if (len >= Size) - return false; - MyStringCopy(Buf, s); - Buf += len; - Size -= len; - return true; -} - -#endif - -class CDoubleZeroStringListW -{ - LPWSTR Buf; - unsigned Size; -public: - CDoubleZeroStringListW(LPWSTR buf, unsigned size): Buf(buf), Size(size) {} - bool Add(LPCWSTR s) throw(); - void Finish() { *Buf = 0; } -}; +/* + GetSaveFileName() + GetOpenFileName() + OPENFILENAME -bool CDoubleZeroStringListW::Add(LPCWSTR s) throw() +(lpstrInitialDir) : the initial directory. +DOCs: the algorithm for selecting the initial directory varies on different platforms: { - unsigned len = MyStringLen(s) + 1; - if (len >= Size) - return false; - MyStringCopy(Buf, s); - Buf += len; - Size -= len; - return true; + Win2000/XP/Vista: + 1. If lpstrFile contains a path, that path is the initial directory. + 2. Otherwise, lpstrInitialDir specifies the initial directory. + + Win7: + If lpstrInitialDir has the same value as was passed the first time + the application used an Open or Save As dialog box, the path + most recently selected by the user is used as the initial directory. } +Win10: + in: + function supports (lpstrInitialDir) path with super prefix "\\\\?\\" + function supports (lpstrInitialDir) path with long path + function doesn't support absolute (lpstrFile) path with super prefix "\\\\?\\" + function doesn't support absolute (lpstrFile) path with long path + out: the path with super prefix "\\\\?\\" will be returned, if selected path is long + +WinXP-64 and Win10: if no filters, the system shows all files. + but DOCs say: If all three members are zero or NULL, + the system does not use any filters and does not + show any files in the file list control of the dialog box. + +in Win7+: GetOpenFileName() and GetSaveFileName() + do not support pstrCustomFilter feature anymore +*/ #ifdef UNDER_CE -#define MY__OFN_PROJECT 0x00400000 -#define MY__OFN_SHOW_ALL 0x01000000 +#define MY_OFN_PROJECT 0x00400000 +#define MY_OFN_SHOW_ALL 0x01000000 #endif -/* if (lpstrFilter == NULL && nFilterIndex == 0) - MSDN : "the system doesn't show any files", - but WinXP-64 shows all files. Why ??? */ /* structures @@ -89,16 +75,16 @@ #endif If we compile the source code with (_WIN32_WINNT >= 0x0500), some functions -will not work at NT 4.0, if we use sizeof(OPENFILENAME*). -So we use size of old version of structure. */ +will not work at NT 4.0, if we use sizeof(OPENFILENAME). +We try to use reduced structure OPENFILENAME_NT4. +*/ -#if defined(UNDER_CE) || defined(_WIN64) || (_WIN32_WINNT < 0x0500) -// || !defined(WINVER) +// #if defined(_WIN64) || (defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0500) +#if defined(__GNUC__) && (__GNUC__ <= 9) || defined(Z7_OLD_WIN_SDK) #ifndef _UNICODE - #define my_compatib_OPENFILENAMEA_size sizeof(OPENFILENAMEA) + #define my_compatib_OPENFILENAMEA OPENFILENAMEA #endif - #define my_compatib_OPENFILENAMEW_size sizeof(OPENFILENAMEW) -#else + #define my_compatib_OPENFILENAMEW OPENFILENAMEW // MinGW doesn't support some required macros. So we define them here: #ifndef CDSIZEOF_STRUCT @@ -117,91 +103,166 @@ #define my_compatib_OPENFILENAMEA_size OPENFILENAME_SIZE_VERSION_400A #endif #define my_compatib_OPENFILENAMEW_size OPENFILENAME_SIZE_VERSION_400W +#else + #ifndef _UNICODE + #define my_compatib_OPENFILENAMEA OPENFILENAME_NT4A + #define my_compatib_OPENFILENAMEA_size sizeof(my_compatib_OPENFILENAMEA) + #endif + #define my_compatib_OPENFILENAMEW OPENFILENAME_NT4W + #define my_compatib_OPENFILENAMEW_size sizeof(my_compatib_OPENFILENAMEW) +#endif +/* +#elif defined(UNDER_CE) || defined(_WIN64) || (_WIN32_WINNT < 0x0500) +// || !defined(WINVER) + #ifndef _UNICODE + #define my_compatib_OPENFILENAMEA OPENFILENAMEA + #define my_compatib_OPENFILENAMEA_size sizeof(OPENFILENAMEA) + #endif + #define my_compatib_OPENFILENAMEW OPENFILENAMEW + #define my_compatib_OPENFILENAMEW_size sizeof(OPENFILENAMEW) +#else + #endif +*/ #ifndef _UNICODE #define CONV_U_To_A(dest, src, temp) AString temp; if (src) { temp = GetSystemString(src); dest = temp; } #endif -bool MyGetOpenFileName(HWND hwnd, LPCWSTR title, - LPCWSTR initialDir, - LPCWSTR filePath, - LPCWSTR filterDescription, - LPCWSTR filter, - UString &resPath - #ifdef UNDER_CE - , bool openFolder - #endif - ) +bool CCommonDialogInfo::CommonDlg_BrowseForFile(LPCWSTR lpstrInitialDir, const UStringVector &filters) { - const unsigned kBufSize = MAX_PATH * 2; - const unsigned kFilterBufSize = MAX_PATH; - if (!filter) - filter = L"*.*"; - #ifndef _UNICODE + /* GetSaveFileName() and GetOpenFileName() could change current dir, + if OFN_NOCHANGEDIR is not used. + We can restore current dir manually, if it's required. + 22.02: we use OFN_NOCHANGEDIR. So we don't need to restore current dir manually. */ + // NFile::NDir::CCurrentDirRestorer curDirRestorer; + +#ifndef _UNICODE if (!g_IsNT) { - CHAR buf[kBufSize]; - MyStringCopy(buf, (const char *)GetSystemString(filePath)); - // OPENFILENAME_NT4A - OPENFILENAMEA p; + AString tempPath; + AStringVector f; + unsigned i; + for (i = 0; i < filters.Size(); i++) + f.Add(GetSystemString(filters[i])); + unsigned size = f.Size() + 1; + for (i = 0; i < f.Size(); i++) + size += f[i].Len(); + CObjArray filterBuf(size); + // memset(filterBuf, 0, size * sizeof(char)); + { + char *dest = filterBuf; + for (i = 0; i < f.Size(); i++) + { + const AString &s = f[i]; + MyStringCopy(dest, s); + dest += s.Len() + 1; + } + *dest = 0; + } + my_compatib_OPENFILENAMEA p; memset(&p, 0, sizeof(p)); p.lStructSize = my_compatib_OPENFILENAMEA_size; - p.hwndOwner = hwnd; - CHAR filterBuf[kFilterBufSize]; + p.hwndOwner = hwndOwner; + if (size > 1) { - CDoubleZeroStringListA dz(filterBuf, kFilterBufSize); - dz.Add(GetSystemString(filterDescription ? filterDescription : filter)); - dz.Add(GetSystemString(filter)); - dz.Finish(); p.lpstrFilter = filterBuf; - p.nFilterIndex = 1; + p.nFilterIndex = (DWORD)(FilterIndex + 1); + } + + CONV_U_To_A(p.lpstrInitialDir, lpstrInitialDir, initialDir_a) + CONV_U_To_A(p.lpstrTitle, lpstrTitle, title_a) + + const AString filePath_a = GetSystemString(FilePath); + const unsigned bufSize = MAX_PATH * 8 + + filePath_a.Len() + + initialDir_a.Len(); + p.nMaxFile = bufSize; + p.lpstrFile = tempPath.GetBuf(bufSize); + MyStringCopy(p.lpstrFile, filePath_a); + p.Flags = + OFN_EXPLORER + | OFN_HIDEREADONLY + | OFN_NOCHANGEDIR; + const BOOL b = SaveMode ? + ::GetSaveFileNameA((LPOPENFILENAMEA)(void *)&p) : + ::GetOpenFileNameA((LPOPENFILENAMEA)(void *)&p); + if (!b) + return false; + { + tempPath.ReleaseBuf_CalcLen(bufSize); + FilePath = GetUnicodeString(tempPath); + FilterIndex = (int)p.nFilterIndex - 1; + return true; } - - p.lpstrFile = buf; - p.nMaxFile = kBufSize; - CONV_U_To_A(p.lpstrInitialDir, initialDir, initialDirA); - CONV_U_To_A(p.lpstrTitle, title, titleA); - p.Flags = OFN_EXPLORER | OFN_HIDEREADONLY; - - bool res = BOOLToBool(::GetOpenFileNameA(&p)); - resPath = GetUnicodeString(buf); - return res; } else - #endif +#endif { - WCHAR buf[kBufSize]; - MyStringCopy(buf, filePath); - // OPENFILENAME_NT4W - OPENFILENAMEW p; + UString tempPath; + unsigned size = filters.Size() + 1; + unsigned i; + for (i = 0; i < filters.Size(); i++) + size += filters[i].Len(); + CObjArray filterBuf(size); + // memset(filterBuf, 0, size * sizeof(wchar_t)); + { + wchar_t *dest = filterBuf; + for (i = 0; i < filters.Size(); i++) + { + const UString &s = filters[i]; + MyStringCopy(dest, s); + dest += s.Len() + 1; + } + *dest = 0; + // if ((unsigned)(dest + 1 - filterBuf) != size) return false; + } + my_compatib_OPENFILENAMEW p; memset(&p, 0, sizeof(p)); p.lStructSize = my_compatib_OPENFILENAMEW_size; - p.hwndOwner = hwnd; - - WCHAR filterBuf[kFilterBufSize]; - { - CDoubleZeroStringListW dz(filterBuf, kFilterBufSize); - dz.Add(filterDescription ? filterDescription : filter); - dz.Add(filter); - dz.Finish(); + p.hwndOwner = hwndOwner; + if (size > 1) + { p.lpstrFilter = filterBuf; - p.nFilterIndex = 1; + p.nFilterIndex = (DWORD)(FilterIndex + 1); } - - p.lpstrFile = buf; - p.nMaxFile = kBufSize; - p.lpstrInitialDir = initialDir; - p.lpstrTitle = title; - p.Flags = OFN_EXPLORER | OFN_HIDEREADONLY - #ifdef UNDER_CE - | (openFolder ? (MY__OFN_PROJECT | MY__OFN_SHOW_ALL) : 0) - #endif + unsigned bufSize = MAX_PATH * 8 + FilePath.Len(); + if (lpstrInitialDir) + { + p.lpstrInitialDir = lpstrInitialDir; + bufSize += MyStringLen(lpstrInitialDir); + } + p.nMaxFile = bufSize; + p.lpstrFile = tempPath.GetBuf(bufSize); + MyStringCopy(p.lpstrFile, FilePath); + p.lpstrTitle = lpstrTitle; + p.Flags = + OFN_EXPLORER + | OFN_HIDEREADONLY + | OFN_NOCHANGEDIR + // | OFN_FORCESHOWHIDDEN // Win10 shows hidden items even without this flag + // | OFN_PATHMUSTEXIST + #ifdef UNDER_CE + | (OpenFolderMode ? (MY_OFN_PROJECT | MY_OFN_SHOW_ALL) : 0) + #endif ; - - bool res = BOOLToBool(::GetOpenFileNameW(&p)); - resPath = buf; - return res; + const BOOL b = SaveMode ? + ::GetSaveFileNameW((LPOPENFILENAMEW)(void *)&p) : + ::GetOpenFileNameW((LPOPENFILENAMEW)(void *)&p); + /* DOCs: lpstrFile : + if the buffer is too small, then: + - the function returns FALSE + - the CommDlgExtendedError() returns FNERR_BUFFERTOOSMALL + - the first two bytes of the lpstrFile buffer contain the + required size, in bytes or characters. */ + if (!b) + return false; + { + tempPath.ReleaseBuf_CalcLen(bufSize); + FilePath = tempPath; + FilterIndex = (int)p.nFilterIndex - 1; + return true; + } } } diff -Nru 7zip-22.01+dfsg/CPP/Windows/CommonDialog.h 7zip-23.01+dfsg/CPP/Windows/CommonDialog.h --- 7zip-22.01+dfsg/CPP/Windows/CommonDialog.h 2013-01-17 10:21:58.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/CommonDialog.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,22 +1,42 @@ // Windows/CommonDialog.h -#ifndef __WINDOWS_COMMON_DIALOG_H -#define __WINDOWS_COMMON_DIALOG_H +#ifndef ZIP7_INC_WINDOWS_COMMON_DIALOG_H +#define ZIP7_INC_WINDOWS_COMMON_DIALOG_H #include "../Common/MyString.h" namespace NWindows { -bool MyGetOpenFileName(HWND hwnd, LPCWSTR title, - LPCWSTR initialDir, // can be NULL, so dir prefix in filePath will be used - LPCWSTR filePath, // full path - LPCWSTR filterDescription, // like "All files (*.*)" - LPCWSTR filter, // like "*.exe" - UString &resPath - #ifdef UNDER_CE - , bool openFolder = false - #endif -); +struct CCommonDialogInfo +{ + /* (FilterIndex == -1) means no selected filter. + and (-1) also is reserved for unsupported custom filter. + if (FilterIndex >= 0), then FilterIndex is index of filter */ + int FilterIndex; // [in / out] + bool SaveMode; + #ifdef UNDER_CE + bool OpenFolderMode; + #endif + HWND hwndOwner; + // LPCWSTR lpstrInitialDir; + LPCWSTR lpstrTitle; + UString FilePath; // [in / out] + + CCommonDialogInfo() + { + FilterIndex = -1; + SaveMode = false; + #ifdef UNDER_CE + OpenFolderMode = false; + #endif + hwndOwner = NULL; + // lpstrInitialDir = NULL; + lpstrTitle = NULL; + } + + /* (filters) : 2 sequential vector strings (Description, Masks) represent each filter */ + bool CommonDlg_BrowseForFile(LPCWSTR lpstrInitialDir, const UStringVector &filters); +}; } diff -Nru 7zip-22.01+dfsg/CPP/Windows/Console.h 7zip-23.01+dfsg/CPP/Windows/Console.h --- 7zip-22.01+dfsg/CPP/Windows/Console.h 2014-07-05 10:51:18.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Console.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Console.h -#ifndef __WINDOWS_CONSOLE_H -#define __WINDOWS_CONSOLE_H +#ifndef ZIP7_INC_WINDOWS_CONSOLE_H +#define ZIP7_INC_WINDOWS_CONSOLE_H #include "Defs.h" diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/ComboBox.cpp 7zip-23.01+dfsg/CPP/Windows/Control/ComboBox.cpp --- 7zip-22.01+dfsg/CPP/Windows/Control/ComboBox.cpp 2021-01-25 19:12:24.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/ComboBox.cpp 2023-01-19 20:00:00.000000000 +0000 @@ -43,10 +43,10 @@ s.Empty(); if (g_IsNT) { - LRESULT len = SendMsgW(CB_GETLBTEXTLEN, MY__int_TO_WPARAM(index), 0); + LRESULT len = SendMsgW(CB_GETLBTEXTLEN, MY_int_TO_WPARAM(index), 0); if (len == CB_ERR) return len; - LRESULT len2 = SendMsgW(CB_GETLBTEXT, MY__int_TO_WPARAM(index), (LPARAM)s.GetBuf((unsigned)len)); + LRESULT len2 = SendMsgW(CB_GETLBTEXT, MY_int_TO_WPARAM(index), (LPARAM)s.GetBuf((unsigned)len)); if (len2 == CB_ERR) return len; if (len > len2) @@ -55,11 +55,11 @@ return len; } AString sa; - LRESULT len = GetLBText(index, sa); + const LRESULT len = GetLBText(index, sa); if (len == CB_ERR) return len; s = GetUnicodeString(sa); - return s.Len(); + return (LRESULT)s.Len(); } #endif diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/ComboBox.h 7zip-23.01+dfsg/CPP/Windows/Control/ComboBox.h --- 7zip-22.01+dfsg/CPP/Windows/Control/ComboBox.h 2021-02-09 19:50:06.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/ComboBox.h 2023-03-17 15:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Control/ComboBox.h -#ifndef __WINDOWS_CONTROL_COMBOBOX_H -#define __WINDOWS_CONTROL_COMBOBOX_H +#ifndef ZIP7_INC_WINDOWS_CONTROL_COMBOBOX_H +#define ZIP7_INC_WINDOWS_CONTROL_COMBOBOX_H #include "../../Common/MyWindows.h" @@ -12,8 +12,6 @@ namespace NWindows { namespace NControl { -#define MY__int_TO_WPARAM(i) ((WPARAM)(INT_PTR)(i)) - class CComboBox: public CWindow { public: @@ -24,7 +22,8 @@ #endif /* If this parameter is -1, any current selection in the list is removed and the edit control is cleared.*/ - LRESULT SetCurSel(int index) { return SendMsg(CB_SETCURSEL, MY__int_TO_WPARAM(index), 0); } + LRESULT SetCurSel(int index) { return SendMsg(CB_SETCURSEL, MY_int_TO_WPARAM(index), 0); } + LRESULT SetCurSel(unsigned index) { return SendMsg(CB_SETCURSEL, index, 0); } /* If no item is selected, it returns CB_ERR (-1) */ int GetCurSel() { return (int)SendMsg(CB_GETCURSEL, 0, 0); } @@ -32,15 +31,16 @@ /* If an error occurs, it is CB_ERR (-1) */ int GetCount() { return (int)SendMsg(CB_GETCOUNT, 0, 0); } - LRESULT GetLBTextLen(int index) { return SendMsg(CB_GETLBTEXTLEN, MY__int_TO_WPARAM(index), 0); } - LRESULT GetLBText(int index, LPTSTR s) { return SendMsg(CB_GETLBTEXT, MY__int_TO_WPARAM(index), (LPARAM)s); } + LRESULT GetLBTextLen(int index) { return SendMsg(CB_GETLBTEXTLEN, MY_int_TO_WPARAM(index), 0); } + LRESULT GetLBText(int index, LPTSTR s) { return SendMsg(CB_GETLBTEXT, MY_int_TO_WPARAM(index), (LPARAM)s); } LRESULT GetLBText(int index, CSysString &s); #ifndef _UNICODE LRESULT GetLBText(int index, UString &s); #endif - LRESULT SetItemData(int index, LPARAM lParam) { return SendMsg(CB_SETITEMDATA, MY__int_TO_WPARAM(index), lParam); } - LRESULT GetItemData(int index) { return SendMsg(CB_GETITEMDATA, MY__int_TO_WPARAM(index), 0); } + LRESULT SetItemData(int index, LPARAM lParam) { return SendMsg(CB_SETITEMDATA, MY_int_TO_WPARAM(index), lParam); } + LRESULT GetItemData(int index) { return SendMsg(CB_GETITEMDATA, MY_int_TO_WPARAM(index), 0); } + LRESULT GetItemData(unsigned index) { return SendMsg(CB_GETITEMDATA, index, 0); } LRESULT GetItemData_of_CurSel() { return GetItemData(GetCurSel()); } @@ -57,7 +57,7 @@ /* Returns: an INT value that represents the number of items remaining in the control. If (index) is invalid, the message returns CB_ERR. */ - LRESULT DeleteItem(int index) { return SendMsg(CBEM_DELETEITEM, MY__int_TO_WPARAM(index), 0); } + LRESULT DeleteItem(int index) { return SendMsg(CBEM_DELETEITEM, MY_int_TO_WPARAM(index), 0); } LRESULT InsertItem(COMBOBOXEXITEM *item) { return SendMsg(CBEM_INSERTITEM, 0, (LPARAM)item); } #ifndef _UNICODE @@ -65,7 +65,7 @@ #endif LRESULT SetItem(COMBOBOXEXITEM *item) { return SendMsg(CBEM_SETITEM, 0, (LPARAM)item); } - DWORD SetExtendedStyle(DWORD exMask, DWORD exStyle) { return (DWORD)SendMsg(CBEM_SETEXTENDEDSTYLE, exMask, exStyle); } + DWORD SetExtendedStyle(DWORD exMask, DWORD exStyle) { return (DWORD)SendMsg(CBEM_SETEXTENDEDSTYLE, exMask, (LPARAM)exStyle); } HWND GetEditControl() { return (HWND)SendMsg(CBEM_GETEDITCONTROL, 0, 0); } HIMAGELIST SetImageList(HIMAGELIST imageList) { return (HIMAGELIST)SendMsg(CBEM_SETIMAGELIST, 0, (LPARAM)imageList); } }; diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/CommandBar.h 7zip-23.01+dfsg/CPP/Windows/Control/CommandBar.h --- 7zip-22.01+dfsg/CPP/Windows/Control/CommandBar.h 2015-08-02 11:20:47.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/CommandBar.h 2023-03-17 12:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Control/CommandBar.h -#ifndef __WINDOWS_CONTROL_COMMANDBAR_H -#define __WINDOWS_CONTROL_COMMANDBAR_H +#ifndef ZIP7_INC_WINDOWS_CONTROL_COMMANDBAR_H +#define ZIP7_INC_WINDOWS_CONTROL_COMMANDBAR_H #ifdef UNDER_CE @@ -26,12 +26,12 @@ // Macros // void Destroy() { CommandBar_Destroy(_window); } // bool AddButtons(UINT numButtons, LPTBBUTTON buttons) { return BOOLToBool(SendMsg(TB_ADDBUTTONS, (WPARAM)numButtons, (LPARAM)buttons)); } - bool InsertButton(int iButton, LPTBBUTTON button) { return BOOLToBool(SendMsg(TB_INSERTBUTTON, (WPARAM)iButton, (LPARAM)button)); } - BOOL AddToolTips(UINT numToolTips, LPTSTR toolTips) { return BOOLToBool(SendMsg(TB_SETTOOLTIPS, (WPARAM)numToolTips, (LPARAM)toolTips)); } + // bool InsertButton(unsigned iButton, LPTBBUTTON button) { return BOOLToBool(SendMsg(TB_INSERTBUTTON, (WPARAM)iButton, (LPARAM)button)); } + // BOOL AddToolTips(UINT numToolTips, LPTSTR toolTips) { return BOOLToBool(SendMsg(TB_SETTOOLTIPS, (WPARAM)numToolTips, (LPARAM)toolTips)); } void AutoSize() { SendMsg(TB_AUTOSIZE, 0, 0); } - bool AddAdornments(DWORD dwFlags) { return BOOLToBool(::CommandBar_AddAdornments(_window, dwFlags, 0)); } - int AddBitmap(HINSTANCE hInst, int idBitmap, int iNumImages, int iImageWidth, int iImageHeight) { return ::CommandBar_AddBitmap(_window, hInst, idBitmap, iNumImages, iImageWidth, iImageHeight); } + // bool AddAdornments(DWORD dwFlags) { return BOOLToBool(::CommandBar_AddAdornments(_window, dwFlags, 0)); } + // int AddBitmap(HINSTANCE hInst, int idBitmap, int iNumImages, int iImageWidth, int iImageHeight) { return ::CommandBar_AddBitmap(_window, hInst, idBitmap, iNumImages, iImageWidth, iImageHeight); } bool DrawMenuBar(WORD iButton) { return BOOLToBool(::CommandBar_DrawMenuBar(_window, iButton)); } HMENU GetMenu(WORD iButton) { return ::CommandBar_GetMenu(_window, iButton); } int Height() { return CommandBar_Height(_window); } diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/Dialog.cpp 7zip-23.01+dfsg/CPP/Windows/Control/Dialog.cpp --- 7zip-22.01+dfsg/CPP/Windows/Control/Dialog.cpp 2021-12-20 04:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/Dialog.cpp 2023-03-17 10:00:00.000000000 +0000 @@ -18,7 +18,14 @@ namespace NWindows { namespace NControl { -static INT_PTR APIENTRY DialogProcedure(HWND dialogHWND, UINT message, WPARAM wParam, LPARAM lParam) +static +#ifdef Z7_OLD_WIN_SDK + BOOL +#else + INT_PTR +#endif +APIENTRY +DialogProcedure(HWND dialogHWND, UINT message, WPARAM wParam, LPARAM lParam) { CWindow tempDialog(dialogHWND); if (message == WM_INITDIALOG) @@ -45,7 +52,7 @@ switch (message) { case WM_INITDIALOG: return OnInit(); - case WM_COMMAND: return OnCommand(wParam, lParam); + case WM_COMMAND: return OnCommand(HIWORD(wParam), LOWORD(wParam), lParam); case WM_NOTIFY: return OnNotify((UINT)wParam, (LPNMHDR) lParam); case WM_TIMER: return OnTimer(wParam, lParam); case WM_SIZE: return OnSize(wParam, LOWORD(lParam), HIWORD(lParam)); @@ -65,19 +72,21 @@ } } -bool CDialog::OnCommand(WPARAM wParam, LPARAM lParam) +/* +bool CDialog::OnCommand2(WPARAM wParam, LPARAM lParam) { return OnCommand(HIWORD(wParam), LOWORD(wParam), lParam); } +*/ -bool CDialog::OnCommand(int code, int itemID, LPARAM lParam) +bool CDialog::OnCommand(unsigned code, unsigned itemID, LPARAM lParam) { if (code == BN_CLICKED) return OnButtonClicked(itemID, (HWND)lParam); return false; } -bool CDialog::OnButtonClicked(int buttonID, HWND /* buttonHWND */) +bool CDialog::OnButtonClicked(unsigned buttonID, HWND /* buttonHWND */) { switch (buttonID) { @@ -90,6 +99,28 @@ return true; } +#ifndef UNDER_CE +/* in win2000/win98 : monitor functions are supported. + We need dynamic linking, if we want nt4/win95 support in program. + Even if we compile the code with low (WINVER) value, we still + want to use monitor functions. So we declare missing functions here */ +// #if (WINVER < 0x0500) +#ifndef MONITOR_DEFAULTTOPRIMARY +extern "C" { +DECLARE_HANDLE(HMONITOR); +#define MONITOR_DEFAULTTOPRIMARY 0x00000001 +typedef struct tagMONITORINFO +{ + DWORD cbSize; + RECT rcMonitor; + RECT rcWork; + DWORD dwFlags; +} MONITORINFO, *LPMONITORINFO; +WINUSERAPI HMONITOR WINAPI MonitorFromWindow(HWND hwnd, DWORD dwFlags); +WINUSERAPI BOOL WINAPI GetMonitorInfoA(HMONITOR hMonitor, LPMONITORINFO lpmi); +} +#endif +#endif static bool GetWorkAreaRect(RECT *rect, HWND hwnd) { @@ -172,7 +203,7 @@ return rect.right - rect.left; } -bool CDialog::GetItemSizes(int id, int &x, int &y) +bool CDialog::GetItemSizes(unsigned id, int &x, int &y) { RECT rect; if (!::GetWindowRect(GetItem(id), &rect)) @@ -182,13 +213,13 @@ return true; } -void CDialog::GetClientRectOfItem(int id, RECT &rect) +void CDialog::GetClientRectOfItem(unsigned id, RECT &rect) { ::GetWindowRect(GetItem(id), &rect); ScreenToClient(&rect); } -bool CDialog::MoveItem(int id, int x, int y, int width, int height, bool repaint) +bool CDialog::MoveItem(unsigned id, int x, int y, int width, int height, bool repaint) { return BOOLToBool(::MoveWindow(GetItem(id), x, y, width, height, BoolToBOOL(repaint))); } @@ -356,8 +387,8 @@ bool CModelessDialog::Create(LPCTSTR templateName, HWND parentWindow) { - HWND aHWND = CreateDialogParam(g_hInstance, templateName, parentWindow, DialogProcedure, (LPARAM)this); - if (aHWND == 0) + const HWND aHWND = CreateDialogParam(g_hInstance, templateName, parentWindow, DialogProcedure, (LPARAM)this); + if (!aHWND) return false; Attach(aHWND); return true; diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/Dialog.h 7zip-23.01+dfsg/CPP/Windows/Control/Dialog.h --- 7zip-22.01+dfsg/CPP/Windows/Control/Dialog.h 2021-12-19 15:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/Dialog.h 2023-03-17 12:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Control/Dialog.h -#ifndef __WINDOWS_CONTROL_DIALOG_H -#define __WINDOWS_CONTROL_DIALOG_H +#ifndef ZIP7_INC_WINDOWS_CONTROL_DIALOG_H +#define ZIP7_INC_WINDOWS_CONTROL_DIALOG_H #include "../Window.h" @@ -10,65 +10,66 @@ class CDialog: public CWindow { + // Z7_CLASS_NO_COPY(CDialog) public: - CDialog(HWND wnd = NULL): CWindow(wnd){}; - virtual ~CDialog() {}; + CDialog(HWND wnd = NULL): CWindow(wnd) {} + virtual ~CDialog() {} - HWND GetItem(int itemID) const - { return GetDlgItem(_window, itemID); } + HWND GetItem(unsigned itemID) const + { return GetDlgItem(_window, (int)itemID); } - bool EnableItem(int itemID, bool enable) const + bool EnableItem(unsigned itemID, bool enable) const { return BOOLToBool(::EnableWindow(GetItem(itemID), BoolToBOOL(enable))); } - bool ShowItem(int itemID, int cmdShow) const + bool ShowItem(unsigned itemID, int cmdShow) const { return BOOLToBool(::ShowWindow(GetItem(itemID), cmdShow)); } - bool ShowItem_Bool(int itemID, bool show) const + bool ShowItem_Bool(unsigned itemID, bool show) const { return ShowItem(itemID, show ? SW_SHOW: SW_HIDE); } - bool HideItem(int itemID) const { return ShowItem(itemID, SW_HIDE); } + bool HideItem(unsigned itemID) const { return ShowItem(itemID, SW_HIDE); } - bool SetItemText(int itemID, LPCTSTR s) - { return BOOLToBool(SetDlgItemText(_window, itemID, s)); } + bool SetItemText(unsigned itemID, LPCTSTR s) + { return BOOLToBool(SetDlgItemText(_window, (int)itemID, s)); } - bool SetItemTextA(int itemID, LPCSTR s) - { return BOOLToBool(SetDlgItemTextA(_window, itemID, s)); } + bool SetItemTextA(unsigned itemID, LPCSTR s) + { return BOOLToBool(SetDlgItemTextA(_window, (int)itemID, s)); } - bool SetItemText_Empty(int itemID) + bool SetItemText_Empty(unsigned itemID) { return SetItemText(itemID, TEXT("")); } #ifndef _UNICODE - bool SetItemText(int itemID, LPCWSTR s) + bool SetItemText(unsigned itemID, LPCWSTR s) { CWindow window(GetItem(itemID)); return window.SetText(s); } #endif - UINT GetItemText(int itemID, LPTSTR string, int maxCount) - { return GetDlgItemText(_window, itemID, string, maxCount); } + UINT GetItemText(unsigned itemID, LPTSTR string, unsigned maxCount) + { return GetDlgItemText(_window, (int)itemID, string, (int)maxCount); } #ifndef _UNICODE /* - bool GetItemText(int itemID, LPWSTR string, int maxCount) + bool GetItemText(unsigned itemID, LPWSTR string, int maxCount) { - CWindow window(GetItem(itemID)); + CWindow window(GetItem(unsigned)); return window.GetText(string, maxCount); } */ #endif - bool GetItemText(int itemID, UString &s) + bool GetItemText(unsigned itemID, UString &s) { CWindow window(GetItem(itemID)); return window.GetText(s); } - bool SetItemInt(int itemID, UINT value, bool isSigned) - { return BOOLToBool(SetDlgItemInt(_window, itemID, value, BoolToBOOL(isSigned))); } - bool GetItemInt(int itemID, bool isSigned, UINT &value) + bool SetItemInt(unsigned itemID, UINT value, bool isSigned) + { return BOOLToBool(SetDlgItemInt(_window, (int)itemID, value, BoolToBOOL(isSigned))); } + bool GetItemInt(unsigned itemID, bool isSigned, UINT &value) { BOOL result; - value = GetDlgItemInt(_window, itemID, &result, BoolToBOOL(isSigned)); + value = GetDlgItemInt(_window, (int)itemID, &result, BoolToBOOL(isSigned)); return BOOLToBool(result); } @@ -80,7 +81,7 @@ LRESULT SendMsg_NextDlgCtl(WPARAM wParam, LPARAM lParam) { return SendMsg(WM_NEXTDLGCTL, wParam, lParam); } LRESULT SendMsg_NextDlgCtl_HWND(HWND hwnd) { return SendMsg_NextDlgCtl((WPARAM)hwnd, TRUE); } - LRESULT SendMsg_NextDlgCtl_CtlId(int id) { return SendMsg_NextDlgCtl_HWND(GetItem(id)); } + LRESULT SendMsg_NextDlgCtl_CtlId(unsigned id) { return SendMsg_NextDlgCtl_HWND(GetItem(id)); } LRESULT SendMsg_NextDlgCtl_Next() { return SendMsg_NextDlgCtl(0, FALSE); } LRESULT SendMsg_NextDlgCtl_Prev() { return SendMsg_NextDlgCtl(1, FALSE); } @@ -90,26 +91,27 @@ bool IsMessage(LPMSG message) { return BOOLToBool(IsDialogMessage(_window, message)); } - LRESULT SendItemMessage(int itemID, UINT message, WPARAM wParam, LPARAM lParam) - { return SendDlgItemMessage(_window, itemID, message, wParam, lParam); } + LRESULT SendItemMessage(unsigned itemID, UINT message, WPARAM wParam, LPARAM lParam) + { return SendDlgItemMessage(_window, (int)itemID, message, wParam, lParam); } - bool CheckButton(int buttonID, UINT checkState) - { return BOOLToBool(CheckDlgButton(_window, buttonID, checkState)); } - bool CheckButton(int buttonID, bool checkState) + bool CheckButton(unsigned buttonID, UINT checkState) + { return BOOLToBool(CheckDlgButton(_window, (int)buttonID, checkState)); } + bool CheckButton(unsigned buttonID, bool checkState) { return CheckButton(buttonID, UINT(checkState ? BST_CHECKED : BST_UNCHECKED)); } - UINT IsButtonChecked(int buttonID) const - { return IsDlgButtonChecked(_window, buttonID); } - bool IsButtonCheckedBool(int buttonID) const - { return (IsButtonChecked(buttonID) == BST_CHECKED); } - - bool CheckRadioButton(int firstButtonID, int lastButtonID, int checkButtonID) - { return BOOLToBool(::CheckRadioButton(_window, firstButtonID, lastButtonID, checkButtonID)); } + UINT IsButtonChecked_BST(unsigned buttonID) const + { return IsDlgButtonChecked(_window, (int)buttonID); } + bool IsButtonCheckedBool(unsigned buttonID) const + { return (IsButtonChecked_BST(buttonID) == BST_CHECKED); } + + bool CheckRadioButton(unsigned firstButtonID, unsigned lastButtonID, unsigned checkButtonID) + { return BOOLToBool(::CheckRadioButton(_window, + (int)firstButtonID, (int)lastButtonID, (int)checkButtonID)); } virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam); virtual bool OnInit() { return true; } - virtual bool OnCommand(WPARAM wParam, LPARAM lParam); - virtual bool OnCommand(int code, int itemID, LPARAM lParam); + // virtual bool OnCommand2(WPARAM wParam, LPARAM lParam); + virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM lParam); virtual bool OnSize(WPARAM /* wParam */, int /* xSize */, int /* ySize */) { return false; } virtual bool OnDestroy() { return false; } @@ -120,11 +122,11 @@ virtual void OnHelp(LPHELPINFO) { OnHelp(); } #endif */ - virtual void OnHelp() {}; + virtual void OnHelp() {} - virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); - virtual void OnOK() {}; - virtual void OnCancel() {}; + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND); + virtual void OnOK() {} + virtual void OnCancel() {} virtual void OnClose() {} virtual bool OnNotify(UINT /* controlID */, LPNMHDR /* lParam */) { return false; } virtual bool OnTimer(WPARAM /* timerID */, LPARAM /* callback */) { return false; } @@ -136,9 +138,11 @@ bool GetMargins(int margin, int &x, int &y); int Units_To_Pixels_X(int units); - bool GetItemSizes(int id, int &x, int &y); - void GetClientRectOfItem(int id, RECT &rect); - bool MoveItem(int id, int x, int y, int width, int height, bool repaint = true); + bool GetItemSizes(unsigned id, int &x, int &y); + void GetClientRectOfItem(unsigned id, RECT &rect); + bool MoveItem(unsigned id, int x, int y, int width, int height, bool repaint = true); + bool MoveItem_RECT(unsigned id, const RECT &r, bool repaint = true) + { return MoveItem(id, r.left, r.top, RECT_SIZE_X(r), RECT_SIZE_Y(r), repaint); } void NormalizeSize(bool fullNormalize = false); void NormalizePosition(); @@ -152,9 +156,9 @@ #ifndef _UNICODE bool Create(LPCWSTR templateName, HWND parentWindow); #endif - virtual void OnOK() { Destroy(); } - virtual void OnCancel() { Destroy(); } - virtual void OnClose() { Destroy(); } + virtual void OnOK() Z7_override { Destroy(); } + virtual void OnCancel() Z7_override { Destroy(); } + virtual void OnClose() Z7_override { Destroy(); } }; class CModalDialog: public CDialog @@ -167,18 +171,18 @@ #endif bool End(INT_PTR result) { return BOOLToBool(::EndDialog(_window, result)); } - virtual void OnOK() { End(IDOK); } - virtual void OnCancel() { End(IDCANCEL); } - virtual void OnClose() { End(IDCLOSE); } + virtual void OnOK() Z7_override { End(IDOK); } + virtual void OnCancel() Z7_override { End(IDCANCEL); } + virtual void OnClose() Z7_override { End(IDCLOSE); } }; class CDialogChildControl: public NWindows::CWindow { - int m_ID; + // unsigned m_ID; public: - void Init(const NWindows::NControl::CDialog &parentDialog, int id) + void Init(const NWindows::NControl::CDialog &parentDialog, unsigned id) { - m_ID = id; + // m_ID = id; Attach(parentDialog.GetItem(id)); } }; diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/Edit.h 7zip-23.01+dfsg/CPP/Windows/Control/Edit.h --- 7zip-22.01+dfsg/CPP/Windows/Control/Edit.h 2015-08-02 09:23:25.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/Edit.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Control/Edit.h -#ifndef __WINDOWS_CONTROL_EDIT_H -#define __WINDOWS_CONTROL_EDIT_H +#ifndef ZIP7_INC_WINDOWS_CONTROL_EDIT_H +#define ZIP7_INC_WINDOWS_CONTROL_EDIT_H #include "../Window.h" diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/ImageList.h 7zip-23.01+dfsg/CPP/Windows/Control/ImageList.h --- 7zip-22.01+dfsg/CPP/Windows/Control/ImageList.h 2021-01-26 12:17:40.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/ImageList.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Control/ImageList.h -#ifndef __WINDOWS_CONTROL_IMAGE_LIST_H -#define __WINDOWS_CONTROL_IMAGE_LIST_H +#ifndef ZIP7_INC_WINDOWS_CONTROL_IMAGE_LIST_H +#define ZIP7_INC_WINDOWS_CONTROL_IMAGE_LIST_H #include @@ -56,7 +56,7 @@ bool GetImageInfo(int index, IMAGEINFO* imageInfo) const { return BOOLToBool(ImageList_GetImageInfo(m_Object, index, imageInfo)); } - int Add(HBITMAP hbmImage, HBITMAP hbmMask = 0) + int Add(HBITMAP hbmImage, HBITMAP hbmMask = NULL) { return ImageList_Add(m_Object, hbmImage, hbmMask); } int AddMasked(HBITMAP hbmImage, COLORREF mask) { return ImageList_AddMasked(m_Object, hbmImage, mask); } diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/ListView.cpp 7zip-23.01+dfsg/CPP/Windows/Control/ListView.cpp --- 7zip-22.01+dfsg/CPP/Windows/Control/ListView.cpp 2021-01-25 19:13:37.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/ListView.cpp 2023-03-17 12:00:00.000000000 +0000 @@ -20,78 +20,85 @@ height, parentWindow, idOrHMenu, instance, createParam); } -bool CListView::GetItemParam(int index, LPARAM ¶m) const +/* note: LVITEM and LVCOLUMN structures contain optional fields + depending from preprocessor macros: + #if (_WIN32_IE >= 0x0300) + #if (_WIN32_WINNT >= 0x0501) + #if (_WIN32_WINNT >= 0x0600) +*/ + +bool CListView::GetItemParam(unsigned index, LPARAM ¶m) const { LVITEM item; - item.iItem = index; + item.iItem = (int)index; item.iSubItem = 0; item.mask = LVIF_PARAM; - bool aResult = GetItem(&item); + const bool res = GetItem(&item); param = item.lParam; - return aResult; + return res; } -int CListView::InsertColumn(int columnIndex, LPCTSTR text, int width) +int CListView::InsertColumn(unsigned columnIndex, LPCTSTR text, int width) { LVCOLUMN ci; ci.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_SUBITEM; ci.pszText = (LPTSTR)(void *)text; - ci.iSubItem = columnIndex; + ci.iSubItem = (int)columnIndex; ci.cx = width; return InsertColumn(columnIndex, &ci); } -int CListView::InsertItem(int index, LPCTSTR text) +int CListView::InsertItem(unsigned index, LPCTSTR text) { LVITEM item; item.mask = LVIF_TEXT | LVIF_PARAM; - item.iItem = index; - item.lParam = index; + item.iItem = (int)index; + item.lParam = (LPARAM)index; item.pszText = (LPTSTR)(void *)text; item.iSubItem = 0; return InsertItem(&item); } -int CListView::SetSubItem(int index, int subIndex, LPCTSTR text) +int CListView::SetSubItem(unsigned index, unsigned subIndex, LPCTSTR text) { LVITEM item; item.mask = LVIF_TEXT; - item.iItem = index; + item.iItem = (int)index; item.pszText = (LPTSTR)(void *)text; - item.iSubItem = subIndex; + item.iSubItem = (int)subIndex; return SetItem(&item); } #ifndef _UNICODE -int CListView::InsertColumn(int columnIndex, LPCWSTR text, int width) +int CListView::InsertColumn(unsigned columnIndex, LPCWSTR text, int width) { LVCOLUMNW ci; ci.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_SUBITEM; ci.pszText = (LPWSTR)(void *)text; - ci.iSubItem = columnIndex; + ci.iSubItem = (int)columnIndex; ci.cx = width; return InsertColumn(columnIndex, &ci); } -int CListView::InsertItem(int index, LPCWSTR text) +int CListView::InsertItem(unsigned index, LPCWSTR text) { LVITEMW item; item.mask = LVIF_TEXT | LVIF_PARAM; - item.iItem = index; - item.lParam = index; + item.iItem = (int)index; + item.lParam = (LPARAM)index; item.pszText = (LPWSTR)(void *)text; item.iSubItem = 0; return InsertItem(&item); } -int CListView::SetSubItem(int index, int subIndex, LPCWSTR text) +int CListView::SetSubItem(unsigned index, unsigned subIndex, LPCWSTR text) { LVITEMW item; item.mask = LVIF_TEXT; - item.iItem = index; + item.iItem = (int)index; item.pszText = (LPWSTR)(void *)text; - item.iSubItem = subIndex; + item.iSubItem = (int)subIndex; return SetItem(&item); } diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/ListView.h 7zip-23.01+dfsg/CPP/Windows/Control/ListView.h --- 7zip-22.01+dfsg/CPP/Windows/Control/ListView.h 2021-02-09 19:55:12.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/ListView.h 2023-03-17 16:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Control/ListView.h -#ifndef __WINDOWS_CONTROL_LISTVIEW_H -#define __WINDOWS_CONTROL_LISTVIEW_H +#ifndef ZIP7_INC_WINDOWS_CONTROL_LISTVIEW_H +#define ZIP7_INC_WINDOWS_CONTROL_LISTVIEW_H #include "../../Common/MyWindows.h" @@ -28,11 +28,11 @@ } bool DeleteAllItems() { return BOOLToBool(ListView_DeleteAllItems(_window)); } - bool DeleteColumn(int columnIndex) { return BOOLToBool(ListView_DeleteColumn(_window, columnIndex)); } + bool DeleteColumn(unsigned columnIndex) { return BOOLToBool(ListView_DeleteColumn(_window, columnIndex)); } - int InsertColumn(int columnIndex, const LVCOLUMN *columnInfo) { return ListView_InsertColumn(_window, columnIndex, columnInfo); } - int InsertColumn(int columnIndex, LPCTSTR text, int width); - bool SetColumnOrderArray(int count, const int *columns) + int InsertColumn(unsigned columnIndex, const LVCOLUMN *columnInfo) { return ListView_InsertColumn(_window, columnIndex, columnInfo); } + int InsertColumn(unsigned columnIndex, LPCTSTR text, int width); + bool SetColumnOrderArray(unsigned count, const int *columns) { return BOOLToBool(ListView_SetColumnOrderArray(_window, count, (int *)(void *)columns)); } /* @@ -46,43 +46,49 @@ */ int InsertItem(const LVITEM* item) { return ListView_InsertItem(_window, item); } - int InsertItem(int index, LPCTSTR text); + int InsertItem(unsigned index, LPCTSTR text); bool SetItem(const LVITEM* item) { return BOOLToBool(ListView_SetItem(_window, item)); } - int SetSubItem(int index, int subIndex, LPCTSTR text); + int SetSubItem(unsigned index, unsigned subIndex, LPCTSTR text); #ifndef _UNICODE - int InsertColumn(int columnIndex, const LVCOLUMNW *columnInfo) { return (int)SendMsg(LVM_INSERTCOLUMNW, (WPARAM)columnIndex, (LPARAM)columnInfo); } - int InsertColumn(int columnIndex, LPCWSTR text, int width); + int InsertColumn(unsigned columnIndex, const LVCOLUMNW *columnInfo) { return (int)SendMsg(LVM_INSERTCOLUMNW, (WPARAM)columnIndex, (LPARAM)columnInfo); } + int InsertColumn(unsigned columnIndex, LPCWSTR text, int width); int InsertItem(const LV_ITEMW* item) { return (int)SendMsg(LVM_INSERTITEMW, 0, (LPARAM)item); } - int InsertItem(int index, LPCWSTR text); + int InsertItem(unsigned index, LPCWSTR text); bool SetItem(const LV_ITEMW* item) { return BOOLToBool((BOOL)SendMsg(LVM_SETITEMW, 0, (LPARAM)item)); } - int SetSubItem(int index, int subIndex, LPCWSTR text); + int SetSubItem(unsigned index, unsigned subIndex, LPCWSTR text); #endif - bool DeleteItem(int itemIndex) { return BOOLToBool(ListView_DeleteItem(_window, itemIndex)); } + bool DeleteItem(unsigned itemIndex) { return BOOLToBool(ListView_DeleteItem(_window, itemIndex)); } UINT GetSelectedCount() const { return ListView_GetSelectedCount(_window); } int GetItemCount() const { return ListView_GetItemCount(_window); } INT GetSelectionMark() const { return ListView_GetSelectionMark(_window); } - void SetItemCount(int numItems) { ListView_SetItemCount(_window, numItems); } - void SetItemCountEx(int numItems, DWORD flags) { ListView_SetItemCountEx(_window, numItems, flags); } + void SetItemCount(unsigned numItems) { ListView_SetItemCount(_window, numItems); } + void SetItemCountEx(unsigned numItems, DWORD flags) { ListView_SetItemCountEx(_window, numItems, flags); } + /* startIndex : The index of the item with which to begin the search, + or -1 to find the first item that matches the specified flags. + The specified item itself is excluded from the search. */ int GetNextItem(int startIndex, UINT flags) const { return ListView_GetNextItem(_window, startIndex, flags); } int GetNextSelectedItem(int startIndex) const { return GetNextItem(startIndex, LVNI_SELECTED); } int GetFocusedItem() const { return GetNextItem(-1, LVNI_FOCUSED); } bool GetItem(LVITEM* item) const { return BOOLToBool(ListView_GetItem(_window, item)); } - bool GetItemParam(int itemIndex, LPARAM ¶m) const; - void GetItemText(int itemIndex, int subItemIndex, LPTSTR text, int textSizeMax) const - { ListView_GetItemText(_window, itemIndex, subItemIndex, text, textSizeMax); } + bool GetItemParam(unsigned itemIndex, LPARAM ¶m) const; + /* + void GetItemText(unsigned itemIndex, unsigned subItemIndex, LPTSTR text, unsigned textSizeMax) const + { ListView_GetItemText(_window, itemIndex, subItemIndex, text, textSizeMax) } + */ bool SortItems(PFNLVCOMPARE compareFunction, LPARAM dataParam) { return BOOLToBool(ListView_SortItems(_window, compareFunction, dataParam)); } - void SetItemState(int index, UINT state, UINT mask) { ListView_SetItemState(_window, index, state, mask); } + // If (index == -1), then the state change is applied to all items. + void SetItemState(int index, UINT state, UINT mask) { ListView_SetItemState(_window, index, state, mask) } void SetItemState_Selected(int index, bool select) { SetItemState(index, select ? LVIS_SELECTED : 0, LVIS_SELECTED); } void SetItemState_Selected(int index) { SetItemState(index, LVIS_SELECTED, LVIS_SELECTED); } void SelectAll() { SetItemState_Selected(-1); } @@ -90,7 +96,7 @@ UINT GetItemState(int index, UINT mask) const { return ListView_GetItemState(_window, index, mask); } bool IsItemSelected(int index) const { return GetItemState(index, LVIS_SELECTED) == LVIS_SELECTED; } - bool GetColumn(int columnIndex, LVCOLUMN* columnInfo) const + bool GetColumn(unsigned columnIndex, LVCOLUMN* columnInfo) const { return BOOLToBool(ListView_GetColumn(_window, columnIndex, columnInfo)); } HIMAGELIST SetImageList(HIMAGELIST imageList, int imageListType) @@ -101,7 +107,7 @@ void SetExtendedListViewStyle(DWORD exStyle) { ListView_SetExtendedListViewStyle(_window, exStyle); } void SetExtendedListViewStyle(DWORD exMask, DWORD exStyle) { ListView_SetExtendedListViewStyleEx(_window, exMask, exStyle); } - void SetCheckState(UINT index, bool checkState) { ListView_SetCheckState(_window, index, BoolToBOOL(checkState)); } + void SetCheckState(UINT index, bool checkState) { ListView_SetCheckState(_window, index, BoolToBOOL(checkState)) } bool GetCheckState(UINT index) { return BOOLToBool(ListView_GetCheckState(_window, index)); } bool EnsureVisible(int index, bool partialOK) { return BOOLToBool(ListView_EnsureVisible(_window, index, BoolToBOOL(partialOK))); } @@ -129,7 +135,10 @@ class CListView2: public CListView { WNDPROC _origWindowProc; + // ~CListView2() ZIP7_eq_delete; public: + virtual ~CListView2() {} + CListView2() {} void SetWindowProc(); virtual LRESULT OnMessage(UINT message, WPARAM wParam, LPARAM lParam); }; diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/ProgressBar.h 7zip-23.01+dfsg/CPP/Windows/Control/ProgressBar.h --- 7zip-22.01+dfsg/CPP/Windows/Control/ProgressBar.h 2021-01-26 12:18:22.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/ProgressBar.h 2023-01-19 20:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Control/ProgressBar.h -#ifndef __WINDOWS_CONTROL_PROGRESSBAR_H -#define __WINDOWS_CONTROL_PROGRESSBAR_H +#ifndef ZIP7_INC_WINDOWS_CONTROL_PROGRESSBAR_H +#define ZIP7_INC_WINDOWS_CONTROL_PROGRESSBAR_H #include "../../Common/MyWindows.h" @@ -15,18 +15,18 @@ class CProgressBar: public CWindow { public: - LRESULT SetPos(int pos) { return SendMsg(PBM_SETPOS, pos, 0); } - LRESULT DeltaPos(int increment) { return SendMsg(PBM_DELTAPOS, increment, 0); } - UINT GetPos() { return (UINT)SendMsg(PBM_GETPOS, 0, 0); } - LRESULT SetRange(unsigned short minValue, unsigned short maxValue) { return SendMsg(PBM_SETRANGE, 0, MAKELPARAM(minValue, maxValue)); } - DWORD SetRange32(int minValue, int maxValue) { return (DWORD)SendMsg(PBM_SETRANGE32, minValue, maxValue); } - int SetStep(int step) { return (int)SendMsg(PBM_SETSTEP, step, 0); } - LRESULT StepIt() { return SendMsg(PBM_STEPIT, 0, 0); } - INT GetRange(bool minValue, PPBRANGE range) { return (INT)SendMsg(PBM_GETRANGE, BoolToBOOL(minValue), (LPARAM)range); } + LRESULT SetPos(int pos) { return SendMsg(PBM_SETPOS, (unsigned)pos, 0); } + // LRESULT DeltaPos(int increment) { return SendMsg(PBM_DELTAPOS, increment, 0); } + // UINT GetPos() { return (UINT)SendMsg(PBM_GETPOS, 0, 0); } + // LRESULT SetRange(unsigned short minValue, unsigned short maxValue) { return SendMsg(PBM_SETRANGE, 0, MAKELPARAM(minValue, maxValue)); } + DWORD SetRange32(int minValue, int maxValue) { return (DWORD)SendMsg(PBM_SETRANGE32, (unsigned)minValue, (LPARAM)(unsigned)maxValue); } + // int SetStep(int step) { return (int)SendMsg(PBM_SETSTEP, step, 0); } + // LRESULT StepIt() { return SendMsg(PBM_STEPIT, 0, 0); } + // INT GetRange(bool minValue, PPBRANGE range) { return (INT)SendMsg(PBM_GETRANGE, BoolToBOOL(minValue), (LPARAM)range); } #ifndef UNDER_CE - COLORREF SetBarColor(COLORREF color) { return (COLORREF)SendMsg(PBM_SETBARCOLOR, 0, color); } - COLORREF SetBackgroundColor(COLORREF color) { return (COLORREF)SendMsg(PBM_SETBKCOLOR, 0, color); } + COLORREF SetBarColor(COLORREF color) { return (COLORREF)SendMsg(PBM_SETBARCOLOR, 0, (LPARAM)color); } + COLORREF SetBackgroundColor(COLORREF color) { return (COLORREF)SendMsg(PBM_SETBKCOLOR, 0, (LPARAM)color); } #endif }; diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/PropertyPage.cpp 7zip-23.01+dfsg/CPP/Windows/Control/PropertyPage.cpp --- 7zip-22.01+dfsg/CPP/Windows/Control/PropertyPage.cpp 2017-02-08 11:28:11.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/PropertyPage.cpp 2023-03-16 09:00:00.000000000 +0000 @@ -16,7 +16,13 @@ namespace NWindows { namespace NControl { -static INT_PTR APIENTRY MyProperyPageProcedure(HWND dialogHWND, UINT message, WPARAM wParam, LPARAM lParam) +static +#ifdef Z7_OLD_WIN_SDK + BOOL +#else + INT_PTR +#endif +APIENTRY MyProperyPageProcedure(HWND dialogHWND, UINT message, WPARAM wParam, LPARAM lParam) { CWindow tempDialog(dialogHWND); if (message == WM_INITDIALOG) @@ -34,75 +40,91 @@ { switch (lParam->code) { - case PSN_APPLY: SetMsgResult(OnApply(LPPSHNOTIFY(lParam))); break; - case PSN_KILLACTIVE: SetMsgResult(BoolToBOOL(OnKillActive(LPPSHNOTIFY(lParam)))); break; - case PSN_SETACTIVE: SetMsgResult(OnSetActive(LPPSHNOTIFY(lParam))); break; - case PSN_RESET: OnReset(LPPSHNOTIFY(lParam)); break; - case PSN_HELP: OnNotifyHelp(LPPSHNOTIFY(lParam)); break; + case PSN_APPLY: SetMsgResult(OnApply2(LPPSHNOTIFY(lParam))); break; + case PSN_KILLACTIVE: SetMsgResult(BoolToBOOL(OnKillActive2(LPPSHNOTIFY(lParam)))); break; + case PSN_SETACTIVE: SetMsgResult(OnSetActive2(LPPSHNOTIFY(lParam))); break; + case PSN_RESET: OnReset2(LPPSHNOTIFY(lParam)); break; + case PSN_HELP: OnNotifyHelp2(LPPSHNOTIFY(lParam)); break; default: return false; } return true; } +/* +PROPSHEETPAGE fields depend from +#if (_WIN32_WINNT >= 0x0600) +#elif (_WIN32_WINNT >= 0x0501) +#elif (_WIN32_IE >= 0x0400) +PROPSHEETHEADER fields depend from +#if (_WIN32_IE >= 0x0400) +*/ +#if defined(PROPSHEETPAGEA_V1_SIZE) && !defined(Z7_OLD_WIN_SDK) +#ifndef _UNICODE +#define my_compatib_PROPSHEETPAGEA PROPSHEETPAGEA_V1 +#endif +#define my_compatib_PROPSHEETPAGEW PROPSHEETPAGEW_V1 +#else +// for old mingw: +#ifndef _UNICODE +#define my_compatib_PROPSHEETPAGEA PROPSHEETPAGEA +#endif +#define my_compatib_PROPSHEETPAGEW PROPSHEETPAGEW +#endif + INT_PTR MyPropertySheet(const CObjectVector &pagesInfo, HWND hwndParent, const UString &title) { - #ifndef _UNICODE - AStringVector titles; - #endif - #ifndef _UNICODE - CRecordVector pagesA; - #endif - CRecordVector pagesW; - unsigned i; #ifndef _UNICODE + AStringVector titles; for (i = 0; i < pagesInfo.Size(); i++) titles.Add(GetSystemString(pagesInfo[i].Title)); + CRecordVector pagesA; #endif + CRecordVector pagesW; for (i = 0; i < pagesInfo.Size(); i++) { const CPageInfo &pageInfo = pagesInfo[i]; #ifndef _UNICODE { - PROPSHEETPAGE page; + my_compatib_PROPSHEETPAGEA page; + memset(&page, 0, sizeof(page)); page.dwSize = sizeof(page); page.dwFlags = PSP_HASHELP; page.hInstance = g_hInstance; - page.pszTemplate = MAKEINTRESOURCE(pageInfo.ID); - page.pszIcon = NULL; + page.pszTemplate = MAKEINTRESOURCEA(pageInfo.ID); + // page.pszIcon = NULL; page.pfnDlgProc = NWindows::NControl::MyProperyPageProcedure; - if (titles[i].IsEmpty()) - page.pszTitle = NULL; - else + if (!titles[i].IsEmpty()) { - page.dwFlags |= PSP_USETITLE; page.pszTitle = titles[i]; + page.dwFlags |= PSP_USETITLE; } + // else page.pszTitle = NULL; page.lParam = (LPARAM)pageInfo.Page; - page.pfnCallback = NULL; + // page.pfnCallback = NULL; pagesA.Add(page); } #endif { - PROPSHEETPAGEW page; + my_compatib_PROPSHEETPAGEW page; + memset(&page, 0, sizeof(page)); page.dwSize = sizeof(page); page.dwFlags = PSP_HASHELP; page.hInstance = g_hInstance; page.pszTemplate = MAKEINTRESOURCEW(pageInfo.ID); - page.pszIcon = NULL; + // page.pszIcon = NULL; page.pfnDlgProc = NWindows::NControl::MyProperyPageProcedure; - if (pageInfo.Title.IsEmpty()) - page.pszTitle = NULL; - else + if (!pageInfo.Title.IsEmpty()) { - page.dwFlags |= PSP_USETITLE; page.pszTitle = pageInfo.Title; + page.dwFlags |= PSP_USETITLE; } + // else page.pszTitle = NULL; page.lParam = (LPARAM)pageInfo.Page; - page.pfnCallback = NULL; + // page.pfnCallback = NULL; pagesW.Add(page); } } @@ -110,16 +132,16 @@ #ifndef _UNICODE if (!g_IsNT) { - PROPSHEETHEADER sheet; + PROPSHEETHEADERA sheet; sheet.dwSize = sizeof(sheet); sheet.dwFlags = PSH_PROPSHEETPAGE; sheet.hwndParent = hwndParent; sheet.hInstance = g_hInstance; AString titleA (GetSystemString(title)); sheet.pszCaption = titleA; - sheet.nPages = pagesInfo.Size(); + sheet.nPages = pagesA.Size(); sheet.nStartPage = 0; - sheet.ppsp = &pagesA.Front(); + sheet.ppsp = (LPCPROPSHEETPAGEA)(const void *)&pagesA.Front(); sheet.pfnCallback = NULL; return ::PropertySheetA(&sheet); } @@ -132,9 +154,9 @@ sheet.hwndParent = hwndParent; sheet.hInstance = g_hInstance; sheet.pszCaption = title; - sheet.nPages = pagesInfo.Size(); + sheet.nPages = pagesW.Size(); sheet.nStartPage = 0; - sheet.ppsp = &pagesW.Front(); + sheet.ppsp = (LPCPROPSHEETPAGEW)(const void *)&pagesW.Front(); sheet.pfnCallback = NULL; return ::PropertySheetW(&sheet); } diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/PropertyPage.h 7zip-23.01+dfsg/CPP/Windows/Control/PropertyPage.h --- 7zip-22.01+dfsg/CPP/Windows/Control/PropertyPage.h 2021-01-26 12:15:19.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/PropertyPage.h 2023-03-17 15:00:00.000000000 +0000 @@ -1,11 +1,11 @@ // Windows/Control/PropertyPage.h -#ifndef __WINDOWS_CONTROL_PROPERTYPAGE_H -#define __WINDOWS_CONTROL_PROPERTYPAGE_H +#ifndef ZIP7_INC_WINDOWS_CONTROL_PROPERTYPAGE_H +#define ZIP7_INC_WINDOWS_CONTROL_PROPERTYPAGE_H #include "../../Common/MyWindows.h" -#include +#include #include "Dialog.h" @@ -17,23 +17,23 @@ class CPropertyPage: public CDialog { public: - CPropertyPage(HWND window = NULL): CDialog(window){}; + CPropertyPage(HWND window = NULL): CDialog(window) {} void Changed() { PropSheet_Changed(GetParent(), (HWND)*this); } void UnChanged() { PropSheet_UnChanged(GetParent(), (HWND)*this); } - virtual bool OnNotify(UINT controlID, LPNMHDR lParam); + virtual bool OnNotify(UINT controlID, LPNMHDR lParam) Z7_override; virtual bool OnKillActive() { return false; } // false = OK - virtual bool OnKillActive(const PSHNOTIFY *) { return OnKillActive(); } + virtual bool OnKillActive2(const PSHNOTIFY *) { return OnKillActive(); } virtual LONG OnSetActive() { return false; } // false = OK - virtual LONG OnSetActive(const PSHNOTIFY *) { return OnSetActive(); } + virtual LONG OnSetActive2(const PSHNOTIFY *) { return OnSetActive(); } virtual LONG OnApply() { return PSNRET_NOERROR; } - virtual LONG OnApply(const PSHNOTIFY *) { return OnApply(); } + virtual LONG OnApply2(const PSHNOTIFY *) { return OnApply(); } virtual void OnNotifyHelp() {} - virtual void OnNotifyHelp(const PSHNOTIFY *) { OnNotifyHelp(); } + virtual void OnNotifyHelp2(const PSHNOTIFY *) { OnNotifyHelp(); } virtual void OnReset() {} - virtual void OnReset(const PSHNOTIFY *) { OnReset(); } + virtual void OnReset2(const PSHNOTIFY *) { OnReset(); } }; struct CPageInfo diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/ReBar.h 7zip-23.01+dfsg/CPP/Windows/Control/ReBar.h --- 7zip-22.01+dfsg/CPP/Windows/Control/ReBar.h 2015-08-02 09:26:09.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/ReBar.h 2023-01-19 15:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Control/ReBar.h -#ifndef __WINDOWS_CONTROL_REBAR_H -#define __WINDOWS_CONTROL_REBAR_H +#ifndef ZIP7_INC_WINDOWS_CONTROL_REBAR_H +#define ZIP7_INC_WINDOWS_CONTROL_REBAR_H #include "../Window.h" @@ -14,7 +14,7 @@ bool SetBarInfo(LPREBARINFO barInfo) { return LRESULTToBool(SendMsg(RB_SETBARINFO, 0, (LPARAM)barInfo)); } bool InsertBand(int index, LPREBARBANDINFO bandInfo) - { return LRESULTToBool(SendMsg(RB_INSERTBAND, index, (LPARAM)bandInfo)); } + { return LRESULTToBool(SendMsg(RB_INSERTBAND, MY_int_TO_WPARAM(index), (LPARAM)bandInfo)); } bool SetBandInfo(unsigned index, LPREBARBANDINFO bandInfo) { return LRESULTToBool(SendMsg(RB_SETBANDINFO, index, (LPARAM)bandInfo)); } void MaximizeBand(unsigned index, bool ideal) diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/Static.h 7zip-23.01+dfsg/CPP/Windows/Control/Static.h --- 7zip-22.01+dfsg/CPP/Windows/Control/Static.h 2015-08-02 09:27:54.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/Static.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Control/Static.h -#ifndef __WINDOWS_CONTROL_STATIC_H -#define __WINDOWS_CONTROL_STATIC_H +#ifndef ZIP7_INC_WINDOWS_CONTROL_STATIC_H +#define ZIP7_INC_WINDOWS_CONTROL_STATIC_H #include "../Window.h" diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/StatusBar.h 7zip-23.01+dfsg/CPP/Windows/Control/StatusBar.h --- 7zip-22.01+dfsg/CPP/Windows/Control/StatusBar.h 2015-08-02 09:28:55.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/StatusBar.h 2023-01-19 15:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Control/StatusBar.h -#ifndef __WINDOWS_CONTROL_STATUSBAR_H -#define __WINDOWS_CONTROL_STATUSBAR_H +#ifndef ZIP7_INC_WINDOWS_CONTROL_STATUSBAR_H +#define ZIP7_INC_WINDOWS_CONTROL_STATUSBAR_H #include "../Window.h" @@ -12,7 +12,7 @@ { public: bool Create(LONG style, LPCTSTR text, HWND hwndParent, UINT id) - { return (_window = ::CreateStatusWindow(style, text, hwndParent, id)) != 0; } + { return (_window = ::CreateStatusWindow(style, text, hwndParent, id)) != NULL; } bool SetText(LPCTSTR text) { return CWindow::SetText(text); } bool SetText(unsigned index, LPCTSTR text, UINT type) @@ -22,7 +22,7 @@ #ifndef _UNICODE bool Create(LONG style, LPCWSTR text, HWND hwndParent, UINT id) - { return (_window = ::CreateStatusWindowW(style, text, hwndParent, id)) != 0; } + { return (_window = ::CreateStatusWindowW(style, text, hwndParent, id)) != NULL; } bool SetText(LPCWSTR text) { return CWindow::SetText(text); } bool SetText(unsigned index, LPCWSTR text, UINT type) @@ -34,7 +34,7 @@ bool SetParts(unsigned numParts, const int *edgePostions) { return LRESULTToBool(SendMsg(SB_SETPARTS, numParts, (LPARAM)edgePostions)); } void Simple(bool simple) - { SendMsg(SB_SIMPLE, BoolToBOOL(simple), 0); } + { SendMsg(SB_SIMPLE, (WPARAM)BoolToBOOL(simple), 0); } }; }} diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/StdAfx.h 7zip-23.01+dfsg/CPP/Windows/Control/StdAfx.h --- 7zip-22.01+dfsg/CPP/Windows/Control/StdAfx.h 2013-11-27 10:12:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/StdAfx.h 2023-01-14 11:00:00.000000000 +0000 @@ -1,8 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../../Common/Common.h" #endif diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/ToolBar.h 7zip-23.01+dfsg/CPP/Windows/Control/ToolBar.h --- 7zip-22.01+dfsg/CPP/Windows/Control/ToolBar.h 2015-08-02 09:29:54.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/ToolBar.h 2023-03-17 12:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Control/ToolBar.h -#ifndef __WINDOWS_CONTROL_TOOLBAR_H -#define __WINDOWS_CONTROL_TOOLBAR_H +#ifndef ZIP7_INC_WINDOWS_CONTROL_TOOLBAR_H +#define ZIP7_INC_WINDOWS_CONTROL_TOOLBAR_H #include "../Window.h" @@ -18,7 +18,7 @@ #ifdef UNDER_CE { // maybe it must be fixed for more than 1 buttons - DWORD val = GetButtonSize(); + const DWORD val = GetButtonSize(); size->cx = LOWORD(val); size->cy = HIWORD(val); return true; diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/Trackbar.h 7zip-23.01+dfsg/CPP/Windows/Control/Trackbar.h --- 7zip-22.01+dfsg/CPP/Windows/Control/Trackbar.h 2015-11-22 17:26:37.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/Trackbar.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Control/Trackbar.h -#ifndef __WINDOWS_CONTROL_TRACKBAR_H -#define __WINDOWS_CONTROL_TRACKBAR_H +#ifndef ZIP7_INC_WINDOWS_CONTROL_TRACKBAR_H +#define ZIP7_INC_WINDOWS_CONTROL_TRACKBAR_H #include "../Window.h" diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/Window2.cpp 7zip-23.01+dfsg/CPP/Windows/Control/Window2.cpp --- 7zip-22.01+dfsg/CPP/Windows/Control/Window2.cpp 2015-09-28 13:39:41.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/Window2.cpp 2023-03-17 09:00:00.000000000 +0000 @@ -32,9 +32,9 @@ if (message == MY_START_WM_CREATE) tempWindow.SetUserDataLongPtr((LONG_PTR)(((LPCREATESTRUCT)lParam)->lpCreateParams)); CWindow2 *window = (CWindow2 *)(tempWindow.GetUserDataLongPtr()); - if (window != NULL && message == MY_START_WM_CREATE) + if (window && message == MY_START_WM_CREATE) window->Attach(aHWND); - if (window == 0) + if (!window) { #ifndef _UNICODE if (g_IsNT) @@ -140,7 +140,7 @@ return -1; break; case WM_COMMAND: - if (OnCommand(wParam, lParam, result)) + if (OnCommand(HIWORD(wParam), LOWORD(wParam), lParam, result)) return result; break; case WM_NOTIFY: @@ -160,12 +160,14 @@ return DefProc(message, wParam, lParam); } -bool CWindow2::OnCommand(WPARAM wParam, LPARAM lParam, LRESULT &result) +/* +bool CWindow2::OnCommand2(WPARAM wParam, LPARAM lParam, LRESULT &result) { return OnCommand(HIWORD(wParam), LOWORD(wParam), lParam, result); } +*/ -bool CWindow2::OnCommand(int /* code */, int /* itemID */, LPARAM /* lParam */, LRESULT & /* result */) +bool CWindow2::OnCommand(unsigned /* code */, unsigned /* itemID */, LPARAM /* lParam */, LRESULT & /* result */) { return false; // return DefProc(message, wParam, lParam); @@ -176,7 +178,7 @@ } /* -bool CDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { diff -Nru 7zip-22.01+dfsg/CPP/Windows/Control/Window2.h 7zip-23.01+dfsg/CPP/Windows/Control/Window2.h --- 7zip-22.01+dfsg/CPP/Windows/Control/Window2.h 2014-07-05 10:52:27.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Control/Window2.h 2023-03-17 10:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Control/Window2.h -#ifndef __WINDOWS_CONTROL_WINDOW2_H -#define __WINDOWS_CONTROL_WINDOW2_H +#ifndef ZIP7_INC_WINDOWS_CONTROL_WINDOW2_H +#define ZIP7_INC_WINDOWS_CONTROL_WINDOW2_H #include "../Window.h" @@ -10,10 +10,12 @@ class CWindow2: public CWindow { + // Z7_CLASS_NO_COPY(CWindow2) + LRESULT DefProc(UINT message, WPARAM wParam, LPARAM lParam); public: - CWindow2(HWND newWindow = NULL): CWindow(newWindow){}; - virtual ~CWindow2() {}; + CWindow2(HWND newWindow = NULL): CWindow(newWindow) {} + virtual ~CWindow2() {} bool CreateEx(DWORD exStyle, LPCTSTR className, LPCTSTR windowName, DWORD style, int x, int y, int width, int height, @@ -28,8 +30,8 @@ virtual LRESULT OnMessage(UINT message, WPARAM wParam, LPARAM lParam); virtual bool OnCreate(CREATESTRUCT * /* createStruct */) { return true; } // virtual LRESULT OnCommand(WPARAM wParam, LPARAM lParam); - virtual bool OnCommand(WPARAM wParam, LPARAM lParam, LRESULT &result); - virtual bool OnCommand(int code, int itemID, LPARAM lParam, LRESULT &result); + // bool OnCommand2(WPARAM wParam, LPARAM lParam, LRESULT &result); + virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM lParam, LRESULT &result); virtual bool OnSize(WPARAM /* wParam */, int /* xSize */, int /* ySize */) { return false; } virtual bool OnNotify(UINT /* controlID */, LPNMHDR /* lParam */, LRESULT & /* result */) { return false; } virtual void OnDestroy() { PostQuitMessage(0); } @@ -37,7 +39,7 @@ /* virtual LRESULT OnHelp(LPHELPINFO helpInfo) { OnHelp(); } virtual LRESULT OnHelp() {}; - virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); + virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND); virtual void OnOK() {}; virtual void OnCancel() {}; */ diff -Nru 7zip-22.01+dfsg/CPP/Windows/Defs.h 7zip-23.01+dfsg/CPP/Windows/Defs.h --- 7zip-22.01+dfsg/CPP/Windows/Defs.h 2019-03-02 09:45:30.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Defs.h 2023-01-26 12:00:00.000000000 +0000 @@ -1,12 +1,11 @@ // Windows/Defs.h -#ifndef __WINDOWS_DEFS_H -#define __WINDOWS_DEFS_H +#ifndef ZIP7_INC_WINDOWS_DEFS_H +#define ZIP7_INC_WINDOWS_DEFS_H #include "../Common/MyWindows.h" #ifdef _WIN32 -inline bool LRESULTToBool(LRESULT v) { return (v != FALSE); } inline BOOL BoolToBOOL(bool v) { return (v ? TRUE: FALSE); } #endif diff -Nru 7zip-22.01+dfsg/CPP/Windows/DLL.cpp 7zip-23.01+dfsg/CPP/Windows/DLL.cpp --- 7zip-22.01+dfsg/CPP/Windows/DLL.cpp 2021-03-03 17:56:56.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/DLL.cpp 2023-03-24 11:00:00.000000000 +0000 @@ -17,11 +17,11 @@ bool CLibrary::Free() throw() { - if (_module == 0) + if (_module == NULL) return true; if (!::FreeLibrary(_module)) return false; - _module = 0; + _module = NULL; return true; } @@ -90,7 +90,7 @@ return false; } -#ifndef _SFX +#ifndef Z7_SFX FString GetModuleDirPrefix() { @@ -110,38 +110,35 @@ }} -#else +#else // _WIN32 #include #include +#include "../Common/Common.h" + +// FARPROC +void *GetProcAddress(HMODULE module, LPCSTR procName) +{ + void *ptr = NULL; + if (module) + ptr = dlsym(module, procName); + return ptr; +} namespace NWindows { namespace NDLL { bool CLibrary::Free() throw() { - if (_module == NULL) + if (!_module) return true; - int ret = dlclose(_module); + const int ret = dlclose(_module); if (ret != 0) return false; _module = NULL; return true; } -static -// FARPROC -void * -local_GetProcAddress(HMODULE module, LPCSTR procName) -{ - void *ptr = NULL; - if (module) - { - ptr = dlsym(module, procName); - } - return ptr; -} - bool CLibrary::Load(CFSTR path) throw() { if (!Free()) @@ -163,21 +160,11 @@ #endif #endif - void *handler = dlopen(path, options); - - if (handler) - { - // here we can transfer some settings to DLL - } - else - { - } - - _module = handler; - + _module = dlopen(path, options); return (_module != NULL); } +/* // FARPROC void * CLibrary::GetProc(LPCSTR procName) const { @@ -185,6 +172,7 @@ return local_GetProcAddress(_module, procName); // return NULL; } +*/ }} diff -Nru 7zip-22.01+dfsg/CPP/Windows/DLL.h 7zip-23.01+dfsg/CPP/Windows/DLL.h --- 7zip-22.01+dfsg/CPP/Windows/DLL.h 2020-12-15 17:33:21.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/DLL.h 2023-03-24 11:00:00.000000000 +0000 @@ -1,20 +1,29 @@ // Windows/DLL.h -#ifndef __WINDOWS_DLL_H -#define __WINDOWS_DLL_H +#ifndef ZIP7_INC_WINDOWS_DLL_H +#define ZIP7_INC_WINDOWS_DLL_H #include "../Common/MyString.h" +#ifndef _WIN32 +typedef void * HMODULE; +// typedef int (*FARPROC)(); +// typedef void *FARPROC; +void *GetProcAddress(HMODULE module, LPCSTR procName); +#endif + namespace NWindows { namespace NDLL { #ifdef _WIN32 +/* #ifdef UNDER_CE #define My_GetProcAddress(module, procName) (void *)::GetProcAddressA(module, procName) #else #define My_GetProcAddress(module, procName) (void *)::GetProcAddress(module, procName) #endif +*/ /* Win32: Don't call CLibrary::Free() and FreeLibrary() from another FreeLibrary() code: detaching code in DLL entry-point or in @@ -24,13 +33,25 @@ { HMODULE _module; - // CLASS_NO_COPY(CLibrary); + // Z7_CLASS_NO_COPY(CLibrary); + // copy constructor is required here public: - CLibrary(): _module(NULL) {}; + CLibrary(): _module(NULL) {} ~CLibrary() { Free(); } - operator HMODULE() const { return _module; } - HMODULE* operator&() { return &_module; } + CLibrary(const CLibrary &c): _module(NULL) + { + if (c._module) + { + // we need non const to reference from original item + // c._module = NULL; + throw 20230102; + } + } + + HMODULE Get_HMODULE() const { return _module; } + // operator HMODULE() const { return _module; } + // HMODULE* operator&() { return &_module; } bool IsLoaded() const { return (_module != NULL); } void Attach(HMODULE m) @@ -40,7 +61,7 @@ } HMODULE Detach() { - HMODULE m = _module; + const HMODULE m = _module; _module = NULL; return m; } @@ -49,28 +70,26 @@ bool LoadEx(CFSTR path, DWORD flags = LOAD_LIBRARY_AS_DATAFILE) throw(); bool Load(CFSTR path) throw(); // FARPROC - void *GetProc(LPCSTR procName) const { return My_GetProcAddress(_module, procName); } + // void *GetProc(LPCSTR procName) const { return My_GetProcAddress(_module, procName); } }; #else -typedef void * HMODULE; -// typedef int (*FARPROC)(); -// typedef void *FARPROC; - class CLibrary { HMODULE _module; - // CLASS_NO_COPY(CLibrary); + // Z7_CLASS_NO_COPY(CLibrary); public: - CLibrary(): _module(NULL) {}; + CLibrary(): _module(NULL) {} ~CLibrary() { Free(); } + HMODULE Get_HMODULE() const { return _module; } + bool Free() throw(); bool Load(CFSTR path) throw(); // FARPROC - void *GetProc(LPCSTR procName) const; // { return My_GetProcAddress(_module, procName); } + // void *GetProc(LPCSTR procName) const; // { return My_GetProcAddress(_module, procName); } }; #endif diff -Nru 7zip-22.01+dfsg/CPP/Windows/ErrorMsg.cpp 7zip-23.01+dfsg/CPP/Windows/ErrorMsg.cpp --- 7zip-22.01+dfsg/CPP/Windows/ErrorMsg.cpp 2021-10-18 08:38:52.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/ErrorMsg.cpp 2023-01-29 16:00:00.000000000 +0000 @@ -19,8 +19,8 @@ static bool MyFormatMessage(DWORD errorCode, UString &message) { - #ifndef _SFX - if ((HRESULT)errorCode == MY_HRES_ERROR__INTERNAL_ERROR) + #ifndef Z7_SFX + if ((HRESULT)errorCode == MY_HRES_ERROR_INTERNAL_ERROR) { message = "Internal Error: The failure in hardware (RAM or CPU), OS or program"; return true; @@ -72,7 +72,7 @@ case E_OUTOFMEMORY : s = "E_OUTOFMEMORY : Can't allocate required memory"; break; case E_INVALIDARG : s = "E_INVALIDARG : One or more arguments are invalid"; break; - // case MY__E_ERROR_NEGATIVE_SEEK : s = "MY__E_ERROR_NEGATIVE_SEEK"; break; + // case MY_E_ERROR_NEGATIVE_SEEK : s = "MY_E_ERROR_NEGATIVE_SEEK"; break; default: break; } @@ -81,7 +81,7 @@ So we must transfer error codes before strerror() */ if (!s) { - if ((errorCode & 0xFFFF0000) == (UInt32)((MY__FACILITY__WRes << 16) | 0x80000000)) + if ((errorCode & 0xFFFF0000) == (UInt32)((MY_FACILITY_WRes << 16) | 0x80000000)) errorCode &= 0xFFFF; else if ((errorCode & ((UInt32)1 << 31))) return false; // we will show hex error later for that case diff -Nru 7zip-22.01+dfsg/CPP/Windows/ErrorMsg.h 7zip-23.01+dfsg/CPP/Windows/ErrorMsg.h --- 7zip-22.01+dfsg/CPP/Windows/ErrorMsg.h 2021-01-24 17:52:03.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/ErrorMsg.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/ErrorMsg.h -#ifndef __WINDOWS_ERROR_MSG_H -#define __WINDOWS_ERROR_MSG_H +#ifndef ZIP7_INC_WINDOWS_ERROR_MSG_H +#define ZIP7_INC_WINDOWS_ERROR_MSG_H #include "../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/Windows/FileDir.cpp 7zip-23.01+dfsg/CPP/Windows/FileDir.cpp --- 7zip-22.01+dfsg/CPP/Windows/FileDir.cpp 2022-03-31 14:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/FileDir.cpp 2023-03-17 17:00:00.000000000 +0000 @@ -65,46 +65,55 @@ bool GetWindowsDir(FString &path) { - UINT needLength; + const unsigned kBufSize = MAX_PATH + 16; + UINT len; #ifndef _UNICODE if (!g_IsNT) { - TCHAR s[MAX_PATH + 2]; + TCHAR s[kBufSize + 1]; s[0] = 0; - needLength = ::GetWindowsDirectory(s, MAX_PATH + 1); + len = ::GetWindowsDirectory(s, kBufSize); path = fas2fs(s); } else #endif { - WCHAR s[MAX_PATH + 2]; + WCHAR s[kBufSize + 1]; s[0] = 0; - needLength = ::GetWindowsDirectoryW(s, MAX_PATH + 1); + len = ::GetWindowsDirectoryW(s, kBufSize); path = us2fs(s); } - return (needLength > 0 && needLength <= MAX_PATH); + return (len != 0 && len < kBufSize); } + +/* +new DOCs for GetSystemDirectory: + returned path does not end with a backslash unless the + system directory is the root directory. +*/ + bool GetSystemDir(FString &path) { - UINT needLength; + const unsigned kBufSize = MAX_PATH + 16; + UINT len; #ifndef _UNICODE if (!g_IsNT) { - TCHAR s[MAX_PATH + 2]; + TCHAR s[kBufSize + 1]; s[0] = 0; - needLength = ::GetSystemDirectory(s, MAX_PATH + 1); + len = ::GetSystemDirectory(s, kBufSize); path = fas2fs(s); } else #endif { - WCHAR s[MAX_PATH + 2]; + WCHAR s[kBufSize + 1]; s[0] = 0; - needLength = ::GetSystemDirectoryW(s, MAX_PATH + 1); + len = ::GetSystemDirectoryW(s, kBufSize); path = us2fs(s); } - return (needLength > 0 && needLength <= MAX_PATH); + return (len != 0 && len < kBufSize); } #endif // UNDER_CE @@ -123,7 +132,7 @@ IF_USE_MAIN_PATH hDir = ::CreateFileW(fs2us(path), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if (hDir == INVALID_HANDLE_VALUE && USE_SUPER_PATH) { UString superPath; @@ -158,7 +167,7 @@ IF_USE_MAIN_PATH if (::SetFileAttributesW(fs2us(path), attrib)) return true; - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if (USE_SUPER_PATH) { UString superPath; @@ -195,7 +204,7 @@ IF_USE_MAIN_PATH if (::RemoveDirectoryW(fs2us(path))) return true; - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if (USE_SUPER_PATH) { UString superPath; @@ -224,7 +233,7 @@ if (::MoveFileW(fs2us(oldFile), fs2us(newFile))) return true; } - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if (USE_SUPER_PATH_2) { UString d1, d2; @@ -261,8 +270,11 @@ else #endif { - Func_CreateHardLinkW my_CreateHardLinkW = (Func_CreateHardLinkW) - (void *)::GetProcAddress(::GetModuleHandleW(L"kernel32.dll"), "CreateHardLinkW"); + const + Func_CreateHardLinkW + my_CreateHardLinkW = Z7_GET_PROC_ADDRESS( + Func_CreateHardLinkW, ::GetModuleHandleW(L"kernel32.dll"), + "CreateHardLinkW"); if (!my_CreateHardLinkW) return false; IF_USE_MAIN_PATH_2(newFileName, existFileName) @@ -270,7 +282,7 @@ if (my_CreateHardLinkW(fs2us(newFileName), fs2us(existFileName), NULL)) return true; } - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if (USE_SUPER_PATH_2) { UString d1, d2; @@ -320,7 +332,7 @@ IF_USE_MAIN_PATH if (::CreateDirectoryW(fs2us(path), NULL)) return true; - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if ((!USE_MAIN_PATH || ::GetLastError() != ERROR_ALREADY_EXISTS) && USE_SUPER_PATH) { UString superPath; @@ -355,7 +367,7 @@ IF_USE_MAIN_PATH if (::CreateDirectoryW(fs2us(path), NULL)) return true; - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if ((!USE_MAIN_PATH || ::GetLastError() != ERROR_ALREADY_EXISTS) && USE_SUPER_PATH) { UString superPath; @@ -390,7 +402,7 @@ #ifdef _WIN32 { - DWORD attrib = NFind::GetFileAttrib(_path); + const DWORD attrib = NFind::GetFileAttrib(_path); if (attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY) != 0) return true; } @@ -496,7 +508,7 @@ IF_USE_MAIN_PATH if (::DeleteFileW(fs2us(path))) return true; - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if (USE_SUPER_PATH) { UString superPath; @@ -586,9 +598,12 @@ #ifdef _WIN32 +/* Win10: SetCurrentDirectory() doesn't support long paths and + doesn't support super prefix "\\?\", if long path behavior is not + enabled in registry (LongPathsEnabled) and in manifest (longPathAware). */ + bool SetCurrentDir(CFSTR path) { - // SetCurrentDirectory doesn't support \\?\ prefix #ifndef _UNICODE if (!g_IsNT) { @@ -602,28 +617,74 @@ } +/* +we use system function GetCurrentDirectory() +new GetCurrentDirectory() DOCs: + - If the function fails, the return value is zero. + - If the function succeeds, the return value specifies + the number of characters that are written to the buffer, + not including the terminating null character. + - If the buffer is not large enough, the return value specifies + the required size of the buffer, in characters, + including the null-terminating character. + +GetCurrentDir() calls GetCurrentDirectory(). +GetCurrentDirectory() in win10 in tests: + the returned (path) does not end with a backslash, if + current directory is not root directory of drive. + But that behavior is not guarantied in specification docs. +*/ + bool GetCurrentDir(FString &path) { + const unsigned kBufSize = MAX_PATH + 16; path.Empty(); - DWORD needLength; #ifndef _UNICODE if (!g_IsNT) { - TCHAR s[MAX_PATH + 2]; + TCHAR s[kBufSize + 1]; s[0] = 0; - needLength = ::GetCurrentDirectory(MAX_PATH + 1, s); + const DWORD len = ::GetCurrentDirectory(kBufSize, s); + if (len == 0 || len >= kBufSize) + return false; + s[kBufSize] = 0; // optional guard path = fas2fs(s); + return true; } else #endif { - WCHAR s[MAX_PATH + 2]; - s[0] = 0; - needLength = ::GetCurrentDirectoryW(MAX_PATH + 1, s); - path = us2fs(s); + DWORD len; + { + WCHAR s[kBufSize + 1]; + s[0] = 0; + len = ::GetCurrentDirectoryW(kBufSize, s); + if (len == 0) + return false; + if (len < kBufSize) + { + s[kBufSize] = 0; // optional guard + path = us2fs(s); + return true; + } + } + UString temp; + const DWORD len2 = ::GetCurrentDirectoryW(len, temp.GetBuf(len)); + if (len2 == 0) + return false; + temp.ReleaseBuf_CalcLen(len); + if (temp.Len() != len2 || len - 1 != len2) + { + /* it's unexpected case, if current dir of process + was changed between two function calls, + or some unexpected function implementation */ + // SetLastError((DWORD)E_FAIL); // we can set some error code + return false; + } + path = us2fs(temp); + return true; } - return (needLength > 0 && needLength <= MAX_PATH); } #endif // _WIN32 @@ -648,41 +709,59 @@ return GetFullPathAndSplit(path, resDirPrefix, resFileName); } + + bool MyGetTempPath(FString &path) { #ifdef _WIN32 - path.Empty(); - DWORD needLength; + + /* + new DOCs for GetTempPathW(): + - The returned string ends with a backslash. + - The maximum possible return value is MAX_PATH+1 (261). + */ + + const unsigned kBufSize = MAX_PATH + 16; + DWORD len; #ifndef _UNICODE if (!g_IsNT) { - TCHAR s[MAX_PATH + 2]; + TCHAR s[kBufSize + 1]; s[0] = 0; - needLength = ::GetTempPath(MAX_PATH + 1, s); + len = ::GetTempPath(kBufSize, s); path = fas2fs(s); } else #endif { - WCHAR s[MAX_PATH + 2]; + WCHAR s[kBufSize + 1]; s[0] = 0; - needLength = ::GetTempPathW(MAX_PATH + 1, s);; + len = ::GetTempPathW(kBufSize, s); path = us2fs(s); } - return (needLength > 0 && needLength <= MAX_PATH); + /* win10: GetTempPathW() doesn't set backslash at the end of path, + if (buffer_size == len_of(path_with_backslash)). + So we normalize path here: */ + NormalizeDirPathPrefix(path); + return (len != 0 && len < kBufSize); - #else + #else // !_WIN32 // FIXME: improve that code - path = "/tmp/"; - if (!NFind::DoesDirExist_FollowLink(path)) - path = "./"; + path = STRING_PATH_SEPARATOR "tmp"; + const char *s; + if (NFind::DoesDirExist_FollowLink(path)) + s = STRING_PATH_SEPARATOR "tmp" STRING_PATH_SEPARATOR; + else + s = "." STRING_PATH_SEPARATOR; + path = s; return true; + #endif } -static bool CreateTempFile(CFSTR prefix, bool addRandom, FString &path, NIO::COutFile *outFile) +bool CreateTempFile2(CFSTR prefix, bool addRandom, AString &postfix, NIO::COutFile *outFile) { UInt32 d = #ifdef _WIN32 @@ -693,7 +772,7 @@ for (unsigned i = 0; i < 100; i++) { - path = prefix; + postfix.Empty(); if (addRandom) { char s[16]; @@ -701,14 +780,14 @@ unsigned k; for (k = 0; k < 8; k++) { - unsigned t = val & 0xF; + const unsigned t = val & 0xF; val >>= 4; s[k] = (char)((t < 10) ? ('0' + t) : ('A' + (t - 10))); } s[k] = '\0'; if (outFile) - path += '.'; - path += s; + postfix.Add_Dot(); + postfix += s; UInt32 step = GetTickCount() + 2; if (step == 0) step = 1; @@ -716,7 +795,9 @@ } addRandom = true; if (outFile) - path += ".tmp"; + postfix += ".tmp"; + FString path (prefix); + path += postfix; if (NFind::DoesFileOrDirExist(path)) { SetLastError(ERROR_ALREADY_EXISTS); @@ -732,12 +813,12 @@ if (CreateDir(path)) return true; } - DWORD error = GetLastError(); + const DWORD error = GetLastError(); if (error != ERROR_FILE_EXISTS && error != ERROR_ALREADY_EXISTS) break; } - path.Empty(); + postfix.Empty(); return false; } @@ -745,8 +826,12 @@ { if (!Remove()) return false; - if (!CreateTempFile(prefix, false, _path, outFile)) + _path.Empty(); + AString postfix; + if (!CreateTempFile2(prefix, false, postfix, outFile)) return false; + _path = prefix; + _path += postfix; _mustBeDeleted = true; return true; } @@ -755,11 +840,16 @@ { if (!Remove()) return false; + _path.Empty(); FString tempPath; if (!MyGetTempPath(tempPath)) return false; - if (!CreateTempFile(tempPath + namePrefix, true, _path, outFile)) + AString postfix; + tempPath += namePrefix; + if (!CreateTempFile2(tempPath, true, postfix, outFile)) return false; + _path = tempPath; + _path += postfix; _mustBeDeleted = true; return true; } @@ -802,11 +892,16 @@ { if (!Remove()) return false; + _path.Empty(); FString tempPath; if (!MyGetTempPath(tempPath)) return false; - if (!CreateTempFile(tempPath + prefix, true, _path, NULL)) + tempPath += prefix; + AString postfix; + if (!CreateTempFile2(tempPath, true, postfix, NULL)) return false; + _path = tempPath; + _path += postfix; _mustBeDeleted = true; return true; } @@ -830,7 +925,7 @@ } -static BOOL My__CopyFile(CFSTR oldFile, CFSTR newFile) +static BOOL My_CopyFile(CFSTR oldFile, CFSTR newFile) { NWindows::NFile::NIO::COutFile outFile; if (!outFile.Create(newFile, false)) @@ -865,7 +960,7 @@ if (errno != EXDEV) // (oldFile and newFile are not on the same mounted filesystem) return false; - if (My__CopyFile(oldFile, newFile) == FALSE) + if (My_CopyFile(oldFile, newFile) == FALSE) return false; struct stat info_file; @@ -906,11 +1001,11 @@ { path.Empty(); - #define MY__PATH_MAX PATH_MAX - // #define MY__PATH_MAX 1024 + #define MY_PATH_MAX PATH_MAX + // #define MY_PATH_MAX 1024 - char s[MY__PATH_MAX + 1]; - char *res = getcwd(s, MY__PATH_MAX); + char s[MY_PATH_MAX + 1]; + char *res = getcwd(s, MY_PATH_MAX); if (res) { path = fas2fs(s); @@ -1035,10 +1130,10 @@ #define PRF(x) #define TRACE_SetFileAttrib(msg) \ - PRF(printf("\nSetFileAttrib(%s, %x) : %s\n", (const char *)path, attrib, msg)); + PRF(printf("\nSetFileAttrib(%s, %x) : %s\n", (const char *)path, attrib, msg);) #define TRACE_chmod(s, mode) \ - PRF(printf("\n chmod(%s, %o)\n", (const char *)path, (unsigned)(mode))); + PRF(printf("\n chmod(%s, %o)\n", (const char *)path, (unsigned)(mode));) int my_chown(CFSTR path, uid_t owner, gid_t group) { @@ -1047,7 +1142,7 @@ bool SetFileAttrib_PosixHighDetect(CFSTR path, DWORD attrib) { - TRACE_SetFileAttrib(""); + TRACE_SetFileAttrib("") struct stat st; @@ -1056,7 +1151,7 @@ { if (lstat(path, &st) != 0) { - TRACE_SetFileAttrib("bad lstat()"); + TRACE_SetFileAttrib("bad lstat()") return false; } // TRACE_chmod("lstat", st.st_mode); @@ -1065,14 +1160,14 @@ { if (stat(path, &st) != 0) { - TRACE_SetFileAttrib("bad stat()"); + TRACE_SetFileAttrib("bad stat()") return false; } } if (attrib & FILE_ATTRIBUTE_UNIX_EXTENSION) { - TRACE_SetFileAttrib("attrib & FILE_ATTRIBUTE_UNIX_EXTENSION"); + TRACE_SetFileAttrib("attrib & FILE_ATTRIBUTE_UNIX_EXTENSION") st.st_mode = attrib >> 16; if (S_ISDIR(st.st_mode)) { @@ -1092,7 +1187,7 @@ } else { - TRACE_SetFileAttrib("Only Windows Attributes"); + TRACE_SetFileAttrib("Only Windows Attributes") // Only Windows Attributes if (S_ISDIR(st.st_mode) || (attrib & FILE_ATTRIBUTE_READONLY) == 0) @@ -1105,7 +1200,7 @@ if (S_ISLNK(st.st_mode)) { printf("\nfchmodat()\n"); - TRACE_chmod(path, (st.st_mode) & g_umask.mask); + TRACE_chmod(path, (st.st_mode) & g_umask.mask) // AT_SYMLINK_NOFOLLOW is not implemted still in Linux. res = fchmodat(AT_FDCWD, path, (st.st_mode) & g_umask.mask, S_ISLNK(st.st_mode) ? AT_SYMLINK_NOFOLLOW : 0); @@ -1113,7 +1208,7 @@ else */ { - TRACE_chmod(path, (st.st_mode) & g_umask.mask); + TRACE_chmod(path, (st.st_mode) & g_umask.mask) res = chmod(path, (st.st_mode) & g_umask.mask); } // TRACE_SetFileAttrib("End") @@ -1123,7 +1218,7 @@ bool MyCreateHardLink(CFSTR newFileName, CFSTR existFileName) { - PRF(printf("\nhard link() %s -> %s\n", newFileName, existFileName)); + PRF(printf("\nhard link() %s -> %s\n", newFileName, existFileName);) return (link(existFileName, newFileName) == 0); } diff -Nru 7zip-22.01+dfsg/CPP/Windows/FileDir.h 7zip-23.01+dfsg/CPP/Windows/FileDir.h --- 7zip-22.01+dfsg/CPP/Windows/FileDir.h 2022-03-28 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/FileDir.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/FileDir.h -#ifndef __WINDOWS_FILE_DIR_H -#define __WINDOWS_FILE_DIR_H +#ifndef ZIP7_INC_WINDOWS_FILE_DIR_H +#define ZIP7_INC_WINDOWS_FILE_DIR_H #include "../Common/MyString.h" @@ -73,6 +73,8 @@ bool MyGetTempPath(FString &resultPath); +bool CreateTempFile2(CFSTR prefix, bool addRandom, AString &postfix, NIO::COutFile *outFile); + class CTempFile MY_UNCOPYABLE { bool _mustBeDeleted; diff -Nru 7zip-22.01+dfsg/CPP/Windows/FileFind.cpp 7zip-23.01+dfsg/CPP/Windows/FileFind.cpp --- 7zip-22.01+dfsg/CPP/Windows/FileFind.cpp 2022-03-31 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/FileFind.cpp 2023-03-17 18:00:00.000000000 +0000 @@ -39,10 +39,10 @@ WCHAR cStreamName[MAX_PATH + 36]; } MY_WIN32_FIND_STREAM_DATA, *MY_PWIN32_FIND_STREAM_DATA; -typedef HANDLE (WINAPI *FindFirstStreamW_Ptr)(LPCWSTR fileName, MY_STREAM_INFO_LEVELS infoLevel, +typedef HANDLE (WINAPI *Func_FindFirstStreamW)(LPCWSTR fileName, MY_STREAM_INFO_LEVELS infoLevel, LPVOID findStreamData, DWORD flags); -typedef BOOL (APIENTRY *FindNextStreamW_Ptr)(HANDLE findStream, LPVOID findStreamData); +typedef BOOL (APIENTRY *Func_FindNextStreamW)(HANDLE findStream, LPVOID findStreamData); EXTERN_C_END @@ -54,7 +54,7 @@ #ifdef _WIN32 -#ifdef SUPPORT_DEVICE_FILE +#ifdef Z7_DEVICE_FILE namespace NSystem { bool MyGetDiskFreeSpace(CFSTR rootPath, UInt64 &clusterSize, UInt64 &totalSize, UInt64 &freeSize); @@ -128,7 +128,7 @@ static void Convert_WIN32_FIND_DATA_to_FileInfo(const WIN32_FIND_DATAW &fd, CFileInfo &fi) { - WIN_FD_TO_MY_FI(fi, fd); + WIN_FD_TO_MY_FI(fi, fd) fi.Name = us2fs(fd.cFileName); #if defined(_WIN32) && !defined(UNDER_CE) // fi.ShortName = us2fs(fd.cAlternateFileName); @@ -138,7 +138,7 @@ #ifndef _UNICODE static void Convert_WIN32_FIND_DATA_to_FileInfo(const WIN32_FIND_DATA &fd, CFileInfo &fi) { - WIN_FD_TO_MY_FI(fi, fd); + WIN_FD_TO_MY_FI(fi, fd) fi.Name = fas2fs(fd.cFileName); #if defined(_WIN32) && !defined(UNDER_CE) // fi.ShortName = fas2fs(fd.cAlternateFileName); @@ -211,7 +211,7 @@ IF_USE_MAIN_PATH _handle = ::FindFirstFileW(fs2us(path), &fd); - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if (_handle == INVALID_HANDLE_VALUE && USE_SUPER_PATH) { UString superPath; @@ -252,23 +252,27 @@ //////////////////////////////// // AltStreams -static FindFirstStreamW_Ptr g_FindFirstStreamW; -static FindNextStreamW_Ptr g_FindNextStreamW; +static Func_FindFirstStreamW g_FindFirstStreamW; +static Func_FindNextStreamW g_FindNextStreamW; static struct CFindStreamLoader { CFindStreamLoader() { - HMODULE hm = ::GetModuleHandleA("kernel32.dll"); - g_FindFirstStreamW = (FindFirstStreamW_Ptr)(void *)::GetProcAddress(hm, "FindFirstStreamW"); - g_FindNextStreamW = (FindNextStreamW_Ptr)(void *)::GetProcAddress(hm, "FindNextStreamW"); + const HMODULE hm = ::GetModuleHandleA("kernel32.dll"); + g_FindFirstStreamW = Z7_GET_PROC_ADDRESS( + Func_FindFirstStreamW, hm, + "FindFirstStreamW"); + g_FindNextStreamW = Z7_GET_PROC_ADDRESS( + Func_FindNextStreamW, hm, + "FindNextStreamW"); } } g_FindStreamLoader; bool CStreamInfo::IsMainStream() const throw() { return StringsAreEqualNoCase_Ascii(Name, "::$DATA"); -}; +} UString CStreamInfo::GetReducedName() const { @@ -331,7 +335,7 @@ if (::GetLastError() == ERROR_HANDLE_EOF) return false; // long name can be tricky for path like ".\dirName". - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if (USE_SUPER_PATH) { UString superPath; @@ -414,7 +418,7 @@ if (dw != INVALID_FILE_ATTRIBUTES) return dw; } - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if (USE_SUPER_PATH) { UString superPath; @@ -451,7 +455,7 @@ bool CFileInfo::Find(CFSTR path, bool followLink) { - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE if (IS_PATH_SEPAR(path[0]) && IS_PATH_SEPAR(path[1]) && @@ -847,7 +851,7 @@ { IF_USE_MAIN_PATH _handle = ::FindFirstChangeNotificationW(fs2us(path), BoolToBOOL(watchSubtree), notifyFilter); - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if (!IsHandleAllocated()) { UString superPath; diff -Nru 7zip-22.01+dfsg/CPP/Windows/FileFind.h 7zip-23.01+dfsg/CPP/Windows/FileFind.h --- 7zip-22.01+dfsg/CPP/Windows/FileFind.h 2022-03-31 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/FileFind.h 2023-03-17 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/FileFind.h -#ifndef __WINDOWS_FILE_FIND_H -#define __WINDOWS_FILE_FIND_H +#ifndef ZIP7_INC_WINDOWS_FILE_FIND_H +#define ZIP7_INC_WINDOWS_FILE_FIND_H #ifndef _WIN32 #include @@ -249,7 +249,15 @@ HANDLE _handle; public: operator HANDLE () { return _handle; } - bool IsHandleAllocated() const { return _handle != INVALID_HANDLE_VALUE && _handle != 0; } + bool IsHandleAllocated() const + { + /* at least on win2000/XP (undocumented): + if pathName is "" or NULL, + FindFirstChangeNotification() could return NULL. + So we check for INVALID_HANDLE_VALUE and NULL. + */ + return _handle != INVALID_HANDLE_VALUE && _handle != NULL; + } CFindChangeNotification(): _handle(INVALID_HANDLE_VALUE) {} ~CFindChangeNotification() { Close(); } bool Close() throw(); diff -Nru 7zip-22.01+dfsg/CPP/Windows/FileIO.cpp 7zip-23.01+dfsg/CPP/Windows/FileIO.cpp --- 7zip-22.01+dfsg/CPP/Windows/FileIO.cpp 2022-03-31 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/FileIO.cpp 2023-04-07 18:00:00.000000000 +0000 @@ -2,7 +2,7 @@ #include "StdAfx.h" -#ifdef SUPPORT_DEVICE_FILE +#ifdef Z7_DEVICE_FILE #include "../../C/Alloc.h" #endif @@ -21,7 +21,7 @@ HRESULT GetLastError_noZero_HRESULT() { - DWORD res = ::GetLastError(); + const DWORD res = ::GetLastError(); if (res == 0) return E_FAIL; return HRESULT_FROM_WIN32(res); @@ -40,7 +40,7 @@ namespace NWindows { namespace NFile { -#ifdef SUPPORT_DEVICE_FILE +#ifdef Z7_DEVICE_FILE namespace NSystem { @@ -72,7 +72,7 @@ if (!Close()) return false; - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE IsDeviceFile = false; #endif @@ -88,7 +88,7 @@ IF_USE_MAIN_PATH _handle = ::CreateFileW(fs2us(path), desiredAccess, shareMode, (LPSECURITY_ATTRIBUTES)NULL, creationDisposition, flagsAndAttributes, (HANDLE)NULL); - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if (_handle == INVALID_HANDLE_VALUE && USE_SUPER_PATH) { UString superPath; @@ -101,7 +101,7 @@ /* #ifndef UNDER_CE - #ifndef _SFX + #ifndef Z7_SFX if (_handle == INVALID_HANDLE_VALUE) { // it's debug hack to open symbolic links in Windows XP and WSL links in Windows 10 @@ -149,7 +149,7 @@ bool CFileBase::GetLength(UInt64 &length) const throw() { - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE if (IsDeviceFile && SizeDefined) { length = Size; @@ -219,7 +219,7 @@ bool CFileBase::Seek(Int64 distanceToMove, DWORD moveMethod, UInt64 &newPosition) const throw() { - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE if (IsDeviceFile && SizeDefined && moveMethod == FILE_END) { distanceToMove += Size; @@ -262,12 +262,12 @@ // ---------- CInFile --------- -#ifdef SUPPORT_DEVICE_FILE +#ifdef Z7_DEVICE_FILE void CInFile::CorrectDeviceSize() { // maybe we must decrease kClusterSize to 1 << 12, if we want correct size at tail - static const UInt32 kClusterSize = 1 << 14; + const UInt32 kClusterSize = 1 << 14; UInt64 pos = Size & ~(UInt64)(kClusterSize - 1); UInt64 realNewPosition; if (!Seek(pos, realNewPosition)) @@ -462,7 +462,7 @@ bool CInFile::Read1(void *data, UInt32 size, UInt32 &processedSize) throw() { DWORD processedLoc = 0; - bool res = BOOLToBool(::ReadFile(_handle, data, size, &processedLoc, NULL)); + const bool res = BOOLToBool(::ReadFile(_handle, data, size, &processedLoc, NULL)); processedSize = (UInt32)processedLoc; return res; } @@ -480,7 +480,7 @@ do { UInt32 processedLoc = 0; - bool res = ReadPart(data, size, processedLoc); + const bool res = ReadPart(data, size, processedLoc); processedSize += processedLoc; if (!res) return false; @@ -551,7 +551,7 @@ do { UInt32 processedLoc = 0; - bool res = WritePart(data, size, processedLoc); + const bool res = WritePart(data, size, processedLoc); processedSize += processedLoc; if (!res) return false; @@ -628,14 +628,14 @@ namespace NIO { -bool CFileBase::OpenBinary(const char *name, int flags) +bool CFileBase::OpenBinary(const char *name, int flags, mode_t mode) { #ifdef O_BINARY flags |= O_BINARY; #endif Close(); - _handle = ::open(name, flags, 0666); + _handle = ::open(name, flags, mode); return _handle != -1; /* @@ -804,10 +804,10 @@ if (createAlways) { Close(); - _handle = ::creat(name, 0666); + _handle = ::creat(name, mode_for_Create); return _handle != -1; } - return OpenBinary(name, O_CREAT | O_EXCL | O_WRONLY); + return OpenBinary(name, O_CREAT | O_EXCL | O_WRONLY, mode_for_Create); } bool COutFile::Open(const char *name, DWORD creationDisposition) @@ -850,13 +850,13 @@ return false; } // The value of the seek pointer shall not be modified by a call to ftruncate(). - int iret = ftruncate(_handle, len2); + const int iret = ftruncate(_handle, len2); return (iret == 0); } bool COutFile::Close() { - bool res = CFileBase::Close(); + const bool res = CFileBase::Close(); if (!res) return res; if (CTime_defined || ATime_defined || MTime_defined) diff -Nru 7zip-22.01+dfsg/CPP/Windows/FileIO.h 7zip-23.01+dfsg/CPP/Windows/FileIO.h --- 7zip-22.01+dfsg/CPP/Windows/FileIO.h 2022-03-31 13:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/FileIO.h 2023-03-17 18:00:00.000000000 +0000 @@ -1,23 +1,23 @@ // Windows/FileIO.h -#ifndef __WINDOWS_FILE_IO_H -#define __WINDOWS_FILE_IO_H +#ifndef ZIP7_INC_WINDOWS_FILE_IO_H +#define ZIP7_INC_WINDOWS_FILE_IO_H #include "../Common/MyWindows.h" -#define _my_IO_REPARSE_TAG_MOUNT_POINT (0xA0000003L) -#define _my_IO_REPARSE_TAG_SYMLINK (0xA000000CL) -#define _my_IO_REPARSE_TAG_LX_SYMLINK (0xA000001DL) +#define Z7_WIN_IO_REPARSE_TAG_MOUNT_POINT (0xA0000003L) +#define Z7_WIN_IO_REPARSE_TAG_SYMLINK (0xA000000CL) +#define Z7_WIN_IO_REPARSE_TAG_LX_SYMLINK (0xA000001DL) -#define _my_SYMLINK_FLAG_RELATIVE 1 +#define Z7_WIN_SYMLINK_FLAG_RELATIVE 1 // what the meaning of that FLAG or field (2)? -#define _my_LX_SYMLINK_FLAG 2 +#define Z7_WIN_LX_SYMLINK_FLAG 2 #ifdef _WIN32 #if defined(_WIN32) && !defined(UNDER_CE) -#include +#include #endif #else @@ -76,11 +76,11 @@ // returns (false) and (ErrorCode = ERROR_REPARSE_TAG_INVALID), if unknown tag bool Parse(const Byte *p, size_t size); - bool IsMountPoint() const { return Tag == _my_IO_REPARSE_TAG_MOUNT_POINT; } // it's Junction - bool IsSymLink_Win() const { return Tag == _my_IO_REPARSE_TAG_SYMLINK; } - bool IsSymLink_WSL() const { return Tag == _my_IO_REPARSE_TAG_LX_SYMLINK; } + bool IsMountPoint() const { return Tag == Z7_WIN_IO_REPARSE_TAG_MOUNT_POINT; } // it's Junction + bool IsSymLink_Win() const { return Tag == Z7_WIN_IO_REPARSE_TAG_SYMLINK; } + bool IsSymLink_WSL() const { return Tag == Z7_WIN_IO_REPARSE_TAG_LX_SYMLINK; } - bool IsRelative_Win() const { return Flags == _my_SYMLINK_FLAG_RELATIVE; } + bool IsRelative_Win() const { return Flags == Z7_WIN_SYMLINK_FLAG_RELATIVE; } bool IsRelative_WSL() const { @@ -141,17 +141,19 @@ public: bool PreserveATime; - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE bool IsDeviceFile; bool SizeDefined; UInt64 Size; // it can be larger than real available size #endif - CFileBase(): _handle(INVALID_HANDLE_VALUE), PreserveATime(false) {}; + CFileBase(): _handle(INVALID_HANDLE_VALUE), PreserveATime(false) {} ~CFileBase() { Close(); } HANDLE GetHandle() const { return _handle; } + // void Detach() { _handle = INVALID_HANDLE_VALUE; } + bool Close() throw(); bool GetPosition(UInt64 &position) const throw(); @@ -193,7 +195,7 @@ class CInFile: public CFileBase { - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE #ifndef UNDER_CE @@ -232,6 +234,14 @@ // we must use (FILE_FLAG_BACKUP_SEMANTICS) to open handle of directory. } + bool Open_for_FileRenameInformation(CFSTR fileName) + { + return Create(fileName, DELETE | SYNCHRONIZE | GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL); + // we must use (FILE_FLAG_BACKUP_SEMANTICS) to open handle of directory. + } + bool OpenReparse(CFSTR fileName) { // 17.02 fix: to support Windows XP compatibility junctions: @@ -295,12 +305,13 @@ UInt64 Size; // it can be larger than real available size */ - bool OpenBinary(const char *name, int flags); + bool OpenBinary(const char *name, int flags, mode_t mode = 0666); public: bool PreserveATime; - CFileBase(): _handle(-1), PreserveATime(false) {}; + CFileBase(): _handle(-1), PreserveATime(false) {} ~CFileBase() { Close(); } + // void Detach() { _handle = -1; } bool Close(); bool GetLength(UInt64 &length) const; off_t seek(off_t distanceToMove, int moveMethod) const; @@ -330,7 +341,6 @@ bool CTime_defined; bool ATime_defined; bool MTime_defined; - CFiTime CTime; CFiTime ATime; CFiTime MTime; @@ -338,10 +348,13 @@ AString Path; ssize_t write_part(const void *data, size_t size) throw(); public: + mode_t mode_for_Create; + COutFile(): CTime_defined(false), ATime_defined(false), - MTime_defined(false) + MTime_defined(false), + mode_for_Create(0666) {} bool Close(); diff -Nru 7zip-22.01+dfsg/CPP/Windows/FileLink.cpp 7zip-23.01+dfsg/CPP/Windows/FileLink.cpp --- 7zip-22.01+dfsg/CPP/Windows/FileLink.cpp 2021-04-21 08:59:36.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/FileLink.cpp 2023-03-16 09:00:00.000000000 +0000 @@ -8,7 +8,7 @@ #include #endif -#ifdef SUPPORT_DEVICE_FILE +#ifdef Z7_DEVICE_FILE #include "../../C/Alloc.h" #endif @@ -20,6 +20,15 @@ #include "FileIO.h" #include "FileName.h" +#ifdef Z7_OLD_WIN_SDK +#ifndef ERROR_INVALID_REPARSE_DATA +#define ERROR_INVALID_REPARSE_DATA 4392L +#endif +#ifndef ERROR_REPARSE_TAG_INVALID +#define ERROR_REPARSE_TAG_INVALID 4393L +#endif +#endif + #ifndef _UNICODE extern bool g_IsNT; #endif @@ -72,13 +81,13 @@ static const UInt32 kReparseFlags_HighLatency = (1 << 30); static const UInt32 kReparseFlags_Microsoft = ((UInt32)1 << 31); -#define _my_IO_REPARSE_TAG_HSM (0xC0000004L) -#define _my_IO_REPARSE_TAG_HSM2 (0x80000006L) -#define _my_IO_REPARSE_TAG_SIS (0x80000007L) -#define _my_IO_REPARSE_TAG_WIM (0x80000008L) -#define _my_IO_REPARSE_TAG_CSV (0x80000009L) -#define _my_IO_REPARSE_TAG_DFS (0x8000000AL) -#define _my_IO_REPARSE_TAG_DFSR (0x80000012L) +#define Z7_WIN_IO_REPARSE_TAG_HSM (0xC0000004L) +#define Z7_WIN_IO_REPARSE_TAG_HSM2 (0x80000006L) +#define Z7_WIN_IO_REPARSE_TAG_SIS (0x80000007L) +#define Z7_WIN_IO_REPARSE_TAG_WIM (0x80000008L) +#define Z7_WIN_IO_REPARSE_TAG_CSV (0x80000009L) +#define Z7_WIN_IO_REPARSE_TAG_DFS (0x8000000AL) +#define Z7_WIN_IO_REPARSE_TAG_DFSR (0x80000012L) */ #define Get16(p) GetUi16(p) @@ -112,7 +121,7 @@ wchar_t c = *path++; if (c == 0) return; - Set16(dest, (UInt16)c); + Set16(dest, (UInt16)c) dest += 2; } } @@ -133,10 +142,10 @@ return false; dest.Alloc(8 + size); Byte *p = dest; - Set32(p, _my_IO_REPARSE_TAG_LX_SYMLINK); - Set16(p + 4, (UInt16)(size)); - Set16(p + 6, 0); - Set32(p + 8, _my_LX_SYMLINK_FLAG); + Set32(p, Z7_WIN_IO_REPARSE_TAG_LX_SYMLINK) + Set16(p + 4, (UInt16)(size)) + Set16(p + 6, 0) + Set32(p + 8, Z7_WIN_LX_SYMLINK_FLAG) memcpy(p + 12, utf.Ptr(), utf.Len()); return true; } @@ -176,12 +185,12 @@ dest.Alloc(size); memset(dest, 0, size); const UInt32 tag = isSymLink ? - _my_IO_REPARSE_TAG_SYMLINK : - _my_IO_REPARSE_TAG_MOUNT_POINT; + Z7_WIN_IO_REPARSE_TAG_SYMLINK : + Z7_WIN_IO_REPARSE_TAG_MOUNT_POINT; Byte *p = dest; - Set32(p, tag); - Set16(p + 4, (UInt16)(size - 8)); - Set16(p + 6, 0); + Set32(p, tag) + Set16(p + 4, (UInt16)(size - 8)) + Set16(p + 6, 0) p += 8; unsigned subOffs = 0; @@ -191,16 +200,16 @@ else printOffs = (unsigned)len1 + 2; - Set16(p + 0, (UInt16)subOffs); - Set16(p + 2, (UInt16)len1); - Set16(p + 4, (UInt16)printOffs); - Set16(p + 6, (UInt16)len2); + Set16(p + 0, (UInt16)subOffs) + Set16(p + 2, (UInt16)len1) + Set16(p + 4, (UInt16)printOffs) + Set16(p + 6, (UInt16)len2) p += 8; if (isSymLink) { - UInt32 flags = isAbs ? 0 : _my_SYMLINK_FLAG_RELATIVE; - Set32(p, flags); + UInt32 flags = isAbs ? 0 : Z7_WIN_SYMLINK_FLAG_RELATIVE; + Set32(p, flags) p += 4; } @@ -255,9 +264,9 @@ HeaderError = false; - if ( Tag != _my_IO_REPARSE_TAG_MOUNT_POINT - && Tag != _my_IO_REPARSE_TAG_SYMLINK - && Tag != _my_IO_REPARSE_TAG_LX_SYMLINK) + if ( Tag != Z7_WIN_IO_REPARSE_TAG_MOUNT_POINT + && Tag != Z7_WIN_IO_REPARSE_TAG_SYMLINK + && Tag != Z7_WIN_IO_REPARSE_TAG_LX_SYMLINK) { // for unsupported reparse points ErrorCode = (DWORD)ERROR_REPARSE_TAG_INVALID; // ERROR_REPARSE_TAG_MISMATCH @@ -270,12 +279,12 @@ p += 8; size -= 8; - if (Tag == _my_IO_REPARSE_TAG_LX_SYMLINK) + if (Tag == Z7_WIN_IO_REPARSE_TAG_LX_SYMLINK) { if (len < 4) return false; Flags = Get32(p); // maybe it's not Flags - if (Flags != _my_LX_SYMLINK_FLAG) + if (Flags != Z7_WIN_LX_SYMLINK_FLAG) return false; len -= 4; p += 4; @@ -304,7 +313,7 @@ p += 8; Flags = 0; - if (Tag == _my_IO_REPARSE_TAG_SYMLINK) + if (Tag == Z7_WIN_IO_REPARSE_TAG_SYMLINK) { if (len < 4) return false; @@ -341,8 +350,8 @@ (type & kReparseFlags_Microsoft) == 0 || (type & 0xFFFF) != 3) */ - if (Tag != _my_IO_REPARSE_TAG_MOUNT_POINT && - Tag != _my_IO_REPARSE_TAG_SYMLINK) + if (Tag != Z7_WIN_IO_REPARSE_TAG_MOUNT_POINT && + Tag != Z7_WIN_IO_REPARSE_TAG_SYMLINK) // return true; return false; @@ -365,7 +374,7 @@ p += 8; // UInt32 Flags = 0; - if (Tag == _my_IO_REPARSE_TAG_SYMLINK) + if (Tag == Z7_WIN_IO_REPARSE_TAG_SYMLINK) { if (len < 4) return false; @@ -426,13 +435,13 @@ return s; } -#ifdef SUPPORT_DEVICE_FILE +#ifdef Z7_DEVICE_FILE namespace NSystem { bool MyGetDiskFreeSpace(CFSTR rootPath, UInt64 &clusterSize, UInt64 &totalSize, UInt64 &freeSize); } -#endif // SUPPORT_DEVICE_FILE +#endif // Z7_DEVICE_FILE #if defined(_WIN32) && !defined(UNDER_CE) diff -Nru 7zip-22.01+dfsg/CPP/Windows/FileMapping.h 7zip-23.01+dfsg/CPP/Windows/FileMapping.h --- 7zip-22.01+dfsg/CPP/Windows/FileMapping.h 2013-01-23 17:57:14.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/FileMapping.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/FileMapping.h -#ifndef __WINDOWS_FILEMAPPING_H -#define __WINDOWS_FILEMAPPING_H +#ifndef ZIP7_INC_WINDOWS_FILE_MAPPING_H +#define ZIP7_INC_WINDOWS_FILE_MAPPING_H #include "../Common/MyTypes.h" @@ -34,7 +34,7 @@ return res; #else _handle = ::OpenFileMapping(desiredAccess, FALSE, name); - if (_handle != 0) + if (_handle != NULL) return 0; return ::GetLastError(); #endif diff -Nru 7zip-22.01+dfsg/CPP/Windows/FileName.cpp 7zip-23.01+dfsg/CPP/Windows/FileName.cpp --- 7zip-22.01+dfsg/CPP/Windows/FileName.cpp 2021-10-23 17:30:30.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/FileName.cpp 2023-05-01 10:00:00.000000000 +0000 @@ -6,9 +6,9 @@ #include #include #include "../Common/StringConvert.h" -#include "FileDir.h" #endif +#include "FileDir.h" #include "FileName.h" #ifndef _UNICODE @@ -68,7 +68,7 @@ #ifdef _WIN32 #ifndef USE_UNICODE_FSTRING -#ifdef WIN_LONG_PATH +#ifdef Z7_LONG_PATH static void NormalizeDirSeparators(UString &s) { const unsigned len = s.Len(); @@ -90,7 +90,7 @@ #endif -#define IS_LETTER_CHAR(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z')) +#define IS_LETTER_CHAR(c) ((((unsigned)(int)(c) | 0x20) - (unsigned)'a' <= (unsigned)('z' - 'a'))) bool IsDrivePath(const wchar_t *s) throw() { return IS_LETTER_CHAR(s[0]) && s[1] == ':' && IS_SEPAR(s[2]); } @@ -120,7 +120,7 @@ #if defined(_WIN32) && !defined(UNDER_CE) const char * const kSuperPathPrefix = "\\\\?\\"; -#ifdef WIN_LONG_PATH +#ifdef Z7_LONG_PATH static const char * const kSuperUncPrefix = "\\\\?\\UNC\\"; #endif @@ -191,7 +191,7 @@ if (c == '.' || c == '?') return 0; } - int pos = FindSepar(s + prefixSize); + const int pos = FindSepar(s + prefixSize); if (pos < 0) return 0; return prefixSize + (unsigned)(pos + 1); @@ -199,11 +199,11 @@ bool IsNetworkShareRootPath(CFSTR s) throw() { - unsigned prefixSize = GetNetworkServerPrefixSize(s); + const unsigned prefixSize = GetNetworkServerPrefixSize(s); if (prefixSize == 0) return false; s += prefixSize; - int pos = FindSepar(s); + const int pos = FindSepar(s); if (pos < 0) return true; return s[(unsigned)pos + 1] == 0; @@ -217,6 +217,37 @@ bool IsSuperOrDevicePath(const wchar_t *s) throw() { return IS_SUPER_OR_DEVICE_PATH(s); } // bool IsSuperUncPath(const wchar_t *s) throw() { return (IS_SUPER_PREFIX(s) && IS_UNC_WITH_SLASH(s + kSuperPathPrefixSize)); } +bool IsAltStreamPrefixWithColon(const UString &s) throw() +{ + if (s.IsEmpty()) + return false; + if (s.Back() != ':') + return false; + unsigned pos = 0; + if (IsSuperPath(s)) + pos = kSuperPathPrefixSize; + if (s.Len() - pos == 2 && IsDrivePath2(s.Ptr(pos))) + return false; + return true; +} + +bool If_IsSuperPath_RemoveSuperPrefix(UString &s) +{ + if (!IsSuperPath(s)) + return false; + unsigned start = 0; + unsigned count = kSuperPathPrefixSize; + const wchar_t *s2 = s.Ptr(kSuperPathPrefixSize); + if (IS_UNC_WITH_SLASH(s2)) + { + start = 2; + count = kSuperUncPathPrefixSize - 2; + } + s.Delete(start, count); + return true; +} + + #ifndef USE_UNICODE_FSTRING bool IsDrivePath2(CFSTR s) throw() { return IS_LETTER_CHAR(s[0]) && s[1] == ':'; } // bool IsDriveName2(CFSTR s) throw() { return IS_LETTER_CHAR(s[0]) && s[1] == ':' && s[2] == 0; } @@ -288,7 +319,7 @@ return 0; if (s[1] == 0 || !IS_SEPAR(s[1])) return 1; - unsigned size = GetRootPrefixSize_Of_NetworkPath(s + 2); + const unsigned size = GetRootPrefixSize_Of_NetworkPath(s + 2); return (size == 0) ? 0 : 2 + size; } @@ -296,11 +327,11 @@ { if (IS_UNC_WITH_SLASH(s + kSuperPathPrefixSize)) { - unsigned size = GetRootPrefixSize_Of_NetworkPath(s + kSuperUncPathPrefixSize); + const unsigned size = GetRootPrefixSize_Of_NetworkPath(s + kSuperUncPathPrefixSize); return (size == 0) ? 0 : kSuperUncPathPrefixSize + size; } // we support \\?\c:\ paths and volume GUID paths \\?\Volume{GUID}\" - int pos = FindSepar(s + kSuperPathPrefixSize); + const int pos = FindSepar(s + kSuperPathPrefixSize); if (pos < 0) return 0; return kSuperPathPrefixSize + pos + 1; @@ -379,42 +410,26 @@ #ifndef UNDER_CE -static bool GetCurDir(UString &path) -{ - path.Empty(); - #ifdef _WIN32 +#ifdef USE_UNICODE_FSTRING - DWORD needLength; - #ifndef _UNICODE - if (!g_IsNT) - { - TCHAR s[MAX_PATH + 2]; - s[0] = 0; - needLength = ::GetCurrentDirectory(MAX_PATH + 1, s); - path = fs2us(fas2fs(s)); - } - else - #endif - { - WCHAR s[MAX_PATH + 2]; - s[0] = 0; - needLength = ::GetCurrentDirectoryW(MAX_PATH + 1, s); - path = s; - } - return (needLength > 0 && needLength <= MAX_PATH); +#define GetCurDir NDir::GetCurrentDir - #else +#else +static bool GetCurDir(UString &path) +{ + path.Empty(); FString s; if (!NDir::GetCurrentDir(s)) return false; - path = GetUnicodeString(s); + path = fs2us(s); return true; - - #endif } +#endif + + static bool ResolveDotsFolders(UString &s) { #ifdef _WIN32 @@ -516,7 +531,7 @@ #endif #endif // LONG_PATH_DOTS_FOLDERS_PARSING -#ifdef WIN_LONG_PATH +#ifdef Z7_LONG_PATH /* Most of Windows versions have problems, if some file or dir name @@ -610,11 +625,11 @@ return true; UString temp = fs2us(s); - unsigned fixedSize = GetRootPrefixSize_Of_SuperPath(temp); + const unsigned fixedSize = GetRootPrefixSize_Of_SuperPath(temp); if (fixedSize == 0) return true; - UString rem = &temp[fixedSize]; + UString rem = temp.Ptr(fixedSize); if (!ResolveDotsFolders(rem)) return true; @@ -632,13 +647,13 @@ if (IS_SEPAR(s[1])) { UString temp = fs2us(s + 2); - unsigned fixedSize = GetRootPrefixSize_Of_NetworkPath(temp); + const unsigned fixedSize = GetRootPrefixSize_Of_NetworkPath(temp); // we ignore that error to allow short network paths server\share? /* if (fixedSize == 0) return false; */ - UString rem = &temp[fixedSize]; + UString rem = temp.Ptr(fixedSize); if (!ResolveDotsFolders(rem)) return false; res += kSuperUncPrefix; @@ -783,7 +798,7 @@ return false; } */ -#endif // WIN_LONG_PATH +#endif // Z7_LONG_PATH bool GetFullPath(CFSTR dirPrefix, CFSTR s, FString &res) { @@ -801,8 +816,11 @@ #else - unsigned prefixSize = GetRootPrefixSize(s); + const unsigned prefixSize = GetRootPrefixSize(s); if (prefixSize != 0) +#ifdef _WIN32 + if (prefixSize != 1) +#endif { if (!AreThereDotsFolders(s + prefixSize)) return true; @@ -815,21 +833,9 @@ return true; } - /* - FChar c = s[0]; - if (c == 0) - return true; - if (c == '.' && (s[1] == 0 || (s[1] == '.' && s[2] == 0))) - return true; - if (IS_SEPAR(c) && IS_SEPAR(s[1])) - return true; - if (IsDrivePath(s)) - return true; - */ - UString curDir; - if (dirPrefix) - curDir = fs2us(dirPrefix); + if (dirPrefix && prefixSize == 0) + curDir = fs2us(dirPrefix); // we use (dirPrefix), only if (s) path is relative else { if (!GetCurDir(curDir)) @@ -837,46 +843,40 @@ } NormalizeDirPathPrefix(curDir); - unsigned fixedSize = 0; + unsigned fixedSize = GetRootPrefixSize(curDir); - #ifdef _WIN32 - - if (IsSuperPath(curDir)) + UString temp; +#ifdef _WIN32 + if (prefixSize != 0) { - fixedSize = GetRootPrefixSize_Of_SuperPath(curDir); + /* (s) is absolute path, but only (prefixSize == 1) is possible here. + So for full resolving we need root of current folder and + relative part of (s). */ + s += prefixSize; + // (s) is relative part now if (fixedSize == 0) - return false; - } - else - { - if (IsDrivePath(curDir)) - fixedSize = kDrivePrefixSize; - else { - if (!IsPathSepar(curDir[0]) || !IsPathSepar(curDir[1])) - return false; - fixedSize = GetRootPrefixSize_Of_NetworkPath(curDir.Ptr(2)); - if (fixedSize == 0) - return false; - fixedSize += 2; + // (curDir) is not absolute. + // That case is unexpected, but we support it too. + curDir.Empty(); + curDir.Add_PathSepar(); + fixedSize = 1; + // (curDir) now is just Separ character. + // So final (res) path later also will have Separ prefix. } } - - #endif // _WIN32 - - UString temp; - if (IS_SEPAR(s[0])) - { - temp = fs2us(s + 1); - } else +#endif // _WIN32 { - temp += curDir.Ptr(fixedSize); - temp += fs2us(s); + // (s) is relative path + temp = curDir.Ptr(fixedSize); + // (temp) is relative_part_of(curDir) } + temp += fs2us(s); if (!ResolveDotsFolders(temp)) return false; curDir.DeleteFrom(fixedSize); + // (curDir) now contains only absolute prefix part res = us2fs(curDir); res += us2fs(temp); @@ -885,6 +885,7 @@ return true; } + bool GetFullPath(CFSTR path, FString &fullPath) { return GetFullPath(NULL, path, fullPath); diff -Nru 7zip-22.01+dfsg/CPP/Windows/FileName.h 7zip-23.01+dfsg/CPP/Windows/FileName.h --- 7zip-22.01+dfsg/CPP/Windows/FileName.h 2021-04-20 09:43:28.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/FileName.h 2023-04-24 18:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/FileName.h -#ifndef __WINDOWS_FILE_NAME_H -#define __WINDOWS_FILE_NAME_H +#ifndef ZIP7_INC_WINDOWS_FILE_NAME_H +#define ZIP7_INC_WINDOWS_FILE_NAME_H #include "../Common/MyString.h" @@ -54,6 +54,10 @@ bool IsSuperPath(const wchar_t *s) throw(); bool IsSuperOrDevicePath(const wchar_t *s) throw(); +bool IsAltStreamPrefixWithColon(const UString &s) throw(); +// returns true, if super prefix was removed +bool If_IsSuperPath_RemoveSuperPrefix(UString &s); + #ifndef USE_UNICODE_FSTRING bool IsDrivePath2(CFSTR s) throw(); // first 2 chars are drive chars like "a:" // bool IsDriveName2(CFSTR s) throw(); // is drive name like "a:" @@ -82,7 +86,7 @@ bool IsAbsolutePath(const wchar_t *s) throw(); unsigned GetRootPrefixSize(const wchar_t *s) throw(); -#ifdef WIN_LONG_PATH +#ifdef Z7_LONG_PATH const int kSuperPathType_UseOnlyMain = 0; const int kSuperPathType_UseOnlySuper = 1; @@ -92,16 +96,16 @@ bool GetSuperPath(CFSTR path, UString &superPath, bool onlyIfNew); bool GetSuperPaths(CFSTR s1, CFSTR s2, UString &d1, UString &d2, bool onlyIfNew); -#define USE_MAIN_PATH (__useSuperPathType != kSuperPathType_UseOnlySuper) -#define USE_MAIN_PATH_2 (__useSuperPathType1 != kSuperPathType_UseOnlySuper && __useSuperPathType2 != kSuperPathType_UseOnlySuper) +#define USE_MAIN_PATH (_useSuperPathType != kSuperPathType_UseOnlySuper) +#define USE_MAIN_PATH_2 (_useSuperPathType1 != kSuperPathType_UseOnlySuper && _useSuperPathType2 != kSuperPathType_UseOnlySuper) -#define USE_SUPER_PATH (__useSuperPathType != kSuperPathType_UseOnlyMain) -#define USE_SUPER_PATH_2 (__useSuperPathType1 != kSuperPathType_UseOnlyMain || __useSuperPathType2 != kSuperPathType_UseOnlyMain) +#define USE_SUPER_PATH (_useSuperPathType != kSuperPathType_UseOnlyMain) +#define USE_SUPER_PATH_2 (_useSuperPathType1 != kSuperPathType_UseOnlyMain || _useSuperPathType2 != kSuperPathType_UseOnlyMain) -#define IF_USE_MAIN_PATH int __useSuperPathType = GetUseSuperPathType(path); if (USE_MAIN_PATH) +#define IF_USE_MAIN_PATH int _useSuperPathType = GetUseSuperPathType(path); if (USE_MAIN_PATH) #define IF_USE_MAIN_PATH_2(x1, x2) \ - int __useSuperPathType1 = GetUseSuperPathType(x1); \ - int __useSuperPathType2 = GetUseSuperPathType(x2); \ + int _useSuperPathType1 = GetUseSuperPathType(x1); \ + int _useSuperPathType2 = GetUseSuperPathType(x2); \ if (USE_MAIN_PATH_2) #else @@ -109,8 +113,18 @@ #define IF_USE_MAIN_PATH #define IF_USE_MAIN_PATH_2(x1, x2) -#endif // WIN_LONG_PATH +#endif // Z7_LONG_PATH +/* + if (dirPrefix != NULL && (path) is relative) + { + (dirPrefix) will be used + result (fullPath) will contain prefix part of (dirPrefix). + } + Current_Dir path can be used in 2 cases: + 1) if (path) is relative && dirPrefix == NULL + 2) for _WIN32: if (path) is absolute starting wuth "\" +*/ bool GetFullPath(CFSTR dirPrefix, CFSTR path, FString &fullPath); bool GetFullPath(CFSTR path, FString &fullPath); diff -Nru 7zip-22.01+dfsg/CPP/Windows/FileSystem.cpp 7zip-23.01+dfsg/CPP/Windows/FileSystem.cpp --- 7zip-22.01+dfsg/CPP/Windows/FileSystem.cpp 2020-09-30 17:43:16.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/FileSystem.cpp 2023-03-06 18:00:00.000000000 +0000 @@ -71,14 +71,14 @@ } } -typedef BOOL (WINAPI * GetDiskFreeSpaceExA_Pointer)( +typedef BOOL (WINAPI * Func_GetDiskFreeSpaceExA)( LPCSTR lpDirectoryName, // directory name PULARGE_INTEGER lpFreeBytesAvailable, // bytes available to caller PULARGE_INTEGER lpTotalNumberOfBytes, // bytes on disk PULARGE_INTEGER lpTotalNumberOfFreeBytes // free bytes on disk ); -typedef BOOL (WINAPI * GetDiskFreeSpaceExW_Pointer)( +typedef BOOL (WINAPI * Func_GetDiskFreeSpaceExW)( LPCWSTR lpDirectoryName, // directory name PULARGE_INTEGER lpFreeBytesAvailable, // bytes available to caller PULARGE_INTEGER lpTotalNumberOfBytes, // bytes on disk @@ -92,12 +92,14 @@ #ifndef _UNICODE if (!g_IsNT) { - GetDiskFreeSpaceExA_Pointer pGetDiskFreeSpaceEx = (GetDiskFreeSpaceExA_Pointer)(void *)GetProcAddress( - GetModuleHandle(TEXT("kernel32.dll")), "GetDiskFreeSpaceExA"); - if (pGetDiskFreeSpaceEx) + const + Func_GetDiskFreeSpaceExA f = Z7_GET_PROC_ADDRESS( + Func_GetDiskFreeSpaceExA, GetModuleHandle(TEXT("kernel32.dll")), + "GetDiskFreeSpaceExA"); + if (f) { ULARGE_INTEGER freeBytesToCaller2, totalSize2, freeSize2; - sizeIsDetected = BOOLToBool(pGetDiskFreeSpaceEx(fs2fas(rootPath), &freeBytesToCaller2, &totalSize2, &freeSize2)); + sizeIsDetected = BOOLToBool(f(fs2fas(rootPath), &freeBytesToCaller2, &totalSize2, &freeSize2)); totalSize = totalSize2.QuadPart; freeSize = freeSize2.QuadPart; } @@ -107,12 +109,14 @@ else #endif { - GetDiskFreeSpaceExW_Pointer pGetDiskFreeSpaceEx = (GetDiskFreeSpaceExW_Pointer)(void *)GetProcAddress( - GetModuleHandle(TEXT("kernel32.dll")), "GetDiskFreeSpaceExW"); - if (pGetDiskFreeSpaceEx) + const + Func_GetDiskFreeSpaceExW f = Z7_GET_PROC_ADDRESS( + Func_GetDiskFreeSpaceExW, GetModuleHandle(TEXT("kernel32.dll")), + "GetDiskFreeSpaceExW"); + if (f) { ULARGE_INTEGER freeBytesToCaller2, totalSize2, freeSize2; - sizeIsDetected = BOOLToBool(pGetDiskFreeSpaceEx(fs2us(rootPath), &freeBytesToCaller2, &totalSize2, &freeSize2)); + sizeIsDetected = BOOLToBool(f(fs2us(rootPath), &freeBytesToCaller2, &totalSize2, &freeSize2)); totalSize = totalSize2.QuadPart; freeSize = freeSize2.QuadPart; } diff -Nru 7zip-22.01+dfsg/CPP/Windows/FileSystem.h 7zip-23.01+dfsg/CPP/Windows/FileSystem.h --- 7zip-22.01+dfsg/CPP/Windows/FileSystem.h 2019-03-02 09:39:44.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/FileSystem.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/FileSystem.h -#ifndef __WINDOWS_FILE_SYSTEM_H -#define __WINDOWS_FILE_SYSTEM_H +#ifndef ZIP7_INC_WINDOWS_FILE_SYSTEM_H +#define ZIP7_INC_WINDOWS_FILE_SYSTEM_H #include "../Common/MyString.h" #include "../Common/MyTypes.h" diff -Nru 7zip-22.01+dfsg/CPP/Windows/Handle.h 7zip-23.01+dfsg/CPP/Windows/Handle.h --- 7zip-22.01+dfsg/CPP/Windows/Handle.h 2020-10-20 16:41:28.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Handle.h 2023-03-17 18:00:00.000000000 +0000 @@ -1,9 +1,9 @@ // Windows/Handle.h -#ifndef __WINDOWS_HANDLE_H -#define __WINDOWS_HANDLE_H +#ifndef ZIP7_INC_WINDOWS_HANDLE_H +#define ZIP7_INC_WINDOWS_HANDLE_H -#include "../Common/MyTypes.h" +#include "../Common/MyWindows.h" namespace NWindows { @@ -28,7 +28,7 @@ void Attach(HANDLE handle) { _handle = handle; } HANDLE Detach() { - HANDLE handle = _handle; + const HANDLE handle = _handle; _handle = NULL; return handle; } diff -Nru 7zip-22.01+dfsg/CPP/Windows/MemoryGlobal.h 7zip-23.01+dfsg/CPP/Windows/MemoryGlobal.h --- 7zip-22.01+dfsg/CPP/Windows/MemoryGlobal.h 2015-08-01 13:23:23.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/MemoryGlobal.h 2023-03-17 18:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/MemoryGlobal.h -#ifndef __WINDOWS_MEMORY_GLOBAL_H -#define __WINDOWS_MEMORY_GLOBAL_H +#ifndef ZIP7_INC_WINDOWS_MEMORY_GLOBAL_H +#define ZIP7_INC_WINDOWS_MEMORY_GLOBAL_H #include "../Common/MyWindows.h" @@ -12,7 +12,7 @@ { HGLOBAL _global; public: - CGlobal(): _global(NULL){}; + CGlobal(): _global(NULL) {} ~CGlobal() { Free(); } operator HGLOBAL() const { return _global; } void Attach(HGLOBAL hGlobal) @@ -22,7 +22,7 @@ } HGLOBAL Detach() { - HGLOBAL h = _global; + const HGLOBAL h = _global; _global = NULL; return h; } @@ -42,10 +42,10 @@ CGlobalLock(HGLOBAL hGlobal): _global(hGlobal) { _ptr = GlobalLock(hGlobal); - }; + } ~CGlobalLock() { - if (_ptr != NULL) + if (_ptr) GlobalUnlock(_global); } }; diff -Nru 7zip-22.01+dfsg/CPP/Windows/MemoryLock.cpp 7zip-23.01+dfsg/CPP/Windows/MemoryLock.cpp --- 7zip-22.01+dfsg/CPP/Windows/MemoryLock.cpp 2022-07-14 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/MemoryLock.cpp 2023-03-18 09:00:00.000000000 +0000 @@ -21,7 +21,10 @@ typedef BOOL (WINAPI * Func_AdjustTokenPrivileges)(HANDLE TokenHandle, BOOL DisableAllPrivileges, PTOKEN_PRIVILEGES NewState, DWORD BufferLength, PTOKEN_PRIVILEGES PreviousState, PDWORD ReturnLength); } -#define GET_PROC_ADDR(fff, name) Func_ ## fff my_ ## fff = (Func_ ## fff) (void(*)()) GetProcAddress(hModule, name) + +#define GET_PROC_ADDR(fff, name) \ + const Func_ ## fff my_ ## fff = Z7_GET_PROC_ADDRESS( \ + Func_ ## fff, hModule, name); #endif bool EnablePrivilege(LPCTSTR privilegeName, bool enable) @@ -30,13 +33,19 @@ #ifndef _UNICODE - HMODULE hModule = ::LoadLibrary(TEXT("Advapi32.dll")); - if (hModule == NULL) + const HMODULE hModule = ::LoadLibrary(TEXT("advapi32.dll")); + if (!hModule) return false; - GET_PROC_ADDR(OpenProcessToken, "OpenProcessToken"); - GET_PROC_ADDR(LookupPrivilegeValue, "LookupPrivilegeValueA"); - GET_PROC_ADDR(AdjustTokenPrivileges, "AdjustTokenPrivileges"); + GET_PROC_ADDR( + OpenProcessToken, + "OpenProcessToken") + GET_PROC_ADDR( + LookupPrivilegeValue, + "LookupPrivilegeValueA") + GET_PROC_ADDR( + AdjustTokenPrivileges, + "AdjustTokenPrivileges") if (my_OpenProcessToken && my_AdjustTokenPrivileges && @@ -85,10 +94,13 @@ unsigned Get_LargePages_RiskLevel() { OSVERSIONINFOEXW vi; - HMODULE ntdll = ::GetModuleHandleW(L"ntdll.dll"); + const HMODULE ntdll = ::GetModuleHandleW(L"ntdll.dll"); if (!ntdll) return 0; - Func_RtlGetVersion func = (Func_RtlGetVersion)(void *)GetProcAddress(ntdll, "RtlGetVersion"); + const + Func_RtlGetVersion func = Z7_GET_PROC_ADDRESS( + Func_RtlGetVersion, ntdll, + "RtlGetVersion"); if (!func) return 0; func(&vi); diff -Nru 7zip-22.01+dfsg/CPP/Windows/MemoryLock.h 7zip-23.01+dfsg/CPP/Windows/MemoryLock.h --- 7zip-22.01+dfsg/CPP/Windows/MemoryLock.h 2018-04-30 10:52:22.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/MemoryLock.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/MemoryLock.h -#ifndef __WINDOWS_MEMORY_LOCK_H -#define __WINDOWS_MEMORY_LOCK_H +#ifndef ZIP7_INC_WINDOWS_MEMORY_LOCK_H +#define ZIP7_INC_WINDOWS_MEMORY_LOCK_H #include "../Common/MyWindows.h" diff -Nru 7zip-22.01+dfsg/CPP/Windows/Menu.cpp 7zip-23.01+dfsg/CPP/Windows/Menu.cpp --- 7zip-22.01+dfsg/CPP/Windows/Menu.cpp 2021-01-26 09:19:21.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Menu.cpp 2023-03-06 16:00:00.000000000 +0000 @@ -22,8 +22,23 @@ HBITMAP hbmpItem; #endif If we compile the source code with (WINVER >= 0x0500), some functions -will not work at NT 4.0, if cbSize is set as sizeof(MENUITEMINFO*). -So we use size of old version of structure. */ +will not work at NT4, if cbSize is set as sizeof(MENUITEMINFO). +So we use size of old version of structure in some conditions. +Win98 probably supports full structure including hbmpItem. + +We have 2 ways to get/set string in menu item: +win95/NT4: we must use MIIM_TYPE only. + MIIM_TYPE : Retrieves or sets the fType and dwTypeData members. +win98/win2000: there are new flags that can be used instead of MIIM_TYPE: + MIIM_FTYPE : Retrieves or sets the fType member. + MIIM_STRING : Retrieves or sets the dwTypeData member. + +Windows versions probably support MIIM_TYPE flag, if we set MENUITEMINFO::cbSize +as sizeof of old (small) MENUITEMINFO that doesn't include (hbmpItem) field. +But do all Windows versions support old MIIM_TYPE flag, if we use +MENUITEMINFO::cbSize as sizeof of new (big) MENUITEMINFO including (hbmpItem) field ? +win10 probably supports any combination of small/big (cbSize) and old/new MIIM_TYPE/MIIM_STRING. +*/ #if defined(UNDER_CE) || defined(_WIN64) || (WINVER < 0x0500) #ifndef _UNICODE @@ -36,20 +51,31 @@ #define my_compatib_MENUITEMINFOA_size MY_STRUCT_SIZE_BEFORE(MENUITEMINFOA, hbmpItem) #endif #define my_compatib_MENUITEMINFOW_size MY_STRUCT_SIZE_BEFORE(MENUITEMINFOW, hbmpItem) +#if defined(__clang__) && __clang_major__ >= 13 +// error : performing pointer subtraction with a null pointer may have undefined behavior +#pragma GCC diagnostic ignored "-Wnull-pointer-subtraction" #endif +#endif + + +#define COPY_MENUITEM_field(d, s, name) \ + d.name = s.name; + +#define COPY_MENUITEM_fields(d, s) \ + COPY_MENUITEM_field(d, s, fMask) \ + COPY_MENUITEM_field(d, s, fType) \ + COPY_MENUITEM_field(d, s, fState) \ + COPY_MENUITEM_field(d, s, wID) \ + COPY_MENUITEM_field(d, s, hSubMenu) \ + COPY_MENUITEM_field(d, s, hbmpChecked) \ + COPY_MENUITEM_field(d, s, hbmpUnchecked) \ + COPY_MENUITEM_field(d, s, dwItemData) \ static void ConvertItemToSysForm(const CMenuItem &item, MENUITEMINFOW &si) { ZeroMemory(&si, sizeof(si)); si.cbSize = my_compatib_MENUITEMINFOW_size; // sizeof(si); - si.fMask = item.fMask; - si.fType = item.fType; - si.fState = item.fState; - si.wID = item.wID; - si.hSubMenu = item.hSubMenu; - si.hbmpChecked = item.hbmpChecked; - si.hbmpUnchecked = item.hbmpUnchecked; - si.dwItemData = item.dwItemData; + COPY_MENUITEM_fields(si, item) } #ifndef _UNICODE @@ -57,62 +83,63 @@ { ZeroMemory(&si, sizeof(si)); si.cbSize = my_compatib_MENUITEMINFOA_size; // sizeof(si); - si.fMask = item.fMask; - si.fType = item.fType; - si.fState = item.fState; - si.wID = item.wID; - si.hSubMenu = item.hSubMenu; - si.hbmpChecked = item.hbmpChecked; - si.hbmpUnchecked = item.hbmpUnchecked; - si.dwItemData = item.dwItemData; + COPY_MENUITEM_fields(si, item) } #endif static void ConvertItemToMyForm(const MENUITEMINFOW &si, CMenuItem &item) { - item.fMask = si.fMask; - item.fType = si.fType; - item.fState = si.fState; - item.wID = si.wID; - item.hSubMenu = si.hSubMenu; - item.hbmpChecked = si.hbmpChecked; - item.hbmpUnchecked = si.hbmpUnchecked; - item.dwItemData = si.dwItemData; + COPY_MENUITEM_fields(item, si) } #ifndef _UNICODE static void ConvertItemToMyForm(const MENUITEMINFOA &si, CMenuItem &item) { - item.fMask = si.fMask; - item.fType = si.fType; - item.fState = si.fState; - item.wID = si.wID; - item.hSubMenu = si.hSubMenu; - item.hbmpChecked = si.hbmpChecked; - item.hbmpUnchecked = si.hbmpUnchecked; - item.dwItemData = si.dwItemData; + COPY_MENUITEM_fields(item, si) } #endif -bool CMenu::GetItem(UINT itemIndex, bool byPosition, CMenuItem &item) + +bool CMenu::GetItem(UINT itemIndex, bool byPosition, CMenuItem &item) const { - const UINT kMaxSize = 512; + item.StringValue.Empty(); + const unsigned kMaxSize = 512; #ifndef _UNICODE if (!g_IsNT) { - CHAR s[kMaxSize + 1]; MENUITEMINFOA si; ConvertItemToSysForm(item, si); - if (item.IsString()) - { - si.cch = kMaxSize; - si.dwTypeData = s; - } - if (GetItemInfo(itemIndex, byPosition, &si)) + const bool isString = item.IsString(); + unsigned bufSize = kMaxSize; + AString a; + if (isString) + { + si.cch = bufSize; + si.dwTypeData = a.GetBuf(bufSize); + } + bool res = GetItemInfo(itemIndex, byPosition, &si); + if (isString) + a.ReleaseBuf_CalcLen(bufSize); + if (!res) + return false; { + if (isString && si.cch >= bufSize - 1) + { + si.dwTypeData = NULL; + res = GetItemInfo(itemIndex, byPosition, &si); + if (!res) + return false; + si.cch++; + bufSize = si.cch; + si.dwTypeData = a.GetBuf(bufSize); + res = GetItemInfo(itemIndex, byPosition, &si); + a.ReleaseBuf_CalcLen(bufSize); + if (!res) + return false; + } ConvertItemToMyForm(si, item); - if (item.IsString()) - item.StringValue = GetUnicodeString(s); + if (isString) + item.StringValue = GetUnicodeString(a); return true; } } @@ -120,24 +147,45 @@ #endif { wchar_t s[kMaxSize + 1]; + s[0] = 0; MENUITEMINFOW si; ConvertItemToSysForm(item, si); - if (item.IsString()) + const bool isString = item.IsString(); + unsigned bufSize = kMaxSize; + if (isString) { - si.cch = kMaxSize; + si.cch = bufSize; si.dwTypeData = s; } - if (GetItemInfo(itemIndex, byPosition, &si)) + bool res = GetItemInfo(itemIndex, byPosition, &si); + if (!res) + return false; + if (isString) { - ConvertItemToMyForm(si, item); - if (item.IsString()) - item.StringValue = s; - return true; + s[Z7_ARRAY_SIZE(s) - 1] = 0; + item.StringValue = s; + if (si.cch >= bufSize - 1) + { + si.dwTypeData = NULL; + res = GetItemInfo(itemIndex, byPosition, &si); + if (!res) + return false; + si.cch++; + bufSize = si.cch; + si.dwTypeData = item.StringValue.GetBuf(bufSize); + res = GetItemInfo(itemIndex, byPosition, &si); + item.StringValue.ReleaseBuf_CalcLen(bufSize); + if (!res) + return false; + } + // if (item.StringValue.Len() != si.cch) throw 123; // for debug } + ConvertItemToMyForm(si, item); + return true; } - return false; } + bool CMenu::SetItem(UINT itemIndex, bool byPosition, const CMenuItem &item) { #ifndef _UNICODE @@ -164,6 +212,7 @@ } } + bool CMenu::InsertItem(UINT itemIndex, bool byPosition, const CMenuItem &item) { #ifndef _UNICODE @@ -188,11 +237,11 @@ si.dwTypeData = item.StringValue.Ptr_non_const(); #ifdef UNDER_CE UINT flags = (item.fType & MFT_SEPARATOR) ? MF_SEPARATOR : MF_STRING; - UINT id = item.wID; + UINT_PTR id = item.wID; if ((item.fMask & MIIM_SUBMENU) != 0) { flags |= MF_POPUP; - id = (UINT)item.hSubMenu; + id = (UINT_PTR)item.hSubMenu; } if (!Insert(itemIndex, flags | (byPosition ? MF_BYPOSITION : MF_BYCOMMAND), id, item.StringValue)) return false; diff -Nru 7zip-22.01+dfsg/CPP/Windows/Menu.h 7zip-23.01+dfsg/CPP/Windows/Menu.h --- 7zip-22.01+dfsg/CPP/Windows/Menu.h 2014-08-28 10:17:19.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Menu.h 2023-01-22 07:00:00.000000000 +0000 @@ -1,14 +1,27 @@ // Windows/Menu.h -#ifndef __WINDOWS_MENU_H -#define __WINDOWS_MENU_H +#ifndef ZIP7_INC_WINDOWS_MENU_H +#define ZIP7_INC_WINDOWS_MENU_H +#include "../Common/MyWindows.h" #include "../Common/MyString.h" #include "Defs.h" namespace NWindows { +#ifndef MIIM_STRING +#define MIIM_STRING 0x00000040 +#endif +/* +#ifndef MIIM_BITMAP +#define MIIM_BITMAP 0x00000080 +#endif +*/ +#ifndef MIIM_FTYPE +#define MIIM_FTYPE 0x00000100 +#endif + struct CMenuItem { UString StringValue; @@ -23,24 +36,23 @@ // LPTSTR dwTypeData; // UINT cch; // HBITMAP hbmpItem; - bool IsString() const // change it MIIM_STRING - { return ((fMask & MIIM_TYPE) != 0 && (fType == MFT_STRING)); } + bool IsString() const { return (fMask & (MIIM_TYPE | MIIM_STRING)) != 0; } bool IsSeparator() const { return (fType == MFT_SEPARATOR); } - CMenuItem(): fMask(0), fType(0), fState(0), wID(0), hSubMenu(0), hbmpChecked(0), - hbmpUnchecked(0), dwItemData(0) {} + CMenuItem(): fMask(0), fType(0), fState(0), wID(0), + hSubMenu(NULL), hbmpChecked(NULL), hbmpUnchecked(NULL), dwItemData(0) {} }; class CMenu { HMENU _menu; public: - CMenu(): _menu(NULL) {}; + CMenu(): _menu(NULL) {} operator HMENU() const { return _menu; } void Attach(HMENU menu) { _menu = menu; } HMENU Detach() { - HMENU menu = _menu; + const HMENU menu = _menu; _menu = NULL; return menu; } @@ -59,27 +71,27 @@ bool Destroy() { - if (_menu == NULL) + if (!_menu) return false; return BOOLToBool(::DestroyMenu(Detach())); } - int GetItemCount() + int GetItemCount() const { #ifdef UNDER_CE - for (int i = 0;; i++) + for (unsigned i = 0;; i++) { CMenuItem item; item.fMask = MIIM_STATE; if (!GetItem(i, true, item)) - return i; + return (int)i; } #else return GetMenuItemCount(_menu); #endif } - HMENU GetSubMenu(int pos) { return ::GetSubMenu(_menu, pos); } + HMENU GetSubMenu(int pos) const { return ::GetSubMenu(_menu, pos); } #ifndef UNDER_CE /* bool GetItemString(UINT idItem, UINT flag, CSysString &result) @@ -93,11 +105,11 @@ return (len != 0); } */ - UINT GetItemID(int pos) { return ::GetMenuItemID(_menu, pos); } - UINT GetItemState(UINT id, UINT flags) { return ::GetMenuState(_menu, id, flags); } + UINT GetItemID(int pos) const { return ::GetMenuItemID(_menu, pos); } + UINT GetItemState(UINT id, UINT flags) const { return ::GetMenuState(_menu, id, flags); } #endif - bool GetItemInfo(UINT itemIndex, bool byPosition, LPMENUITEMINFO itemInfo) + bool GetItemInfo(UINT itemIndex, bool byPosition, LPMENUITEMINFO itemInfo) const { return BOOLToBool(::GetMenuItemInfo(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); } bool SetItemInfo(UINT itemIndex, bool byPosition, LPMENUITEMINFO itemInfo) { return BOOLToBool(::SetMenuItemInfo(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); } @@ -118,7 +130,7 @@ void RemoveAllItems() { RemoveAllItemsFrom(0); } #ifndef _UNICODE - bool GetItemInfo(UINT itemIndex, bool byPosition, LPMENUITEMINFOW itemInfo) + bool GetItemInfo(UINT itemIndex, bool byPosition, LPMENUITEMINFOW itemInfo) const { return BOOLToBool(::GetMenuItemInfoW(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); } bool InsertItem(UINT itemIndex, bool byPosition, LPMENUITEMINFOW itemInfo) { return BOOLToBool(::InsertMenuItemW(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); } @@ -127,7 +139,7 @@ bool AppendItem(UINT flags, UINT_PTR newItemID, LPCWSTR newItem); #endif - bool GetItem(UINT itemIndex, bool byPosition, CMenuItem &item); + bool GetItem(UINT itemIndex, bool byPosition, CMenuItem &item) const; bool SetItem(UINT itemIndex, bool byPosition, const CMenuItem &item); bool InsertItem(UINT itemIndex, bool byPosition, const CMenuItem &item); @@ -147,10 +159,10 @@ CMenu *_menu; public: CMenuDestroyer(CMenu &menu): _menu(&menu) {} - CMenuDestroyer(): _menu(0) {} + CMenuDestroyer(): _menu(NULL) {} ~CMenuDestroyer() { if (_menu) _menu->Destroy(); } void Attach(CMenu &menu) { _menu = &menu; } - void Disable() { _menu = 0; } + void Disable() { _menu = NULL; } }; } diff -Nru 7zip-22.01+dfsg/CPP/Windows/NationalTime.cpp 7zip-23.01+dfsg/CPP/Windows/NationalTime.cpp --- 7zip-22.01+dfsg/CPP/Windows/NationalTime.cpp 2015-03-28 12:42:05.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/NationalTime.cpp 2023-01-17 11:00:00.000000000 +0000 @@ -16,8 +16,8 @@ if (numChars == 0) return false; numChars = ::GetTimeFormat(locale, flags, time, format, - resultString.GetBuf(numChars), numChars + 1); - resultString.ReleaseBuf_CalcLen(numChars); + resultString.GetBuf((unsigned)numChars), numChars + 1); + resultString.ReleaseBuf_CalcLen((unsigned)numChars); return (numChars != 0); } @@ -29,8 +29,8 @@ if (numChars == 0) return false; numChars = ::GetDateFormat(locale, flags, time, format, - resultString.GetBuf(numChars), numChars + 1); - resultString.ReleaseBuf_CalcLen(numChars); + resultString.GetBuf((unsigned)numChars), numChars + 1); + resultString.ReleaseBuf_CalcLen((unsigned)numChars); return (numChars != 0); } diff -Nru 7zip-22.01+dfsg/CPP/Windows/NationalTime.h 7zip-23.01+dfsg/CPP/Windows/NationalTime.h --- 7zip-22.01+dfsg/CPP/Windows/NationalTime.h 2015-06-14 09:27:38.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/NationalTime.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/NationalTime.h -#ifndef __WINDOWS_NATIONAL_TIME_H -#define __WINDOWS_NATIONAL_TIME_H +#ifndef ZIP7_INC_WINDOWS_NATIONAL_TIME_H +#define ZIP7_INC_WINDOWS_NATIONAL_TIME_H #include "../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/Windows/Net.cpp 7zip-23.01+dfsg/CPP/Windows/Net.cpp --- 7zip-22.01+dfsg/CPP/Windows/Net.cpp 2021-01-26 11:57:16.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Net.cpp 2023-03-18 07:00:00.000000000 +0000 @@ -14,13 +14,41 @@ extern bool g_IsNT; #endif +extern "C" +{ +#if !defined(WNetGetResourceParent) +// #if defined(Z7_OLD_WIN_SDK) +// #if (WINVER >= 0x0400) +DWORD APIENTRY WNetGetResourceParentA(IN LPNETRESOURCEA lpNetResource, + OUT LPVOID lpBuffer, IN OUT LPDWORD lpcbBuffer); +DWORD APIENTRY WNetGetResourceParentW(IN LPNETRESOURCEW lpNetResource, + OUT LPVOID lpBuffer, IN OUT LPDWORD lpcbBuffer); +#ifdef UNICODE +#define WNetGetResourceParent WNetGetResourceParentW +#else +#define WNetGetResourceParent WNetGetResourceParentA +#endif + +DWORD APIENTRY WNetGetResourceInformationA(IN LPNETRESOURCEA lpNetResource, + OUT LPVOID lpBuffer, IN OUT LPDWORD lpcbBuffer, OUT LPSTR *lplpSystem); +DWORD APIENTRY WNetGetResourceInformationW(IN LPNETRESOURCEW lpNetResource, + OUT LPVOID lpBuffer, IN OUT LPDWORD lpcbBuffer, OUT LPWSTR *lplpSystem); +#ifdef UNICODE +#define WNetGetResourceInformation WNetGetResourceInformationW +#else +#define WNetGetResourceInformation WNetGetResourceInformationA +#endif +// #endif // (WINVER >= 0x0400) +#endif +} + namespace NWindows { namespace NNet { DWORD CEnum::Open(DWORD scope, DWORD type, DWORD usage, LPNETRESOURCE netResource) { Close(); - DWORD result = ::WNetOpenEnum(scope, type, usage, netResource, &_handle); + const DWORD result = ::WNetOpenEnum(scope, type, usage, netResource, &_handle); _handleAllocated = (result == NO_ERROR); return result; } @@ -29,7 +57,7 @@ DWORD CEnum::Open(DWORD scope, DWORD type, DWORD usage, LPNETRESOURCEW netResource) { Close(); - DWORD result = ::WNetOpenEnumW(scope, type, usage, netResource, &_handle); + const DWORD result = ::WNetOpenEnumW(scope, type, usage, netResource, &_handle); _handleAllocated = (result == NO_ERROR); return result; } @@ -37,7 +65,7 @@ static void SetComplexString(bool &defined, CSysString &destString, LPCTSTR srcString) { - defined = (srcString != 0); + defined = (srcString != NULL); if (defined) destString = srcString; else @@ -179,7 +207,7 @@ { if (!_handleAllocated) return NO_ERROR; - DWORD result = ::WNetCloseEnum(_handle); + const DWORD result = ::WNetCloseEnum(_handle); _handleAllocated = (result != NO_ERROR); return result; } @@ -204,7 +232,7 @@ ZeroMemory(lpnrLocal, kBufferSize); DWORD bufferSize = kBufferSize; DWORD numEntries = 1; - DWORD result = Next(&numEntries, lpnrLocal, &bufferSize); + const DWORD result = Next(&numEntries, lpnrLocal, &bufferSize); if (result != NO_ERROR) return result; if (numEntries != 1) @@ -224,7 +252,7 @@ ZeroMemory(lpnrLocal, kBufferSize); DWORD bufferSize = kBufferSize; DWORD numEntries = 1; - DWORD result = NextW(&numEntries, lpnrLocal, &bufferSize); + const DWORD result = NextW(&numEntries, lpnrLocal, &bufferSize); if (result != NO_ERROR) return result; if (numEntries != 1) @@ -233,7 +261,7 @@ return result; } CResource resourceA; - DWORD result = Next(resourceA); + const DWORD result = Next(resourceA); ConvertResourceToResourceW(resourceA, resource); return result; } @@ -249,7 +277,7 @@ DWORD bufferSize = kBufferSize; NETRESOURCE netResource; ConvertCResourceToNETRESOURCE(resource, netResource); - DWORD result = ::WNetGetResourceParent(&netResource, lpnrLocal, &bufferSize); + const DWORD result = ::WNetGetResourceParent(&netResource, lpnrLocal, &bufferSize); if (result != NO_ERROR) return result; ConvertNETRESOURCEToCResource(lpnrLocal[0], parentResource); @@ -268,7 +296,7 @@ DWORD bufferSize = kBufferSize; NETRESOURCEW netResource; ConvertCResourceToNETRESOURCE(resource, netResource); - DWORD result = ::WNetGetResourceParentW(&netResource, lpnrLocal, &bufferSize); + const DWORD result = ::WNetGetResourceParentW(&netResource, lpnrLocal, &bufferSize); if (result != NO_ERROR) return result; ConvertNETRESOURCEToCResource(lpnrLocal[0], parentResource); @@ -276,7 +304,7 @@ } CResource resourceA, parentResourceA; ConvertResourceWToResource(resource, resourceA); - DWORD result = GetResourceParent(resourceA, parentResourceA); + const DWORD result = GetResourceParent(resourceA, parentResourceA); ConvertResourceToResourceW(parentResourceA, parentResource); return result; } @@ -293,11 +321,11 @@ NETRESOURCE netResource; ConvertCResourceToNETRESOURCE(resource, netResource); LPTSTR lplpSystem; - DWORD result = ::WNetGetResourceInformation(&netResource, + const DWORD result = ::WNetGetResourceInformation(&netResource, lpnrLocal, &bufferSize, &lplpSystem); if (result != NO_ERROR) return result; - if (lplpSystem != 0) + if (lplpSystem != NULL) systemPathPart = lplpSystem; ConvertNETRESOURCEToCResource(lpnrLocal[0], destResource); return result; @@ -317,7 +345,7 @@ NETRESOURCEW netResource; ConvertCResourceToNETRESOURCE(resource, netResource); LPWSTR lplpSystem; - DWORD result = ::WNetGetResourceInformationW(&netResource, + const DWORD result = ::WNetGetResourceInformationW(&netResource, lpnrLocal, &bufferSize, &lplpSystem); if (result != NO_ERROR) return result; @@ -329,7 +357,7 @@ CResource resourceA, destResourceA; ConvertResourceWToResource(resource, resourceA); AString systemPathPartA; - DWORD result = GetResourceInformation(resourceA, destResourceA, systemPathPartA); + const DWORD result = GetResourceInformation(resourceA, destResourceA, systemPathPartA); ConvertResourceToResourceW(destResourceA, destResource); systemPathPart = GetUnicodeString(systemPathPartA); return result; diff -Nru 7zip-22.01+dfsg/CPP/Windows/Net.h 7zip-23.01+dfsg/CPP/Windows/Net.h --- 7zip-22.01+dfsg/CPP/Windows/Net.h 2013-01-17 17:44:48.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Net.h 2023-03-18 07:00:00.000000000 +0000 @@ -1,9 +1,10 @@ // Windows/Net.h -#ifndef __WINDOWS_NET_H -#define __WINDOWS_NET_H +#ifndef ZIP7_INC_WINDOWS_NET_H +#define ZIP7_INC_WINDOWS_NET_H #include "../Common/MyString.h" +#include "../Common/MyWindows.h" namespace NWindows { namespace NNet { diff -Nru 7zip-22.01+dfsg/CPP/Windows/NtCheck.h 7zip-23.01+dfsg/CPP/Windows/NtCheck.h --- 7zip-22.01+dfsg/CPP/Windows/NtCheck.h 2021-01-26 08:19:23.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/NtCheck.h 2023-03-08 18:00:00.000000000 +0000 @@ -1,19 +1,29 @@ // Windows/NtCheck.h -#ifndef __WINDOWS_NT_CHECK_H -#define __WINDOWS_NT_CHECK_H +#ifndef ZIP7_INC_WINDOWS_NT_CHECK_H +#define ZIP7_INC_WINDOWS_NT_CHECK_H #ifdef _WIN32 #include "../Common/MyWindows.h" #if !defined(_WIN64) && !defined(UNDER_CE) + +#if defined(_MSC_VER) && _MSC_VER >= 1900 +#pragma warning(push) +// GetVersionExW was declared deprecated +#pragma warning(disable : 4996) +#endif static inline bool IsItWindowsNT() { OSVERSIONINFO vi; vi.dwOSVersionInfoSize = sizeof(vi); return (::GetVersionEx(&vi) && vi.dwPlatformId == VER_PLATFORM_WIN32_NT); } +#if defined(_MSC_VER) && _MSC_VER >= 1900 +#pragma warning(pop) +#endif + #endif #ifndef _UNICODE diff -Nru 7zip-22.01+dfsg/CPP/Windows/ProcessMessages.h 7zip-23.01+dfsg/CPP/Windows/ProcessMessages.h --- 7zip-22.01+dfsg/CPP/Windows/ProcessMessages.h 2015-11-13 16:44:32.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/ProcessMessages.h 2023-03-18 07:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/ProcessMessages.h -#ifndef __WINDOWS_PROCESSMESSAGES_H -#define __WINDOWS_PROCESSMESSAGES_H +#ifndef ZIP7_INC_WINDOWS_PROCESS_MESSAGES_H +#define ZIP7_INC_WINDOWS_PROCESS_MESSAGES_H namespace NWindows { diff -Nru 7zip-22.01+dfsg/CPP/Windows/ProcessUtils.cpp 7zip-23.01+dfsg/CPP/Windows/ProcessUtils.cpp --- 7zip-22.01+dfsg/CPP/Windows/ProcessUtils.cpp 2021-01-25 19:05:13.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/ProcessUtils.cpp 2023-03-18 07:00:00.000000000 +0000 @@ -46,9 +46,9 @@ #endif params; #ifdef UNDER_CE - curDir = 0; + curDir = NULL; #else - imageName = 0; + imageName = NULL; #endif PROCESS_INFORMATION pi; BOOL result; @@ -57,12 +57,12 @@ { STARTUPINFOA si; si.cb = sizeof(si); - si.lpReserved = 0; - si.lpDesktop = 0; - si.lpTitle = 0; + si.lpReserved = NULL; + si.lpDesktop = NULL; + si.lpTitle = NULL; si.dwFlags = 0; si.cbReserved2 = 0; - si.lpReserved2 = 0; + si.lpReserved2 = NULL; CSysString curDirA; if (curDir != 0) @@ -76,12 +76,12 @@ { STARTUPINFOW si; si.cb = sizeof(si); - si.lpReserved = 0; - si.lpDesktop = 0; - si.lpTitle = 0; + si.lpReserved = NULL; + si.lpDesktop = NULL; + si.lpTitle = NULL; si.dwFlags = 0; si.cbReserved2 = 0; - si.lpReserved2 = 0; + si.lpReserved2 = NULL; result = CreateProcessW(imageName, params2.Ptr_non_const(), NULL, NULL, FALSE, 0, NULL, curDir, &si, &pi); @@ -96,7 +96,7 @@ WRes MyCreateProcess(LPCWSTR imageName, const UString ¶ms) { CProcess process; - return process.Create(imageName, params, 0); + return process.Create(imageName, params, NULL); } } diff -Nru 7zip-22.01+dfsg/CPP/Windows/ProcessUtils.h 7zip-23.01+dfsg/CPP/Windows/ProcessUtils.h --- 7zip-22.01+dfsg/CPP/Windows/ProcessUtils.h 2021-01-26 12:14:08.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/ProcessUtils.h 2023-03-18 07:00:00.000000000 +0000 @@ -1,9 +1,41 @@ // Windows/ProcessUtils.h -#ifndef __WINDOWS_PROCESS_UTILS_H -#define __WINDOWS_PROCESS_UTILS_H +#ifndef ZIP7_INC_WINDOWS_PROCESS_UTILS_H +#define ZIP7_INC_WINDOWS_PROCESS_UTILS_H +#include "../Common/MyWindows.h" + +#ifndef Z7_OLD_WIN_SDK + +#if defined(__MINGW32__) || defined(__MINGW64__) +#include +#else #include +#endif + +#else // Z7_OLD_WIN_SDK + +typedef struct _MODULEINFO { + LPVOID lpBaseOfDll; + DWORD SizeOfImage; + LPVOID EntryPoint; +} MODULEINFO, *LPMODULEINFO; + +typedef struct _PROCESS_MEMORY_COUNTERS { + DWORD cb; + DWORD PageFaultCount; + SIZE_T PeakWorkingSetSize; + SIZE_T WorkingSetSize; + SIZE_T QuotaPeakPagedPoolUsage; + SIZE_T QuotaPagedPoolUsage; + SIZE_T QuotaPeakNonPagedPoolUsage; + SIZE_T QuotaNonPagedPoolUsage; + SIZE_T PagefileUsage; + SIZE_T PeakPagefileUsage; +} PROCESS_MEMORY_COUNTERS; +typedef PROCESS_MEMORY_COUNTERS *PPROCESS_MEMORY_COUNTERS; + +#endif // Z7_OLD_WIN_SDK #include "../Common/MyString.h" @@ -18,7 +50,7 @@ bool Open(DWORD desiredAccess, bool inheritHandle, DWORD processId) { _handle = ::OpenProcess(desiredAccess, inheritHandle, processId); - return (_handle != 0); + return (_handle != NULL); } #ifndef UNDER_CE @@ -43,9 +75,14 @@ { return BOOLToBool(::ReadProcessMemory(_handle, baseAddress, buffer, size, numberOfBytesRead)); } bool WriteMemory(LPVOID baseAddress, LPCVOID buffer, SIZE_T size, SIZE_T* numberOfBytesWritten) - { return BOOLToBool(::WriteProcessMemory(_handle, baseAddress, buffer, size, numberOfBytesWritten)); } + { return BOOLToBool(::WriteProcessMemory(_handle, baseAddress, + #ifdef Z7_OLD_WIN_SDK + (LPVOID) + #endif + buffer, + size, numberOfBytesWritten)); } - bool FlushInstructionCache(LPCVOID baseAddress = 0, SIZE_T size = 0) + bool FlushInstructionCache(LPCVOID baseAddress = NULL, SIZE_T size = 0) { return BOOLToBool(::FlushInstructionCache(_handle, baseAddress, size)); } LPVOID VirtualAlloc(LPVOID address, SIZE_T size, DWORD allocationType, DWORD protect) @@ -56,17 +93,17 @@ // Process Status API (PSAPI) + /* bool EmptyWorkingSet() { return BOOLToBool(::EmptyWorkingSet(_handle)); } bool EnumModules(HMODULE *hModules, DWORD arraySizeInBytes, LPDWORD receivedBytes) { return BOOLToBool(::EnumProcessModules(_handle, hModules, arraySizeInBytes, receivedBytes)); } - DWORD MyGetModuleBaseName(HMODULE hModule, LPTSTR baseName, DWORD size) { return ::GetModuleBaseName(_handle, hModule, baseName, size); } bool MyGetModuleBaseName(HMODULE hModule, CSysString &name) { const unsigned len = MAX_PATH + 100; - DWORD resultLen = MyGetModuleBaseName(hModule, name.GetBuf(len), len); + const DWORD resultLen = MyGetModuleBaseName(hModule, name.GetBuf(len), len); name.ReleaseBuf_CalcLen(len); return (resultLen != 0); } @@ -76,7 +113,7 @@ bool MyGetModuleFileNameEx(HMODULE hModule, CSysString &name) { const unsigned len = MAX_PATH + 100; - DWORD resultLen = MyGetModuleFileNameEx(hModule, name.GetBuf(len), len); + const DWORD resultLen = MyGetModuleFileNameEx(hModule, name.GetBuf(len), len); name.ReleaseBuf_CalcLen(len); return (resultLen != 0); } @@ -85,6 +122,7 @@ { return BOOLToBool(::GetModuleInformation(_handle, hModule, moduleInfo, sizeof(MODULEINFO))); } bool GetMemoryInfo(PPROCESS_MEMORY_COUNTERS memCounters) { return BOOLToBool(::GetProcessMemoryInfo(_handle, memCounters, sizeof(PROCESS_MEMORY_COUNTERS))); } + */ #endif diff -Nru 7zip-22.01+dfsg/CPP/Windows/PropVariantConv.cpp 7zip-23.01+dfsg/CPP/Windows/PropVariantConv.cpp --- 7zip-22.01+dfsg/CPP/Windows/PropVariantConv.cpp 2022-03-29 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/PropVariantConv.cpp 2022-12-19 22:00:00.000000000 +0000 @@ -36,17 +36,17 @@ s[0] = (char)('0' + val / 10); s += 4; } - UINT_TO_STR_2('-', st.wMonth); - UINT_TO_STR_2('-', st.wDay); + UINT_TO_STR_2('-', st.wMonth) + UINT_TO_STR_2('-', st.wDay) if (level > kTimestampPrintLevel_DAY) { - UINT_TO_STR_2(' ', st.wHour); - UINT_TO_STR_2(':', st.wMinute); + UINT_TO_STR_2(' ', st.wHour) + UINT_TO_STR_2(':', st.wMinute) if (level >= kTimestampPrintLevel_SEC) { - UINT_TO_STR_2(':', st.wSecond); + UINT_TO_STR_2(':', st.wSecond) if (level > kTimestampPrintLevel_SEC) { diff -Nru 7zip-22.01+dfsg/CPP/Windows/PropVariantConv.h 7zip-23.01+dfsg/CPP/Windows/PropVariantConv.h --- 7zip-22.01+dfsg/CPP/Windows/PropVariantConv.h 2022-03-29 11:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/PropVariantConv.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/PropVariantConv.h -#ifndef __PROP_VARIANT_CONV_H -#define __PROP_VARIANT_CONV_H +#ifndef ZIP7_INC_PROP_VARIANT_CONV_H +#define ZIP7_INC_PROP_VARIANT_CONV_H #include "../Common/MyTypes.h" diff -Nru 7zip-22.01+dfsg/CPP/Windows/PropVariant.cpp 7zip-23.01+dfsg/CPP/Windows/PropVariant.cpp --- 7zip-22.01+dfsg/CPP/Windows/PropVariant.cpp 2022-03-30 12:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/PropVariant.cpp 2023-01-29 10:00:00.000000000 +0000 @@ -197,17 +197,17 @@ void CPropVariant::Set_Int32(Int32 value) throw() { - SET_PROP_id_dest(VT_I4, lVal); + SET_PROP_id_dest(VT_I4, lVal) } void CPropVariant::Set_Int64(Int64 value) throw() { - SET_PROP_id_dest(VT_I8, hVal.QuadPart); + SET_PROP_id_dest(VT_I8, hVal.QuadPart) } #define SET_PROP_FUNC(type, id, dest) \ CPropVariant& CPropVariant::operator=(type value) throw() \ - { SET_PROP_id_dest(id, dest); return *this; } + { SET_PROP_id_dest(id, dest) return *this; } SET_PROP_FUNC(Byte, VT_UI1, bVal) // SET_PROP_FUNC(Int16, VT_I2, iVal) @@ -245,7 +245,7 @@ we call system functions for VT_BSTR and for unknown typed */ -CPropVariant::~CPropVariant() +CPropVariant::~CPropVariant() throw() { switch ((unsigned)vt) { diff -Nru 7zip-22.01+dfsg/CPP/Windows/PropVariant.h 7zip-23.01+dfsg/CPP/Windows/PropVariant.h --- 7zip-22.01+dfsg/CPP/Windows/PropVariant.h 2022-05-15 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/PropVariant.h 2023-01-28 16:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/PropVariant.h -#ifndef __WINDOWS_PROP_VARIANT_H -#define __WINDOWS_PROP_VARIANT_H +#ifndef ZIP7_INC_WINDOWS_PROP_VARIANT_H +#define ZIP7_INC_WINDOWS_PROP_VARIANT_H #include "../Common/MyTypes.h" #include "../Common/MyWindows.h" @@ -64,7 +64,7 @@ // wReserved2 = 0; // wReserved3 = 0; // uhVal.QuadPart = 0; - bstrVal = 0; + bstrVal = NULL; } @@ -104,13 +104,13 @@ const unsigned ns100 = wReserved2; if (prec == 0 && prec <= k_PropVar_TimePrec_1ns - && ns100 < 100 + && ns100 < 100 && wReserved3 == 0) return ns100; return 0; } - ~CPropVariant(); + ~CPropVariant() throw(); CPropVariant(const PROPVARIANT &varSrc); CPropVariant(const CPropVariant &varSrc); CPropVariant(BSTR bstrSrc); diff -Nru 7zip-22.01+dfsg/CPP/Windows/PropVariantUtils.h 7zip-23.01+dfsg/CPP/Windows/PropVariantUtils.h --- 7zip-22.01+dfsg/CPP/Windows/PropVariantUtils.h 2016-11-01 08:44:03.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/PropVariantUtils.h 2023-03-06 16:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/PropVariantUtils.h -#ifndef __PROP_VARIANT_UTILS_H -#define __PROP_VARIANT_UTILS_H +#ifndef ZIP7_INC_PROP_VARIANT_UTILS_H +#define ZIP7_INC_PROP_VARIANT_UTILS_H #include "../Common/MyString.h" @@ -24,11 +24,11 @@ AString TypeToString(const char * const table[], unsigned num, UInt32 value); void TypeToProp(const char * const table[], unsigned num, UInt32 value, NWindows::NCOM::CPropVariant &prop); -#define PAIR_TO_PROP(pairs, value, prop) PairToProp(pairs, ARRAY_SIZE(pairs), value, prop) -#define FLAGS_TO_PROP(pairs, value, prop) FlagsToProp(pairs, ARRAY_SIZE(pairs), value, prop) -#define TYPE_TO_PROP(table, value, prop) TypeToProp(table, ARRAY_SIZE(table), value, prop) +#define PAIR_TO_PROP(pairs, value, prop) PairToProp(pairs, Z7_ARRAY_SIZE(pairs), value, prop) +#define FLAGS_TO_PROP(pairs, value, prop) FlagsToProp(pairs, Z7_ARRAY_SIZE(pairs), value, prop) +#define TYPE_TO_PROP(table, value, prop) TypeToProp(table, Z7_ARRAY_SIZE(table), value, prop) void Flags64ToProp(const CUInt32PCharPair *pairs, unsigned num, UInt64 flags, NWindows::NCOM::CPropVariant &prop); -#define FLAGS64_TO_PROP(pairs, value, prop) Flags64ToProp(pairs, ARRAY_SIZE(pairs), value, prop) +#define FLAGS64_TO_PROP(pairs, value, prop) Flags64ToProp(pairs, Z7_ARRAY_SIZE(pairs), value, prop) #endif diff -Nru 7zip-22.01+dfsg/CPP/Windows/Registry.h 7zip-23.01+dfsg/CPP/Windows/Registry.h --- 7zip-22.01+dfsg/CPP/Windows/Registry.h 2015-03-28 12:34:09.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Registry.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Registry.h -#ifndef __WINDOWS_REGISTRY_H -#define __WINDOWS_REGISTRY_H +#ifndef ZIP7_INC_WINDOWS_REGISTRY_H +#define ZIP7_INC_WINDOWS_REGISTRY_H #include "../Common/MyBuffer.h" #include "../Common/MyString.h" diff -Nru 7zip-22.01+dfsg/CPP/Windows/ResourceString.h 7zip-23.01+dfsg/CPP/Windows/ResourceString.h --- 7zip-22.01+dfsg/CPP/Windows/ResourceString.h 2013-01-17 17:53:59.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/ResourceString.h 2023-03-18 08:00:00.000000000 +0000 @@ -1,9 +1,10 @@ // Windows/ResourceString.h -#ifndef __WINDOWS_RESOURCE_STRING_H -#define __WINDOWS_RESOURCE_STRING_H +#ifndef ZIP7_INC_WINDOWS_RESOURCE_STRING_H +#define ZIP7_INC_WINDOWS_RESOURCE_STRING_H #include "../Common/MyString.h" +#include "../Common/MyWindows.h" namespace NWindows { diff -Nru 7zip-22.01+dfsg/CPP/Windows/SecurityUtils.cpp 7zip-23.01+dfsg/CPP/Windows/SecurityUtils.cpp --- 7zip-22.01+dfsg/CPP/Windows/SecurityUtils.cpp 2022-07-15 08:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/SecurityUtils.cpp 2023-03-18 09:00:00.000000000 +0000 @@ -4,9 +4,6 @@ #include "SecurityUtils.h" -#define MY_CAST_FUNC (void(*)()) -// #define MY_CAST_FUNC - namespace NWindows { namespace NSecurity { @@ -35,7 +32,7 @@ static void SetLsaString(LPWSTR src, PLSA_UNICODE_STRING dest) { - size_t len = (size_t)wcslen(src); + const size_t len = (size_t)wcslen(src); dest->Length = (USHORT)(len * sizeof(WCHAR)); dest->MaximumLength = (USHORT)((len + 1) * sizeof(WCHAR)); dest->Buffer = src; @@ -72,13 +69,14 @@ static PSID GetSid(LPWSTR accountName) { #ifndef _UNICODE - HMODULE hModule = GetModuleHandle(TEXT("Advapi32.dll")); - if (hModule == NULL) + const HMODULE hModule = GetModuleHandle(TEXT("advapi32.dll")); + if (!hModule) return NULL; - Func_LookupAccountNameW lookupAccountNameW = (Func_LookupAccountNameW) - MY_CAST_FUNC - GetProcAddress(hModule, "LookupAccountNameW"); - if (lookupAccountNameW == NULL) + const + Func_LookupAccountNameW lookupAccountNameW = Z7_GET_PROC_ADDRESS( + Func_LookupAccountNameW, hModule, + "LookupAccountNameW"); + if (!lookupAccountNameW) return NULL; #endif @@ -88,21 +86,21 @@ #ifdef _UNICODE ::LookupAccountNameW #else - lookupAccountNameW + lookupAccountNameW #endif - (NULL, accountName, NULL, &sidLen, NULL, &domainLen, &sidNameUse)) + (NULL, accountName, NULL, &sidLen, NULL, &domainLen, &sidNameUse)) { if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER) { - PSID pSid = ::HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sidLen); + const PSID pSid = ::HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sidLen); LPWSTR domainName = (LPWSTR)::HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (domainLen + 1) * sizeof(WCHAR)); - BOOL res = + const BOOL res = #ifdef _UNICODE ::LookupAccountNameW #else - lookupAccountNameW + lookupAccountNameW #endif - (NULL, accountName, pSid, &sidLen, domainName, &domainLen, &sidNameUse); + (NULL, accountName, pSid, &sidLen, domainName, &domainLen, &sidNameUse); ::HeapFree(GetProcessHeap(), 0, domainName); if (res) return pSid; @@ -111,7 +109,7 @@ return NULL; } -#define MY__SE_LOCK_MEMORY_NAME L"SeLockMemoryPrivilege" +#define Z7_WIN_SE_LOCK_MEMORY_NAME L"SeLockMemoryPrivilege" bool AddLockMemoryPrivilege() { @@ -131,13 +129,13 @@ != 0) return false; LSA_UNICODE_STRING userRights; - wchar_t s[128] = MY__SE_LOCK_MEMORY_NAME; + wchar_t s[128] = Z7_WIN_SE_LOCK_MEMORY_NAME; SetLsaString(s, &userRights); WCHAR userName[256 + 2]; DWORD size = 256; if (!GetUserNameW(userName, &size)) return false; - PSID psid = GetSid(userName); + const PSID psid = GetSid(userName); if (psid == NULL) return false; bool res = false; @@ -176,7 +174,7 @@ res = true; } */ - NTSTATUS status = policy.AddAccountRights(psid, &userRights); + const NTSTATUS status = policy.AddAccountRights(psid, &userRights); if (status == 0) res = true; // ULONG res = LsaNtStatusToWinError(status); diff -Nru 7zip-22.01+dfsg/CPP/Windows/SecurityUtils.h 7zip-23.01+dfsg/CPP/Windows/SecurityUtils.h --- 7zip-22.01+dfsg/CPP/Windows/SecurityUtils.h 2022-07-15 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/SecurityUtils.h 2023-03-18 09:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/SecurityUtils.h -#ifndef __WINDOWS_SECURITY_UTILS_H -#define __WINDOWS_SECURITY_UTILS_H +#ifndef ZIP7_INC_WINDOWS_SECURITY_UTILS_H +#define ZIP7_INC_WINDOWS_SECURITY_UTILS_H #include @@ -20,7 +20,7 @@ #define POLICY_FUNC_CALL(fff, str) \ if (hModule == NULL) return MY_STATUS_NOT_IMPLEMENTED; \ - Func_ ## fff v = (Func_ ## fff) (void(*)()) GetProcAddress(hModule, str); \ + const Func_ ## fff v = Z7_GET_PROC_ADDRESS(Func_ ## fff, hModule, str); \ if (!v) return MY_STATUS_NOT_IMPLEMENTED; \ const NTSTATUS res = v @@ -39,7 +39,7 @@ { HANDLE _handle; public: - CAccessToken(): _handle(NULL) {}; + CAccessToken(): _handle(NULL) {} ~CAccessToken() { Close(); } bool Close() { @@ -93,9 +93,9 @@ CPolicy(): _handle(NULL) { #ifndef _UNICODE - hModule = GetModuleHandle(TEXT("Advapi32.dll")); + hModule = GetModuleHandle(TEXT("advapi32.dll")); #endif - }; + } ~CPolicy() { Close(); } NTSTATUS Open(PLSA_UNICODE_STRING systemName, PLSA_OBJECT_ATTRIBUTES objectAttributes, diff -Nru 7zip-22.01+dfsg/CPP/Windows/Shell.cpp 7zip-23.01+dfsg/CPP/Windows/Shell.cpp --- 7zip-22.01+dfsg/CPP/Windows/Shell.cpp 2022-07-15 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Shell.cpp 2023-03-18 10:40:00.000000000 +0000 @@ -2,23 +2,50 @@ #include "StdAfx.h" -/* -#include -#include -*/ - #include "../Common/MyCom.h" -#ifndef _UNICODE #include "../Common/StringConvert.h" -#endif #include "COM.h" +#include "FileName.h" +#include "MemoryGlobal.h" #include "Shell.h" #ifndef _UNICODE extern bool g_IsNT; #endif +// MSVC6 and old SDK don't support this function: +// #define LWSTDAPI EXTERN_C DECLSPEC_IMPORT HRESULT STDAPICALLTYPE +// LWSTDAPI StrRetToStrW(STRRET *pstr, LPCITEMIDLIST pidl, LPWSTR *ppsz); + +// #define SHOW_DEBUG_SHELL + +#ifdef SHOW_DEBUG_SHELL + +#include "../Common/IntToString.h" + +static void Print_Number(UInt32 number, const char *s) +{ + AString s2; + s2.Add_UInt32(number); + s2.Add_Space(); + s2 += s; + OutputDebugStringA(s2); +} + +#define ODS(sz) { OutputDebugStringA(sz); } +#define ODS_U(s) { OutputDebugStringW(s); } +#define ODS_(op) { op; } + +#else + +#define ODS(sz) +#define ODS_U(s) +#define ODS_(op) + +#endif + + namespace NWindows { namespace NShell { @@ -28,12 +55,24 @@ void CItemIDList::Free() { - if (m_Object == NULL) + if (!m_Object) return; + /* DOCs: + SHGetMalloc was introduced in Windows 95 and Microsoft Windows NT 4.0, + but as of Windows 2000 it is no longer necessary. + In its place, programs can call the equivalent (and easier to use) CoTaskMemAlloc and CoTaskMemFree. + Description from oldnewthings: + shell functions could work without COM (if OLE32.DLL is not loaded), + but now if OLE32.DLL is loaded, then shell functions and com functions do same things. + 22.02: so we use OLE32.DLL function to free memory: + */ + /* CMyComPtr shellMalloc; if (::SHGetMalloc(&shellMalloc) != NOERROR) throw 41099; shellMalloc->Free(m_Object); + */ + CoTaskMemFree(m_Object); m_Object = NULL; } @@ -70,9 +109,354 @@ } */ + +static HRESULT ReadUnicodeStrings(const wchar_t *p, size_t size, UStringVector &names) +{ + names.Clear(); + const wchar_t *lim = p + size; + UString s; + /* + if (size == 0 || p[size - 1] != 0) + return E_INVALIDARG; + if (size == 1) + return S_OK; + if (p[size - 2] != 0) + return E_INVALIDARG; + */ + for (;;) + { + const wchar_t *start = p; + for (;;) + { + if (p == lim) return E_INVALIDARG; // S_FALSE + if (*p++ == 0) + break; + } + const size_t num = (size_t)(p - start); + if (num == 1) + { + if (p != lim) return E_INVALIDARG; // S_FALSE + return S_OK; + } + s.SetFrom(start, (unsigned)(num - 1)); + ODS_U(s) + names.Add(s); + // names.ReserveOnePosition(); + // names.AddInReserved_Ptr_of_new(new UString((unsigned)num - 1, start)); + } +} + + +static HRESULT ReadAnsiStrings(const char *p, size_t size, UStringVector &names) +{ + names.Clear(); + AString name; + for (; size != 0; size--) + { + const char c = *p++; + if (c == 0) + { + if (name.IsEmpty()) + return S_OK; + names.Add(GetUnicodeString(name)); + name.Empty(); + } + else + name += c; + } + return E_INVALIDARG; +} + + +#define INIT_FORMATETC_HGLOBAL(type) { (type), NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL } + +static HRESULT DataObject_GetData_HGLOBAL(IDataObject *dataObject, CLIPFORMAT cf, NCOM::CStgMedium &medium) +{ + FORMATETC etc = INIT_FORMATETC_HGLOBAL(cf); + RINOK(dataObject->GetData(&etc, &medium)) + if (medium.tymed != TYMED_HGLOBAL) + return E_INVALIDARG; + return S_OK; +} + +static HRESULT DataObject_GetData_HDROP_Names(IDataObject *dataObject, UStringVector &names) +{ + names.Clear(); + NCOM::CStgMedium medium; + + /* Win10 : if (dataObject) is from IContextMenu::Initialize() and + if (len_of_path >= MAX_PATH (260) for some file in data object) + { + GetData() returns HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) + "The data area passed to a system call is too small", + Is there a way to fix this code for long paths? + } */ + + RINOK(DataObject_GetData_HGLOBAL(dataObject, CF_HDROP, medium)) + const size_t blockSize = GlobalSize(medium.hGlobal); + if (blockSize < sizeof(DROPFILES)) + return E_INVALIDARG; + NMemory::CGlobalLock dropLock(medium.hGlobal); + const DROPFILES *dropFiles = (const DROPFILES *)dropLock.GetPointer(); + if (!dropFiles) + return E_INVALIDARG; + if (blockSize < dropFiles->pFiles + || dropFiles->pFiles < sizeof(DROPFILES) + // || dropFiles->pFiles != sizeof(DROPFILES) + ) + return E_INVALIDARG; + const size_t size = blockSize - dropFiles->pFiles; + const void *namesData = (const Byte *)(const void *)dropFiles + dropFiles->pFiles; + HRESULT hres; + if (dropFiles->fWide) + { + if (size % sizeof(wchar_t) != 0) + return E_INVALIDARG; + hres = ReadUnicodeStrings((const wchar_t *)namesData, size / sizeof(wchar_t), names); + } + else + hres = ReadAnsiStrings((const char *)namesData, size, names); + + ODS_(Print_Number(names.Size(), "DataObject_GetData_HDROP_Names")) + return hres; +} + + + +// CF_IDLIST: +#define MYWIN_CFSTR_SHELLIDLIST TEXT("Shell IDList Array") + +typedef struct +{ + UINT cidl; + UINT aoffset[1]; +} MYWIN_CIDA; +/* + cidl : number of PIDLs that are being transferred, not including the parent folder. + aoffset : An array of offsets, relative to the beginning of this structure. + aoffset[0] - fully qualified PIDL of a parent folder. + If this PIDL is empty, the parent folder is the desktop. + aoffset[1] ... aoffset[cidl] : offset to one of the PIDLs to be transferred. + All of these PIDLs are relative to the PIDL of the parent folder. +*/ + +static HRESULT DataObject_GetData_IDLIST(IDataObject *dataObject, UStringVector &names) +{ + names.Clear(); + NCOM::CStgMedium medium; + RINOK(DataObject_GetData_HGLOBAL(dataObject, (CLIPFORMAT) + RegisterClipboardFormat(MYWIN_CFSTR_SHELLIDLIST), medium)) + const size_t blockSize = GlobalSize(medium.hGlobal); + if (blockSize < sizeof(MYWIN_CIDA) || blockSize >= (UInt32)((UInt32)0 - 1)) + return E_INVALIDARG; + NMemory::CGlobalLock dropLock(medium.hGlobal); + const MYWIN_CIDA *cida = (const MYWIN_CIDA *)dropLock.GetPointer(); + if (!cida) + return E_INVALIDARG; + if (cida->cidl == 0) + { + // is it posssible to have no selected items? + // it's unexpected case. + return E_INVALIDARG; + } + if (cida->cidl >= (blockSize - (UInt32)sizeof(MYWIN_CIDA)) / sizeof(UINT)) + return E_INVALIDARG; + const UInt32 start = cida->cidl * (UInt32)sizeof(UINT) + (UInt32)sizeof(MYWIN_CIDA); + + STRRET strret; + CMyComPtr parentFolder; + { + const UINT offset = cida->aoffset[0]; + if (offset < start || offset >= blockSize + // || offset != start + ) + return E_INVALIDARG; + + CMyComPtr desktopFolder; + RINOK(::SHGetDesktopFolder(&desktopFolder)) + if (!desktopFolder) + return E_FAIL; + + LPCITEMIDLIST const lpcItem = (LPCITEMIDLIST)(const void *)((const Byte *)cida + offset); + + #ifdef SHOW_DEBUG_SHELL + { + const HRESULT res = desktopFolder->GetDisplayNameOf( + lpcItem, SHGDN_FORPARSING, &strret); + if (res == S_OK && strret.uType == STRRET_WSTR) + { + ODS_U(strret.pOleStr) + /* if lpcItem is empty, the path will be + "C:\Users\user_name\Desktop" + if lpcItem is "My Computer" folder, the path will be + "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" */ + CoTaskMemFree(strret.pOleStr); + } + } + #endif + + RINOK(desktopFolder->BindToObject(lpcItem, + NULL, IID_IShellFolder, (void **)&parentFolder)) + if (!parentFolder) + return E_FAIL; + } + + names.ClearAndReserve(cida->cidl); + UString path; + + // for (int y = 0; y < 1; y++) // for debug + for (unsigned i = 1; i <= cida->cidl; i++) + { + const UINT offset = cida->aoffset[i]; + if (offset < start || offset >= blockSize) + return E_INVALIDARG; + const void *p = (const Byte *)(const void *)cida + offset; + /* ITEMIDLIST of file can contain more than one SHITEMID item. + In win10 only SHGDN_FORPARSING returns path that contains + all path parts related to parts of ITEMIDLIST. + So we can use only SHGDN_FORPARSING here. + Don't use (SHGDN_INFOLDER) + Don't use (SHGDN_INFOLDER | SHGDN_FORPARSING) + */ + RINOK(parentFolder->GetDisplayNameOf((LPCITEMIDLIST)p, SHGDN_FORPARSING, &strret)) + + /* + // MSVC6 and old SDK do not support StrRetToStrW(). + LPWSTR lpstr; + RINOK (StrRetToStrW(&strret, NULL, &lpstr)) + ODS_U(lpstr) + path = lpstr; + CoTaskMemFree(lpstr); + */ + if (strret.uType != STRRET_WSTR) + return E_INVALIDARG; + ODS_U(strret.pOleStr) + path = strret.pOleStr; + // the path could have super path prefix "\\\\?\\" + // we can remove super path prefix here, if we don't need that prefix + #ifdef Z7_LONG_PATH + // we remove super prefix, if we can work without that prefix + NFile::NName::If_IsSuperPath_RemoveSuperPrefix(path); + #endif + names.AddInReserved(path); + CoTaskMemFree(strret.pOleStr); + } + + ODS_(Print_Number(cida->cidl, "CFSTR_SHELLIDLIST END")) + return S_OK; +} + + +HRESULT DataObject_GetData_HDROP_or_IDLIST_Names(IDataObject *dataObject, UStringVector &paths) +{ + ODS("-- DataObject_GetData_HDROP_or_IDLIST_Names START") + HRESULT hres = NShell::DataObject_GetData_HDROP_Names(dataObject, paths); + // if (hres == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)) + if (hres != S_OK) + { + ODS("-- DataObject_GetData_IDLIST START") + // for (int y = 0; y < 10000; y++) // for debug + hres = NShell::DataObject_GetData_IDLIST(dataObject, paths); + } + ODS("-- DataObject_GetData_HDROP_or_IDLIST_Names END") + return hres; +} + + + +// #if (NTDDI_VERSION >= NTDDI_VISTA) +typedef struct +{ + UINT cItems; // number of items in rgdwFileAttributes array + DWORD dwSumFileAttributes; // all of the attributes ORed together + DWORD dwProductFileAttributes; // all of the attributes ANDed together + DWORD rgdwFileAttributes[1]; // array +} MYWIN_FILE_ATTRIBUTES_ARRAY; + +#define MYWIN_CFSTR_FILE_ATTRIBUTES_ARRAY TEXT("File Attributes Array") + +HRESULT DataObject_GetData_FILE_ATTRS(IDataObject *dataObject, CFileAttribs &attribs) +{ + attribs.Clear(); + NCOM::CStgMedium medium; + RINOK(DataObject_GetData_HGLOBAL(dataObject, (CLIPFORMAT) + RegisterClipboardFormat(MYWIN_CFSTR_FILE_ATTRIBUTES_ARRAY), medium)) + const size_t blockSize = GlobalSize(medium.hGlobal); + if (blockSize < sizeof(MYWIN_FILE_ATTRIBUTES_ARRAY)) + return E_INVALIDARG; + NMemory::CGlobalLock dropLock(medium.hGlobal); + const MYWIN_FILE_ATTRIBUTES_ARRAY *faa = (const MYWIN_FILE_ATTRIBUTES_ARRAY *)dropLock.GetPointer(); + if (!faa) + return E_INVALIDARG; + const unsigned numFiles = faa->cItems; + if (numFiles == 0) + { + // is it posssible to have empty array here? + return E_INVALIDARG; + } + if ((blockSize - (sizeof(MYWIN_FILE_ATTRIBUTES_ARRAY) - sizeof(DWORD))) + / sizeof(DWORD) != numFiles) + return E_INVALIDARG; + // attribs.Sum = faa->dwSumFileAttributes; + // attribs.Product = faa->dwProductFileAttributes; + // attribs.Vals.SetFromArray(faa->rgdwFileAttributes, numFiles); + // attribs.IsDirVector.ClearAndSetSize(numFiles); + + if ((faa->dwSumFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) + { + /* in win10: if selected items are volumes (c:\, d:\ ..) in My Compter, + all items have FILE_ATTRIBUTE_DIRECTORY attribute + ntfs volume also have FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM + udf volume: FILE_ATTRIBUTE_READONLY + dvd-rom device: (-1) : all bits are set + */ + const DWORD *attr = faa->rgdwFileAttributes; + // DWORD product = (UInt32)0 - 1, sum = 0; + for (unsigned i = 0; i < numFiles; i++) + { + if (attr[i] & FILE_ATTRIBUTE_DIRECTORY) + { + // attribs.ThereAreDirs = true; + attribs.FirstDirIndex = (int)i; + break; + } + // attribs.IsDirVector[i] = (attr[i] & FILE_ATTRIBUTE_DIRECTORY) != 0; + // product &= v; + // sum |= v; + } + // ODS_(Print_Number(product, "Product calc FILE_ATTRIBUTES_ARRAY ==== DataObject_GetData_HDROP_Names")) + // ODS_(Print_Number(sum, "Sum calc FILE_ATTRIBUTES_ARRAY ==== DataObject_GetData_HDROP_Names")) + } + // ODS_(Print_Number(attribs.Product, "Product FILE_ATTRIBUTES_ARRAY ==== DataObject_GetData_HDROP_Names")) + // ODS_(Print_Number(attribs.Sum, "Sum FILE_ATTRIBUTES_ARRAY ==== DataObject_GetData_HDROP_Names")) + ODS_(Print_Number(numFiles, "FILE_ATTRIBUTES_ARRAY ==== DataObject_GetData_HDROP_Names")) + return S_OK; +} + + ///////////////////////////// // CDrop +/* + win10: + DragQueryFile() implementation code is not effective because + there is no pointer inside DROP internal file list, so + DragQueryFile(fileIndex) runs all names in range [0, fileIndex]. + DragQueryFile(,, buf, bufSize) + if (buf == NULL) by spec + { + returns value is the required size + in characters, of the buffer, not including the terminating null character + tests show that if (bufSize == 0), then it also returns required size. + } + if (bufSize != NULL) + { + returns: the count of the characters copied, not including null character. + win10: null character is also copied at position buf[ret_count]; + } +*/ + +/* void CDrop::Attach(HDROP object) { Free(); @@ -92,56 +476,133 @@ return QueryFile(0xFFFFFFFF, (LPTSTR)NULL, 0); } -UString CDrop::QueryFileName(UINT fileIndex) +void CDrop::QueryFileName(UINT fileIndex, UString &fileName) { - UString fileName; #ifndef _UNICODE if (!g_IsNT) { AString fileNameA; - UINT bufferSize = QueryFile(fileIndex, (LPTSTR)NULL, 0); - const unsigned len = bufferSize + 2; - QueryFile(fileIndex, fileNameA.GetBuf(len), bufferSize + 1); + const UINT len = QueryFile(fileIndex, (LPTSTR)NULL, 0); + const UINT numCopied = QueryFile(fileIndex, fileNameA.GetBuf(len + 2), len + 2); fileNameA.ReleaseBuf_CalcLen(len); + if (numCopied != len) + throw 20221223; fileName = GetUnicodeString(fileNameA); } else #endif { - UINT bufferSize = QueryFile(fileIndex, (LPWSTR)NULL, 0); - const unsigned len = bufferSize + 2; - QueryFile(fileIndex, fileName.GetBuf(len), bufferSize + 1); + // kReserve must be >= 3 for additional buffer size + // safety and for optimal performance + const unsigned kReserve = 3; + { + unsigned len = 0; + wchar_t *buf = fileName.GetBuf_GetMaxAvail(len); + if (len >= kReserve) + { + const UINT numCopied = QueryFile(fileIndex, buf, len); + if (numCopied < len - 1) + { + // (numCopied < len - 1) case means that it have copied full string. + fileName.ReleaseBuf_CalcLen(numCopied); + return; + } + } + } + const UINT len = QueryFile(fileIndex, (LPWSTR)NULL, 0); + const UINT numCopied = QueryFile(fileIndex, + fileName.GetBuf(len + kReserve), len + kReserve); fileName.ReleaseBuf_CalcLen(len); + if (numCopied != len) + throw 20221223; } - return fileName; } + void CDrop::QueryFileNames(UStringVector &fileNames) { UINT numFiles = QueryCountOfFiles(); - /* - char s[100]; - sprintf(s, "QueryFileNames: %d files", numFiles); - OutputDebugStringA(s); - */ + + Print_Number(numFiles, "\n====== CDrop::QueryFileNames START ===== \n"); + fileNames.ClearAndReserve(numFiles); + UString s; for (UINT i = 0; i < numFiles; i++) { - const UString s2 = QueryFileName(i); - if (!s2.IsEmpty()) - fileNames.AddInReserved(s2); - /* - OutputDebugStringW(L"file ---"); - OutputDebugStringW(s2); - */ + QueryFileName(i, s); + if (!s.IsEmpty()) + fileNames.AddInReserved(s); } + Print_Number(numFiles, "\n====== CDrop::QueryFileNames END ===== \n"); +} +*/ + + +// #if (NTDDI_VERSION >= NTDDI_VISTA) +// SHGetPathFromIDListEx returns a win32 file system path for the item in the name space. +typedef int Z7_WIN_GPFIDL_FLAGS; + +extern "C" { +typedef BOOL (WINAPI * Func_SHGetPathFromIDListW)(LPCITEMIDLIST pidl, LPWSTR pszPath); +typedef BOOL (WINAPI * Func_SHGetPathFromIDListEx)(LPCITEMIDLIST pidl, PWSTR pszPath, DWORD cchPath, Z7_WIN_GPFIDL_FLAGS uOpts); } +#ifndef _UNICODE -bool GetPathFromIDList(LPCITEMIDLIST itemIDList, CSysString &path) +bool GetPathFromIDList(LPCITEMIDLIST itemIDList, AString &path) +{ + path.Empty(); + const unsigned len = MAX_PATH + 16; + const bool result = BOOLToBool(::SHGetPathFromIDList(itemIDList, path.GetBuf(len))); + path.ReleaseBuf_CalcLen(len); + return result; +} + +#endif + +bool GetPathFromIDList(LPCITEMIDLIST itemIDList, UString &path) { - const unsigned len = MAX_PATH * 2; + path.Empty(); + unsigned len = MAX_PATH + 16; + +#ifdef _UNICODE bool result = BOOLToBool(::SHGetPathFromIDList(itemIDList, path.GetBuf(len))); +#else + const + Func_SHGetPathFromIDListW + shGetPathFromIDListW = Z7_GET_PROC_ADDRESS( + Func_SHGetPathFromIDListW, ::GetModuleHandleW(L"shell32.dll"), + "SHGetPathFromIDListW"); + if (!shGetPathFromIDListW) + return false; + bool result = BOOLToBool(shGetPathFromIDListW(itemIDList, path.GetBuf(len))); +#endif + + if (!result) + { + ODS("==== GetPathFromIDList() SHGetPathFromIDList() returned false") + /* for long path we need SHGetPathFromIDListEx(). + win10: SHGetPathFromIDListEx() for long path returns path with + with super path prefix "\\\\?\\". */ + const + Func_SHGetPathFromIDListEx + func_SHGetPathFromIDListEx = Z7_GET_PROC_ADDRESS( + Func_SHGetPathFromIDListEx, ::GetModuleHandleW(L"shell32.dll"), + "SHGetPathFromIDListEx"); + if (func_SHGetPathFromIDListEx) + { + ODS("==== GetPathFromIDList() (SHGetPathFromIDListEx)") + do + { + len *= 4; + result = BOOLToBool(func_SHGetPathFromIDListEx(itemIDList, path.GetBuf(len), len, 0)); + if (result) + break; + } + while (len <= (1 << 16)); + } + } + path.ReleaseBuf_CalcLen(len); return result; } @@ -180,11 +641,16 @@ #else +/* win10: SHBrowseForFolder() doesn't support long paths, + even if long path suppport is enabled in registry and in manifest. + and SHBrowseForFolder() doesn't support super path prefix "\\\\?\\". */ + bool BrowseForFolder(LPBROWSEINFO browseInfo, CSysString &resultPath) { + resultPath.Empty(); NWindows::NCOM::CComInitializer comInitializer; LPITEMIDLIST itemIDList = ::SHBrowseForFolder(browseInfo); - if (itemIDList == NULL) + if (!itemIDList) return false; CItemIDList itemIDListHolder; itemIDListHolder.Attach(itemIDList); @@ -240,11 +706,18 @@ browseInfo.lpszTitle = title; // #endif browseInfo.ulFlags = ulFlags; - browseInfo.lpfn = (initialFolder != NULL) ? BrowseCallbackProc : NULL; + browseInfo.lpfn = initialFolder ? BrowseCallbackProc : NULL; browseInfo.lParam = (LPARAM)initialFolder; return BrowseForFolder(&browseInfo, resultPath); } +#ifdef Z7_OLD_WIN_SDK +// ShlObj.h: +#ifndef BIF_NEWDIALOGSTYLE +#define BIF_NEWDIALOGSTYLE 0x0040 +#endif +#endif + bool BrowseForFolder(HWND owner, LPCTSTR title, LPCTSTR initialFolder, CSysString &resultPath) { @@ -259,38 +732,21 @@ #ifndef _UNICODE extern "C" { -typedef BOOL (WINAPI * Func_SHGetPathFromIDListW)(LPCITEMIDLIST pidl, LPWSTR pszPath); typedef LPITEMIDLIST (WINAPI * Func_SHBrowseForFolderW)(LPBROWSEINFOW lpbi); } -#define MY_CAST_FUNC (void(*)()) -// #define MY_CAST_FUNC - -bool GetPathFromIDList(LPCITEMIDLIST itemIDList, UString &path) -{ - path.Empty(); - Func_SHGetPathFromIDListW shGetPathFromIDListW = (Func_SHGetPathFromIDListW) - MY_CAST_FUNC - ::GetProcAddress(::GetModuleHandleW(L"shell32.dll"), "SHGetPathFromIDListW"); - if (!shGetPathFromIDListW) - return false; - const unsigned len = MAX_PATH * 2; - bool result = BOOLToBool(shGetPathFromIDListW(itemIDList, path.GetBuf(len))); - path.ReleaseBuf_CalcLen(len); - return result; -} - - static bool BrowseForFolder(LPBROWSEINFOW browseInfo, UString &resultPath) { NWindows::NCOM::CComInitializer comInitializer; - Func_SHBrowseForFolderW shBrowseForFolderW = (Func_SHBrowseForFolderW) - MY_CAST_FUNC - ::GetProcAddress(::GetModuleHandleW(L"shell32.dll"), "SHBrowseForFolderW"); - if (!shBrowseForFolderW) + const + Func_SHBrowseForFolderW + f_SHBrowseForFolderW = Z7_GET_PROC_ADDRESS( + Func_SHBrowseForFolderW, ::GetModuleHandleW(L"shell32.dll"), + "SHBrowseForFolderW"); + if (!f_SHBrowseForFolderW) return false; - LPITEMIDLIST itemIDList = shBrowseForFolderW(browseInfo); - if (itemIDList == NULL) + LPITEMIDLIST itemIDList = f_SHBrowseForFolderW(browseInfo); + if (!itemIDList) return false; CItemIDList itemIDListHolder; itemIDListHolder.Attach(itemIDList); @@ -336,7 +792,7 @@ browseInfo.pszDisplayName = displayName.GetBuf(MAX_PATH); browseInfo.lpszTitle = title; browseInfo.ulFlags = ulFlags; - browseInfo.lpfn = (initialFolder != NULL) ? BrowseCallbackProc2 : NULL; + browseInfo.lpfn = initialFolder ? BrowseCallbackProc2 : NULL; browseInfo.lParam = (LPARAM)initialFolder; return BrowseForFolder(&browseInfo, resultPath); } diff -Nru 7zip-22.01+dfsg/CPP/Windows/Shell.h 7zip-23.01+dfsg/CPP/Windows/Shell.h --- 7zip-22.01+dfsg/CPP/Windows/Shell.h 2021-01-26 19:17:16.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Shell.h 2023-03-23 08:00:00.000000000 +0000 @@ -1,17 +1,22 @@ // Windows/Shell.h -#ifndef __WINDOWS_SHELL_H -#define __WINDOWS_SHELL_H +#ifndef ZIP7_WINDOWS_SHELL_H +#define ZIP7_WINDOWS_SHELL_H +#include "../Common/Common.h" #include "../Common/MyWindows.h" +#if defined(__MINGW32__) || defined(__MINGW64__) +#include +#else #include +#endif #include "../Common/MyString.h" #include "Defs.h" -namespace NWindows{ -namespace NShell{ +namespace NWindows { +namespace NShell { ///////////////////////// // CItemIDList @@ -20,6 +25,7 @@ class CItemIDList { LPITEMIDLIST m_Object; + Z7_CLASS_NO_COPY(CItemIDList) public: CItemIDList(): m_Object(NULL) {} // CItemIDList(LPCITEMIDLIST itemIDList); @@ -49,6 +55,7 @@ ///////////////////////////// // CDrop +/* class CDrop { HDROP m_Object; @@ -63,22 +70,51 @@ operator HDROP() { return m_Object;} bool QueryPoint(LPPOINT point) { return BOOLToBool(::DragQueryPoint(m_Object, point)); } - void Finish() { ::DragFinish(m_Object); } - UINT QueryFile(UINT fileIndex, LPTSTR fileName, UINT fileNameSize) - { return ::DragQueryFile(m_Object, fileIndex, fileName, fileNameSize); } + void Finish() + { + ::DragFinish(m_Object); + } + UINT QueryFile(UINT fileIndex, LPTSTR fileName, UINT bufSize) + { return ::DragQueryFile(m_Object, fileIndex, fileName, bufSize); } #ifndef _UNICODE - UINT QueryFile(UINT fileIndex, LPWSTR fileName, UINT fileNameSize) - { return ::DragQueryFileW(m_Object, fileIndex, fileName, fileNameSize); } + UINT QueryFile(UINT fileIndex, LPWSTR fileName, UINT bufSize) + { return ::DragQueryFileW(m_Object, fileIndex, fileName, bufSize); } #endif UINT QueryCountOfFiles(); - UString QueryFileName(UINT fileIndex); + void QueryFileName(UINT fileIndex, UString &fileName); void QueryFileNames(UStringVector &fileNames); }; - +*/ #endif -///////////////////////////// -// Functions +struct CFileAttribs +{ + int FirstDirIndex; + // DWORD Sum; + // DWORD Product; + // CRecordVector Vals; + // CRecordVector IsDirVector; + + CFileAttribs() + { + Clear(); + } + + void Clear() + { + FirstDirIndex = -1; + // Sum = 0; + // Product = 0; + // IsDirVector.Clear(); + } +}; + + +/* read pathnames from HDROP or SHELLIDLIST. + The parser can return E_INVALIDARG, if there is some unexpected data in dataObject */ +HRESULT DataObject_GetData_HDROP_or_IDLIST_Names(IDataObject *dataObject, UStringVector &names); + +HRESULT DataObject_GetData_FILE_ATTRS(IDataObject *dataObject, CFileAttribs &attribs); bool GetPathFromIDList(LPCITEMIDLIST itemIDList, CSysString &path); bool BrowseForFolder(LPBROWSEINFO lpbi, CSysString &resultPath); diff -Nru 7zip-22.01+dfsg/CPP/Windows/StdAfx.h 7zip-23.01+dfsg/CPP/Windows/StdAfx.h --- 7zip-22.01+dfsg/CPP/Windows/StdAfx.h 2013-11-27 10:18:38.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/StdAfx.h 2023-03-24 11:00:00.000000000 +0000 @@ -1,7 +1,11 @@ // StdAfx.h -#ifndef __STDAFX_H -#define __STDAFX_H +#ifndef ZIP7_INC_STDAFX_H +#define ZIP7_INC_STDAFX_H + +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif #include "../Common/Common.h" diff -Nru 7zip-22.01+dfsg/CPP/Windows/Synchronization.cpp 7zip-23.01+dfsg/CPP/Windows/Synchronization.cpp --- 7zip-22.01+dfsg/CPP/Windows/Synchronization.cpp 2020-10-20 16:07:12.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Synchronization.cpp 2023-03-18 10:00:00.000000000 +0000 @@ -19,6 +19,30 @@ DWORD WaitForMultipleObjects(DWORD count, const HANDLE *handles, BOOL wait_all, DWORD timeout); */ +/* clang: we need to place some virtual functions in cpp file to rid off the warning: + 'CBaseHandle_WFMO' has no out-of-line virtual method definitions; + its vtable will be emitted in every translation unit */ +CBaseHandle_WFMO::~CBaseHandle_WFMO() +{ +} + +bool CBaseEvent_WFMO::IsSignaledAndUpdate() +{ + if (this->_state == false) + return false; + if (this->_manual_reset == false) + this->_state = false; + return true; +} + +bool CSemaphore_WFMO::IsSignaledAndUpdate() +{ + if (this->_count == 0) + return false; + this->_count--; + return true; +} + DWORD WINAPI WaitForMultiObj_Any_Infinite(DWORD count, const CHandle_WFMO *handles) { if (count < 1) diff -Nru 7zip-22.01+dfsg/CPP/Windows/Synchronization.h 7zip-23.01+dfsg/CPP/Windows/Synchronization.h --- 7zip-22.01+dfsg/CPP/Windows/Synchronization.h 2021-06-05 11:27:02.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Synchronization.h 2023-03-18 10:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Synchronization.h -#ifndef __WINDOWS_SYNCHRONIZATION_H -#define __WINDOWS_SYNCHRONIZATION_H +#ifndef ZIP7_INC_WINDOWS_SYNCHRONIZATION_H +#define ZIP7_INC_WINDOWS_SYNCHRONIZATION_H #include "../../C/Threads.h" @@ -32,14 +32,14 @@ WRes Create(bool manualReset, bool initiallyOwn, LPCTSTR name = NULL, LPSECURITY_ATTRIBUTES sa = NULL) { _object = ::CreateEvent(sa, BoolToBOOL(manualReset), BoolToBOOL(initiallyOwn), name); - if (name == NULL && _object != 0) + if (name == NULL && _object != NULL) return 0; return ::GetLastError(); } WRes Open(DWORD desiredAccess, bool inheritHandle, LPCTSTR name) { _object = ::OpenEvent(desiredAccess, BoolToBOOL(inheritHandle), name); - if (_object != 0) + if (_object != NULL) return 0; return ::GetLastError(); } @@ -227,8 +227,8 @@ } WRes Create() { - RINOK(::pthread_mutex_init(&_mutex, 0)); - WRes ret = ::pthread_cond_init(&_cond, 0); + RINOK(::pthread_mutex_init(&_mutex, NULL)) + const WRes ret = ::pthread_cond_init(&_cond, NULL); _isValid = 1; return ret; } @@ -246,8 +246,8 @@ } WRes LeaveAndSignal() { - WRes res1 = ::pthread_cond_broadcast(&_cond); - WRes res2 = ::pthread_mutex_unlock(&_mutex); + const WRes res1 = ::pthread_cond_broadcast(&_cond); + const WRes res2 = ::pthread_mutex_unlock(&_mutex); return (res2 ? res2 : res1); } }; @@ -268,6 +268,7 @@ CSynchro *_sync; CBaseHandle_WFMO(): _sync(NULL) {} + virtual ~CBaseHandle_WFMO(); operator CHandle_WFMO() { return this; } virtual bool IsSignaledAndUpdate() = 0; @@ -283,7 +284,7 @@ // bool IsCreated() { return (this->_sync != NULL); } // CBaseEvent_WFMO() { ; } - ~CBaseEvent_WFMO() { Close(); } + // ~CBaseEvent_WFMO() Z7_override { Close(); } WRes Close() { this->_sync = NULL; return 0; } @@ -299,37 +300,30 @@ WRes Set() { - RINOK(this->_sync->Enter()); + RINOK(this->_sync->Enter()) this->_state = true; return this->_sync->LeaveAndSignal(); } WRes Reset() { - RINOK(this->_sync->Enter()); + RINOK(this->_sync->Enter()) this->_state = false; return this->_sync->Leave(); } - virtual bool IsSignaledAndUpdate() - { - if (this->_state == false) - return false; - if (this->_manual_reset == false) - this->_state = false; - return true; - } + virtual bool IsSignaledAndUpdate() Z7_override; }; -class CManualResetEvent_WFMO: public CBaseEvent_WFMO +class CManualResetEvent_WFMO Z7_final: public CBaseEvent_WFMO { public: WRes Create(CSynchro *sync, bool initiallyOwn = false) { return CBaseEvent_WFMO::Create(sync, true, initiallyOwn); } }; -class CAutoResetEvent_WFMO: public CBaseEvent_WFMO +class CAutoResetEvent_WFMO Z7_final: public CBaseEvent_WFMO { public: WRes Create(CSynchro *sync) { return CBaseEvent_WFMO::Create(sync, false, false); } @@ -340,7 +334,7 @@ }; -class CSemaphore_WFMO : public CBaseHandle_WFMO +class CSemaphore_WFMO Z7_final: public CBaseHandle_WFMO { UInt32 _count; UInt32 _maxCount; @@ -365,11 +359,11 @@ if (releaseCount < 1) return EINVAL; - RINOK(this->_sync->Enter()); + RINOK(this->_sync->Enter()) UInt32 newCount = this->_count + releaseCount; if (newCount > this->_maxCount) { - RINOK(this->_sync->Leave()); + RINOK(this->_sync->Leave()) return ERROR_TOO_MANY_POSTS; // EINVAL } this->_count = newCount; @@ -377,13 +371,7 @@ return this->_sync->LeaveAndSignal(); } - virtual bool IsSignaledAndUpdate() - { - if (this->_count == 0) - return false; - this->_count--; - return true; - } + virtual bool IsSignaledAndUpdate() Z7_override; }; #endif // _WIN32 diff -Nru 7zip-22.01+dfsg/CPP/Windows/System.cpp 7zip-23.01+dfsg/CPP/Windows/System.cpp --- 7zip-22.01+dfsg/CPP/Windows/System.cpp 2021-10-18 10:33:42.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/System.cpp 2023-03-18 10:00:00.000000000 +0000 @@ -4,6 +4,7 @@ #ifndef _WIN32 #include +#include #ifdef __APPLE__ #include #else @@ -74,7 +75,7 @@ return TRUE; */ - #ifdef _7ZIP_AFFINITY_SUPPORTED + #ifdef Z7_AFFINITY_SUPPORTED // numSysThreads = sysconf(_SC_NPROCESSORS_ONLN); // The number of processors currently online if (sched_getaffinity(0, sizeof(cpu_set), &cpu_set) != 0) @@ -93,7 +94,7 @@ UInt32 GetNumberOfProcessors() { - #ifndef _7ZIP_ST + #ifndef Z7_ST long n = sysconf(_SC_NPROCESSORS_CONF); // The number of processors configured if (n < 1) n = 1; @@ -110,7 +111,8 @@ #ifndef UNDER_CE -#if !defined(_WIN64) && defined(__GNUC__) +#if !defined(_WIN64) && \ + (defined(__MINGW32_VERSION) || defined(Z7_OLD_WIN_SDK)) typedef struct _MY_MEMORYSTATUSEX { DWORD dwLength; @@ -131,7 +133,7 @@ #endif -typedef BOOL (WINAPI *GlobalMemoryStatusExP)(MY_LPMEMORYSTATUSEX lpBuffer); +typedef BOOL (WINAPI *Func_GlobalMemoryStatusEx)(MY_LPMEMORYSTATUSEX lpBuffer); #endif // !UNDER_CE @@ -155,9 +157,11 @@ #else #ifndef UNDER_CE - GlobalMemoryStatusExP globalMemoryStatusEx = (GlobalMemoryStatusExP) - (void *)::GetProcAddress(::GetModuleHandleA("kernel32.dll"), "GlobalMemoryStatusEx"); - if (globalMemoryStatusEx && globalMemoryStatusEx(&stat)) + const + Func_GlobalMemoryStatusEx fn = Z7_GET_PROC_ADDRESS( + Func_GlobalMemoryStatusEx, ::GetModuleHandleA("kernel32.dll"), + "GlobalMemoryStatusEx"); + if (fn && fn(&stat)) { size = MyMin(stat.ullTotalVirtual, stat.ullTotalPhys); return true; @@ -231,4 +235,44 @@ #endif + +unsigned long Get_File_OPEN_MAX() +{ + #ifdef _WIN32 + return (1 << 24) - (1 << 16); // ~16M handles + #else + // some linux versions have default open file limit for user process of 1024 files. + long n = sysconf(_SC_OPEN_MAX); + // n = -1; // for debug + // n = 9; // for debug + if (n < 1) + { + // n = OPEN_MAX; // ??? + // n = FOPEN_MAX; // = 16 : + #ifdef _POSIX_OPEN_MAX + n = _POSIX_OPEN_MAX; // = 20 : + #else + n = 30; // our limit + #endif + } + return (unsigned long)n; + #endif +} + +unsigned Get_File_OPEN_MAX_Reduced_for_3_tasks() +{ + unsigned long numFiles_OPEN_MAX = NSystem::Get_File_OPEN_MAX(); + const unsigned delta = 10; // the reserve for another internal needs of process + if (numFiles_OPEN_MAX > delta) + numFiles_OPEN_MAX -= delta; + else + numFiles_OPEN_MAX = 1; + numFiles_OPEN_MAX /= 3; // we suppose that we have up to 3 tasks in total for multiple file processing + numFiles_OPEN_MAX = MyMax(numFiles_OPEN_MAX, (unsigned long)3); + unsigned n = (UInt32)(UInt32)-1; + if (n > numFiles_OPEN_MAX) + n = (unsigned)numFiles_OPEN_MAX; + return n; +} + }} diff -Nru 7zip-22.01+dfsg/CPP/Windows/System.h 7zip-23.01+dfsg/CPP/Windows/System.h --- 7zip-22.01+dfsg/CPP/Windows/System.h 2021-04-02 16:31:51.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/System.h 2023-03-22 19:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/System.h -#ifndef __WINDOWS_SYSTEM_H -#define __WINDOWS_SYSTEM_H +#ifndef ZIP7_INC_WINDOWS_SYSTEM_H +#define ZIP7_INC_WINDOWS_SYSTEM_H #ifndef _WIN32 // #include @@ -9,11 +9,11 @@ #endif #include "../Common/MyTypes.h" +#include "../Common/MyWindows.h" namespace NWindows { namespace NSystem { - #ifdef _WIN32 UInt32 CountAffinity(DWORD_PTR mask); @@ -64,7 +64,7 @@ UInt32 GetNumSystemThreads() const { return (UInt32)numSysThreads; } BOOL Get(); - #ifdef _7ZIP_AFFINITY_SUPPORTED + #ifdef Z7_AFFINITY_SUPPORTED CCpuSet cpu_set; @@ -86,7 +86,7 @@ return sched_setaffinity(0, sizeof(cpu_set), &cpu_set) == 0; } - #else + #else // Z7_AFFINITY_SUPPORTED void InitST() { @@ -114,16 +114,19 @@ return FALSE; } - #endif + #endif // Z7_AFFINITY_SUPPORTED }; -#endif +#endif // _WIN32 UInt32 GetNumberOfProcessors(); bool GetRamSize(UInt64 &size); // returns false, if unknown ram size +unsigned long Get_File_OPEN_MAX(); +unsigned Get_File_OPEN_MAX_Reduced_for_3_tasks(); + }} #endif diff -Nru 7zip-22.01+dfsg/CPP/Windows/SystemInfo.cpp 7zip-23.01+dfsg/CPP/Windows/SystemInfo.cpp --- 7zip-22.01+dfsg/CPP/Windows/SystemInfo.cpp 2021-11-06 08:19:39.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/SystemInfo.cpp 2023-05-03 10:00:00.000000000 +0000 @@ -102,38 +102,44 @@ #ifdef MY_CPU_X86_OR_AMD64 +Z7_NO_INLINE static void PrintCpuChars(AString &s, UInt32 v) { - for (int j = 0; j < 4; j++) + for (unsigned j = 0; j < 4; j++) { Byte b = (Byte)(v & 0xFF); v >>= 8; if (b == 0) break; - s += (char)b; + if (b >= 0x20 && b <= 0x7f) + s += (char)b; + else + { + s += '['; + char temp[16]; + ConvertUInt32ToHex(b, temp); + s += temp; + s += ']'; + } } } -static void x86cpuid_to_String(const Cx86cpuid &c, AString &s, AString &ver) +static void x86cpuid_to_String(AString &s) { s.Empty(); - UInt32 maxFunc2 = 0; - UInt32 t[3]; + UInt32 a[4]; + // cpuid was called already. So we don't check for cpuid availability here + z7_x86_cpuid(a, 0x80000000); - MyCPUID(0x80000000, &maxFunc2, &t[0], &t[1], &t[2]); - - bool fullNameIsAvail = (maxFunc2 >= 0x80000004); - - if (fullNameIsAvail) + if (a[0] >= 0x80000004) // if (maxFunc2 >= hi+4) the full name is available { for (unsigned i = 0; i < 3; i++) { - UInt32 d[4] = { 0 }; - MyCPUID(0x80000002 + i, &d[0], &d[1], &d[2], &d[3]); + z7_x86_cpuid(a, 0x80000002 + i); for (unsigned j = 0; j < 4; j++) - PrintCpuChars(s, d[j]); + PrintCpuChars(s, a[j]); } } @@ -141,16 +147,14 @@ if (s.IsEmpty()) { - for (int i = 0; i < 3; i++) - PrintCpuChars(s, c.vendor[i]); + z7_x86_cpuid(a, 0); + for (unsigned i = 1; i < 4; i++) + { + const unsigned j = (i ^ (i >> 1)); + PrintCpuChars(s, a[j]); + } s.Trim(); } - - { - char temp[32]; - ConvertUInt32ToHex(c.ver, temp); - ver += temp; - } } /* @@ -184,7 +188,7 @@ { char temp[32]; ConvertUInt32ToHex8Digits(d[i], temp); - s += " "; + s.Add_Space(); s += temp; } } @@ -215,12 +219,12 @@ , "ARM32_ON_WIN64" }; -#define MY__PROCESSOR_ARCHITECTURE_INTEL 0 -#define MY__PROCESSOR_ARCHITECTURE_AMD64 9 +#define Z7_WIN_PROCESSOR_ARCHITECTURE_INTEL 0 +#define Z7_WIN_PROCESSOR_ARCHITECTURE_AMD64 9 -#define MY__PROCESSOR_INTEL_PENTIUM 586 -#define MY__PROCESSOR_AMD_X8664 8664 +#define Z7_WIN_PROCESSOR_INTEL_PENTIUM 586 +#define Z7_WIN_PROCESSOR_AMD_X8664 8664 /* static const CUInt32PCharPair k_PROCESSOR[] = @@ -303,19 +307,20 @@ #endif -#ifdef _WIN32 - -static void PrintPage(AString &s, UInt32 v) +static void PrintPage(AString &s, UInt64 v) { - if ((v & 0x3FF) == 0) + const char *t = "B"; + if ((v & 0x3ff) == 0) { - s.Add_UInt32(v >> 10); - s += "K"; + v >>= 10; + t = "KB"; } - else - s.Add_UInt32(v >> 10); + s.Add_UInt64(v); + s += t; } +#ifdef _WIN32 + static AString TypeToString2(const char * const table[], unsigned num, UInt32 value) { char sz[16]; @@ -330,7 +335,7 @@ return (AString)p; } -// #if defined(_7ZIP_LARGE_PAGES) || defined(_WIN32) +// #if defined(Z7_LARGE_PAGES) || defined(_WIN32) // #ifdef _WIN32 void PrintSize_KMGT_Or_Hex(AString &s, UInt64 v) { @@ -342,32 +347,32 @@ }}}} else { + // s += "0x"; PrintHex(s, v); return; } - char temp[32]; - ConvertUInt64ToString(v, temp); - s += temp; + s.Add_UInt64(v); if (c) s += c; + s += 'B'; } // #endif // #endif static void SysInfo_To_String(AString &s, const SYSTEM_INFO &si) { - s += TypeToString2(k_PROCESSOR_ARCHITECTURE, ARRAY_SIZE(k_PROCESSOR_ARCHITECTURE), si.wProcessorArchitecture); + s += TypeToString2(k_PROCESSOR_ARCHITECTURE, Z7_ARRAY_SIZE(k_PROCESSOR_ARCHITECTURE), si.wProcessorArchitecture); - if (!( (si.wProcessorArchitecture == MY__PROCESSOR_ARCHITECTURE_INTEL && si.dwProcessorType == MY__PROCESSOR_INTEL_PENTIUM) - || (si.wProcessorArchitecture == MY__PROCESSOR_ARCHITECTURE_AMD64 && si.dwProcessorType == MY__PROCESSOR_AMD_X8664))) + if (!( (si.wProcessorArchitecture == Z7_WIN_PROCESSOR_ARCHITECTURE_INTEL && si.dwProcessorType == Z7_WIN_PROCESSOR_INTEL_PENTIUM) + || (si.wProcessorArchitecture == Z7_WIN_PROCESSOR_ARCHITECTURE_AMD64 && si.dwProcessorType == Z7_WIN_PROCESSOR_AMD_X8664))) { - s += " "; - // s += TypePairToString(k_PROCESSOR, ARRAY_SIZE(k_PROCESSOR), si.dwProcessorType); + s.Add_Space(); + // s += TypePairToString(k_PROCESSOR, Z7_ARRAY_SIZE(k_PROCESSOR), si.dwProcessorType); s.Add_UInt32(si.dwProcessorType); } - s += " "; + s.Add_Space(); PrintHex(s, si.wProcessorLevel); - s += "."; + s.Add_Dot(); PrintHex(s, si.wProcessorRevision); if ((UInt64)si.dwActiveProcessorMask + 1 != ((UInt64)1 << si.dwNumberOfProcessors)) if ((UInt64)si.dwActiveProcessorMask + 1 != 0 || si.dwNumberOfProcessors != sizeof(UInt64) * 8) @@ -387,9 +392,9 @@ s += " gran:"; PrintPage(s, si.dwAllocationGranularity); } - s += " "; + s.Add_Space(); - DWORD_PTR minAdd = (DWORD_PTR)si.lpMinimumApplicationAddress; + const DWORD_PTR minAdd = (DWORD_PTR)si.lpMinimumApplicationAddress; UInt64 maxSize = (UInt64)(DWORD_PTR)si.lpMaximumApplicationAddress + 1; const UInt32 kReserveSize = ((UInt32)1 << 16); if (minAdd != kReserveSize) @@ -419,7 +424,7 @@ { size_t bufSize = 256; char buf[256]; - if (My_sysctlbyname_Get(name, &buf, &bufSize) == 0) + if (z7_sysctlbyname_Get(name, &buf, &bufSize) == 0) s += buf; } #endif @@ -440,12 +445,14 @@ } #if !defined(_WIN64) && !defined(UNDER_CE) - Func_GetNativeSystemInfo fn_GetNativeSystemInfo = (Func_GetNativeSystemInfo)(void *)GetProcAddress( - GetModuleHandleA("kernel32.dll"), "GetNativeSystemInfo"); - if (fn_GetNativeSystemInfo) + const + Func_GetNativeSystemInfo fn = Z7_GET_PROC_ADDRESS( + Func_GetNativeSystemInfo, GetModuleHandleA("kernel32.dll"), + "GetNativeSystemInfo"); + if (fn) { SYSTEM_INFO si2; - fn_GetNativeSystemInfo(&si2); + fn(&si2); // if (memcmp(&si, &si2, sizeof(si)) != 0) { // s += " - "; @@ -500,18 +507,20 @@ #ifdef MY_CPU_X86_OR_AMD64 { - Cx86cpuid cpuid; - if (x86cpuid_CheckAndRead(&cpuid)) - { - x86cpuid_to_String(cpuid, s, Revision); - } + #if !defined(MY_CPU_AMD64) + if (!z7_x86_cpuid_GetMaxFunc()) + s += "x86"; else - { - #ifdef MY_CPU_AMD64 - s += "x64"; - #else - s += "x86"; #endif + { + x86cpuid_to_String(s); + { + UInt32 a[4]; + z7_x86_cpuid(a, 1); + char temp[16]; + ConvertUInt32ToHex(a[0], temp); + Revision += temp; + } } } #elif defined(__APPLE__) @@ -534,12 +543,12 @@ { AString s2; UInt32 v = 0; - if (My_sysctlbyname_Get_UInt32("machdep.cpu.core_count", &v) == 0) + if (z7_sysctlbyname_Get_UInt32("machdep.cpu.core_count", &v) == 0) { s2.Add_UInt32(v); s2 += 'C'; } - if (My_sysctlbyname_Get_UInt32("machdep.cpu.thread_count", &v) == 0) + if (z7_sysctlbyname_Get_UInt32("machdep.cpu.thread_count", &v) == 0) { s2.Add_UInt32(v); s2 += 'T'; @@ -561,7 +570,7 @@ LONG res[2]; CByteBuffer bufs[2]; { - for (int i = 0; i < 2; i++) + for (unsigned i = 0; i < 2; i++) { UInt32 size = 0; res[i] = key.QueryValue(i == 0 ? @@ -574,7 +583,7 @@ } if (res[0] == ERROR_SUCCESS || res[1] == ERROR_SUCCESS) { - for (int i = 0; i < 2; i++) + for (unsigned i = 0; i < 2; i++) { if (i == 1) Microcode += "->"; @@ -598,7 +607,7 @@ #endif - #ifdef _7ZIP_LARGE_PAGES + #ifdef Z7_LARGE_PAGES Add_LargePages_String(LargePages); #endif } @@ -608,7 +617,7 @@ { #ifdef _WIN32 // const unsigned kNumFeatures_Extra = 32; // we check also for unknown features - // const unsigned kNumFeatures = ARRAY_SIZE(k_PF) + kNumFeatures_Extra; + // const unsigned kNumFeatures = Z7_ARRAY_SIZE(k_PF) + kNumFeatures_Extra; const unsigned kNumFeatures = 64; UInt64 flags = 0; for (unsigned i = 0; i < kNumFeatures; i++) @@ -617,7 +626,7 @@ { flags += (UInt64)1 << i; // s.Add_Space_if_NotEmpty(); - // s += TypeToString2(k_PF, ARRAY_SIZE(k_PF), i); + // s += TypeToString2(k_PF, Z7_ARRAY_SIZE(k_PF), i); } } s.Add_OptSpaced("f:"); @@ -626,11 +635,10 @@ #elif defined(__APPLE__) { UInt32 v = 0; - if (My_sysctlbyname_Get_UInt32("hw.pagesize", &v) == 0) + if (z7_sysctlbyname_Get_UInt32("hw.pagesize", &v) == 0) { - s += "PageSize:"; - s.Add_UInt32(v >> 10); - s += "KB"; + s.Add_OptSpaced("PageSize:"); + PrintPage(s, v); } } @@ -639,10 +647,8 @@ const long v = sysconf(_SC_PAGESIZE); if (v != -1) { - s.Add_Space_if_NotEmpty(); - s += "PageSize:"; - s.Add_UInt32((UInt32)(v >> 10)); - s += "KB"; + s.Add_OptSpaced("PageSize:"); + PrintPage(s, (unsigned long)v); } #if !defined(_AIX) @@ -659,11 +665,11 @@ const int pos = s2.Find('['); if (pos >= 0) { - const int pos2 = s2.Find(']', pos + 1); + const int pos2 = s2.Find(']', (unsigned)pos + 1); if (pos2 >= 0) { - s2.DeleteFrom(pos2); - s2.DeleteFrontal(pos + 1); + s2.DeleteFrom((unsigned)pos2); + s2.DeleteFrontal((unsigned)pos + 1); } } s += s2; @@ -722,10 +728,13 @@ static BOOL My_RtlGetVersion(OSVERSIONINFOEXW *vi) { - HMODULE ntdll = ::GetModuleHandleW(L"ntdll.dll"); + const HMODULE ntdll = ::GetModuleHandleW(L"ntdll.dll"); if (!ntdll) return FALSE; - Func_RtlGetVersion func = (Func_RtlGetVersion)(void *)GetProcAddress(ntdll, "RtlGetVersion"); + const + Func_RtlGetVersion func = Z7_GET_PROC_ADDRESS( + Func_RtlGetVersion, ntdll, + "RtlGetVersion"); if (!func) return FALSE; func(vi); @@ -752,18 +761,18 @@ s += "Windows"; if (vi.dwPlatformId != VER_PLATFORM_WIN32_NT) s.Add_UInt32(vi.dwPlatformId); - s += " "; s.Add_UInt32(vi.dwMajorVersion); - s += "."; s.Add_UInt32(vi.dwMinorVersion); - s += " "; s.Add_UInt32(vi.dwBuildNumber); + s.Add_Space(); s.Add_UInt32(vi.dwMajorVersion); + s.Add_Dot(); s.Add_UInt32(vi.dwMinorVersion); + s.Add_Space(); s.Add_UInt32(vi.dwBuildNumber); if (vi.wServicePackMajor != 0 || vi.wServicePackMinor != 0) { s += " SP:"; s.Add_UInt32(vi.wServicePackMajor); - s += "."; s.Add_UInt32(vi.wServicePackMinor); + s.Add_Dot(); s.Add_UInt32(vi.wServicePackMinor); } // s += " Suite:"; PrintHex(s, vi.wSuiteMask); // s += " Type:"; s.Add_UInt32(vi.wProductType); - // s += " "; s += GetOemString(vi.szCSDVersion); + // s.Add_Space(); s += GetOemString(vi.szCSDVersion); } /* { @@ -793,6 +802,17 @@ #endif // _WIN32 sRes += s; + #ifdef MY_CPU_X86_OR_AMD64 + { + AString s2; + GetVirtCpuid(s2); + if (!s2.IsEmpty()) + { + sRes += " : "; + sRes += s2; + } + } + #endif } @@ -875,6 +895,61 @@ } } + +#ifdef MY_CPU_X86_OR_AMD64 + +void GetVirtCpuid(AString &s) +{ + const UInt32 kHv = 0x40000000; + + Z7_IF_X86_CPUID_SUPPORTED + { + UInt32 a[4]; + z7_x86_cpuid(a, kHv); + + if (a[0] < kHv || a[0] >= kHv + (1 << 16)) + return; + { + { + for (unsigned j = 1; j < 4; j++) + PrintCpuChars(s, a[j]); + } + } + if (a[0] >= kHv + 1) + { + UInt32 d[4]; + z7_x86_cpuid(d, kHv + 1); + s += " : "; + PrintCpuChars(s, d[0]); + if (a[0] >= kHv + 2) + { + z7_x86_cpuid(d, kHv + 2); + s += " : "; + s.Add_UInt32(d[1] >> 16); + s.Add_Dot(); s.Add_UInt32(d[1] & 0xffff); + s.Add_Dot(); s.Add_UInt32(d[0]); + s.Add_Dot(); s.Add_UInt32(d[2]); + s.Add_Dot(); s.Add_UInt32(d[3] >> 24); + s.Add_Dot(); s.Add_UInt32(d[3] & 0xffffff); + } + /* + if (a[0] >= kHv + 5) + { + z7_x86_cpuid(d, kHv + 5); + s += " : "; + s.Add_UInt32(d[0]); + s += "p"; + s.Add_UInt32(d[1]); + s += "t"; + } + */ + } + } +} + +#endif + + void GetCompiler(AString &s) { #ifdef __VERSION__ @@ -884,28 +959,28 @@ #ifdef __GNUC__ s += " GCC "; s.Add_UInt32(__GNUC__); - s += '.'; + s.Add_Dot(); s.Add_UInt32(__GNUC_MINOR__); - s += '.'; + s.Add_Dot(); s.Add_UInt32(__GNUC_PATCHLEVEL__); #endif #ifdef __clang__ s += " CLANG "; s.Add_UInt32(__clang_major__); - s += '.'; + s.Add_Dot(); s.Add_UInt32(__clang_minor__); #endif #ifdef __xlC__ s += " XLC "; s.Add_UInt32(__xlC__ >> 8); - s += '.'; + s.Add_Dot(); s.Add_UInt32(__xlC__ & 0xFF); #ifdef __xlC_ver__ - s += '.'; + s.Add_Dot(); s.Add_UInt32(__xlC_ver__ >> 8); - s += '.'; + s.Add_Dot(); s.Add_UInt32(__xlC_ver__ & 0xFF); #endif #endif @@ -914,4 +989,34 @@ s += " MSC "; s.Add_UInt32(_MSC_VER); #endif + + #if defined(__AVX2__) + #define MY_CPU_COMPILE_ISA "AVX2" + #elif defined(__AVX__) + #define MY_CPU_COMPILE_ISA "AVX" + #elif defined(__SSE2__) + #define MY_CPU_COMPILE_ISA "SSE2" + #elif defined(_M_IX86_FP) && (_M_IX86_FP >= 2) + #define MY_CPU_COMPILE_ISA "SSE2" + #elif defined(__SSE__) + #define MY_CPU_COMPILE_ISA "SSE" + #elif defined(_M_IX86_FP) && (_M_IX86_FP >= 1) + #define MY_CPU_COMPILE_ISA "SSE" + #elif defined(__i686__) + #define MY_CPU_COMPILE_ISA "i686" + #elif defined(__i586__) + #define MY_CPU_COMPILE_ISA "i586" + #elif defined(__i486__) + #define MY_CPU_COMPILE_ISA "i486" + #elif defined(__i386__) + #define MY_CPU_COMPILE_ISA "i386" + #elif defined(_M_IX86_FP) + #define MY_CPU_COMPILE_ISA "IA32" + #endif + + + #ifdef MY_CPU_COMPILE_ISA + s += ':'; + s.Add_OptSpaced(MY_CPU_COMPILE_ISA); + #endif } diff -Nru 7zip-22.01+dfsg/CPP/Windows/SystemInfo.h 7zip-23.01+dfsg/CPP/Windows/SystemInfo.h --- 7zip-22.01+dfsg/CPP/Windows/SystemInfo.h 2021-07-18 08:15:17.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/SystemInfo.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/SystemInfo.h -#ifndef __WINDOWS_SYSTEM_INFO_H -#define __WINDOWS_SYSTEM_INFO_H +#ifndef ZIP7_INC_WINDOWS_SYSTEM_INFO_H +#define ZIP7_INC_WINDOWS_SYSTEM_INFO_H #include "../Common/MyString.h" @@ -14,5 +14,6 @@ void Add_LargePages_String(AString &s); void GetCompiler(AString &s); +void GetVirtCpuid(AString &s); #endif diff -Nru 7zip-22.01+dfsg/CPP/Windows/Thread.h 7zip-23.01+dfsg/CPP/Windows/Thread.h --- 7zip-22.01+dfsg/CPP/Windows/Thread.h 2021-12-20 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Thread.h 2023-03-04 09:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Thread.h -#ifndef __WINDOWS_THREAD_H -#define __WINDOWS_THREAD_H +#ifndef ZIP7_INC_WINDOWS_THREAD_H +#define ZIP7_INC_WINDOWS_THREAD_H #include "../../C/Threads.h" @@ -13,7 +13,7 @@ { ::CThread thread; public: - CThread() { Thread_Construct(&thread); } + CThread() { Thread_CONSTRUCT(&thread) } ~CThread() { Close(); } bool IsCreated() { return Thread_WasCreated(&thread) != 0; } WRes Close() { return Thread_Close(&thread); } diff -Nru 7zip-22.01+dfsg/CPP/Windows/TimeUtils.cpp 7zip-23.01+dfsg/CPP/Windows/TimeUtils.cpp --- 7zip-22.01+dfsg/CPP/Windows/TimeUtils.cpp 2022-03-29 10:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/TimeUtils.cpp 2023-03-21 07:00:00.000000000 +0000 @@ -258,7 +258,7 @@ FiTime_Clear(ft); struct timeval now; - if (gettimeofday(&now, 0 ) == 0) + if (gettimeofday(&now, NULL) == 0) { ft.tv_sec = now.tv_sec; ft.tv_nsec = now.tv_usec * 1000; @@ -272,7 +272,7 @@ { UInt64 v = 0; struct timeval now; - if (gettimeofday(&now, 0 ) == 0) + if (gettimeofday(&now, NULL) == 0) { v = ((UInt64)now.tv_sec + kUnixTimeOffset) * kNumTimeQuantumsInSecond + (UInt64)now.tv_usec * 10; diff -Nru 7zip-22.01+dfsg/CPP/Windows/TimeUtils.h 7zip-23.01+dfsg/CPP/Windows/TimeUtils.h --- 7zip-22.01+dfsg/CPP/Windows/TimeUtils.h 2022-04-06 09:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/TimeUtils.h 2023-01-10 17:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/TimeUtils.h -#ifndef __WINDOWS_TIME_UTILS_H -#define __WINDOWS_TIME_UTILS_H +#ifndef ZIP7_INC_WINDOWS_TIME_UTILS_H +#define ZIP7_INC_WINDOWS_TIME_UTILS_H #include "../Common/MyTypes.h" #include "../Common/MyWindows.h" diff -Nru 7zip-22.01+dfsg/CPP/Windows/Window.cpp 7zip-23.01+dfsg/CPP/Windows/Window.cpp --- 7zip-22.01+dfsg/CPP/Windows/Window.cpp 2021-01-25 19:10:49.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Window.cpp 2023-01-01 08:00:00.000000000 +0000 @@ -111,7 +111,7 @@ } #endif -bool CWindow::GetText(CSysString &s) +bool CWindow::GetText(CSysString &s) const { s.Empty(); unsigned len = (unsigned)GetTextLength(); @@ -119,7 +119,7 @@ return (::GetLastError() == ERROR_SUCCESS); TCHAR *p = s.GetBuf(len); { - unsigned len2 = (unsigned)GetText(p, (int)(len + 1)); + const unsigned len2 = (unsigned)GetText(p, (int)(len + 1)); if (len > len2) len = len2; } @@ -130,7 +130,7 @@ } #ifndef _UNICODE -bool CWindow::GetText(UString &s) +bool CWindow::GetText(UString &s) const { if (g_IsNT) { @@ -140,7 +140,7 @@ return (::GetLastError() == ERROR_SUCCESS); wchar_t *p = s.GetBuf(len); { - unsigned len2 = (unsigned)GetWindowTextW(_window, p, (int)(len + 1)); + const unsigned len2 = (unsigned)GetWindowTextW(_window, p, (int)(len + 1)); if (len > len2) len = len2; } @@ -150,7 +150,7 @@ return true; } CSysString sysString; - bool result = GetText(sysString); + const bool result = GetText(sysString); MultiByteToUnicodeString2(s, sysString); return result; } diff -Nru 7zip-22.01+dfsg/CPP/Windows/Window.h 7zip-23.01+dfsg/CPP/Windows/Window.h --- 7zip-22.01+dfsg/CPP/Windows/Window.h 2021-01-24 14:35:02.000000000 +0000 +++ 7zip-23.01+dfsg/CPP/Windows/Window.h 2023-03-21 12:00:00.000000000 +0000 @@ -1,7 +1,7 @@ // Windows/Window.h -#ifndef __WINDOWS_WINDOW_H -#define __WINDOWS_WINDOW_H +#ifndef ZIP7_INC_WINDOWS_WINDOW_H +#define ZIP7_INC_WINDOWS_WINDOW_H #include "../Common/MyWindows.h" #include "../Common/MyString.h" @@ -9,23 +9,100 @@ #include "Defs.h" #ifndef UNDER_CE +#ifdef WM_CHANGEUISTATE +#define Z7_WIN_WM_CHANGEUISTATE WM_CHANGEUISTATE +#define Z7_WIN_WM_UPDATEUISTATE WM_UPDATEUISTATE +#define Z7_WIN_WM_QUERYUISTATE WM_QUERYUISTATE +#else +// these are defined for (_WIN32_WINNT >= 0x0500): +#define Z7_WIN_WM_CHANGEUISTATE 0x0127 +#define Z7_WIN_WM_UPDATEUISTATE 0x0128 +#define Z7_WIN_WM_QUERYUISTATE 0x0129 +#endif + +#ifdef UIS_SET + +#define Z7_WIN_UIS_SET UIS_SET +#define Z7_WIN_UIS_CLEAR UIS_CLEAR +#define Z7_WIN_UIS_INITIALIZE UIS_INITIALIZE -#define MY__WM_CHANGEUISTATE 0x0127 -#define MY__WM_UPDATEUISTATE 0x0128 -#define MY__WM_QUERYUISTATE 0x0129 +#define Z7_WIN_UISF_HIDEFOCUS UISF_HIDEFOCUS +#define Z7_WIN_UISF_HIDEACCEL UISF_HIDEACCEL +#else +// these are defined for (_WIN32_WINNT >= 0x0500): // LOWORD(wParam) values in WM_*UISTATE -#define MY__UIS_SET 1 -#define MY__UIS_CLEAR 2 -#define MY__UIS_INITIALIZE 3 +#define Z7_WIN_UIS_SET 1 +#define Z7_WIN_UIS_CLEAR 2 +#define Z7_WIN_UIS_INITIALIZE 3 // HIWORD(wParam) values in WM_*UISTATE -#define MY__UISF_HIDEFOCUS 0x1 -#define MY__UISF_HIDEACCEL 0x2 -#define MY__UISF_ACTIVE 0x4 +#define Z7_WIN_UISF_HIDEFOCUS 0x1 +#define Z7_WIN_UISF_HIDEACCEL 0x2 +// defined for for (_WIN32_WINNT >= 0x0501): +// #define Z7_WIN_UISF_ACTIVE 0x4 #endif +#endif // UNDER_CE + + +#ifdef Z7_OLD_WIN_SDK + +// #define VK_OEM_1 0xBA // ';:' for US +#define VK_OEM_PLUS 0xBB // '+' any country +// #define VK_OEM_COMMA 0xBC // ',' any country +#define VK_OEM_MINUS 0xBD // '-' any country +// #define VK_OEM_PERIOD 0xBE // '.' any country +// #define VK_OEM_2 0xBF // '/?' for US +// #define VK_OEM_3 0xC0 // '`~' for US + +// #ifndef GWLP_USERDATA +#define GWLP_WNDPROC (-4) +#define GWLP_USERDATA (-21) +// #endif +#define DWLP_MSGRESULT 0 +// #define DWLP_DLGPROC DWLP_MSGRESULT + sizeof(LRESULT) +// #define DWLP_USER DWLP_DLGPROC + sizeof(DLGPROC) + +#define BTNS_BUTTON TBSTYLE_BUTTON // 0x0000 + +/* +vc6 defines INT_PTR via long: + typedef long INT_PTR, *PINT_PTR; + typedef unsigned long UINT_PTR, *PUINT_PTR; +but newer sdk (sdk2003+) defines INT_PTR via int: + typedef _W64 int INT_PTR, *PINT_PTR; + typedef _W64 unsigned int UINT_PTR, *PUINT_PTR; +*/ + +#define IS_INTRESOURCE(_r) (((ULONG_PTR)(_r) >> 16) == 0) + +#define GetWindowLongPtrA GetWindowLongA +#define GetWindowLongPtrW GetWindowLongW +#ifdef UNICODE +#define GetWindowLongPtr GetWindowLongPtrW +#else +#define GetWindowLongPtr GetWindowLongPtrA +#endif // !UNICODE + +#define SetWindowLongPtrA SetWindowLongA +#define SetWindowLongPtrW SetWindowLongW +#ifdef UNICODE +#define SetWindowLongPtr SetWindowLongPtrW +#else +#define SetWindowLongPtr SetWindowLongPtrA +#endif // !UNICODE + +#define ListView_SetCheckState(hwndLV, i, fCheck) \ + ListView_SetItemState(hwndLV, i, INDEXTOSTATEIMAGEMASK((fCheck)?2:1), LVIS_STATEIMAGEMASK) + +#endif // Z7_OLD_WIN_SDK + +inline bool LRESULTToBool(LRESULT v) { return (v != FALSE); } + +#define MY_int_TO_WPARAM(i) ((WPARAM)(INT_PTR)(i)) + namespace NWindows { inline ATOM MyRegisterClass(CONST WNDCLASS *wndClass) @@ -52,12 +129,13 @@ class CWindow { + Z7_CLASS_NO_COPY(CWindow) private: - // bool ModifyStyleBase(int styleOffset, DWORD remove, DWORD add, UINT flags); + // bool ModifyStyleBase(int styleOffset, DWORD remove, DWORD add, UINT flags); protected: HWND _window; public: - CWindow(HWND newWindow = NULL): _window(newWindow){}; + CWindow(HWND newWindow = NULL): _window(newWindow) {} CWindow& operator=(HWND newWindow) { _window = newWindow; @@ -174,6 +252,7 @@ void SetRedraw(bool redraw = true) { SendMsg(WM_SETREDRAW, (WPARAM)BoolToBOOL(redraw), 0); } LONG_PTR SetStyle(LONG_PTR style) { return SetLongPtr(GWL_STYLE, style); } + // LONG_PTR SetStyle(DWORD style) { return SetLongPtr(GWL_STYLE, (LONG_PTR)style); } LONG_PTR GetStyle() const { return GetLongPtr(GWL_STYLE); } // bool MyIsMaximized() const { return ((GetStyle() & WS_MAXIMIZE) != 0); } @@ -246,19 +325,19 @@ { return GetWindowTextLength(_window); } int GetText(LPTSTR string, int maxCount) const { return GetWindowText(_window, string, maxCount); } - bool GetText(CSysString &s); + bool GetText(CSysString &s) const; #ifndef _UNICODE /* UINT GetText(LPWSTR string, int maxCount) const { return GetWindowTextW(_window, string, maxCount); } */ - bool GetText(UString &s); + bool GetText(UString &s) const; #endif bool Enable(bool enable) { return BOOLToBool(::EnableWindow(_window, BoolToBOOL(enable))); } - bool IsEnabled() + bool IsEnabled() const { return BOOLToBool(::IsWindowEnabled(_window)); } #ifndef UNDER_CE @@ -266,7 +345,7 @@ { return ::GetSystemMenu(_window, BoolToBOOL(revert)); } #endif - UINT_PTR SetTimer(UINT_PTR idEvent, UINT elapse, TIMERPROC timerFunc = 0) + UINT_PTR SetTimer(UINT_PTR idEvent, UINT elapse, TIMERPROC timerFunc = NULL) { return ::SetTimer(_window, idEvent, elapse, timerFunc); } bool KillTimer(UINT_PTR idEvent) {return BOOLToBool(::KillTimer(_window, idEvent)); } diff -Nru 7zip-22.01+dfsg/debian/7zip.docs 7zip-23.01+dfsg/debian/7zip.docs --- 7zip-22.01+dfsg/debian/7zip.docs 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/7zip.docs 2023-06-20 20:43:43.000000000 +0000 @@ -0,0 +1,6 @@ +DOC/7zC.txt +DOC/7zFormat.txt +DOC/lzma.txt +DOC/Methods.txt +DOC/readme.txt +DOC/src-history.txt diff -Nru 7zip-22.01+dfsg/debian/7zip.install 7zip-23.01+dfsg/debian/7zip.install --- 7zip-22.01+dfsg/debian/7zip.install 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/7zip.install 2023-06-20 20:43:43.000000000 +0000 @@ -0,0 +1,13 @@ +#! /usr/bin/dh-exec +CPP/7zip/Bundles/Alone/b/g/7za usr/lib/7zip +CPP/7zip/Bundles/Alone2/b/g/7zz usr/lib/7zip +CPP/7zip/Bundles/Alone7z/b/g/7zr usr/lib/7zip +CPP/7zip/Bundles/Format7zF/b/g/7z.so usr/lib/7zip +CPP/7zip/UI/Console/b/g/7z usr/lib/7zip +# +CPP/7zip/Bundles/SFXCon/b/g/7zCon => usr/lib/7zip/7zCon.sfx +# +debian/scripts/7z.sh => usr/bin/7z.7zip +debian/scripts/7za.sh => usr/bin/7za.7zip +debian/scripts/7zr.sh => usr/bin/7zr.7zip +debian/scripts/7zz.sh => usr/bin/7zz diff -Nru 7zip-22.01+dfsg/debian/7zip.manpages 7zip-23.01+dfsg/debian/7zip.manpages --- 7zip-22.01+dfsg/debian/7zip.manpages 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/7zip.manpages 2023-06-20 20:43:43.000000000 +0000 @@ -0,0 +1,4 @@ +debian/man/7z.7zip.1 +debian/man/7zz.1 +debian/man/7za.7zip.1 +debian/man/7zr.7zip.1 diff -Nru 7zip-22.01+dfsg/debian/7zz.1 7zip-23.01+dfsg/debian/7zz.1 --- 7zip-22.01+dfsg/debian/7zz.1 2021-12-28 08:55:14.000000000 +0000 +++ 7zip-23.01+dfsg/debian/7zz.1 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ -.\" -.TH 7zz "1" "August 2021" "21.03" -.SH NAME -7zz \- 7-Zip file archiver with a high compression ratio -.SH SYNOPSIS -.SY 7zz -\fI\,command\/\fR -[\fI\,switches\/\fR\&.\|.\|.\&] -\fI\,archive_name\/\fR -[\fI\,file_names\/\fR] -[@\fI\,listfile\/\fR] -.YS -.SH DESCRIPTION -7-Zip file archiver with a high compression ratio -.SH OPTIONS -.SS Commands -.TP -a -Add files to archive -.TP -b -Benchmark -.TP -d -Delete files from archive -.TP -e -Extract files from archive (without using directory names) -.TP -h -Calculate hash values for files -.TP -i -Show information about supported formats -.TP -l -List contents of archive -.TP -rn -Rename files in archive -.TP -t -Test integrity of archive -.TP -u -Update files to archive -.TP -x -eXtract files with full paths -.SS Switches -.TP -\-\- -Stop switches and @\fI\,listfile\/\fR parsing -.TP -\-ai[r[\-|0]]{@\fI\,listfile\/\fR|!\fI\,wildcard\/\fR} -Include archives -.TP -\-ax[r[\-|0]]{@\fI\,listfile\/\fR|!\fI\,wildcard\/\fR} -eXclude archives -.TP -\-ao{a|s|t|u} -set Overwrite mode -.TP -\-an -disable archive_name field -.TP -\-bb[0\-3] -set output log level -.TP -\-bd -disable progress indicator -.TP -\-bs{o|e|p}{0|1|2} -set output stream for output/error/progress line -.TP -\-bt -show execution time statistics -.TP -\-i[r[\-|0]]{@\fI\,listfile\/\fR|!\fI\,wildcard\/\fR} -Include filenames -.TP -\-m{\fI\,Parameters\/\fR} -set compression Method -.RS -.TQ -\-mmt[\fI\,N\/\fR] -set number of CPU threads -.TQ -\-mx[\fI\,N\/\fR] -set compression level: \-mx1 (fastest) ... \-mx9 (ultra) -.RE -.TP -\-o{\fI\,Directory\/\fR} -set Output directory -.TP -\-p{\fI\,Password\/\fR} -set Password -.TP -\-r[\-|0] -Recurse subdirectories for name search -.TP -\-sa{a|e|s} -set Archive name mode -.TP -\-scc{UTF\-8|WIN|DOS} -set charset for for console input/output -.TP -\-scs{UTF\-8|UTF\-16LE|UTF\-16BE|WIN|DOS|{\fI\,id\/\fR}} -set charset for list files -.TP -\-scrc[CRC32|CRC64|SHA1|SHA256|*] -set hash function for \fBx\fR, \fBe\fR, \fBh\fR commands -.TP -\-sdel -delete files after compression -.TP -\-seml[.] -send archive by email -.TP -\-sfx[{\fI\,name\/\fR}] -Create SFX archive -.TP -\-si[{\fI\,name\/\fR}] -read data from stdin -.TP -\-slp -set Large Pages mode -.TP -\-slt -show technical information for \fBl\fR (List) command -.TP -\-snh -store hard links as links -.TP -\-snl -store symbolic links as links -.TP -\-sni -store NT security information -.TP -\-sns[\-] -store NTFS alternate streams -.TP -\-so -write data to stdout -.TP -\-spd -disable wildcard matching for file names -.TP -\-spe -eliminate duplication of root folder for extract command -.TP -\-spf -use fully qualified file paths -.TP -\-ssc[\-] -set sensitive case mode -.TP -\-sse -stop archive creating, if it can't open some input file -.TP -\-ssp -do not change Last Access Time of source files while archiving -.TP -\-ssw -compress shared files -.TP -\-stl -set archive timestamp from the most recently modified file -.TP -\-stm{\fI\,HexMask\/\fR} -set CPU thread affinity mask (hexadecimal number) -.TP -\-stx{\fI\,Type\/\fR} -exclude archive type -.TP -\-t{\fI\,Type\/\fR} -Set type of archive -.TP -\-u[\-][p\fI\,#\/\fR][q\fI\,#\/\fR][r\fI\,#\/\fR][x\fI\,#\/\fR][y\fI\,#\/\fR][z\fI\,#\/\fR][!\fI\,newArchiveName\/\fR] -Update options -.TP -\-v{\fI\,Size\/\fR}[b|k|m|g] -Create volumes -.TP -\-w[{\fI\,path\/\fR}] -assign Work directory. Empty path means a temporary directory -.TP -\-x[r[\-|0]]{@\fI\,listfile\/\fR|!\fI\,wildcard\/\fR} -eXclude filenames -.TP -\-y -assume Yes on all queries -.SH SEE ALSO -7-Zip -.UR https://\:www.7-zip.org/ -.UE -.SH COPYRIGHT -Copyright \(co 1999\-2021 Igor Pavlov. -.br -Distributed under the LGPL-2.1+ license. diff -Nru 7zip-22.01+dfsg/debian/changelog 7zip-23.01+dfsg/debian/changelog --- 7zip-22.01+dfsg/debian/changelog 2022-07-28 20:48:59.000000000 +0000 +++ 7zip-23.01+dfsg/debian/changelog 2023-07-10 10:08:28.000000000 +0000 @@ -1,11 +1,121 @@ -7zip (22.01+dfsg-1~16.04.sav0) xenial; urgency=medium +7zip (23.01+dfsg-3~16.04.sav0) xenial; urgency=medium * Backport to Xenial - * Revert "Use GCC 10 warning options" (building with GCC 9) * debian/control: Set debhelper-compat (= 10) BD (LP highest for Xenial) - Add g++ (>= 4:9.3.0-1~) BD (ppa:savoury1/gcc-defaults-9) - -- Rob Savoury Thu, 28 Jul 2022 13:48:59 -0700 + -- Rob Savoury Mon, 10 Jul 2023 20:08:28 +1000 + +7zip (23.01+dfsg-3) unstable; urgency=medium + + * Rediff patches + * Forward patches to upstream + * Revise armhf patch + + -- YOKOTA Hiroshi Fri, 23 Jun 2023 08:10:08 +0900 + +7zip (23.01+dfsg-2) unstable; urgency=medium + + * Compilation fix for armel/armhf/powerpc + + -- YOKOTA Hiroshi Wed, 21 Jun 2023 12:52:27 +0900 + +7zip (23.01+dfsg-1) unstable; urgency=medium + + * Rediff patches + * Remove unwanted exec permissions + * New upstream version 23.01+dfsg + * Rediff patches + * Rediff patches + * Renumber patches + + -- YOKOTA Hiroshi Wed, 21 Jun 2023 03:29:25 +0900 + +7zip (22.01+dfsg-9) unstable; urgency=medium + + This version provides 7z/7za/7zr commands as 7z.7zip/7za.7zip/7zr.7zip . + + * Remove unwanted exec permissions when importing from upstream tarball + * Strict paths in post-unpack hook + * Remove unwanted exec permissions + * Rediff patches + * Build other flavors binary + * Use dh-exec to install with another name + * Update ignore list + * Install files to another place + * Install trampoline scripts to invoke real executable + * Install "7za" and "7zr" + * Move manual path + * Add alternative selection + * Update clean target + * Add "7zip" prefix to packager files + * Update ignore list + * Rediff patches + * Use conf-mode + * Add tests for other binaries + * Show supported format list + * Enable Rar format for 7z as "p7zip" package + * Mention "7zip-rar" package to support RAR files + * Update copyright years + * Text fix + * Update manual page + * Add manuals for variant binaries + * Update alternative list + * Disable alternative selection + * Add some text about variant commands to manual page + * Fixup test code + * Rediff patches + + -- YOKOTA Hiroshi Wed, 31 May 2023 23:03:45 +0900 + +7zip (22.01+dfsg-8) unstable; urgency=medium + + * Upgrade Debian standards + + -- YOKOTA Hiroshi Sun, 18 Dec 2022 21:09:42 +0900 + +7zip (22.01+dfsg-7) unstable; urgency=medium + + Reproducible build tester in Sid (unstable) fails to strip some debug infos + like build paths. This makes fail to reproducible build. + + * Rediff patches + * Revert "Enable link time optimization (LTO)" + + -- YOKOTA Hiroshi Fri, 09 Dec 2022 20:26:57 +0900 + +7zip (22.01+dfsg-6) unstable; urgency=medium + + * Remove unwanted hack for object files + + -- YOKOTA Hiroshi Wed, 07 Dec 2022 21:34:51 +0900 + +7zip (22.01+dfsg-5) unstable; urgency=medium + + * Enable link time optimization (LTO) + * Manually de-reference pointers + + -- YOKOTA Hiroshi Sat, 03 Dec 2022 19:40:39 +0900 + +7zip (22.01+dfsg-4) unstable; urgency=medium + + * Revert "Enable link time optimization (LTO)" + * Revert "Manually de-reference pointers" + + -- YOKOTA Hiroshi Sat, 27 Aug 2022 20:28:56 +0900 + +7zip (22.01+dfsg-3) unstable; urgency=medium + + * Enable link time optimization (LTO) + * Manually de-reference pointers + + -- YOKOTA Hiroshi Sat, 27 Aug 2022 15:02:19 +0900 + +7zip (22.01+dfsg-2) unstable; urgency=medium + + * Rebuild with GCC 12 (Closes: #1012886) + + -- YOKOTA Hiroshi Sat, 23 Jul 2022 10:16:24 +0900 7zip (22.01+dfsg-1) unstable; urgency=medium diff -Nru 7zip-22.01+dfsg/debian/control 7zip-23.01+dfsg/debian/control --- 7zip-22.01+dfsg/debian/control 2022-07-07 20:15:24.000000000 +0000 +++ 7zip-23.01+dfsg/debian/control 2023-07-10 10:08:26.000000000 +0000 @@ -3,8 +3,8 @@ Priority: optional Maintainer: YOKOTA Hiroshi Uploaders: Dylan Aïssi -Build-Depends: debhelper-compat (= 10), g++ (>= 4:9.3.0-1~) -Standards-Version: 4.6.1 +Build-Depends: debhelper-compat (= 10), dh-exec, g++ (>= 4:9.3.0-1~) +Standards-Version: 4.6.2 Rules-Requires-Root: no Homepage: https://www.7-zip.org/ Vcs-Git: https://salsa.debian.org/debian/7zip.git @@ -13,6 +13,7 @@ Package: 7zip Architecture: any Depends: ${misc:Depends}, ${shlibs:Depends} +Suggests: 7zip-rar Description: 7-Zip file archiver with a high compression ratio 7-Zip is a file archiver with a high compression ratio. The main features of 7-Zip are: @@ -28,3 +29,4 @@ * Powerful command line version . Note: The unRAR code was dropped to keep compatible with DFSG. + Install 7zip-rar pacakge in non-free section to use RAR files. diff -Nru 7zip-22.01+dfsg/debian/copyright 7zip-23.01+dfsg/debian/copyright --- 7zip-22.01+dfsg/debian/copyright 2021-12-28 08:55:14.000000000 +0000 +++ 7zip-23.01+dfsg/debian/copyright 2023-06-20 20:43:43.000000000 +0000 @@ -154,7 +154,7 @@ Files: debian/* Copyright: 2021 Collabora, Ltd. - 2021 YOKOTA Hiroshi + 2021-2023 YOKOTA Hiroshi License: LGPL-2.1+ License: LGPL-2.1+ diff -Nru 7zip-22.01+dfsg/debian/docs 7zip-23.01+dfsg/debian/docs --- 7zip-22.01+dfsg/debian/docs 2021-12-28 08:55:14.000000000 +0000 +++ 7zip-23.01+dfsg/debian/docs 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -DOC/7zC.txt -DOC/7zFormat.txt -DOC/lzma.txt -DOC/Methods.txt -DOC/readme.txt -DOC/src-history.txt diff -Nru 7zip-22.01+dfsg/debian/gbp.conf 7zip-23.01+dfsg/debian/gbp.conf --- 7zip-22.01+dfsg/debian/gbp.conf 2021-12-28 08:55:14.000000000 +0000 +++ 7zip-23.01+dfsg/debian/gbp.conf 2023-06-20 20:43:43.000000000 +0000 @@ -1,2 +1,3 @@ [import-orig] pristine-tar = True +postunpack = find Asm C CPP DOC -type f -execdir chmod -x {} ";" diff -Nru 7zip-22.01+dfsg/debian/install 7zip-23.01+dfsg/debian/install --- 7zip-22.01+dfsg/debian/install 2021-12-28 08:55:14.000000000 +0000 +++ 7zip-23.01+dfsg/debian/install 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -CPP/7zip/Bundles/Alone2/b/g/7zz usr/bin/ diff -Nru 7zip-22.01+dfsg/debian/man/7z.7zip.1 7zip-23.01+dfsg/debian/man/7z.7zip.1 --- 7zip-22.01+dfsg/debian/man/7z.7zip.1 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/man/7z.7zip.1 2023-06-20 20:43:43.000000000 +0000 @@ -0,0 +1,237 @@ +.\" +.TH 7z "1" "May 2023" "22.01" +.SH NAME +7z \- 7-Zip file archiver with a high compression ratio +.SH SYNOPSIS +.SY 7z +\fI\,command\/\fR +[\fI\,switches\/\fR\&.\|.\|.\&] +\fI\,archive_name\/\fR +[\fI\,file_names\/\fR] +[@\fI\,listfile\/\fR] +.YS +.SY 7zz +\fI\,command\/\fR +[\fI\,switches\/\fR\&.\|.\|.\&] +\fI\,archive_name\/\fR +[\fI\,file_names\/\fR] +[@\fI\,listfile\/\fR] +.YS +.SY 7za +\fI\,command\/\fR +[\fI\,switches\/\fR\&.\|.\|.\&] +\fI\,archive_name\/\fR +[\fI\,file_names\/\fR] +[@\fI\,listfile\/\fR] +.YS +.SY 7zr +\fI\,command\/\fR +[\fI\,switches\/\fR\&.\|.\|.\&] +\fI\,archive_name\/\fR +[\fI\,file_names\/\fR] +[@\fI\,listfile\/\fR] +.YS +.SH DESCRIPTION +7-Zip file archiver with a high compression ratio +.br +There are some variants for 7z executable. +.TP +7z +Full featured with plugin support +.TP +7zz +Full featured single binary executable without plugin support +.TP +7za +Supports major formats only, but smaller excutable size +.TP +7zr +Only supports LZMA codec and related formats (7z, lzma, xz), +but smallest binary size +.SH OPTIONS +.SS Commands +.TP +a +Add files to archive +.TP +b +Benchmark +.TP +d +Delete files from archive +.TP +e +Extract files from archive (without using directory names) +.TP +h +Calculate hash values for files +.TP +i +Show information about supported formats +.TP +l +List contents of archive +.TP +rn +Rename files in archive +.TP +t +Test integrity of archive +.TP +u +Update files to archive +.TP +x +eXtract files with full paths +.SS Switches +.TP +\-\- +Stop switches and @\fI\,listfile\/\fR parsing +.TP +\-ai[r[\-|0]]{@\fI\,listfile\/\fR|!\fI\,wildcard\/\fR} +Include archives +.TP +\-ax[r[\-|0]]{@\fI\,listfile\/\fR|!\fI\,wildcard\/\fR} +eXclude archives +.TP +\-ao{a|s|t|u} +set Overwrite mode +.TP +\-an +disable archive_name field +.TP +\-bb[0\-3] +set output log level +.TP +\-bd +disable progress indicator +.TP +\-bs{o|e|p}{0|1|2} +set output stream for output/error/progress line +.TP +\-bt +show execution time statistics +.TP +\-i[r[\-|0]]{@\fI\,listfile\/\fR|!\fI\,wildcard\/\fR} +Include filenames +.TP +\-m{\fI\,Parameters\/\fR} +set compression Method +.RS +.TQ +\-mmt[\fI\,N\/\fR] +set number of CPU threads +.TQ +\-mx[\fI\,N\/\fR] +set compression level: \-mx1 (fastest) ... \-mx9 (ultra) +.RE +.TP +\-o{\fI\,Directory\/\fR} +set Output directory +.TP +\-p{\fI\,Password\/\fR} +set Password +.TP +\-r[\-|0] +Recurse subdirectories for name search +.TP +\-sa{a|e|s} +set Archive name mode +.TP +\-scc{UTF\-8|WIN|DOS} +set charset for for console input/output +.TP +\-scs{UTF\-8|UTF\-16LE|UTF\-16BE|WIN|DOS|{\fI\,id\/\fR}} +set charset for list files +.TP +\-scrc[CRC32|CRC64|SHA1|SHA256|*] +set hash function for \fBx\fR, \fBe\fR, \fBh\fR commands +.TP +\-sdel +delete files after compression +.TP +\-seml[.] +send archive by email +.TP +\-sfx[{\fI\,name\/\fR}] +Create SFX archive +.TP +\-si[{\fI\,name\/\fR}] +read data from stdin +.TP +\-slp +set Large Pages mode +.TP +\-slt +show technical information for \fBl\fR (List) command +.TP +\-snh +store hard links as links +.TP +\-snl +store symbolic links as links +.TP +\-sni +store NT security information +.TP +\-sns[\-] +store NTFS alternate streams +.TP +\-so +write data to stdout +.TP +\-spd +disable wildcard matching for file names +.TP +\-spe +eliminate duplication of root folder for extract command +.TP +\-spf +use fully qualified file paths +.TP +\-ssc[\-] +set sensitive case mode +.TP +\-sse +stop archive creating, if it can't open some input file +.TP +\-ssp +do not change Last Access Time of source files while archiving +.TP +\-ssw +compress shared files +.TP +\-stl +set archive timestamp from the most recently modified file +.TP +\-stm{\fI\,HexMask\/\fR} +set CPU thread affinity mask (hexadecimal number) +.TP +\-stx{\fI\,Type\/\fR} +exclude archive type +.TP +\-t{\fI\,Type\/\fR} +Set type of archive +.TP +\-u[\-][p\fI\,#\/\fR][q\fI\,#\/\fR][r\fI\,#\/\fR][x\fI\,#\/\fR][y\fI\,#\/\fR][z\fI\,#\/\fR][!\fI\,newArchiveName\/\fR] +Update options +.TP +\-v{\fI\,Size\/\fR}[b|k|m|g] +Create volumes +.TP +\-w[{\fI\,path\/\fR}] +assign Work directory. Empty path means a temporary directory +.TP +\-x[r[\-|0]]{@\fI\,listfile\/\fR|!\fI\,wildcard\/\fR} +eXclude filenames +.TP +\-y +assume Yes on all queries +.SH SEE ALSO +7-Zip +.UR https://\:www.7-zip.org/ +.UE +.SH COPYRIGHT +Copyright \(co 1999\-2023 Igor Pavlov. +.br +Distributed under the LGPL-2.1+ license. diff -Nru 7zip-22.01+dfsg/debian/man/7za.7zip.1 7zip-23.01+dfsg/debian/man/7za.7zip.1 --- 7zip-22.01+dfsg/debian/man/7za.7zip.1 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/man/7za.7zip.1 2023-06-20 20:43:43.000000000 +0000 @@ -0,0 +1 @@ +.so man1/7z.7zip.1 diff -Nru 7zip-22.01+dfsg/debian/man/7zr.7zip.1 7zip-23.01+dfsg/debian/man/7zr.7zip.1 --- 7zip-22.01+dfsg/debian/man/7zr.7zip.1 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/man/7zr.7zip.1 2023-06-20 20:43:43.000000000 +0000 @@ -0,0 +1 @@ +.so man1/7z.7zip.1 diff -Nru 7zip-22.01+dfsg/debian/man/7zz.1 7zip-23.01+dfsg/debian/man/7zz.1 --- 7zip-22.01+dfsg/debian/man/7zz.1 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/man/7zz.1 2023-06-20 20:43:43.000000000 +0000 @@ -0,0 +1 @@ +.so man1/7z.7zip.1 diff -Nru 7zip-22.01+dfsg/debian/manpages 7zip-23.01+dfsg/debian/manpages --- 7zip-22.01+dfsg/debian/manpages 2021-12-28 08:55:14.000000000 +0000 +++ 7zip-23.01+dfsg/debian/manpages 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -debian/7zz.1 diff -Nru 7zip-22.01+dfsg/debian/patches/0001-Accept-Debian-build-flags.patch 7zip-23.01+dfsg/debian/patches/0001-Accept-Debian-build-flags.patch --- 7zip-22.01+dfsg/debian/patches/0001-Accept-Debian-build-flags.patch 2022-07-16 13:50:37.000000000 +0000 +++ 7zip-23.01+dfsg/debian/patches/0001-Accept-Debian-build-flags.patch 2023-06-22 17:45:47.000000000 +0000 @@ -4,46 +4,54 @@ Forwarded: not-needed --- - CPP/7zip/7zip_gcc.mak | 8 ++++---- - 1 file changed, 4 insertions(+), 4 deletions(-) + CPP/7zip/7zip_gcc.mak | 10 +++++----- + 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/CPP/7zip/7zip_gcc.mak b/CPP/7zip/7zip_gcc.mak -index 2a24e06..090e498 100755 +index a8eb6e3..0bb776d 100644 --- a/CPP/7zip/7zip_gcc.mak +++ b/CPP/7zip/7zip_gcc.mak -@@ -82,7 +82,7 @@ endif +@@ -87,14 +87,14 @@ SHARED_EXT=.dll + LDFLAGS = -shared -DEF $(DEF_FILE) $(LDFLAGS_STATIC) + else + SHARED_EXT=.so +-LDFLAGS = -shared -fPIC $(LDFLAGS_STATIC) ++LDFLAGS = -shared -fPIC $(DEB_LDFLAGS) $(LDFLAGS_STATIC) + CC_SHARED=-fPIC + endif + else -LDFLAGS = $(LDFLAGS_STATIC) +LDFLAGS = $(DEB_LDFLAGS) $(LDFLAGS_STATIC) - # -s is not required for clang, do we need it for GGC ??? - # -s + # -s is not required for clang, do we need it for GCC ??? -@@ -138,7 +138,7 @@ endif + #-static -static-libgcc -static-libstdc++ +@@ -149,7 +149,7 @@ endif --CFLAGS = $(MY_ARCH_2) $(LOCAL_FLAGS) $(CFLAGS_BASE2) $(CFLAGS_BASE) $(CC_SHARED) -o $@ -+CFLAGS = $(DEB_CFLAGS) $(DEB_CPPFLAGS) $(MY_ARCH_2) $(LOCAL_FLAGS) $(CFLAGS_BASE2) $(CFLAGS_BASE) $(CC_SHARED) -o $@ +-CFLAGS = $(MY_ARCH_2) $(LOCAL_FLAGS) $(CFLAGS_BASE2) $(CFLAGS_BASE) $(FLAGS_FLTO) $(CC_SHARED) -o $@ ++CFLAGS = $(DEB_CFLAGS) $(DEB_CPPFLAGS) $(MY_ARCH_2) $(LOCAL_FLAGS) $(CFLAGS_BASE2) $(CFLAGS_BASE) $(FLAGS_FLTO) $(CC_SHARED) -o $@ ifdef IS_MINGW -@@ -179,7 +179,7 @@ CXX_WARN_FLAGS = +@@ -190,7 +190,7 @@ CXX_WARN_FLAGS = #-Wno-invalid-offsetof #-Wno-reorder --CXXFLAGS = $(MY_ARCH_2) $(LOCAL_FLAGS) $(CXXFLAGS_BASE2) $(CFLAGS_BASE) $(CXXFLAGS_EXTRA) $(CC_SHARED) -o $@ $(CXX_WARN_FLAGS) -+CXXFLAGS = $(DEB_CXXFLAGS) $(DEB_CPPFLAGS) $(MY_ARCH_2) $(LOCAL_FLAGS) $(CXXFLAGS_BASE2) $(CFLAGS_BASE) $(CXXFLAGS_EXTRA) $(CC_SHARED) -o $@ $(CXX_WARN_FLAGS) +-CXXFLAGS = $(MY_ARCH_2) $(LOCAL_FLAGS) $(CXXFLAGS_BASE2) $(CFLAGS_BASE) $(FLAGS_FLTO) $(CXXFLAGS_EXTRA) $(CC_SHARED) $(CXX_WARN_FLAGS) $(CXX_STD_FLAGS) -o $@ ++CXXFLAGS = $(DEB_CXXFLAGS) $(DEB_CPPFLAGS) $(MY_ARCH_2) $(LOCAL_FLAGS) $(CXXFLAGS_BASE2) $(CFLAGS_BASE) $(FLAGS_FLTO) $(CXXFLAGS_EXTRA) $(CC_SHARED) $(CXX_WARN_FLAGS) $(CXX_STD_FLAGS) -o $@ STATIC_TARGET= ifdef COMPL_STATIC -@@ -192,7 +192,7 @@ all: $(O) $(PROGPATH) $(STATIC_TARGET) - $(O): - $(MY_MKDIR) $(O) - --LFLAGS_ALL = -s $(MY_ARCH_2) $(LDFLAGS) $(LD_arch) $(OBJS) $(MY_LIBS) $(LIB2) -+LFLAGS_ALL = $(MY_ARCH_2) $(LDFLAGS) $(LD_arch) $(OBJS) $(MY_LIBS) $(LIB2) - $(PROGPATH): $(OBJS) - $(CXX) -o $(PROGPATH) $(LFLAGS_ALL) +@@ -208,7 +208,7 @@ $(O): + # -Wl,--print-gc-sections + + ifneq ($(CC), $(CROSS_COMPILE)clang) +-LFLAGS_STRIP = -s ++LFLAGS_STRIP = + endif + LFLAGS_ALL = $(LFLAGS_STRIP) $(MY_ARCH_2) $(LDFLAGS) $(FLAGS_FLTO) $(LD_arch) $(OBJS) $(MY_LIBS) $(LIB2) diff -Nru 7zip-22.01+dfsg/debian/patches/0002-Disable-hardware-acceleration-support-on-armel.patch 7zip-23.01+dfsg/debian/patches/0002-Disable-hardware-acceleration-support-on-armel.patch --- 7zip-22.01+dfsg/debian/patches/0002-Disable-hardware-acceleration-support-on-armel.patch 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/patches/0002-Disable-hardware-acceleration-support-on-armel.patch 2023-06-22 17:45:47.000000000 +0000 @@ -0,0 +1,164 @@ +From: YOKOTA Hiroshi +Date: Tue, 14 Sep 2021 23:51:04 +0900 +Subject: Disable hardware acceleration support on armel + +Forwarded: https://sourceforge.net/p/sevenzip/patches/369/ + +Use "__ARM_ARCH" to split "armel" and "armhf". + +ARM v7 feature breaks ARM v5 compiler because the feature is not supported +by ARM v5 compiler. + +__ARM_ARCH: + armel = 5 + armhf = 7 +--- + C/Aes.c | 2 ++ + C/AesOpt.c | 2 ++ + C/Sha1.c | 2 ++ + C/Sha1Opt.c | 2 ++ + C/Sha256.c | 2 ++ + C/Sha256Opt.c | 2 ++ + CPP/7zip/Crypto/MyAes.cpp | 2 ++ + 7 files changed, 14 insertions(+) + +diff --git a/C/Aes.c b/C/Aes.c +index d6732a6..f7b632f 100644 +--- a/C/Aes.c ++++ b/C/Aes.c +@@ -56,6 +56,7 @@ static Byte InvS[256]; + #ifdef MY_CPU_X86_OR_AMD64 + #define USE_HW_AES + #elif defined(MY_CPU_ARM_OR_ARM64) && defined(MY_CPU_LE) ++ #if (__ARM_ARCH >= 7) + #if defined(__clang__) + #if (__clang_major__ >= 8) // fix that check + #define USE_HW_AES +@@ -69,6 +70,7 @@ static Byte InvS[256]; + #define USE_HW_AES + #endif + #endif ++ #endif + #endif + + #ifdef USE_HW_AES +diff --git a/C/AesOpt.c b/C/AesOpt.c +index af911e2..b989692 100644 +--- a/C/AesOpt.c ++++ b/C/AesOpt.c +@@ -556,6 +556,7 @@ VAES_COMPAT_STUB (AesCtr_Code_HW) + + #elif defined(MY_CPU_ARM_OR_ARM64) && defined(MY_CPU_LE) + ++ #if (__ARM_ARCH >= 7) + #if defined(__clang__) + #if (__clang_major__ >= 8) // fix that check + #define USE_HW_AES +@@ -569,6 +570,7 @@ VAES_COMPAT_STUB (AesCtr_Code_HW) + #define USE_HW_AES + #endif + #endif ++ #endif + + #ifdef USE_HW_AES + +diff --git a/C/Sha1.c b/C/Sha1.c +index 6405fe2..9237d17 100644 +--- a/C/Sha1.c ++++ b/C/Sha1.c +@@ -33,6 +33,7 @@ This code is based on public domain code of Steve Reid from Wei Dai's Crypto++ l + #endif + #endif + #elif defined(MY_CPU_ARM_OR_ARM64) ++ #if (__ARM_ARCH >= 7) + #ifdef _MSC_VER + #if _MSC_VER >= 1910 && _MSC_VER >= 1929 && _MSC_FULL_VER >= 192930037 + #define Z7_COMPILER_SHA1_SUPPORTED +@@ -46,6 +47,7 @@ This code is based on public domain code of Steve Reid from Wei Dai's Crypto++ l + #define Z7_COMPILER_SHA1_SUPPORTED + #endif + #endif ++ #endif + #endif + + void Z7_FASTCALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks); +diff --git a/C/Sha1Opt.c b/C/Sha1Opt.c +index b47a73a..435a915 100644 +--- a/C/Sha1Opt.c ++++ b/C/Sha1Opt.c +@@ -204,6 +204,7 @@ void Z7_FASTCALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t + + #elif defined(MY_CPU_ARM_OR_ARM64) + ++ #if (__ARM_ARCH >= 7) + #if defined(__clang__) + #if (__clang_major__ >= 8) // fix that check + #define USE_HW_SHA +@@ -217,6 +218,7 @@ void Z7_FASTCALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t + #define USE_HW_SHA + #endif + #endif ++ #endif + + #ifdef USE_HW_SHA + +diff --git a/C/Sha256.c b/C/Sha256.c +index 538ccaa..667f749 100644 +--- a/C/Sha256.c ++++ b/C/Sha256.c +@@ -33,6 +33,7 @@ This code is based on public domain code from Wei Dai's Crypto++ library. */ + #endif + #endif + #elif defined(MY_CPU_ARM_OR_ARM64) ++ #if (__ARM_ARCH >= 7) + #ifdef _MSC_VER + #if _MSC_VER >= 1910 + #define Z7_COMPILER_SHA256_SUPPORTED +@@ -46,6 +47,7 @@ This code is based on public domain code from Wei Dai's Crypto++ library. */ + #define Z7_COMPILER_SHA256_SUPPORTED + #endif + #endif ++ #endif + #endif + + void Z7_FASTCALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); +diff --git a/C/Sha256Opt.c b/C/Sha256Opt.c +index 4fccb33..0fb2d6f 100644 +--- a/C/Sha256Opt.c ++++ b/C/Sha256Opt.c +@@ -204,6 +204,7 @@ void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_ + + #elif defined(MY_CPU_ARM_OR_ARM64) + ++ #if (__ARM_ARCH >= 7) + #if defined(__clang__) + #if (__clang_major__ >= 8) // fix that check + #define USE_HW_SHA +@@ -217,6 +218,7 @@ void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_ + #define USE_HW_SHA + #endif + #endif ++ #endif + + #ifdef USE_HW_SHA + +diff --git a/CPP/7zip/Crypto/MyAes.cpp b/CPP/7zip/Crypto/MyAes.cpp +index 9275d16..e543759 100644 +--- a/CPP/7zip/Crypto/MyAes.cpp ++++ b/CPP/7zip/Crypto/MyAes.cpp +@@ -155,6 +155,7 @@ Z7_COM7F_IMF2(UInt32, CAesCtrCoder::Filter(Byte *data, UInt32 size)) + #ifdef MY_CPU_X86_OR_AMD64 + #define USE_HW_AES + #elif defined(MY_CPU_ARM_OR_ARM64) && defined(MY_CPU_LE) ++ #if (__ARM_ARCH >= 7) + #if defined(__clang__) + #if (__clang_major__ >= 8) // fix that check + #define USE_HW_AES +@@ -168,6 +169,7 @@ Z7_COM7F_IMF2(UInt32, CAesCtrCoder::Filter(Byte *data, UInt32 size)) + #define USE_HW_AES + #endif + #endif ++ #endif + #endif + + #ifdef USE_HW_AES diff -Nru 7zip-22.01+dfsg/debian/patches/0003-Disable-hardware-acceleration-support-on-armel.patch 7zip-23.01+dfsg/debian/patches/0003-Disable-hardware-acceleration-support-on-armel.patch --- 7zip-22.01+dfsg/debian/patches/0003-Disable-hardware-acceleration-support-on-armel.patch 2022-07-16 13:50:37.000000000 +0000 +++ 7zip-23.01+dfsg/debian/patches/0003-Disable-hardware-acceleration-support-on-armel.patch 1970-01-01 00:00:00.000000000 +0000 @@ -1,159 +0,0 @@ -From: YOKOTA Hiroshi -Date: Tue, 14 Sep 2021 23:51:04 +0900 -Subject: Disable hardware acceleration support on armel - -Use "__ARM_ARCH" to split "armel" and "armhf" - -__ARM_ARCH: - armel = 5 - armhf = 7 ---- - C/Aes.c | 2 ++ - C/AesOpt.c | 2 ++ - C/Sha1.c | 2 ++ - C/Sha1Opt.c | 2 ++ - C/Sha256.c | 2 ++ - C/Sha256Opt.c | 2 ++ - CPP/7zip/Crypto/MyAes.cpp | 2 ++ - 7 files changed, 14 insertions(+) - -diff --git a/C/Aes.c b/C/Aes.c -index 9ad66c5..2af4298 100755 ---- a/C/Aes.c -+++ b/C/Aes.c -@@ -56,6 +56,7 @@ static Byte InvS[256]; - #ifdef MY_CPU_X86_OR_AMD64 - #define USE_HW_AES - #elif defined(MY_CPU_ARM_OR_ARM64) && defined(MY_CPU_LE) -+ #if (__ARM_ARCH >= 7) - #if defined(__clang__) - #if (__clang_major__ >= 8) // fix that check - #define USE_HW_AES -@@ -69,6 +70,7 @@ static Byte InvS[256]; - #define USE_HW_AES - #endif - #endif -+ #endif - #endif - - #ifdef USE_HW_AES -diff --git a/C/AesOpt.c b/C/AesOpt.c -index 1bdc9a8..60058bc 100755 ---- a/C/AesOpt.c -+++ b/C/AesOpt.c -@@ -508,6 +508,7 @@ VAES_COMPAT_STUB (AesCtr_Code_HW) - - #elif defined(MY_CPU_ARM_OR_ARM64) && defined(MY_CPU_LE) - -+ #if (__ARM_ARCH >= 7) - #if defined(__clang__) - #if (__clang_major__ >= 8) // fix that check - #define USE_HW_AES -@@ -521,6 +522,7 @@ VAES_COMPAT_STUB (AesCtr_Code_HW) - #define USE_HW_AES - #endif - #endif -+ #endif - - #ifdef USE_HW_AES - -diff --git a/C/Sha1.c b/C/Sha1.c -index 7adeb44..b6ee739 100755 ---- a/C/Sha1.c -+++ b/C/Sha1.c -@@ -33,6 +33,7 @@ This code is based on public domain code of Steve Reid from Wei Dai's Crypto++ l - #endif - #endif - #elif defined(MY_CPU_ARM_OR_ARM64) -+ #if (__ARM_ARCH >= 7) - #ifdef _MSC_VER - #if _MSC_VER >= 1910 && _MSC_VER >= 1929 && _MSC_FULL_VER >= 192930037 - #define _SHA_SUPPORTED -@@ -46,6 +47,7 @@ This code is based on public domain code of Steve Reid from Wei Dai's Crypto++ l - #define _SHA_SUPPORTED - #endif - #endif -+ #endif - #endif - - void MY_FAST_CALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks); -diff --git a/C/Sha1Opt.c b/C/Sha1Opt.c -index dcedfbc..574d469 100755 ---- a/C/Sha1Opt.c -+++ b/C/Sha1Opt.c -@@ -214,6 +214,7 @@ void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t - - #elif defined(MY_CPU_ARM_OR_ARM64) - -+ #if (__ARM_ARCH >= 7) - #if defined(__clang__) - #if (__clang_major__ >= 8) // fix that check - #define USE_HW_SHA -@@ -227,6 +228,7 @@ void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t - #define USE_HW_SHA - #endif - #endif -+ #endif - - #ifdef USE_HW_SHA - -diff --git a/C/Sha256.c b/C/Sha256.c -index c03b75a..e997ad4 100755 ---- a/C/Sha256.c -+++ b/C/Sha256.c -@@ -33,6 +33,7 @@ This code is based on public domain code from Wei Dai's Crypto++ library. */ - #endif - #endif - #elif defined(MY_CPU_ARM_OR_ARM64) -+ #if (__ARM_ARCH >= 7) - #ifdef _MSC_VER - #if _MSC_VER >= 1910 - #define _SHA_SUPPORTED -@@ -46,6 +47,7 @@ This code is based on public domain code from Wei Dai's Crypto++ library. */ - #define _SHA_SUPPORTED - #endif - #endif -+ #endif - #endif - - void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); -diff --git a/C/Sha256Opt.c b/C/Sha256Opt.c -index cc8c53e..b13cf7b 100755 ---- a/C/Sha256Opt.c -+++ b/C/Sha256Opt.c -@@ -214,6 +214,7 @@ void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size - - #elif defined(MY_CPU_ARM_OR_ARM64) - -+ #if (__ARM_ARCH >= 7) - #if defined(__clang__) - #if (__clang_major__ >= 8) // fix that check - #define USE_HW_SHA -@@ -227,6 +228,7 @@ void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size - #define USE_HW_SHA - #endif - #endif -+ #endif - - #ifdef USE_HW_SHA - -diff --git a/CPP/7zip/Crypto/MyAes.cpp b/CPP/7zip/Crypto/MyAes.cpp -index 7e7cced..0df7b2f 100755 ---- a/CPP/7zip/Crypto/MyAes.cpp -+++ b/CPP/7zip/Crypto/MyAes.cpp -@@ -86,6 +86,7 @@ STDMETHODIMP CAesCoder::SetInitVector(const Byte *data, UInt32 size) - #ifdef MY_CPU_X86_OR_AMD64 - #define USE_HW_AES - #elif defined(MY_CPU_ARM_OR_ARM64) && defined(MY_CPU_LE) -+ #if (__ARM_ARCH >= 7) - #if defined(__clang__) - #if (__clang_major__ >= 8) // fix that check - #define USE_HW_AES -@@ -99,6 +100,7 @@ STDMETHODIMP CAesCoder::SetInitVector(const Byte *data, UInt32 size) - #define USE_HW_AES - #endif - #endif -+ #endif - #endif - - #endif diff -Nru 7zip-22.01+dfsg/debian/patches/0003-Guard-ARM-v8-feature-from-old-architecture.patch 7zip-23.01+dfsg/debian/patches/0003-Guard-ARM-v8-feature-from-old-architecture.patch --- 7zip-22.01+dfsg/debian/patches/0003-Guard-ARM-v8-feature-from-old-architecture.patch 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/patches/0003-Guard-ARM-v8-feature-from-old-architecture.patch 2023-06-22 17:45:47.000000000 +0000 @@ -0,0 +1,25 @@ +From: YOKOTA Hiroshi +Date: Wed, 13 Oct 2021 07:59:13 +0900 +Subject: Guard ARM v8 feature from old architecture + +Forwarded: https://sourceforge.net/p/sevenzip/patches/369/ +--- + C/7zCrc.c | 5 +++-- + 1 file changed, 3 insertions(+), 2 deletions(-) + +diff --git a/C/7zCrc.c b/C/7zCrc.c +index 0871899..4bbcec3 100644 +--- a/C/7zCrc.c ++++ b/C/7zCrc.c +@@ -84,8 +84,9 @@ UInt32 Z7_FASTCALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UI + #endif + #endif + #endif +- #elif (defined(__clang__) && (__clang_major__ >= 3)) \ +- || (defined(__GNUC__) && (__GNUC__ > 4)) ++ #elif ( (defined(__clang__) && (__clang_major__ >= 3)) || \ ++ (defined(__GNUC__) && (__GNUC__ > 4) ) ) && \ ++ (__ARM_ARCH >= 8) + #if !defined(__ARM_FEATURE_CRC32) + #define __ARM_FEATURE_CRC32 1 + #if defined(__clang__) diff -Nru 7zip-22.01+dfsg/debian/patches/0004-Guard-ARM-v8-feature-from-old-architecture.patch 7zip-23.01+dfsg/debian/patches/0004-Guard-ARM-v8-feature-from-old-architecture.patch --- 7zip-22.01+dfsg/debian/patches/0004-Guard-ARM-v8-feature-from-old-architecture.patch 2022-07-16 13:50:37.000000000 +0000 +++ 7zip-23.01+dfsg/debian/patches/0004-Guard-ARM-v8-feature-from-old-architecture.patch 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -From: YOKOTA Hiroshi -Date: Wed, 13 Oct 2021 07:59:13 +0900 -Subject: Guard ARM v8 feature from old architecture - -Forwarded: not-needed ---- - C/7zCrc.c | 5 +++-- - 1 file changed, 3 insertions(+), 2 deletions(-) - -diff --git a/C/7zCrc.c b/C/7zCrc.c -index c7ec353..230d8a5 100755 ---- a/C/7zCrc.c -+++ b/C/7zCrc.c -@@ -81,8 +81,9 @@ UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const U - #define USE_ARM64_CRC - #endif - #endif -- #elif (defined(__clang__) && (__clang_major__ >= 3)) \ -- || (defined(__GNUC__) && (__GNUC__ > 4)) -+ #elif ( (defined(__clang__) && (__clang_major__ >= 3)) || \ -+ (defined(__GNUC__) && (__GNUC__ > 4) ) ) && \ -+ (__ARM_ARCH >= 8) - #if !defined(__ARM_FEATURE_CRC32) - #define __ARM_FEATURE_CRC32 1 - #if (!defined(__clang__) || (__clang_major__ > 3)) // fix these numbers diff -Nru 7zip-22.01+dfsg/debian/patches/0004-Use-getcwd-3-POSIX-extension-to-avoid-PATH_MAX-macro.patch 7zip-23.01+dfsg/debian/patches/0004-Use-getcwd-3-POSIX-extension-to-avoid-PATH_MAX-macro.patch --- 7zip-22.01+dfsg/debian/patches/0004-Use-getcwd-3-POSIX-extension-to-avoid-PATH_MAX-macro.patch 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/patches/0004-Use-getcwd-3-POSIX-extension-to-avoid-PATH_MAX-macro.patch 2023-06-22 17:45:47.000000000 +0000 @@ -0,0 +1,39 @@ +From: YOKOTA Hiroshi +Date: Wed, 15 Sep 2021 00:02:36 +0900 +Subject: Use getcwd(3) POSIX extension to avoid PATH_MAX macro + +Forwarded: https://sourceforge.net/p/sevenzip/patches/369/ + +This fix helps GNU Hurd. +--- + CPP/Windows/FileDir.cpp | 13 +------------ + 1 file changed, 1 insertion(+), 12 deletions(-) + +diff --git a/CPP/Windows/FileDir.cpp b/CPP/Windows/FileDir.cpp +index 0d3a3a9..77277c7 100644 +--- a/CPP/Windows/FileDir.cpp ++++ b/CPP/Windows/FileDir.cpp +@@ -1001,22 +1001,11 @@ bool GetCurrentDir(FString &path) + { + path.Empty(); + +- #define MY_PATH_MAX PATH_MAX +- // #define MY_PATH_MAX 1024 +- +- char s[MY_PATH_MAX + 1]; +- char *res = getcwd(s, MY_PATH_MAX); +- if (res) +- { +- path = fas2fs(s); +- return true; +- } + { +- // if (errno != ERANGE) return false; + #if defined(__GLIBC__) || defined(__APPLE__) + /* As an extension to the POSIX.1-2001 standard, glibc's getcwd() + allocates the buffer dynamically using malloc(3) if buf is NULL. */ +- res = getcwd(NULL, 0); ++ char *res = getcwd(NULL, 0); + if (res) + { + path = fas2fs(res); diff -Nru 7zip-22.01+dfsg/debian/patches/0005-Disable-local-echo-display-when-in-input-passwords-C.patch 7zip-23.01+dfsg/debian/patches/0005-Disable-local-echo-display-when-in-input-passwords-C.patch --- 7zip-22.01+dfsg/debian/patches/0005-Disable-local-echo-display-when-in-input-passwords-C.patch 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/patches/0005-Disable-local-echo-display-when-in-input-passwords-C.patch 2023-06-22 17:45:47.000000000 +0000 @@ -0,0 +1,88 @@ +From: YOKOTA Hiroshi +Date: Tue, 22 Feb 2022 21:02:14 +0900 +Subject: Disable local echo display when in input passwords (Closes: + #1006238) + +Forwarded: https://sourceforge.net/p/sevenzip/patches/381/ +Bug-Debian: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1006238 +--- + CPP/7zip/UI/Console/UserInputUtils.cpp | 33 ++++++++++++++++++++++++++++++++- + CPP/Common/StdInStream.h | 3 +++ + 2 files changed, 35 insertions(+), 1 deletion(-) + +diff --git a/CPP/7zip/UI/Console/UserInputUtils.cpp b/CPP/7zip/UI/Console/UserInputUtils.cpp +index bae463a..dc893e8 100644 +--- a/CPP/7zip/UI/Console/UserInputUtils.cpp ++++ b/CPP/7zip/UI/Console/UserInputUtils.cpp +@@ -56,9 +56,18 @@ NUserAnswerMode::EEnum ScanUserYesNoAllQuit(CStdOutStream *outStream) + #ifdef _WIN32 + #ifndef UNDER_CE + #define MY_DISABLE_ECHO ++#define MY_DISABLE_ECHO_WIN32 + #endif + #endif + ++#ifdef unix ++#include ++#include ++#include ++#define MY_DISABLE_ECHO ++#define MY_DISABLE_ECHO_UNIX ++#endif ++ + static bool GetPassword(CStdOutStream *outStream, UString &psw) + { + if (outStream) +@@ -71,7 +80,7 @@ static bool GetPassword(CStdOutStream *outStream, UString &psw) + outStream->Flush(); + } + +- #ifdef MY_DISABLE_ECHO ++ #ifdef MY_DISABLE_ECHO_WIN32 + + const HANDLE console = GetStdHandle(STD_INPUT_HANDLE); + +@@ -90,6 +99,28 @@ static bool GetPassword(CStdOutStream *outStream, UString &psw) + if (wasChanged) + SetConsoleMode(console, mode); + ++ #elif defined(MY_DISABLE_ECHO_UNIX) ++ ++ int ifd = fileno(&(*g_StdIn)); ++ bool wasChanged = false; ++ struct termios old_mode = {}; ++ struct termios new_mode = {}; ++ ++ if (tcgetattr(ifd, &old_mode) == 0) { ++ new_mode = old_mode; ++ new_mode.c_lflag &= ~ECHO; ++ ++ tcsetattr(ifd, TCSAFLUSH, &new_mode); ++ ++ wasChanged = true; ++ } ++ ++ bool res = g_StdIn.ScanUStringUntilNewLine(psw); ++ ++ if (wasChanged) { ++ tcsetattr(ifd, TCSAFLUSH, &old_mode); ++ } ++ + #else + + const bool res = g_StdIn.ScanUStringUntilNewLine(psw); +diff --git a/CPP/Common/StdInStream.h b/CPP/Common/StdInStream.h +index 2253c43..69d84fe 100644 +--- a/CPP/Common/StdInStream.h ++++ b/CPP/Common/StdInStream.h +@@ -23,7 +23,10 @@ public: + + /* + ~CStdInStream() { Close(); } ++ */ + ++ operator FILE *() { return _stream; } ++ /* + bool Open(LPCTSTR fileName) throw(); + bool Close() throw(); + */ diff -Nru 7zip-22.01+dfsg/debian/patches/0005-Use-getcwd-3-POSIX-extension-to-avoid-PATH_MAX-macro.patch 7zip-23.01+dfsg/debian/patches/0005-Use-getcwd-3-POSIX-extension-to-avoid-PATH_MAX-macro.patch --- 7zip-22.01+dfsg/debian/patches/0005-Use-getcwd-3-POSIX-extension-to-avoid-PATH_MAX-macro.patch 2022-07-16 13:50:37.000000000 +0000 +++ 7zip-23.01+dfsg/debian/patches/0005-Use-getcwd-3-POSIX-extension-to-avoid-PATH_MAX-macro.patch 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -From: YOKOTA Hiroshi -Date: Wed, 15 Sep 2021 00:02:36 +0900 -Subject: Use getcwd(3) POSIX extension to avoid PATH_MAX macro - -Forwarded: not-needed - -This fix helps GNU Hurd. ---- - CPP/Windows/FileDir.cpp | 13 +------------ - 1 file changed, 1 insertion(+), 12 deletions(-) - -diff --git a/CPP/Windows/FileDir.cpp b/CPP/Windows/FileDir.cpp -index 5e95204..9b5394e 100755 ---- a/CPP/Windows/FileDir.cpp -+++ b/CPP/Windows/FileDir.cpp -@@ -906,22 +906,11 @@ bool GetCurrentDir(FString &path) - { - path.Empty(); - -- #define MY__PATH_MAX PATH_MAX -- // #define MY__PATH_MAX 1024 -- -- char s[MY__PATH_MAX + 1]; -- char *res = getcwd(s, MY__PATH_MAX); -- if (res) -- { -- path = fas2fs(s); -- return true; -- } - { -- // if (errno != ERANGE) return false; - #if defined(__GLIBC__) || defined(__APPLE__) - /* As an extension to the POSIX.1-2001 standard, glibc's getcwd() - allocates the buffer dynamically using malloc(3) if buf is NULL. */ -- res = getcwd(NULL, 0); -+ char *res = getcwd(NULL, 0); - if (res) - { - path = fas2fs(res); diff -Nru 7zip-22.01+dfsg/debian/patches/0006-Disable-local-echo-display-when-in-input-passwords-C.patch 7zip-23.01+dfsg/debian/patches/0006-Disable-local-echo-display-when-in-input-passwords-C.patch --- 7zip-22.01+dfsg/debian/patches/0006-Disable-local-echo-display-when-in-input-passwords-C.patch 2022-07-16 13:50:37.000000000 +0000 +++ 7zip-23.01+dfsg/debian/patches/0006-Disable-local-echo-display-when-in-input-passwords-C.patch 1970-01-01 00:00:00.000000000 +0000 @@ -1,83 +0,0 @@ -From: YOKOTA Hiroshi -Date: Tue, 22 Feb 2022 21:02:14 +0900 -Subject: Disable local echo display when in input passwords (Closes: - #1006238) - ---- - CPP/7zip/UI/Console/UserInputUtils.cpp | 33 ++++++++++++++++++++++++++++++++- - CPP/Common/StdInStream.h | 1 + - 2 files changed, 33 insertions(+), 1 deletion(-) - -diff --git a/CPP/7zip/UI/Console/UserInputUtils.cpp b/CPP/7zip/UI/Console/UserInputUtils.cpp -index b3ca88e..6f60a78 100755 ---- a/CPP/7zip/UI/Console/UserInputUtils.cpp -+++ b/CPP/7zip/UI/Console/UserInputUtils.cpp -@@ -56,9 +56,18 @@ NUserAnswerMode::EEnum ScanUserYesNoAllQuit(CStdOutStream *outStream) - #ifdef _WIN32 - #ifndef UNDER_CE - #define MY_DISABLE_ECHO -+#define MY_DISABLE_ECHO_WIN32 - #endif - #endif - -+#ifdef unix -+#include -+#include -+#include -+#define MY_DISABLE_ECHO -+#define MY_DISABLE_ECHO_UNIX -+#endif -+ - static bool GetPassword(CStdOutStream *outStream, UString &psw) - { - if (outStream) -@@ -71,7 +80,7 @@ static bool GetPassword(CStdOutStream *outStream, UString &psw) - outStream->Flush(); - } - -- #ifdef MY_DISABLE_ECHO -+ #ifdef MY_DISABLE_ECHO_WIN32 - - HANDLE console = GetStdHandle(STD_INPUT_HANDLE); - bool wasChanged = false; -@@ -83,6 +92,28 @@ static bool GetPassword(CStdOutStream *outStream, UString &psw) - if (wasChanged) - SetConsoleMode(console, mode); - -+ #elif defined(MY_DISABLE_ECHO_UNIX) -+ -+ int ifd = fileno(&(*g_StdIn)); -+ bool wasChanged = false; -+ struct termios old_mode = {}; -+ struct termios new_mode = {}; -+ -+ if (tcgetattr(ifd, &old_mode) == 0) { -+ new_mode = old_mode; -+ new_mode.c_lflag &= ~ECHO; -+ -+ tcsetattr(ifd, TCSAFLUSH, &new_mode); -+ -+ wasChanged = true; -+ } -+ -+ bool res = g_StdIn.ScanUStringUntilNewLine(psw); -+ -+ if (wasChanged) { -+ tcsetattr(ifd, TCSAFLUSH, &old_mode); -+ } -+ - #else - - bool res = g_StdIn.ScanUStringUntilNewLine(psw); -diff --git a/CPP/Common/StdInStream.h b/CPP/Common/StdInStream.h -index 7f27e92..23c7bf8 100755 ---- a/CPP/Common/StdInStream.h -+++ b/CPP/Common/StdInStream.h -@@ -23,6 +23,7 @@ public: - - ~CStdInStream() { Close(); } - -+ operator FILE *() { return _stream; } - bool Open(LPCTSTR fileName) throw(); - bool Close() throw(); - diff -Nru 7zip-22.01+dfsg/debian/patches/0006-Fix-ARM-architecture-selection-code.patch 7zip-23.01+dfsg/debian/patches/0006-Fix-ARM-architecture-selection-code.patch --- 7zip-22.01+dfsg/debian/patches/0006-Fix-ARM-architecture-selection-code.patch 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/patches/0006-Fix-ARM-architecture-selection-code.patch 2023-06-22 17:45:47.000000000 +0000 @@ -0,0 +1,25 @@ +From: YOKOTA Hiroshi +Date: Wed, 21 Jun 2023 08:58:52 +0900 +Subject: Fix ARM architecture selection code + +Forwarded: https://sourceforge.net/p/sevenzip/patches/413/ + +This fix guards NEON function usage from older ARM architectures like armel +(__ARM_ARCH == 5). +--- + C/SwapBytes.c | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/C/SwapBytes.c b/C/SwapBytes.c +index 0bfe95c..8f4c356 100644 +--- a/C/SwapBytes.c ++++ b/C/SwapBytes.c +@@ -330,7 +330,7 @@ ShufBytes_256(void *items8, const void *lim8, const void *mask128_ptr) + + + // compile message "NEON intrinsics not available with the soft-float ABI" +-#elif defined(MY_CPU_ARM_OR_ARM64) || \ ++#elif defined(MY_CPU_ARM_OR_ARM64) && \ + (defined(__ARM_ARCH) && (__ARM_ARCH >= 7)) + // #elif defined(MY_CPU_ARM64) + diff -Nru 7zip-22.01+dfsg/debian/patches/0007-Add-__target__-fpu-neon-attribute-to-use-NEON-specif.patch 7zip-23.01+dfsg/debian/patches/0007-Add-__target__-fpu-neon-attribute-to-use-NEON-specif.patch --- 7zip-22.01+dfsg/debian/patches/0007-Add-__target__-fpu-neon-attribute-to-use-NEON-specif.patch 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/patches/0007-Add-__target__-fpu-neon-attribute-to-use-NEON-specif.patch 2023-06-22 18:03:45.000000000 +0000 @@ -0,0 +1,50 @@ +From: YOKOTA Hiroshi +Date: Wed, 21 Jun 2023 09:43:09 +0900 +Subject: Add __target__("fpu=neon") attribute to use NEON specific codes +MIME-Version: 1.0 +Content-Type: text/plain; charset="utf-8" +Content-Transfer-Encoding: 8bit + +Forwarded: https://sourceforge.net/p/sevenzip/patches/413/ + +https://sourceforge.net/p/sevenzip/patches/413/#8bce +> Igor Pavlov: +> 7-zip detects neon availability at runtime via hwcap. +> And 7-zip can select between neon and non-neon code. +> So we want to use NEON in some functions, even if main code is not neon. +> for x86, we just use `__attribute__` for avx2 functions: +> +> ``` +> __attribute__((__target__("avx2"))) +> ``` +> +> What way to do similar thing for arm-neon ? + +From armhf build log: +> /usr/lib/gcc/arm-linux-gnueabihf/12/include/arm_neon.h:9186:1: +> error: inlining failed in call to ‘always_inline’ ‘vrev16q_u8’: +> target specific option mismatch + +vrev16q_u8() requires NEON option to use. +Add __target__("fpu=neon") attribute to enable NEON intrinsics. + +__target__("fpu=crypto-neon-fp-armv8") is too much to use vrev16q_u8(). +Use simple __target__("fpu=neon") to satisfy lowest requirement to +use vrev16q_u8(). +--- + C/SwapBytes.c | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/C/SwapBytes.c b/C/SwapBytes.c +index 8f4c356..7de5be3 100644 +--- a/C/SwapBytes.c ++++ b/C/SwapBytes.c +@@ -343,7 +343,7 @@ ShufBytes_256(void *items8, const void *lim8, const void *mask128_ptr) + #ifdef MY_CPU_ARM64 + // #define SWAP_ATTRIB_NEON __attribute__((__target__(""))) + #else +- // #define SWAP_ATTRIB_NEON __attribute__((__target__("fpu=crypto-neon-fp-armv8"))) ++ #define SWAP_ATTRIB_NEON __attribute__((__target__("fpu=neon"))) + #endif + #elif defined(_MSC_VER) + #if (_MSC_VER >= 1910) diff -Nru 7zip-22.01+dfsg/debian/patches/0008-PPC-is-already-defined-as-1-on-PowerPC-compilers.patch 7zip-23.01+dfsg/debian/patches/0008-PPC-is-already-defined-as-1-on-PowerPC-compilers.patch --- 7zip-22.01+dfsg/debian/patches/0008-PPC-is-already-defined-as-1-on-PowerPC-compilers.patch 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/patches/0008-PPC-is-already-defined-as-1-on-PowerPC-compilers.patch 2023-06-22 17:45:47.000000000 +0000 @@ -0,0 +1,98 @@ +From: YOKOTA Hiroshi +Date: Wed, 21 Jun 2023 12:08:38 +0900 +Subject: "PPC" is already defined as "1" on PowerPC compilers + +Forwarded: https://sourceforge.net/p/sevenzip/patches/413/ + +Use "Z7_PPC" to avoid symbol name conflicts +--- + C/Bra.c | 4 ++-- + C/Bra.h | 2 +- + C/XzDec.c | 2 +- + C/XzEnc.c | 2 +- + CPP/7zip/Compress/BranchRegister.cpp | 4 ++-- + 5 files changed, 7 insertions(+), 7 deletions(-) + +diff --git a/C/Bra.c b/C/Bra.c +index 411f252..d772220 100644 +--- a/C/Bra.c ++++ b/C/Bra.c +@@ -155,7 +155,7 @@ Z7_BRANCH_FUNC_MAIN(ARM) + Z7_BRANCH_FUNCS_IMP(ARM) + + +-Z7_BRANCH_FUNC_MAIN(PPC) ++Z7_BRANCH_FUNC_MAIN(Z7_PPC) + { + // Byte *p = data; + const Byte *lim; +@@ -192,7 +192,7 @@ Z7_BRANCH_FUNC_MAIN(PPC) + } + } + } +-Z7_BRANCH_FUNCS_IMP(PPC) ++Z7_BRANCH_FUNCS_IMP(Z7_PPC) + + + #ifdef Z7_CPU_FAST_ROTATE_SUPPORTED +diff --git a/C/Bra.h b/C/Bra.h +index aeedaba..373f62f 100644 +--- a/C/Bra.h ++++ b/C/Bra.h +@@ -30,7 +30,7 @@ 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(Z7_PPC) + Z7_BRANCH_FUNCS_DECL(SPARC) + Z7_BRANCH_FUNCS_DECL(IA64) + +diff --git a/C/XzDec.c b/C/XzDec.c +index 2d113a6..d280ab5 100644 +--- a/C/XzDec.c ++++ b/C/XzDec.c +@@ -151,7 +151,7 @@ static void XzBcFilterState_Init(void *pp) + + static const z7_Func_BranchConv g_Funcs_BranchConv_RISC_Dec[] = + { +- Z7_BRANCH_CONV_DEC(PPC), ++ Z7_BRANCH_CONV_DEC(Z7_PPC), + Z7_BRANCH_CONV_DEC(IA64), + Z7_BRANCH_CONV_DEC(ARM), + Z7_BRANCH_CONV_DEC(ARMT), +diff --git a/C/XzEnc.c b/C/XzEnc.c +index d0c36ea..f4579d1 100644 +--- a/C/XzEnc.c ++++ b/C/XzEnc.c +@@ -325,7 +325,7 @@ typedef struct + + static const z7_Func_BranchConv g_Funcs_BranchConv_RISC_Enc[] = + { +- Z7_BRANCH_CONV_ENC(PPC), ++ Z7_BRANCH_CONV_ENC(Z7_PPC), + Z7_BRANCH_CONV_ENC(IA64), + Z7_BRANCH_CONV_ENC(ARM), + Z7_BRANCH_CONV_ENC(ARMT), +diff --git a/CPP/7zip/Compress/BranchRegister.cpp b/CPP/7zip/Compress/BranchRegister.cpp +index 5bf5f4d..c6ebd09 100644 +--- a/CPP/7zip/Compress/BranchRegister.cpp ++++ b/CPP/7zip/Compress/BranchRegister.cpp +@@ -22,7 +22,7 @@ namespace NBranch { + REGISTER_FILTER_CREATE(CreateBra_Decoder_ ## n, CCoder(Z7_BRANCH_CONV_DEC(n))) \ + CREATE_BRA_E(n) + +-CREATE_BRA(PPC) ++CREATE_BRA(Z7_PPC) + CREATE_BRA(IA64) + CREATE_BRA(ARM) + CREATE_BRA(ARMT) +@@ -36,7 +36,7 @@ CREATE_BRA(SPARC) + + REGISTER_CODECS_VAR + { +- METHOD_ITEM(PPC, 0x205, "PPC"), ++ METHOD_ITEM(Z7_PPC,0x205, "PPC"), + METHOD_ITEM(IA64, 0x401, "IA64"), + METHOD_ITEM(ARM, 0x501, "ARM"), + METHOD_ITEM(ARMT, 0x701, "ARMT"), diff -Nru 7zip-22.01+dfsg/debian/patches/series 7zip-23.01+dfsg/debian/patches/series --- 7zip-22.01+dfsg/debian/patches/series 2022-07-28 20:48:28.000000000 +0000 +++ 7zip-23.01+dfsg/debian/patches/series 2023-06-22 18:03:45.000000000 +0000 @@ -1,5 +1,8 @@ 0001-Accept-Debian-build-flags.patch -0003-Disable-hardware-acceleration-support-on-armel.patch -0004-Guard-ARM-v8-feature-from-old-architecture.patch -0005-Use-getcwd-3-POSIX-extension-to-avoid-PATH_MAX-macro.patch -0006-Disable-local-echo-display-when-in-input-passwords-C.patch +0002-Disable-hardware-acceleration-support-on-armel.patch +0003-Guard-ARM-v8-feature-from-old-architecture.patch +0004-Use-getcwd-3-POSIX-extension-to-avoid-PATH_MAX-macro.patch +0005-Disable-local-echo-display-when-in-input-passwords-C.patch +0006-Fix-ARM-architecture-selection-code.patch +0007-Add-__target__-fpu-neon-attribute-to-use-NEON-specif.patch +0008-PPC-is-already-defined-as-1-on-PowerPC-compilers.patch diff -Nru 7zip-22.01+dfsg/debian/rules 7zip-23.01+dfsg/debian/rules --- 7zip-22.01+dfsg/debian/rules 2022-06-21 06:07:22.000000000 +0000 +++ 7zip-23.01+dfsg/debian/rules 2023-06-20 20:43:43.000000000 +0000 @@ -17,6 +17,47 @@ DEB_CXXFLAGS="$(CXXFLAGS) -pipe" \ DEB_CPPFLAGS="$(CPPFLAGS)" \ DEB_LDFLAGS="$(LDFLAGS) -pipe" + $(MAKE) -C CPP/7zip/Bundles/Format7zF -f ../../cmpl_gcc.mak \ + CROSS_COMPILE="$(DEB_HOST_GNU_TYPE)-" \ + DISABLE_RAR_COMPRESS=1 \ + DEB_CFLAGS="$(CFLAGS) -pipe" \ + DEB_CXXFLAGS="$(CXXFLAGS) -pipe" \ + DEB_CPPFLAGS="$(CPPFLAGS)" \ + DEB_LDFLAGS="$(LDFLAGS) -pipe" + $(MAKE) -C CPP/7zip/UI/Console -f ../../cmpl_gcc.mak \ + CROSS_COMPILE="$(DEB_HOST_GNU_TYPE)-" \ + DISABLE_RAR=1 \ + DEB_CFLAGS="$(CFLAGS) -pipe" \ + DEB_CXXFLAGS="$(CXXFLAGS) -pipe" \ + DEB_CPPFLAGS="$(CPPFLAGS)" \ + DEB_LDFLAGS="$(LDFLAGS) -pipe" + $(MAKE) -C CPP/7zip/Bundles/SFXCon -f ../../cmpl_gcc.mak \ + CROSS_COMPILE="$(DEB_HOST_GNU_TYPE)-" \ + DISABLE_RAR=1 \ + DEB_CFLAGS="$(CFLAGS) -pipe" \ + DEB_CXXFLAGS="$(CXXFLAGS) -pipe" \ + DEB_CPPFLAGS="$(CPPFLAGS)" \ + DEB_LDFLAGS="$(LDFLAGS) -pipe" + $(MAKE) -C CPP/7zip/Bundles/Alone -f ../../cmpl_gcc.mak \ + CROSS_COMPILE="$(DEB_HOST_GNU_TYPE)-" \ + DISABLE_RAR=1 \ + DEB_CFLAGS="$(CFLAGS) -pipe" \ + DEB_CXXFLAGS="$(CXXFLAGS) -pipe" \ + DEB_CPPFLAGS="$(CPPFLAGS)" \ + DEB_LDFLAGS="$(LDFLAGS) -pipe" + $(MAKE) -C CPP/7zip/Bundles/Alone7z -f ../../cmpl_gcc.mak \ + CROSS_COMPILE="$(DEB_HOST_GNU_TYPE)-" \ + DISABLE_RAR=1 \ + DEB_CFLAGS="$(CFLAGS) -pipe" \ + DEB_CXXFLAGS="$(CXXFLAGS) -pipe" \ + DEB_CPPFLAGS="$(CPPFLAGS)" \ + DEB_LDFLAGS="$(LDFLAGS) -pipe" override_dh_auto_clean: - $(MAKE) -C CPP/7zip/Bundles/Alone2 -f ../../cmpl_gcc.mak clean + $(MAKE) -C CPP/7zip/Bundles/Alone2 -f ../../cmpl_gcc.mak clean + $(MAKE) -C CPP/7zip/Bundles/Format7zF -f ../../cmpl_gcc.mak clean + $(MAKE) -C CPP/7zip/UI/Console -f ../../cmpl_gcc.mak clean + $(MAKE) -C CPP/7zip/Bundles/Alone7z -f ../../cmpl_gcc.mak clean + $(MAKE) -C CPP/7zip/Bundles/SFXCon -f ../../cmpl_gcc.mak clean + $(MAKE) -C CPP/7zip/Bundles/Alone -f ../../cmpl_gcc.mak clean + $(MAKE) -C CPP/7zip/Bundles/Alone7z -f ../../cmpl_gcc.mak clean diff -Nru 7zip-22.01+dfsg/debian/scripts/7za.sh 7zip-23.01+dfsg/debian/scripts/7za.sh --- 7zip-22.01+dfsg/debian/scripts/7za.sh 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/scripts/7za.sh 2023-06-20 20:43:43.000000000 +0000 @@ -0,0 +1,2 @@ +#! /bin/sh +exec /usr/lib/7zip/7za "$@" diff -Nru 7zip-22.01+dfsg/debian/scripts/7zr.sh 7zip-23.01+dfsg/debian/scripts/7zr.sh --- 7zip-22.01+dfsg/debian/scripts/7zr.sh 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/scripts/7zr.sh 2023-06-20 20:43:43.000000000 +0000 @@ -0,0 +1,2 @@ +#! /bin/sh +exec /usr/lib/7zip/7zr "$@" diff -Nru 7zip-22.01+dfsg/debian/scripts/7z.sh 7zip-23.01+dfsg/debian/scripts/7z.sh --- 7zip-22.01+dfsg/debian/scripts/7z.sh 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/scripts/7z.sh 2023-06-20 20:43:43.000000000 +0000 @@ -0,0 +1,2 @@ +#! /bin/sh +exec /usr/lib/7zip/7z "$@" diff -Nru 7zip-22.01+dfsg/debian/scripts/7zz.sh 7zip-23.01+dfsg/debian/scripts/7zz.sh --- 7zip-22.01+dfsg/debian/scripts/7zz.sh 1970-01-01 00:00:00.000000000 +0000 +++ 7zip-23.01+dfsg/debian/scripts/7zz.sh 2023-06-20 20:43:43.000000000 +0000 @@ -0,0 +1,2 @@ +#! /bin/sh +exec /usr/lib/7zip/7zz "$@" diff -Nru 7zip-22.01+dfsg/debian/tests/control 7zip-23.01+dfsg/debian/tests/control --- 7zip-22.01+dfsg/debian/tests/control 2021-12-28 08:55:14.000000000 +0000 +++ 7zip-23.01+dfsg/debian/tests/control 2023-06-20 20:43:43.000000000 +0000 @@ -1,12 +1,43 @@ # -*- mode: conf -*- -Features: test-name=smoke +Features: test-name=smoke-7zz Test-Command: 7zz Restrictions: superficial -Features: test-name=benchmark-simple +Features: test-name=smoke-7z +Test-Command: 7z.7zip +Restrictions: superficial + +Features: test-name=smoke-7za +Test-Command: 7za.7zip +Restrictions: superficial + +Features: test-name=smoke-7zr +Test-Command: 7zr.7zip +Restrictions: superficial + +Features: test-name=formats-7zz +Test-Command: 7zz i +Restrictions: superficial + +Features: test-name=formats-7z +Test-Command: 7z.7zip i +Restrictions: superficial + +Features: test-name=formats-7za +Test-Command: 7za.7zip i +Restrictions: superficial + +Features: test-name=formats-7zr +Test-Command: 7zr.7zip i +Restrictions: superficial + +Features: test-name=benchmark-7zz-simple Test-Command: 7zz b -bt -Features: test-name=benchmark-full +Features: test-name=benchmark-7z-simple +Test-Command: 7z.7zip b -bt + +Features: test-name=benchmark-7zz-full Test-Command: 7zz b "-mm=*" "-mmt=*" -bt Architecture: !armhf diff -Nru 7zip-22.01+dfsg/DOC/7zip.wxs 7zip-23.01+dfsg/DOC/7zip.wxs --- 7zip-22.01+dfsg/DOC/7zip.wxs 2022-07-15 17:17:34.000000000 +0000 +++ 7zip-23.01+dfsg/DOC/7zip.wxs 2023-06-19 13:00:00.000000000 +0000 @@ -1,6 +1,6 @@ - + diff -Nru 7zip-22.01+dfsg/DOC/lzma.txt 7zip-23.01+dfsg/DOC/lzma.txt --- 7zip-22.01+dfsg/DOC/lzma.txt 2018-04-08 12:44:20.000000000 +0000 +++ 7zip-23.01+dfsg/DOC/lzma.txt 2023-06-20 11:00:00.000000000 +0000 @@ -1,6 +1,6 @@ LZMA compression ---------------- -Version: 9.35 +Version: 23.01 This file describes LZMA encoding and decoding functions written in C language. @@ -169,12 +169,14 @@ Compile files: 7zTypes.h Threads.h + Threads.c LzmaEnc.h LzmaEnc.c LzFind.h LzFind.c LzFindMt.h LzFindMt.c + LzFindOpt.c LzHash.h Memory Requirements: @@ -283,17 +285,26 @@ Defines ------- -_LZMA_SIZE_OPT - Enable some optimizations in LZMA Decoder to get smaller executable code. +Z7_LZMA_SIZE_OPT - Enable some code size optimizations in LZMA Decoder to get smaller executable code. -_LZMA_PROB32 - It can increase the speed on some 32-bit CPUs, but memory usage for - some structures will be doubled in that case. +Z7_LZMA_PROB32 - It can increase the speed on some 32-bit CPUs, but memory usage for + some structures will be doubled in that case. -_LZMA_UINT32_IS_ULONG - Define it if int is 16-bit on your compiler and long is 32-bit. +Z7_DECL_Int32_AS_long - Define it if int is 16-bit on your compiler and long is 32-bit. -_LZMA_NO_SYSTEM_SIZE_T - Define it if you don't want to use size_t type. +Z7_DECL_SizeT_AS_unsigned_int - Define it if you don't want to use size_t type. -_7ZIP_PPMD_SUPPPORT - Define it if you don't want to support PPMD method in AMSI-C .7z decoder. +Defines for 7z decoder written in C +----------------------------------- +These defines are for 7zDec.c only (the decoder in C). +C++ 7z decoder doesn't uses these macros. + +Z7_PPMD_SUPPORT - define it if you need PPMD method support. +Z7_NO_METHODS_FILTERS - do not use filters (except of BCJ2 filter). +Z7_USE_NATIVE_BRANCH_FILTER - use filter for native ISA: + use x86 filter, if compiled to x86 executable, + use arm64 filter, if compiled to arm64 executable. C++ LZMA Encoder/Decoder @@ -305,20 +316,26 @@ C++ Notes ~~~~~~~~~~~~~~~~~~~~~~~~ -If you use some C++ code folders in 7-Zip (for example, C++ code for .7z handling), +If you use some C++ code folders in 7-Zip (for example, C++ code for 7z archive handling), you must check that you correctly work with "new" operator. 7-Zip can be compiled with MSVC 6.0 that doesn't throw "exception" from "new" operator. -So 7-Zip uses "CPP\Common\NewHandler.cpp" that redefines "new" operator: +So 7-Zip uses "CPP\Common\NewHandler.cpp" that redefines "new" operator, +if compiled by old MSVC compilers (MSVC before version VS 2010): + operator new(size_t size) { void *p = ::malloc(size); - if (p == 0) + if (!p) throw CNewException(); return p; } -If you use MSCV that throws exception for "new" operator, you can compile without -"NewHandler.cpp". So standard exception will be used. Actually some code of -7-Zip catches any exception in internal code and converts it to HRESULT code. + +If the compiler is VS 2010 or newer, NewHandler.cpp doesn't redefine "new" operator. +Sp if you use new compiler (VS 2010 or newer), you still can include "NewHandler.cpp" +to compilation, and it will not redefine operator new. +Also you can compile without "NewHandler.cpp" with new compilers. +If 7-zip doesn't redefine operator "new", standard exception will be used instead of CNewException. +Some code of 7-Zip catches any exception in internal code and converts it to HRESULT code. So you don't need to catch CNewException, if you call COM interfaces of 7-Zip. --- diff -Nru 7zip-22.01+dfsg/DOC/Methods.txt 7zip-23.01+dfsg/DOC/Methods.txt --- 7zip-22.01+dfsg/DOC/Methods.txt 2018-12-30 09:16:07.000000000 +0000 +++ 7zip-23.01+dfsg/DOC/Methods.txt 2023-06-20 09:59:27.000000000 +0000 @@ -1,8 +1,8 @@ 7-Zip method IDs for 7z and xz archives --------------------------------------- -Version: 18.06 -Date: 2018-06-30 +Version: 23.01 +Date: 2023-06-30 Each compression or crypto method in 7z is associated with unique binary value (ID). The length of ID in bytes is arbitrary but it can not exceed 63 bits (8 bytes). @@ -37,6 +37,7 @@ 07 - ARM (little-endian) 08 - ARMT (little-endian) 09 - SPARC +0A - ARM64 21 - LZMA2 @@ -88,6 +89,8 @@ 0A - Imploding 0C - BZip2 (not used. Use {040202} instead) 0E - LZMA (LZMA-zip) + + 5D - ZSTD 5F - xz 60 - Jpeg 61 - WavPack diff -Nru 7zip-22.01+dfsg/DOC/readme.txt 7zip-23.01+dfsg/DOC/readme.txt --- 7zip-22.01+dfsg/DOC/readme.txt 2022-07-15 17:16:55.000000000 +0000 +++ 7zip-23.01+dfsg/DOC/readme.txt 2023-06-20 10:00:00.000000000 +0000 @@ -1,17 +1,18 @@ -7-Zip 22.01 Sources +7-Zip 23.01 Sources ------------------- 7-Zip is a file archiver for Windows. -7-Zip Copyright (C) 1999-2022 Igor Pavlov. +7-Zip Copyright (C) 1999-2023 Igor Pavlov. License Info ------------ 7-Zip is free software distributed under the GNU LGPL -(except for unRar code). -read License.txt for more infomation about license. +(except for unRar code). Also some code +is licensed under the "BSD 3-clause License". +Read "License.txt" for more infomation about license. Notes about unRAR license: @@ -46,13 +47,11 @@ ------------------------- To compile the sources to Windows binaries you need Visual Studio compiler and/or Windows SDK. -You can use latest Windows Studio 2017/2019 to compile binaries for x86, x64 and arm64 platforms. +You can use latest Windows Studio 2017/2019/2022 to compile binaries for x86, x64, arm64 and arm platforms. Also you can use old compilers for some platforms: x86 : Visual C++ 6.0 with Platform SDK x64 : Windows Server 2003 R2 Platform SDK - arm64 : Windows Studio 2017 - arm : Windows Studio 2017 - ia64 (itanium) : Windows Server 2003 R2 Platform SDK + ia64 (itanium) : Windows Server 2003 R2 Platform SDK arm for Windows CE : Standard SDK for Windows CE 5.0 If you use MSVC6, specify also Platform SDK directories at top of directories lists: @@ -70,7 +69,7 @@ 2) via dsp file in Visual Studio. The dsp file compiling can be used for development and debug purposes. -The final 7-Zip binaries are compiled via makefiles, that provide best +All final 7-Zip binaries are compiled via makefiles, that provide best optimization options. @@ -94,8 +93,8 @@ Compiling 7-Zip for Unix/Linux ------------------------------ -There are several otpions to compile 7-Zip with different compilers: gcc and clang. -Also 7-Zip code contains two versions for some critical parts of code: in C and in Assembeler. +There are several options to compile 7-Zip with different compilers: gcc and clang. +Also 7-Zip code contains two versions for some parts of code: in C and in Assembeler. So if you compile the version with Assembeler code, you will get faster 7-Zip binary. 7-Zip's assembler code uses the following syntax for different platforms: @@ -109,13 +108,14 @@ https://github.com/nidud/asmc 2) arm64: GNU assembler for ARM64 with preprocessor. - That systax of that arm64 assembler code in 7-Zip is supported by GCC and CLANG for ARM64. + That systax is supported by GCC and CLANG for ARM64. There are different binaries that can be compiled from 7-Zip source. There are 2 main files in folder for compiling: makefile - that can be used for compiling Windows version of 7-Zip with nmake command - makefile.gcc - that can be used for compiling Linux/macOS versions of 7-Zip with make command - + makefile.gcc - that can be used for compiling Linux/macOS versions of 7-Zip or Windows version + with MINGW (GCC) with make command. + At first you must change the current folder to folder that contains `makefile.gcc`: cd CPP/7zip/Bundles/Alone2 @@ -143,7 +143,7 @@ To compile 7-Zip for arm64 for macOS: make -j -f ../../cmpl_mac_arm64.mak -Also you can change some compiler options in the mak files: +Also you can change some compiler options in the "mak" files: cmpl_gcc.mak var_gcc.mak warn_gcc.mak @@ -207,16 +207,17 @@ DOC Documentation --- - 7zFormat.txt - 7z format description - copying.txt - GNU LGPL license - unRarLicense.txt - License for unRAR part of source code + readme.txt - Readme file src-history.txt - Sources history + 7zC.txt - 7z ANSI-C Decoder description + 7zFormat.txt - 7z format description Methods.txt - Compression method IDs - readme.txt - Readme file lzma.txt - LZMA compression description - 7zip.nsi - installer script for NSIS - 7zip.wix - installer script for WIX - + License.txt - license information + copying.txt - GNU LGPL license + unRarLicense.txt - License for unRAR part of source code + 7zip.wxs - installer script for WIX + 7zip.hhp - html help project file Asm - Source code in Assembler : optimized code for CRC, SHA, AES, LZMA decoding. @@ -250,9 +251,9 @@ SFXWin 7z.sfx: Windows 7z SFX module SFXSetup 7zS.sfx: Windows 7z SFX module for Installers - Compress files for compression/decompression + Compress files for compression / decompression - Crypto files for encryption / decompression + Crypto files for encryption / decryption UI diff -Nru 7zip-22.01+dfsg/DOC/src-history.txt 7zip-23.01+dfsg/DOC/src-history.txt --- 7zip-22.01+dfsg/DOC/src-history.txt 2022-06-19 12:53:08.000000000 +0000 +++ 7zip-23.01+dfsg/DOC/src-history.txt 2023-06-20 09:00:00.000000000 +0000 @@ -1,6 +1,28 @@ HISTORY of the 7-Zip source code -------------------------------- +23.01 2023-06-20 +------------------------- +- All external macros for compiling C/C++ code of 7-Zip now have Z7_ prefix. +- 7-Zip COM interfaces now use new macros that allow to declare and implement COM interface. +- The code has been modified to compile with the maximum diagnostic warning level: + -Wall in MSVC and -Weverything in CLANG. + And some warning types are disabled in 2 files: + - C/Compiler.h for C/C++ code warnings. + - CPP/Common/Common.h for C++ code warnings. +- Linux/macOS versions of 7-Zip: IUnknown interface in new code doesn't use + virtual destructor that was used in previous 7-Zip and p7zip: + // virtual ~IUnknown() {} + So 7-Zip's dynamically linked shared libraries (codecs) are not compatible + between new 7-Zip for Linux/macOS and old 7-Zip (and p7zip). +- Some optimizations in filters code: BCJ, BCJ2, Swap* and opthers. +- If 7-Zip uses BCJ2 filter for big datasets compressing, it can use additional temp + files in system's TEMP folder. 7-Zip uses temp file for additional compressed + data stream, if size of such compressed stream is larger than predefined limit: + 16 MiB in 32-bit version, 4 GiB in 64-bit version. +- Some bugs were fixed. + + 22.00 2022-06-16 ------------------------- - 7-Zip interfaces now support high precision (1 ns) timestamps with reserved